问:
NVCC compiles the Eigen library, and the resize of MatrixXd in the structure at runtime fails
I am using the Eigen library version 3.3 with g++ 5.4 and CUDA 8.0 in ubuntu 16.04 LTS.

confusing things happened while writing the code.
A crash occurs when I try to resize Eigen::MatrixXd in a structure

the structure is as follows.

```<code>struct cudaCopy{
      struct s_path_info *nodes_parents
      struct s_path_info *nodes_children
      ...
}
</code>```

the s_path_info structure is as follows.

```<code>struct s_path_info{
    Eigen::MatrixXd supps;
    Eigen::MatrixXd residu;
    ...
</code>```

The problems are as follows.

```<code>struct cudaCopy *mem;
mem = (struct cudaCopy*)malloc(sizeof(struct cudaCopy));
</code>```

and

```<code>mem->nodes_parents = (struct s_path_info*)malloc(50 * sizeof(struct s_path_info))
for(int i=0; i<50; i++){
    mem->nodes_parents[i].supps.resize(1, 1); // ERROR
</code>```

Here is the backtrace that GDB execute the code.

```<code>#0  __GI___libc_free (mem=0x1) at malloc.c:2949
#1  0x000000000040a538 in Eigen::internal::aligned_free (ptr=0x1) at ../Eigen/Eigen/src/Core/util/Memory.h:177
#2  0x000000000040f3e8 in Eigen::internal::conditional_aligned_free<true> (ptr=0x1) at ../Eigen/Eigen/src/Core/util/Memory.h:230
#3  0x000000000040cdd4 in Eigen::internal::conditional_aligned_delete_auto<double, true> (ptr=0x1, size=7209728) at ../Eigen/Eigen/src/Core/util/Memory.h:416
#4  0x000000000040d085 in Eigen::DenseStorage<double, -1, -1, -1, 0>::resize (this=0x6e1348, size=20, rows=20, cols=1) at ../Eigen/Eigen/src/Core/DenseStorage.h:406
#5  0x000000000040ba9e in Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::resize (this=0x6e1348, rows=20, cols=1) at ../Eigen/Eigen/src/Core/PlainObjectBase.h:293
#6  0x000000000040697f in search::islsp_EstMMP_BF_reuse (this=0x7fffffffe4b0) at exam.cu:870
#7  0x0000000000404f33 in main () at exam.cu:422
</code>```

interestingly, the following works well.

```<code>mem->nodes_children = (struct s_path_info*)malloc(10*50*sizeof(struct s_path_info))
for(int i=0; i<10*50; i++){
    mem->nodes_children[i].supps.resize(1, 1); // OK
</code>```

I can't understand why nodes_parents can not be resized.

I would appreciate any comments on this matter. Thank you.

答:
You set nodes_parents to uninitialized memory, that means the constructor of s_path_info (and thus of its members) is never called.
Instead of struct s_path_info *nodes_parents you should simply write:

```<code>std::vector<s_path_info> nodes_parents;
</code>```

And your main cudaCopy should just be a stack variable:

```<code>cudaCopy mem;
</code>```

Generally, do not use malloc inside C++, especially not for non PODs.

N.B.: The fact that it worked with nodes_children is likely by pure coincidence.

Body:
I am using the Eigen library version 3.3 with g++ 5.4 and CUDA 8.0 in ubuntu 16.04 LTS.

confusing things happened while writing the code.
A crash occurs when I try to resize Eigen::MatrixXd in a structure

the structure is as follows.

struct cudaCopy{
      struct s_path_info *nodes_parents
      struct s_path_info *nodes_children
      ...
}

the s_path_info structure is as follows.

struct s_path_info{
    Eigen::MatrixXd supps;
    Eigen::MatrixXd residu;
    ...

The problems are as follows.

struct cudaCopy *mem;
mem = (struct cudaCopy*)malloc(sizeof(struct cudaCopy));

and

mem->nodes_parents = (struct s_path_info*)malloc(50 * sizeof(struct s_path_info))
for(int i=0; i<50; i++){
    mem->nodes_parents[i].supps.resize(1, 1); // ERROR

Here is the backtrace that GDB execute the code.

#0  __GI___libc_free (mem=0x1) at malloc.c:2949
#1  0x000000000040a538 in Eigen::internal::aligned_free (ptr=0x1) at ../Eigen/Eigen/src/Core/util/Memory.h:177
#2  0x000000000040f3e8 in Eigen::internal::conditional_aligned_free<true> (ptr=0x1) at ../Eigen/Eigen/src/Core/util/Memory.h:230
#3  0x000000000040cdd4 in Eigen::internal::conditional_aligned_delete_auto<double, true> (ptr=0x1, size=7209728) at ../Eigen/Eigen/src/Core/util/Memory.h:416
#4  0x000000000040d085 in Eigen::DenseStorage<double, -1, -1, -1, 0>::resize (this=0x6e1348, size=20, rows=20, cols=1) at ../Eigen/Eigen/src/Core/DenseStorage.h:406
#5  0x000000000040ba9e in Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >::resize (this=0x6e1348, rows=20, cols=1) at ../Eigen/Eigen/src/Core/PlainObjectBase.h:293
#6  0x000000000040697f in search::islsp_EstMMP_BF_reuse (this=0x7fffffffe4b0) at exam.cu:870
#7  0x0000000000404f33 in main () at exam.cu:422

interestingly, the following works well.

mem->nodes_children = (struct s_path_info*)malloc(10*50*sizeof(struct s_path_info))
for(int i=0; i<10*50; i++){
    mem->nodes_children[i].supps.resize(1, 1); // OK

I can't understand why nodes_parents can not be resized.

I would appreciate any comments on this matter. Thank you.

Body:
You set nodes_parents to uninitialized memory, that means the constructor of s_path_info (and thus of its members) is never called.
Instead of struct s_path_info *nodes_parents you should simply write:

std::vector<s_path_info> nodes_parents;

And your main cudaCopy should just be a stack variable:

cudaCopy mem;

Generally, do not use malloc inside C++, especially not for non PODs.

N.B.: The fact that it worked with nodes_children is likely by pure coincidence.


来源: stackexchange

问:
PostgreSQL get parameter bigint array
I have a table which has a column id with bigint type . I need to create function which will take a parameter bigint[] and in function I should check where id in (array)

```<code>CREATE OR REPLACE FUNCTION my_function(ids bigint[])
 select * from table where id in ($1)
</code>```

Function creates successfully , but when I call it

```<code>SELECT * FROM my_function(ARRAY [1,2,3,4]);
</code>```

I get an error:

```<code> ERROR:  operator does not exist: bigint = bigint[]
</code>```

答:
As commented:

```<code>where id = any ($1)
</code>```

https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104

ContentLicense: CC BY-SA 4.0

Title: PostgreSQL get parameter bigint array

Body:
I have a table which has a column id with bigint type . I need to create function which will take a parameter bigint[] and in function I should check where id in (array)

CREATE OR REPLACE FUNCTION my_function(ids bigint[])
 select * from table where id in ($1)

Function creates successfully , but when I call it

SELECT * FROM my_function(ARRAY [1,2,3,4]);

I get an error:

 ERROR:  operator does not exist: bigint = bigint[]

Body:
As commented:

where id = any ($1)

https://www.postgresql.org/docs/current/static/functions-comparisons.html#AEN21104

ContentLicense: CC BY-SA 3.0


问:
Google App Maker - Using properties in SQL data sources
There is something (probably simple) I am missing here.  I am trying to create a Data Source in Google App Maker that queries an SQL database.  I want to have a WHERE clause that uses an email address.  I have set up the email property but, for the life of me, I can't figure out where you assign a value to that property.  Do you do it in a server side script? The Data Source loads when the page loads - so it needs to assign this value on load.

Interface screenshot:

答:
your sql is correct, just add input with value binding @datasource.query.parameters.theEmail and update event "onValueChange" -> "Reload DataSource", or set parameter manually and reload datasource:

app.datasources.getEventData.query.parameters.theEmail = 'qwe@asd.zxc';
 app.datasources.getEventData.load();


问:
Windows Container swarm publish port and not access
I use windows container and try to create docker swarm ，I create three virtual machine use hyper-v , and each OS is windows server 2016.There machines ip is :

```<code>windocker211    192.168.1.211
windocker212    192.168.1.212
windocker219    192.168.1.219
</code>```

The docker swarm node is :

```<code>PS C:\ConsoleZ> docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS
4c0g0o0uognheugw4do1a1h7y     windocker212          Ready               Active
bbxot0c8zijq7xw4lm86svgwp *   windocker219          Ready               Active              Leader
wftwpiqpqpbqfdvgenn787psj     windocker211          Ready               Active
</code>```

I create use command:

```<code>docker service create --name=demo5 -p 5005:5005 --replicas 6 192.168.1.245/cqgis/wintestcore:0.6
</code>```

The docker image is asp.net core app , the Dockerfile is:

```<code>FROM  192.168.1.245/win/aspnetcore-runtime:1.1.2
COPY . /app
WORKDIR /app

ENV ASPNETCORE_URLS http://*:5005

EXPOSE 5005/tcp

ENTRYPOINT ["dotnet", "dotnetcore.dll"]
</code>```

then  it create success:

```<code>PS C:\ConsoleZ> docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE                                 PORTS
omhu7e0vo96s        demo5               replicated          6/6                 192.168.1.245/cqgis/wintestcore:0.6   *:5005->5005/tcp

PS C:\ConsoleZ> docker service ps demo5
ID                  NAME                IMAGE                                 NODE                DESIRED STATE       CURRENT STATE                ERROR               PORTS
8pihnak9a2ei        demo5.1             192.168.1.245/cqgis/wintestcore:0.6   windocker212          Running             Running 59 seconds ago
ut3f3b9giu4w        demo5.2             192.168.1.245/cqgis/wintestcore:0.6   windocker219          Running             Running 47 seconds ago
iy1xjevt67yl        demo5.3             192.168.1.245/cqgis/wintestcore:0.6   windocker211          Running             Running about a minute ago
q7f1gnbwslr3        demo5.4             192.168.1.245/cqgis/wintestcore:0.6   windocker212          Running             Running about a minute ago
8zewaktcu32h        demo5.5             192.168.1.245/cqgis/wintestcore:0.6   windocker219          Running             Running about a minute ago
xq820kqwf3v9        demo5.6             192.168.1.245/cqgis/wintestcore:0.6   windocker211          Running             Running 55 seconds ago
</code>```

but my question is  I cann't  accessing The Site  each by

```<code>http://192.168.1.219:5005/
http://192.168.1.219:5005/
http://192.168.1.219:5005/
</code>```

When I use command

```<code>docker run -it -p 5010:5005 192.168.1.245/cqgis/wintestcore:0.6
</code>```

I can use http://192.168.1.219:5010/ get the right result

my docker info is

```<code>PS C:\ConsoleZ> docker info
Containers: 4
 Running: 3
 Paused: 0
 Stopped: 1
Images: 5
Server Version: 17.06.0-ce-rc1
Storage Driver: windowsfilter
 Windows:
Logging Driver: json-file
Plugins:
 Volume: local
 Network: l2bridge l2tunnel nat null overlay transparent
 Log: awslogs etwlogs fluentd json-file logentries splunk syslog
Swarm: active
 NodeID: bbxot0c8zijq7xw4lm86svgwp
 Is Manager: true
 ClusterID: 32vsgwrbn6ihvpevly71gkgxk
 Managers: 1
 Nodes: 3
 Orchestration:
  Task History Retention Limit: 5
 Raft:
  Snapshot Interval: 10000
  Number of Old Snapshots to Retain: 0
  Heartbeat Tick: 1
  Election Tick: 3
 Dispatcher:
  Heartbeat Period: 5 seconds
 CA Configuration:
  Expiry Duration: 3 months
  Force Rotate: 0
 Root Rotation In Progress: false
 Node Address: 192.168.1.219
 Manager Addresses:
  192.168.1.219:2377
Default Isolation: process
Kernel Version: 10.0 14393 (14393.1198.amd64fre.rs1_release_sec.170427-1353)
Operating System: Windows Server 2016 Datacenter
OSType: windows
Architecture: x86_64
CPUs: 8
Total Memory: 2.89GiB
Name: windock219
ID: 7AOY:OT6V:BTJV:NCHA:3OF5:5WR5:K2YR:CFG3:VXLD:QTMD:GA3D:ZFJ2
Docker Root Dir: C:\ProgramData\docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: -1
 Goroutines: 297
 System Time: 2017-06-04T19:58:20.7582294+08:00
 EventsListeners: 2
Registry: https://index.docker.io/v1/
Experimental: true
Insecure Registries:
 192.168.1.245
 127.0.0.0/8
Live Restore Enabled: false
</code>```

答: I beleive you need to publish port in "host" mode (learn.microsoft.com/en-us/virtualization/windowscontainers/…). Also it will be one to one port mapping between running container and host and hence you will not be able to run several containers on the same port. Routing mesh is not working on Windows yet. </p>

Body:
I use windows container and try to create docker swarm ，I create three virtual machine use hyper-v , and each OS is windows server 2016.There machines ip is :

windocker211    192.168.1.211
windocker212    192.168.1.212
windocker219    192.168.1.219

The docker swarm node is :

PS C:\ConsoleZ> docker node ls
ID                            HOSTNAME            STATUS              AVAILABILITY        MANAGER STATUS
4c0g0o0uognheugw4do1a1h7y     windocker212          Ready               Active
bbxot0c8zijq7xw4lm86svgwp *   windocker219          Ready               Active              Leader
wftwpiqpqpbqfdvgenn787psj     windocker211          Ready               Active

I create use command:

docker service create --name=demo5 -p 5005:5005 --replicas 6 192.168.1.245/cqgis/wintestcore:0.6

The docker image is asp.net core app , the Dockerfile is:

FROM  192.168.1.245/win/aspnetcore-runtime:1.1.2
COPY . /app
WORKDIR /app

ENV ASPNETCORE_URLS http://*:5005

EXPOSE 5005/tcp

ENTRYPOINT ["dotnet", "dotnetcore.dll"]

then  it create success:

PS C:\ConsoleZ> docker service ls
ID                  NAME                MODE                REPLICAS            IMAGE                                 PORTS
omhu7e0vo96s        demo5               replicated          6/6                 192.168.1.245/cqgis/wintestcore:0.6   *:5005->5005/tcp

PS C:\ConsoleZ> docker service ps demo5
ID                  NAME                IMAGE                                 NODE                DESIRED STATE       CURRENT STATE                ERROR               PORTS
8pihnak9a2ei        demo5.1             192.168.1.245/cqgis/wintestcore:0.6   windocker212          Running             Running 59 seconds ago
ut3f3b9giu4w        demo5.2             192.168.1.245/cqgis/wintestcore:0.6   windocker219          Running             Running 47 seconds ago
iy1xjevt67yl        demo5.3             192.168.1.245/cqgis/wintestcore:0.6   windocker211          Running             Running about a minute ago
q7f1gnbwslr3        demo5.4             192.168.1.245/cqgis/wintestcore:0.6   windocker212          Running             Running about a minute ago
8zewaktcu32h        demo5.5             192.168.1.245/cqgis/wintestcore:0.6   windocker219          Running             Running about a minute ago
xq820kqwf3v9        demo5.6             192.168.1.245/cqgis/wintestcore:0.6   windocker211          Running             Running 55 seconds ago

but my question is  I cann't  accessing The Site  each by

http://192.168.1.219:5005/
http://192.168.1.219:5005/
http://192.168.1.219:5005/

When I use command

docker run -it -p 5010:5005 192.168.1.245/cqgis/wintestcore:0.6

I can use http://192.168.1.219:5010/ get the right result

my docker info is

PS C:\ConsoleZ> docker info
Containers: 4
 Running: 3
 Paused: 0
 Stopped: 1
Images: 5
Server Version: 17.06.0-ce-rc1
Storage Driver: windowsfilter
 Windows:
Logging Driver: json-file
Plugins:
 Volume: local
 Network: l2bridge l2tunnel nat null overlay transparent
 Log: awslogs etwlogs fluentd json-file logentries splunk syslog
Swarm: active
 NodeID: bbxot0c8zijq7xw4lm86svgwp
 Is Manager: true
 ClusterID: 32vsgwrbn6ihvpevly71gkgxk
 Managers: 1
 Nodes: 3
 Orchestration:
  Task History Retention Limit: 5
 Raft:
  Snapshot Interval: 10000
  Number of Old Snapshots to Retain: 0
  Heartbeat Tick: 1
  Election Tick: 3
 Dispatcher:
  Heartbeat Period: 5 seconds
 CA Configuration:
  Expiry Duration: 3 months
  Force Rotate: 0
 Root Rotation In Progress: false
 Node Address: 192.168.1.219
 Manager Addresses:
  192.168.1.219:2377
Default Isolation: process
Kernel Version: 10.0 14393 (14393.1198.amd64fre.rs1_release_sec.170427-1353)
Operating System: Windows Server 2016 Datacenter
OSType: windows
Architecture: x86_64
CPUs: 8
Total Memory: 2.89GiB
Name: windock219
ID: 7AOY:OT6V:BTJV:NCHA:3OF5:5WR5:K2YR:CFG3:VXLD:QTMD:GA3D:ZFJ2
Docker Root Dir: C:\ProgramData\docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: -1
 Goroutines: 297
 System Time: 2017-06-04T19:58:20.7582294+08:00
 EventsListeners: 2
Registry: https://index.docker.io/v1/
Experimental: true
Insecure Registries:
 192.168.1.245
 127.0.0.0/8
Live Restore Enabled: false


问:
Open full URL in jmeter which return in previous response
I have response which return full url e.g. redirectUrl=https://myurl:9999/path/path2?a=b
I want to submit a sampler without parsing it, as it is.
Can it be done in jmeter or jmeter plugin?</p>

答:
Extract the URL from the response using i.e. Regular Expression Extractor and store it into a JMeter Variable, i.e. use redirectUrl as the "Reference Name"

Add another HTTP Request sampler and put ${redirectUrl} into "Path" section:

JMeter is smart enough to build a proper HTTP request from the URL provided via "Path" section:


问:
JavaFX BarChart, Set Series Color by Series Name
I am trying to dynamically set the BarChart Series color.

I want to have always the same color for the same Series name.
Its not always the same Series names in the chart, which is why I cannot rely on the position in the chart (colors per default always the same at the same position in the data list).

```<code>chart.getData().addListener(new ListChangeListener<Series<String, Number>>() {

        @Override
        public void onChanged(
            final javafx.collections.ListChangeListener.Change<? extends Series<String, Number>> c) {
        while (c.next()) {
            for (final Series s : c.getAddedSubList()) {
            if ("booking".equalsIgnoreCase(s.getName())) {
                if (s.getNode() != null) {
                s.getNode().getStyleClass().add(".source-background-booking");
                }
            } else if ("airbnb".equalsIgnoreCase(s.getName())) {
                if (s.getNode() != null) {
                s.getNode().getStyleClass().add(".source-background-airbnb");
                }
            }
            }
        }
        }
    });
</code>```

This does not work as expected. The Series's Node is always null. Why is that?

EDIT: Another approach that is not working:

```<code>chart.getData().addListener(new ListChangeListener<Series<String, Number>>() {

        @Override
        public void onChanged(
            final javafx.collections.ListChangeListener.Change<? extends Series<String, Number>> c) {
        while (c.next()) {
            System.err.println("Series " + c.getAddedSubList() + " kommt rein..");
            for (final Series<String, Number> s : c.getAddedSubList()) {
            s.nodeProperty().addListener(new ChangeListener<Node>() {

                @Override
                public void changed(final ObservableValue<? extends Node> observable, final Node oldValue,
                    final Node newValue) {
                System.err.println("Already good");
                if ("booking".equalsIgnoreCase(s.getName())) {
                    newValue.getStyleClass().add(".source-background-booking");
                    System.err.println("Seems to work..");
                } else if ("airbnb".equalsIgnoreCase(s.getName())) {
                    newValue.getStyleClass().add(".source-background-airbnb");
                    System.err.println("Seems to work..");
                }
                }
            });

            }
        }
        }
    });
</code>```

Unfortunately, this callback seems to be never called..

答:
Try this:

```<code>import com.sun.javafx.charts.Legend;
import com.sun.javafx.charts.Legend.LegendItem;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class BarChartSample extends Application {
    final static String austria = "Austria";
    final static String brazil = "Brazil";
    final static String france = "France";
    final static String italy = "Italy";
    final static String usa = "USA";

    @Override public void start(Stage stage) {
        stage.setTitle("Bar Chart Sample");
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        final BarChart<String,Number> bc = new BarChart(xAxis,yAxis);
        bc.setTitle("Country Summary");
        xAxis.setLabel("Country");
        yAxis.setLabel("Value");

        XYChart.Series series1 = new XYChart.Series();
        series1.setName("2003");
        series1.getData().add(new XYChart.Data(austria, 25601.34));
        series1.getData().add(new XYChart.Data(brazil, 20148.82));
        series1.getData().add(new XYChart.Data(france, 10000));
        series1.getData().add(new XYChart.Data(italy, 35407.15));
        series1.getData().add(new XYChart.Data(usa, 12000));

        XYChart.Series series2 = new XYChart.Series();
        series2.setName("2004");
        series2.getData().add(new XYChart.Data(austria, 57401.85));
        series2.getData().add(new XYChart.Data(brazil, 41941.19));
        series2.getData().add(new XYChart.Data(france, 45263.37));
        series2.getData().add(new XYChart.Data(italy, 117320.16));
        series2.getData().add(new XYChart.Data(usa, 14845.27));

        XYChart.Series series3 = new XYChart.Series();
        series3.setName("2005");
        series3.getData().add(new XYChart.Data(austria, 45000.65));
        series3.getData().add(new XYChart.Data(brazil, 44835.76));
        series3.getData().add(new XYChart.Data(france, 18722.18));
        series3.getData().add(new XYChart.Data(italy, 17557.31));
        series3.getData().add(new XYChart.Data(usa, 92633.68));

        Scene scene  = new Scene(bc,800,600);
        bc.getData().addAll(series1, series2, series3);
        stage.setScene(scene);
        stage.show();

        //Used to change series color.
        for (XYChart.Series<String, Number> series : bc.getData()) {
            if(series.getName().equals("2003"))
            {
                System.out.println("Series name: " + series.getName());
                for(Data data : series.getData())
                {
                    data.getNode().setStyle("-fx-bar-fill: firebrick;");
                }
            }
        }

        //Used to change legend color
        for(Node n : bc.getChildrenUnmodifiable())
        {
            if(n instanceof Legend)
            {
                System.out.println(((Legend)n).getItems());
                for(LegendItem items : ((Legend)n).getItems())
                {
                    System.out.println("Legend item text: " + items.getText());
                    if(items.getText().equals("2003"))
                    {
                        items.getSymbol().setStyle("-fx-bar-fill: firebrick;");
                    }
                }
            }
        }

    }

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

}
</code>```

For Java 10 and Above replace the Used to change legend color code with code below. Not tested on Java 9

```<code>//Used to change legend color
for(Node node : bc.lookupAll("Label.chart-legend-item"))
{
    Label tempLabel = (Label)node;
    if(tempLabel.getText().equals("2003"))
    {
        tempLabel.getGraphic().setStyle("-fx-bar-fill: firebrick;");
    }
}
</code>```

This app changes the 2003 series color to firebrick. The for loop is the part you should focus on.

UPDATE
I added a way to change the legend color.

UPDATE 08/08/2019
The original code works for Java 8. I am adding code for Java 10 and above.

Body:
I am trying to dynamically set the BarChart Series color.

I want to have always the same color for the same Series name.
Its not always the same Series names in the chart, which is why I cannot rely on the position in the chart (colors per default always the same at the same position in the data list).

chart.getData().addListener(new ListChangeListener<Series<String, Number>>() {

        @Override
        public void onChanged(
            final javafx.collections.ListChangeListener.Change<? extends Series<String, Number>> c) {
        while (c.next()) {
            for (final Series s : c.getAddedSubList()) {
            if ("booking".equalsIgnoreCase(s.getName())) {
                if (s.getNode() != null) {
                s.getNode().getStyleClass().add(".source-background-booking");
                }
            } else if ("airbnb".equalsIgnoreCase(s.getName())) {
                if (s.getNode() != null) {
                s.getNode().getStyleClass().add(".source-background-airbnb");
                }
            }
            }
        }
        }
    });

This does not work as expected. The Series's Node is always null. Why is that?

EDIT: Another approach that is not working:

chart.getData().addListener(new ListChangeListener<Series<String, Number>>() {

        @Override
        public void onChanged(
            final javafx.collections.ListChangeListener.Change<? extends Series<String, Number>> c) {
        while (c.next()) {
            System.err.println("Series " + c.getAddedSubList() + " kommt rein..");
            for (final Series<String, Number> s : c.getAddedSubList()) {
            s.nodeProperty().addListener(new ChangeListener<Node>() {

                @Override
                public void changed(final ObservableValue<? extends Node> observable, final Node oldValue,
                    final Node newValue) {
                System.err.println("Already good");
                if ("booking".equalsIgnoreCase(s.getName())) {
                    newValue.getStyleClass().add(".source-background-booking");
                    System.err.println("Seems to work..");
                } else if ("airbnb".equalsIgnoreCase(s.getName())) {
                    newValue.getStyleClass().add(".source-background-airbnb");
                    System.err.println("Seems to work..");
                }
                }
            });

            }
        }
        }
    });

Unfortunately, this callback seems to be never called..

Body:
Try this:

import com.sun.javafx.charts.Legend;
import com.sun.javafx.charts.Legend.LegendItem;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class BarChartSample extends Application {
    final static String austria = "Austria";
    final static String brazil = "Brazil";
    final static String france = "France";
    final static String italy = "Italy";
    final static String usa = "USA";

    @Override public void start(Stage stage) {
        stage.setTitle("Bar Chart Sample");
        final CategoryAxis xAxis = new CategoryAxis();
        final NumberAxis yAxis = new NumberAxis();
        final BarChart<String,Number> bc = new BarChart(xAxis,yAxis);
        bc.setTitle("Country Summary");
        xAxis.setLabel("Country");
        yAxis.setLabel("Value");

        XYChart.Series series1 = new XYChart.Series();
        series1.setName("2003");
        series1.getData().add(new XYChart.Data(austria, 25601.34));
        series1.getData().add(new XYChart.Data(brazil, 20148.82));
        series1.getData().add(new XYChart.Data(france, 10000));
        series1.getData().add(new XYChart.Data(italy, 35407.15));
        series1.getData().add(new XYChart.Data(usa, 12000));

        XYChart.Series series2 = new XYChart.Series();
        series2.setName("2004");
        series2.getData().add(new XYChart.Data(austria, 57401.85));
        series2.getData().add(new XYChart.Data(brazil, 41941.19));
        series2.getData().add(new XYChart.Data(france, 45263.37));
        series2.getData().add(new XYChart.Data(italy, 117320.16));
        series2.getData().add(new XYChart.Data(usa, 14845.27));

        XYChart.Series series3 = new XYChart.Series();
        series3.setName("2005");
        series3.getData().add(new XYChart.Data(austria, 45000.65));
        series3.getData().add(new XYChart.Data(brazil, 44835.76));
        series3.getData().add(new XYChart.Data(france, 18722.18));
        series3.getData().add(new XYChart.Data(italy, 17557.31));
        series3.getData().add(new XYChart.Data(usa, 92633.68));

        Scene scene  = new Scene(bc,800,600);
        bc.getData().addAll(series1, series2, series3);
        stage.setScene(scene);
        stage.show();

        //Used to change series color.
        for (XYChart.Series<String, Number> series : bc.getData()) {
            if(series.getName().equals("2003"))
            {
                System.out.println("Series name: " + series.getName());
                for(Data data : series.getData())
                {
                    data.getNode().setStyle("-fx-bar-fill: firebrick;");
                }
            }
        }

        //Used to change legend color
        for(Node n : bc.getChildrenUnmodifiable())
        {
            if(n instanceof Legend)
            {
                System.out.println(((Legend)n).getItems());
                for(LegendItem items : ((Legend)n).getItems())
                {
                    System.out.println("Legend item text: " + items.getText());
                    if(items.getText().equals("2003"))
                    {
                        items.getSymbol().setStyle("-fx-bar-fill: firebrick;");
                    }
                }
            }
        }

    }

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

}

For Java 10 and Above replace the Used to change legend color code with code below. Not tested on Java 9

//Used to change legend color
for(Node node : bc.lookupAll("Label.chart-legend-item"))
{
    Label tempLabel = (Label)node;
    if(tempLabel.getText().equals("2003"))
    {
        tempLabel.getGraphic().setStyle("-fx-bar-fill: firebrick;");
    }
}

This app changes the 2003 series color to firebrick. The for loop is the part you should focus on.

UPDATE
I added a way to change the legend color.

UPDATE 08/08/2019
The original code works for Java 8. I am adding code for Java 10 and above.


问:
Creating a foreign key relationship through the UI in VS2015 SQL Server Database Project
I added a new SQL Server database project to my solution in VS2015. I added all of my tables to this project.

I am now trying to figure out how to add foreign keys to the project through the UI preferably .

I am in the table designer and on the right side I click foreign keys and then add new. This adds a new foreign key, but when I go to the properties of it I am unable to set the columns and tables. Everything is grayed out.

The T-SQL looks like this:

```<code>CONSTRAINT [FK_Product_ToTable]
     FOREIGN KEY ([Column]) REFERENCES [ToTable]([ToTableColumn])
</code>```

I know I can just simply replace the params with the correct info in the T-SQL pane, but is there any way to completely do it through the UI and let the T-SQL update on its own?

答:
double click your table in solution explorer to edit the columns

add FK column to the table, optionally check "Allow Nulls"

to the right of the table column list, right click "Foreign Keys"

a menu will appear with an item "Add New Foreign Key"

click that item, and you will see it add a new FK constraint under the "Foreign Keys" list. Rename the FK to your liking, then press ENTER.

This will add a FK SQL statement in the "T-SQL" window below the table column list.

edit the SQL script to define the  "Column", "ToTable", and "ToTableColumn" for your foreign key.
enter image description here

Body:
I added a new SQL Server database project to my solution in VS2015. I added all of my tables to this project.

I am now trying to figure out how to add foreign keys to the project through the UI preferably .

I am in the table designer and on the right side I click foreign keys and then add new. This adds a new foreign key, but when I go to the properties of it I am unable to set the columns and tables. Everything is grayed out.

The T-SQL looks like this:

CONSTRAINT [FK_Product_ToTable]
     FOREIGN KEY ([Column]) REFERENCES [ToTable]([ToTableColumn])

I know I can just simply replace the params with the correct info in the T-SQL pane, but is there any way to completely do it through the UI and let the T-SQL update on its own?


问:
Embedded System - Polling
I have about 6 sensors (GPS, IMU, etc.) that I need to constantly collect data from. For my purposes, I need a reading from each (within a small time frame) to have a complete data packet. Right now I am using interrupts, but this results in more data from certain sensors than others, and, as mentioned, I need to have the data matched up.

Would it be better to move to a polling-based system in which I could poll each sensor in a set order? This way I could have data from each sensor every 'cycle'.

I am, however, worried about the speed of polling because this system needs to operate close to real time.

答:
Polling combined with a "master timer interrupt" could be your friend here.  Let's say that your "slowest" sensor can provide data on 20ms intervals, and that the others can be read faster.  That's 50 updates per second.  If that's close enough to real-time (probably is close for an IMU), perhaps you proceed like this:

Set up a 20ms timer.

When the timer goes off, set a flag inside an interrupt service routine:

```<code>volatile uint8_t timerFlag = 0;

ISR(TIMER_ISR_whatever)
{
    timerFlag = 1;  // nothing but a semaphore for later...
}
</code>```

Then, in your main loop act when timerFlag says it's time:

```<code>while(1)
{
    if(timerFlag == 1)
    {
        <read first device>
        <read second device>
        <you get the idea ;) >
        timerflag = 0;
    }
}
</code>```

In this way you can read each device and keep their readings synched up.  This is a typical way to solve this problem in the embedded space.  Now, if you need data faster than 20ms, then you shorten the timer, etc.  The big question, as it always is in situations like this, is "how fast can you poll" vs. "how fast do you need to poll."  Only experimentation and knowing the characteristics and timing of your various devices can tell you that.  But what I propose is a general solution when all the timings "fit."

EDIT, A DIFFERENT APPROACH

A more interrupt-based example:

```<code>volatile uint8_t device1Read = 0;
volatile uint8_t device2Read = 0;
etc...

ISR(device 1)
{
    <read device>
    device1Read = 1;
}
ISR(device 2)
{
    <read device>
    device2Read = 1;
}
etc...

// main loop
while(1)
{
    if(device1Read == 1 && device2Read == 1 && etc...)
    {
        //< do something with your "packet" of data>
        device1Read = 0;
        device2Read = 0;
        etc...
    }
}
</code>```

In this example, all your devices can be interrupt-driven but the main-loop processing is still governed, paced, by the cadence of the slowest interrupt.  The latest complete reading from each device, regardless of speed or latency, can be used.  Is this pattern closer to what you had in mind?

Title: Embedded System - Polling

Body:
Polling combined with a "master timer interrupt" could be your friend here.  Let's say that your "slowest" sensor can provide data on 20ms intervals, and that the others can be read faster.  That's 50 updates per second.  If that's close enough to real-time (probably is close for an IMU), perhaps you proceed like this:

Set up a 20ms timer.

When the timer goes off, set a flag inside an interrupt service routine:

volatile uint8_t timerFlag = 0;

ISR(TIMER_ISR_whatever)
{
    timerFlag = 1;  // nothing but a semaphore for later...
}

Then, in your main loop act when timerFlag says it's time:

while(1)
{
    if(timerFlag == 1)
    {
        <read first device>
        <read second device>
        <you get the idea ;) >
        timerflag = 0;
    }
}

In this way you can read each device and keep their readings synched up.  This is a typical way to solve this problem in the embedded space.  Now, if you need data faster than 20ms, then you shorten the timer, etc.  The big question, as it always is in situations like this, is "how fast can you poll" vs. "how fast do you need to poll."  Only experimentation and knowing the characteristics and timing of your various devices can tell you that.  But what I propose is a general solution when all the timings "fit."

EDIT, A DIFFERENT APPROACH

A more interrupt-based example:

volatile uint8_t device1Read = 0;
volatile uint8_t device2Read = 0;
etc...

ISR(device 1)
{
    <read device>
    device1Read = 1;
}
ISR(device 2)
{
    <read device>
    device2Read = 1;
}
etc...

// main loop
while(1)
{
    if(device1Read == 1 && device2Read == 1 && etc...)
    {
        //< do something with your "packet" of data>
        device1Read = 0;
        device2Read = 0;
        etc...
    }
}

In this example, all your devices can be interrupt-driven but the main-loop processing is still governed, paced, by the cadence of the slowest interrupt.  The latest complete reading from each device, regardless of speed or latency, can be used.  Is this pattern closer to what you had in mind?


问:
What does "somevar >> 0" mean?

What does the notation somevar >> 0 mean in javascript?

Thanks

答:
In a >> b, >> is a bitwise operator that shifts a in binary representation b (< 32) bits to the right, discarding bits shifted off.
Reference: https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators

Title: What does "somevar >> 0" mean?

ContentLicense: CC BY-SA 2.5


问:
C++ Printing Odd numbers instead of Prime Numbers
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

```<code>int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}
</code>```

答:
Another version, if you don't mind output in reverse order.</p>

```<code>int n = 10;

for (int i = n; i > 1; --i)
{
    int factorCount = 0;
    for (int j = 2; j <= n; ++j)
    {
        if (i % j == 0)
            factorCount++;

        if (factorCount > 1)
            break;
    }
    if (factorCount == 1)
        cout << i << endl;
}
</code>```

Body:
I have been working on an assignment question for days and cannot seem to get the correct output (I've tried so many things!) The question is:

Write a program that uses two nested for loops and the modulus operator (%) to detect and print the prime numbers from 1 to 10,000.

I have been doing from 1 to 10 as a small test to ensure its working. I am getting 2,3,5,7,9 as my output, so I know something is wrong. When I increase the number from 10 to 20 it is printing 2 plus all odd numbers. I am including my code below. Thanks!!

int main() {

        for (int i=2; i <=10; i++){
            for (int j=2; j<=i; j++){
                if (i%j==0 && j!=i) {

                    break;
                }

                else {

                    cout<< i <<endl;
                    break;
                }
            }
        }
}

Body:
Another version, if you don't mind output in reverse order.

int n = 10;

for (int i = n; i > 1; --i)
{
    int factorCount = 0;
    for (int j = 2; j <= n; ++j)
    {
        if (i % j == 0)
            factorCount++;

        if (factorCount > 1)
            break;
    }
    if (factorCount == 1)
        cout << i << endl;
}


问:
Keep 2 <select> in sync when value changes
I have two <select>s with the same <option>s.

If a user selects a value in the first one, the value on the second one should change as well to keep both in sync.

This is what I tried so far:

function data_copy() {
  if (document.form1.copy[0].checked) {
    for (i = document.form1.state.options.length-1; i >= 0; i--) {
      if (document.form1.state.options[i].selected)
        document.form1.state2.options[i].selected = true;
    }
  } else {
    document.form1.state2.options[0].selected = true;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
  <table width='400' border='0' cellspacing='1' cellpadding='0'>
    <form name=form1 method=post action='http://www.plus2net.com'>

      <tr><td >State</td><td>
        <SELECT NAME="state" onchange="data_copy()">
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>
      </td></tr>

      <tr><td >
      <tr><td >State</td><td>
        <SELECT NAME="state2" >
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>
      </td></tr>

      <tr><td colspan=2 align=center><input type=submit value=Submit>
    </form></td></tr>
  </table>
</body></code>```

答:
One for all, pure vanillaJS

function data_copy(n)
{
  document.querySelectorAll('[NAME^="state"]').forEach(el=>el.value = document.form1['state'+n].value)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title></title>

</head>

<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<table width='400' border='0' cellspacing='1' cellpadding='0'>
<form name=form1 method=post action='http://www.plus2net.com'>

<tr><td >State</td><td><SELECT NAME="state1" onchange="data_copy(1)">
<Option value="One">One</option>
<Option value="Two">Two</option>
<Option value="Three">Three</option>
<Option value="Four">Four</option>

</SELECT>
</td></tr>

<tr><td >State</td><td><SELECT NAME="state2" onchange="data_copy(2)">
<Option value="One">One</option>
<Option value="Two">Two</option>
<Option value="Three">Three</option>
<Option value="Four">Four</option>

</SELECT>
</td></tr>

<tr><td colspan=2 align=center><input type=submit value=Submit></td></tr> </form>
</table>
</body>
</html></code>```

Body:
I have two <select>s with the same <option>s.

If a user selects a value in the first one, the value on the second one should change as well to keep both in sync.

This is what I tried so far:

function data_copy() {
  if (document.form1.copy[0].checked) {
    for (i = document.form1.state.options.length-1; i >= 0; i--) {
      if (document.form1.state.options[i].selected)
        document.form1.state2.options[i].selected = true;
    }
  } else {
    document.form1.state2.options[0].selected = true;
  }
}

    <form name=form1 method=post action='http://www.plus2net.com'>

State
        <SELECT NAME="state" onchange="data_copy()">
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>

State
        <SELECT NAME="state2" >
          <Option value="One">One</option>
          <Option value="Two">Two</option>
          <Option value="Three">Three</option>
          <Option value="Four">Four</option>
        </SELECT>

<input type=submit value=Submit>
    </form>

Body:
One for all, pure vanillaJS

function data_copy(n)
{
  document.querySelectorAll('[NAME^="state"]').forEach(el=>el.value = document.form1['state'+n].value)
}

<html>
<head>
<title></title>

</head>

<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000">
<table width='400' border='0' cellspacing='1' cellpadding='0'>
<form name=form1 method=post action='http://www.plus2net.com'>

<tr><td >State</td><td><SELECT NAME="state1" onchange="data_copy(1)">
<Option value="One">One</option>
<Option value="Two">Two</option>
<Option value="Three">Three</option>
<Option value="Four">Four</option>

</SELECT>
</td></tr>

<tr><td >State</td><td><SELECT NAME="state2" onchange="data_copy(2)">
<Option value="One">One</option>
<Option value="Two">Two</option>
<Option value="Three">Three</option>
<Option value="Four">Four</option>

</SELECT>
</td></tr>

<tr><td colspan=2 align=center><input type=submit value=Submit></td></tr> </form>
</table>
</body>
</html>


问:
Why is Popen("cmd.exe echo a", shell=True) not running "echo"?
This leads to a bigger problem I am having here with Popen().

The following does not do what I thought it should:

```<code>x = subprocess.Popen("cmd.exe echo a", stdout=PIPE, shell=True)
print (x.stdout.read())
</code>```

Returns the "title" message of the cmd console, but echo a is never executed.

Same with:

```<code>x = subprocess.Popen(["cmd.exe", "echo a"], stdout=PIPE)
print (x.stdout.read())
</code>```

and

```<code>cmd = "cmd.exe echo a"
x = subprocess.Popen(shlex.split(cmd), stdout=PIPE)
print (x.stdout.read())
</code>```

End result is in open cmd terminal that prints the standard "Microsoft Windows version..." and a CLI position of C:\Python36>.

答:
cmd.exe requires the argument /c to precede a script being passed for execution:

```<code>x = subprocess.Popen(["cmd.exe", "/c", "echo a"], stdout=PIPE)
print (x.stdout.read())
</code>```

Body:
This leads to a bigger problem I am having here with Popen().

The following does not do what I thought it should:

x = subprocess.Popen("cmd.exe echo a", stdout=PIPE, shell=True)
print (x.stdout.read())

Returns the "title" message of the cmd console, but echo a is never executed.

Same with:

x = subprocess.Popen(["cmd.exe", "echo a"], stdout=PIPE)
print (x.stdout.read())

and

cmd = "cmd.exe echo a"
x = subprocess.Popen(shlex.split(cmd), stdout=PIPE)
print (x.stdout.read())

End result is in open cmd terminal that prints the standard "Microsoft Windows version..." and a CLI position of C:\Python36>.

Body:
cmd.exe requires the argument /c to precede a script being passed for execution:

x = subprocess.Popen(["cmd.exe", "/c", "echo a"], stdout=PIPE)
print (x.stdout.read())


问:
How do I run two commands in one line in Windows CMD?
I want to run two commands in a Windows CMD console.

In Linux I would do it like this

```<code>touch thisfile ; ls -lstrh
</code>```

How is it done on Windows?

答:
It's simple: just differentiate them with && signs.
Example:

```<code>echo "Hello World" && echo "GoodBye World".
</code>```

"Goodbye World" will be printed after "Hello World".

Body:
I want to run two commands in a Windows CMD console.

In Linux I would do it like this

touch thisfile ; ls -lstrh

How is it done on Windows?

Body:
It's simple: just differentiate them with && signs.
Example:

echo "Hello World" && echo "GoodBye World".

"Goodbye World" will be printed after "Hello World".


问:
How to get a selected item in collection view using indexPathsForSelectedItems
I have a collectionView of photos and want to pass the photo who was cliked to a detailViewControler.

The collection data come from :

```<code> var timeLineData:NSMutableArray = NSMutableArray ()
</code>```

I would like to use the prepare for segue method.

My problem is how to get the good indexPath from the cell who was clicked ?

```<code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue == "goToZoom" {
        let zoomVC : PhotoZoomViewController = segue.destinationViewController as PhotoZoomViewController
        let cell = sender as UserPostsCell

        let indexPath = self.collectionView!.indexPathForCell(cell)
        let userPost  = self.timeLineData.objectAtIndex(indexPath!.row) as PFObject
        zoomVC.post = userPost

    }
}
</code>```

答:
Swift 3.0

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == “segueID”{
        if let destination = segue.destination as? YourDestinationViewController{
            let cell = sender as! UICollectionViewCell
            let indexPath = myCollectionView.indexPath(for: cell)
            let selectedData = myArray[(indexPath?.row)!]

            // postedData is the variable that will be sent, make sure to declare it in YourDestinationViewController
            destination.postedData = selectedData
        }
    }
}
</code>```

Body:
I have a collectionView of photos and want to pass the photo who was cliked to a detailViewControler.

The collection data come from :

 var timeLineData:NSMutableArray = NSMutableArray ()

I would like to use the prepare for segue method.

My problem is how to get the good indexPath from the cell who was clicked ?

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue == "goToZoom" {
        let zoomVC : PhotoZoomViewController = segue.destinationViewController as PhotoZoomViewController
        let cell = sender as UserPostsCell

        let indexPath = self.collectionView!.indexPathForCell(cell)
        let userPost  = self.timeLineData.objectAtIndex(indexPath!.row) as PFObject
        zoomVC.post = userPost

    }
}

Body:
Swift 3.0

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == “segueID”{
        if let destination = segue.destination as? YourDestinationViewController{
            let cell = sender as! UICollectionViewCell
            let indexPath = myCollectionView.indexPath(for: cell)
            let selectedData = myArray[(indexPath?.row)!]

            // postedData is the variable that will be sent, make sure to declare it in YourDestinationViewController
            destination.postedData = selectedData
        }
    }
}


问:
PhpStorm & XAMPP - debugging not starting
I am having a hard time with PhpStorm debugger. I read all their documentation and I have setup debug properly (according to both phpinfo(), debug tailored installation report and PhpStorm analysis).

However, no matter what I try, the debugger wont trigger.

My setup is the following:

I changed XAMPP document root to: c:\src\project\www

My project has the following structure:

```<code>project
 | www (used by XAMPP to serve the website)
 | src
   | --theme (symlinked to wp-content/themes)
   | --plugins (symlinked to wp-content/plugins)
</code>```

and apparently, this setup works as all my plugins and theme are correctly working and displayed on the screen.

When I then start to run the debugger, it simply won't trigger.

This is the setup for the debugger on PhpStorm:

Server:

```<code>Host: localhost
Port: 80
Debugger: xdebug
</code>```

Mappings (where I think there's something off)

```<code>src/theme   --> c:/src/project/www/wp-content/theme/
src/plugins --> c:/src/project/www/wp-content/plugins/
</code>```

but nothing happens. No mappings errors, no debug, nothing at all.

Can you please explain to me what am I doing wrong here?

let me know if you need more info.

EDIT:

php.ini added line for debug (from xdebug website):

```<code>zend_extension = C:\xampp\php\ext\php_xdebug-2.5.4-7.1-vc14.dll
</code>```

PhpStorm PHP settings:

答:
This is from my setup :

php.ini

```<code>[xdebug]
;zend_extension=xdebug.so
zend_extension=/usr/local/Cellar/php55-xdebug/2.4.0/xdebug.so
xdebug.remote_enable=1
xdebug.remote_connect_back=0
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9002
xdebug.remote_log="/mnt/log/xdebug.log"
xdebug.remote_autostart=1
xdebug.idekey=phpstorm
xdebug.remote_mode = req
</code>```

phpstorm :

setup in accordance with above parameters.  Note that I use port 9002 to skit around a conflict with php-fpm which is part of my stack. Also, i force xdebug logging on a specific drive to ease the burden on my laptop SSD, etc ... Adapt to your configuration.

Body:
I am having a hard time with PhpStorm debugger. I read all their documentation and I have setup debug properly (according to both phpinfo(), debug tailored installation report and PhpStorm analysis).

However, no matter what I try, the debugger wont trigger.

My setup is the following:

I changed XAMPP document root to: c:\src\project\www

My project has the following structure:

project
 | www (used by XAMPP to serve the website)
 | src
   | --theme (symlinked to wp-content/themes)
   | --plugins (symlinked to wp-content/plugins)

and apparently, this setup works as all my plugins and theme are correctly working and displayed on the screen.

When I then start to run the debugger, it simply won't trigger.

This is the setup for the debugger on PhpStorm:

Server:

Host: localhost
Port: 80
Debugger: xdebug

Mappings (where I think there's something off)

src/theme   --> c:/src/project/www/wp-content/theme/
src/plugins --> c:/src/project/www/wp-content/plugins/

but nothing happens. No mappings errors, no debug, nothing at all.

Can you please explain to me what am I doing wrong here?

let me know if you need more info.

EDIT:

php.ini added line for debug (from xdebug website):

zend_extension = C:\xampp\php\ext\php_xdebug-2.5.4-7.1-vc14.dll

PhpStorm PHP settings:

Body:
This is from my setup :

php.ini

[xdebug]
;zend_extension=xdebug.so
zend_extension=/usr/local/Cellar/php55-xdebug/2.4.0/xdebug.so
xdebug.remote_enable=1
xdebug.remote_connect_back=0
xdebug.remote_handler=dbgp
xdebug.remote_host=localhost
xdebug.remote_port=9002
xdebug.remote_log="/mnt/log/xdebug.log"
xdebug.remote_autostart=1
xdebug.idekey=phpstorm
xdebug.remote_mode = req

phpstorm :

setup in accordance with above parameters.  Note that I use port 9002 to skit around a conflict with php-fpm which is part of my stack. Also, i force xdebug logging on a specific drive to ease the burden on my laptop SSD, etc ... Adapt to your configuration.


问:
Call forward to my personal VM after the ring got stopped
When an inbound call reaches my system it is forwarded to my personal number using TwiML. So once the ring stops (missed call) it just hang up the call. Is there any way to reach this call to my personal VM after the ring got stopped?</p>

答:
Twilio developer evangelist here.

It is possible that your phone is taking longer than 30 seconds to go to voicemail. The default timeout on <Dial> is 30 seconds, at which point Twilio will hang up.

You can set the timeout to anything between 5 and 600 seconds, which should cover the needs of your voicemail setting on your phone.


问:
Not getting output for simple java program to find greatest prime factor
```<code>class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}
</code>```

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?

答:
You have an infinite loop on the second for iteration you can only see it when you add logging before the end of the loop. It's not because it's not printing the value, when you stare at the console the iterator is still circling through 6857.

Try running the code with extra logging below.

```<code>public static void main(String args[]) {
    int p = 0;
    long n = 600851475143L;
    for (int i = 2; i < (n / 2); i++) {
        if ((BigInteger.valueOf(i)).isProbablePrime(1)) {
            if (BigInteger.valueOf(n % i).compareTo(BigInteger.valueOf(0)) == 0) {
                p = i;
                System.out.println("Check == true Iteration"+p);
            }
            System.err.println("Second iterator"+p);
        }
    }
    System.out.println("Final Value of P: "+p);
}
</code>```

Body:
class LargestPrimeFactor{
    public static void main(String args[]){
        long p=0L;
        long n=600851475143L;
        for(long i=2L;i<(n/2);i++){
            if((BigInteger.valueOf(i)).isProbablePrime(1)){
                if(n%i==0){
                    p=i;
                }
            }
        }
        System.out.println(p);
    }
}

It's problem 3 from Project Euler. I compiled it and no errors showed up. But am not getting any output. Whats the reason?

Body:
You have an infinite loop on the second for iteration you can only see it when you add logging before the end of the loop. It's not because it's not printing the value, when you stare at the console the iterator is still circling through 6857.

Try running the code with extra logging below.

public static void main(String args[]) {
    int p = 0;
    long n = 600851475143L;
    for (int i = 2; i < (n / 2); i++) {
        if ((BigInteger.valueOf(i)).isProbablePrime(1)) {
            if (BigInteger.valueOf(n % i).compareTo(BigInteger.valueOf(0)) == 0) {
                p = i;
                System.out.println("Check == true Iteration"+p);
            }
            System.err.println("Second iterator"+p);
        }
    }
    System.out.println("Final Value of P: "+p);
}


问:
How to use XML StreamReader in Qt?
i have this XML
located in C:/project/setting.xml

```<code><?xml version='1.0'?>
<configs>
  <interval>10</interval>
  <size>176,144</size>
</configs>
</code>```

how to link to my QT project?

and how to call the interval and size value of my XML in my .cpp file?.

thankyou.

答:
I usually prefer working directly with the DOM document directly for reading, and using the streamer only for writing (QXmlStreamWriter). Using QXmlStreamReader is quite laborious since, for maximum robustness, you have to consider all possibilities for the current position of the reader. If you don't mind changing the reading method you can take a look at this answer.

Qt already provides a good tutorial of how using the DOM document, but here you have a simplified version for your current problem. Just add the XML module to your Qt project.

```<code>#include <QtXML>

bool readXML(const QString& path)
{
  try {
    QFile inFile(path);
    if (!inFile.open(QFile::ReadOnly)) return false;

    QDomDocument xml("xml");
    xml.setContent(inFile.readAll());

    auto configs = xml.documentElement();
    if (configs.tagName() != "configs") return false;

    // No error checking nor other type conversion done here
    qDebug() << configs.firstChildElement("interval").firstChild().nodeValue();
    qDebug() << configs.firstChildElement("size").firstChild().nodeValue();
  } catch (...) {
    return false;
  }

  return true;
}
</code>```

It doesn't make a rigorous error checking, just two of them as an example. You should always check if your current node actually exists.

Important note: A tricky part of the DOM model is that the actual value of a node like <interval>10</interval> is not given by

```<code>auto interval = configs.firstChildElement("interval");
qDebug() << interval.nodeValue();
</code>```

but by

```<code>auto interval = configs.firstChildElement("interval");
qDebug() << interval.firstChild().nodeValue();
</code>```

The text node is actually the first child of the interval node. Take this in mind.

If you want to navigate an XML that contains several elements with the same name at the same level, like

```<code><?xml version='1.0'?>
<configs>
  <interval>10</interval>
  <interval>100</interval>
  <interval>1000</interval>
  <size>176,144</size>
</configs>
</code>```

you can use the nextSiblingElement method to get the next element:

```<code>for (auto interval = configs.firstChildElement("interval");
     !interval.isNull();
     interval= interval.nextSiblingElement("interval")) {
  // ...
}
</code>```

Title: How to use XML StreamReader in Qt?

Body:
i have this XML
located in C:/project/setting.xml

<?xml version='1.0'?>
<configs>
  <interval>10</interval>
  <size>176,144</size>
</configs>

how to link to my QT project?

and how to call the interval and size value of my XML in my .cpp file?.

thankyou.

Body:
I usually prefer working directly with the DOM document directly for reading, and using the streamer only for writing (QXmlStreamWriter). Using QXmlStreamReader is quite laborious since, for maximum robustness, you have to consider all possibilities for the current position of the reader. If you don't mind changing the reading method you can take a look at this answer.

Qt already provides a good tutorial of how using the DOM document, but here you have a simplified version for your current problem. Just add the XML module to your Qt project.

#include <QtXML>

bool readXML(const QString& path)
{
  try {
    QFile inFile(path);
    if (!inFile.open(QFile::ReadOnly)) return false;

    QDomDocument xml("xml");
    xml.setContent(inFile.readAll());

    auto configs = xml.documentElement();
    if (configs.tagName() != "configs") return false;

    // No error checking nor other type conversion done here
    qDebug() << configs.firstChildElement("interval").firstChild().nodeValue();
    qDebug() << configs.firstChildElement("size").firstChild().nodeValue();
  } catch (...) {
    return false;
  }

  return true;
}

It doesn't make a rigorous error checking, just two of them as an example. You should always check if your current node actually exists.

Important note: A tricky part of the DOM model is that the actual value of a node like <interval>10</interval> is not given by

auto interval = configs.firstChildElement("interval");
qDebug() << interval.nodeValue();

but by

auto interval = configs.firstChildElement("interval");
qDebug() << interval.firstChild().nodeValue();

The text node is actually the first child of the interval node. Take this in mind.

If you want to navigate an XML that contains several elements with the same name at the same level, like

<?xml version='1.0'?>
<configs>
  <interval>10</interval>
  <interval>100</interval>
  <interval>1000</interval>
  <size>176,144</size>
</configs>

you can use the nextSiblingElement method to get the next element:

for (auto interval = configs.firstChildElement("interval");
     !interval.isNull();
     interval= interval.nextSiblingElement("interval")) {
  // ...
}


问:
How to handle ISR callback?
I am currently working on a larger Arduino Mega 2560 project; servo controlling and sensor readings involved. I am using ultrasonic proximity sensors (HC-SR04) with the NewPing 1.8 library that uses interrupts for detecting the echo of the sensors. Furthermore, I read temperature and light intensity measurements also. Distance data received from the HC-SR04 ultrasonic sensors are forwarded over USB to the host computer by using the cmdMessenger3 library. Servos are controlled by messages from the host computer using the standard Servo library.

The mess begins as soon as the NewPing library calls the ISR when the ultrasonic echo is detected. This is the function called by the NewPing library when distance data is available:

```<code>void sendSonarData(uint8_t sensorId, uint16_t distance) {
  //noInterrupts();
  cmdMsg3.sendCmdStart(kReadSonar);
  cmdMsg3.sendCmdArg(sensorId);
  cmdMsg3.sendCmdArg(distance);
  cmdMsg3.sendCmdEnd();
  //interrupts();
}
</code>```

Here's another callback that sends temperature data to the host computer by the cmdMessenger3 library:

```<code>void sendTemperatureData(uint8_t sensorId, uint16_t temperature) {
  //noInterrupts();
  cmdMsg3.sendCmdStart(kReadTemperature);
  cmdMsg3.sendCmdArg(sensorId);
  cmdMsg3.sendCmdArg(temperature);
  cmdMsg3.sendCmdEnd();
  //interrupts();
}
</code>```

Problem: While the Arduino e.g. tries to send the temperature data, the ISR from the ultrasonic sensor might jump-in and writes it's own data to the serial stream; ending up in a mess regarding the serial data sent to the host computer, because the sending process is not atomic, consisting of multiple commands to send one message (sendCmdStart->sendCmdArg->sendCmdEnd).

Here's an example:

Temperature is read an sendTemperatureData(...) is called

cmdMsg3.sendCmdStart(kReadTemperature); is called

cmdMsg3.sendCmdArg(sensorId); is called

ISR from sonar sensor jumps-in

sendTemperatureData(); is called

cmdMsg3.sendCmdStart(kReadSonar); is called

cmdMsg3.sendCmdArg(sensorId);

cmdMsg3.sendCmdArg(distance);

cmdMsg3.sendCmdEnd();

remaining statements from sendTemperatureData(...) are called

cmdMsg3.sendCmdArg(temperature);

cmdMsg3.sendCmdEnd();

resulting in a big mess on the serial communication ...

I then tried to prevent ISR calls during the send process by using noInterrupts()/interrupts(); making the send process kind of 'atomic'. But this leads to lots of other problems, millis()/micros() functions are not precise anymore, Serial communication breaks down, etc.; all relying on the timers that are disabled by noInterrupts(). Moreover, the servos behave also quite strange, since timing for the PWM signal generation seems to be messed up also.

Any ideas how to solve this 'concurrency' issue without breaking the interrupt-based paradigm in my program?

答: You are trying to do WAY to much work in your ISRs; generally speaking, they shouldn't do anything that requires a delay (and any serial message over 1 byte falls in that category).  A more reasonable implementation would have the ISR simply store the sensor reading in global variables, and set a flag that the main program checks to see if it should send the serial message.  You might need something fancier (like a message queue) if a second reading from the same sensor might arrive before the previous one had a chance to be sent.</p>

Title: How to handle ISR callback?

Body:
I am currently working on a larger Arduino Mega 2560 project; servo controlling and sensor readings involved. I am using ultrasonic proximity sensors (HC-SR04) with the NewPing 1.8 library that uses interrupts for detecting the echo of the sensors. Furthermore, I read temperature and light intensity measurements also. Distance data received from the HC-SR04 ultrasonic sensors are forwarded over USB to the host computer by using the cmdMessenger3 library. Servos are controlled by messages from the host computer using the standard Servo library.

The mess begins as soon as the NewPing library calls the ISR when the ultrasonic echo is detected. This is the function called by the NewPing library when distance data is available:

void sendSonarData(uint8_t sensorId, uint16_t distance) {
  //noInterrupts();
  cmdMsg3.sendCmdStart(kReadSonar);
  cmdMsg3.sendCmdArg(sensorId);
  cmdMsg3.sendCmdArg(distance);
  cmdMsg3.sendCmdEnd();
  //interrupts();
}

Here's another callback that sends temperature data to the host computer by the cmdMessenger3 library:

void sendTemperatureData(uint8_t sensorId, uint16_t temperature) {
  //noInterrupts();
  cmdMsg3.sendCmdStart(kReadTemperature);
  cmdMsg3.sendCmdArg(sensorId);
  cmdMsg3.sendCmdArg(temperature);
  cmdMsg3.sendCmdEnd();
  //interrupts();
}

Problem: While the Arduino e.g. tries to send the temperature data, the ISR from the ultrasonic sensor might jump-in and writes it's own data to the serial stream; ending up in a mess regarding the serial data sent to the host computer, because the sending process is not atomic, consisting of multiple commands to send one message (sendCmdStart->sendCmdArg->sendCmdEnd).

Here's an example:

Temperature is read an sendTemperatureData(...) is called

cmdMsg3.sendCmdStart(kReadTemperature); is called

cmdMsg3.sendCmdArg(sensorId); is called

ISR from sonar sensor jumps-in

sendTemperatureData(); is called

cmdMsg3.sendCmdStart(kReadSonar); is called

cmdMsg3.sendCmdArg(sensorId);

cmdMsg3.sendCmdArg(distance);

cmdMsg3.sendCmdEnd();

remaining statements from sendTemperatureData(...) are called

cmdMsg3.sendCmdArg(temperature);

cmdMsg3.sendCmdEnd();

resulting in a big mess on the serial communication ...

I then tried to prevent ISR calls during the send process by using noInterrupts()/interrupts(); making the send process kind of 'atomic'. But this leads to lots of other problems, millis()/micros() functions are not precise anymore, Serial communication breaks down, etc.; all relying on the timers that are disabled by noInterrupts(). Moreover, the servos behave also quite strange, since timing for the PWM signal generation seems to be messed up also.

Any ideas how to solve this 'concurrency' issue without breaking the interrupt-based paradigm in my program?


问:
exception_on_overflow parameter not working? PyAudio
I am trying to record some audio using pyaudio but whenever it goes through the recording loop a second time I get this error

```<code>OSError: [Errno Input overflowed] -9981
</code>```

I did some searching and found that in order to solve this problem you simply need to set the 'exception_on_overflow' parameter of pyAudio.read() to False. So I did that and then I get this error

```<code>TypeError: read() got an unexpected keyword argument 'exception_on_overflow'
</code>```

this doesn't make any sense to me as to why it is 'unexpected' because in the PyAudio documentation it shows that it is a valid parameter for that function so is there anyone out there can tell me how to fix this problem? Thank you

答:
I found a solution to my problem. So first I ran the command

```<code>sudo pip install pyaudio
</code>```

Which installed version 0.2.11 of pyaudio. I looked in the code and I saw that it has the exception_on_overflow parameter in the read function. I tested it in my code and it worked! I hope this solves the problem for anyone else that has it

Body:
I am trying to record some audio using pyaudio but whenever it goes through the recording loop a second time I get this error

OSError: [Errno Input overflowed] -9981

I did some searching and found that in order to solve this problem you simply need to set the 'exception_on_overflow' parameter of pyAudio.read() to False. So I did that and then I get this error

TypeError: read() got an unexpected keyword argument 'exception_on_overflow'

this doesn't make any sense to me as to why it is 'unexpected' because in the PyAudio documentation it shows that it is a valid parameter for that function so is there anyone out there can tell me how to fix this problem? Thank you

Body:
I found a solution to my problem. So first I ran the command

sudo pip install pyaudio

Which installed version 0.2.11 of pyaudio. I looked in the code and I saw that it has the exception_on_overflow parameter in the read function. I tested it in my code and it worked! I hope this solves the problem for anyone else that has it


问:
unix command for grand total
Is there a easy way to calculate the grand total of all the numberic values specified line by line using a unix command (no script)

suppose

```<code>7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208
</code>```

assume this is in a file

I want the total of all the values.
thanks in advance

答:
```<code>command | awk '{sum+=$1} END { print sum}'
</code>```

Title: unix command for grand total

Body:
Is there a easy way to calculate the grand total of all the numberic values specified line by line using a unix command (no script)

suppose

7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208

assume this is in a file

I want the total of all the values.
thanks in advance


问:
How do i get this span inside this li?
I am using jquery tabs and trying to setup an indicator on the far right side of the tab to denote selected tab.  When i position a span at the end of the li, I will have css show it when :active/focus is met.  However the span shows up on the outside of the li.

How can i position the span inside the li?

```<code>  <li><a id='someId' href='#tabs-someId'>SomeValue</a><span class='butt'> </span></li>
</code>```

here is the css for the span

```<code>.butt{
    background-color:green;
    width:2px;
    height:2px;
    border-radius:2px;
 }
</code>```

Here is what the above line looks like

答:
```<code>li {
 position: relative;
}
.butt{
  background-color:green;
  width:2px;
  height:2px;
  border-radius:2px;
  position: absolute;
  right: 0;
  top: 0;
 }
</code>```

Title: How do i get this span inside this li?

Body:
I am using jquery tabs and trying to setup an indicator on the far right side of the tab to denote selected tab.  When i position a span at the end of the li, I will have css show it when :active/focus is met.  However the span shows up on the outside of the li.

How can i position the span inside the li?

SomeValue

here is the css for the span

.butt{
    background-color:green;
    width:2px;
    height:2px;
    border-radius:2px;
 }

Here is what the above line looks like


问:
Azure Servicebus: Receive all the message from one session id of a queue
I have 2 question for which I failed to find any solution.

Is there any built in way in azure service bus queue, where I can receive messages only from one session (for that sessionId) in my session handler.

Also is there any way I can receive messages only from the deadlettered queue for that session alone.

I can do this programmatically in my code, but I don't want to write if else logic in my code.

答:
Message Sessions feature is specifically designed for that.

QueueClient.AcceptMessageSessionAsync(sessionID) allows to achieve that for a normal queue.
As for the DLQ - not sure if that works.


问:
C++ templates: How to conditionally compile different code based on data type?
Here's a small example that illustrates the essence of my question:

```<code>#include <iostream>
using namespace std ;
typedef char achar_t ;

template < class T > class STRING
{
   public:
     T *    memory   ;
     int    size     ;
     int    capacity ;
   public:
     STRING() {
        size     =   0 ;
        capacity = 128 ;
        memory   = ( T *) malloc( capacity * sizeof(T) ) ;
     }
     const STRING& operator=( T * buf) {
         if ( typeid(T) == typeid(char) )
            strcpy( memory, buf ) ;
         else
            wcscpy( memory, buf ) ;
        return *this ;
     }
}  ;

void main()
{
  STRING<achar_t> a ;
  STRING<wchar_t> w ;
  a =  "a_test" ;
  w = L"w_test" ;
 cout << " a = " << a.memory << endl ;
 cout << " w = " << w.memory << endl ;
}
</code>```

Can some one please help me compile the above? That is somehow compile either with strcpy() or wcscpy() based on the type of the object i am using.

thank you

答:
Use std::char_traits<CharT>.

You can replace strcpy() and wcscpy() by combining the static methods std::char_traits::length() and std::char_traits::copy(). This will also make your code more generic because std::char_traits has specializations for char16_t and char32_t.

```<code> STRING& operator=( T const * buf) {
    // TODO: Make sure that buffer size for 'memory' is large enough.
    //       You propably also want to assign the 'size' member.

    auto len = std::char_traits< T >::length( buf );
    std::char_traits< T >::copy( memory, buf, len );

    return *this ;
 }
</code>```

Side notes:

I changed the type of parameter buf to T const* because it is not legal to assign a string literal to a pointer that points to non-const data. We only need read access to the data pointed to by buf.

I changed the return type to STRING& because that's the way how the assignment operator usually is declared. The method must be non-const so there is no point in restricting the return type to a constant reference.

Body:
Here's a small example that illustrates the essence of my question:

#include <iostream>
using namespace std ;
typedef char achar_t ;

template < class T > class STRING
{
   public:
     T *    memory   ;
     int    size     ;
     int    capacity ;
   public:
     STRING() {
        size     =   0 ;
        capacity = 128 ;
        memory   = ( T *) malloc( capacity * sizeof(T) ) ;
     }
     const STRING& operator=( T * buf) {
         if ( typeid(T) == typeid(char) )
            strcpy( memory, buf ) ;
         else
            wcscpy( memory, buf ) ;
        return *this ;
     }
}  ;

void main()
{
  STRING<achar_t> a ;
  STRING<wchar_t> w ;
  a =  "a_test" ;
  w = L"w_test" ;
 cout << " a = " << a.memory << endl ;
 cout << " w = " << w.memory << endl ;
}

Can some one please help me compile the above? That is somehow compile either with strcpy() or wcscpy() based on the type of the object i am using.

thank you

Body:
Use std::char_traits<CharT>.

You can replace strcpy() and wcscpy() by combining the static methods std::char_traits::length() and std::char_traits::copy(). This will also make your code more generic because std::char_traits has specializations for char16_t and char32_t.

 STRING& operator=( T const * buf) {
    // TODO: Make sure that buffer size for 'memory' is large enough.
    //       You propably also want to assign the 'size' member.

    auto len = std::char_traits< T >::length( buf );
    std::char_traits< T >::copy( memory, buf, len );

    return *this ;
 }

Side notes:

I changed the type of parameter buf to T const* because it is not legal to assign a string literal to a pointer that points to non-const data. We only need read access to the data pointed to by buf.

I changed the return type to STRING& because that's the way how the assignment operator usually is declared. The method must be non-const so there is no point in restricting the return type to a constant reference.


问:
Mongo aggregate: return total average of array values
I have this data in mongodb

```<code>{
  "name": "FooBar",
  "__v": 0,
  "user_rating": [
  {
    "date": "2017-06-02T16:19:32.002Z",
    "user_rating": 5,
  },
  {
    "date": "2017-06-02T16:19:46.803Z",
    "user_rating": 3,
  },
  {
    "date": "2017-06-02T16:20:01.244Z",
    "user_rating": 5,
  },
  {
    "date": "2017-06-02T16:15:54.673Z",
    "user_rating": 3,
  },
  {
    "date": "2017-06-02T16:53:42.489Z",
    "user_rating": 5,
  }
 ]
}
</code>```

I need to filter this to show the name of the store, the average rating, the total amount of ratings and the how many 5 ratings, how many 4 ratings etc.

This is what I am expecting:

```<code>[
  {
    "_id":"FooBar",
    "countRating":5,
    "averageRating":4.2,
    "ratings": [
       {"num":3,"count":2},
       {"num":5,"count":3}
     ]
  }
 ]
</code>```

However, I can't seem to get the averageRating - instead I get the average for the two combined totals of each rating.

Here is my Mongo query:

```<code> db.collection.aggregate([
      {
        $match: {"name": "FooBar"}
      },
      {
          $unwind: "$user_rating"
      },
      {
        $match: {"name": "FooBar"}
      },
        {
          $group: {
            _id: {
              "name": "$name",
              "rating": "$user_rating.user_rating"
            },
            averageRating: {$avg: "$user_rating.user_rating"},
            countRating: {$sum: 1}
        }
      },
      {
        $group: {
          _id: "$_id.name",
          countRating: {"$sum": "$totalRatings"},
          averageRating: {"$avg": "$averageRating"},
          "rating": {
            "$push": {
              "num": "$_id.rating",
              "count": "$totalRatings"
            }
          },
        }
      }]);
</code>```

Can anyone help get the overall average here?
Thanks!!

答:
```<code>db.collection.aggregate([
      { $match: {"name": "FooBar"} },
      { $unwind: "$user_rating" },
      {
          $group: {
              _id : "$name",
              avg: {$avg: "$user_rating.user_rating" },
              ratings: {$push: "$user_rating.user_rating" }
          }
      },
      { $unwind: "$ratings" },
      {
          $group: {
              _id: { name: "$_id", num: "$ratings", avg: "$avg" },
              count: { $sum: 1 }
          }
      },
      {
          $group: {
              _id: { name: "$_id.name", avg: "$_id.avg" },
              ratings: { $push: { num: "$_id.num", count: "$count" }}
          }
      },
      { $project: {_id:0, name:"$_id.name", averageRating: "$_id.avg", ratings: 1}}
 ])
</code>```

I have used additional grouping here to calculate the total average rating. Then I unwind results and pass calculated avg value in grouping key.

Output:

```<code>{
    "name" : "FooBar",
    "averageRating" : 4.2,
    "ratings" : [
        {
            "num" : 3,
            "count" : 2
        },
        {
            "num" : 5,
            "count" : 3
        }
    ]
}
</code>```

Body:
I have this data in mongodb

{
  "name": "FooBar",
  "__v": 0,
  "user_rating": [
  {
    "date": "2017-06-02T16:19:32.002Z",
    "user_rating": 5,
  },
  {
    "date": "2017-06-02T16:19:46.803Z",
    "user_rating": 3,
  },
  {
    "date": "2017-06-02T16:20:01.244Z",
    "user_rating": 5,
  },
  {
    "date": "2017-06-02T16:15:54.673Z",
    "user_rating": 3,
  },
  {
    "date": "2017-06-02T16:53:42.489Z",
    "user_rating": 5,
  }
 ]
}

I need to filter this to show the name of the store, the average rating, the total amount of ratings and the how many 5 ratings, how many 4 ratings etc.

This is what I am expecting:

[
  {
    "_id":"FooBar",
    "countRating":5,
    "averageRating":4.2,
    "ratings": [
       {"num":3,"count":2},
       {"num":5,"count":3}
     ]
  }
 ]

However, I can't seem to get the averageRating - instead I get the average for the two combined totals of each rating.

Here is my Mongo query:

 db.collection.aggregate([
      {
        $match: {"name": "FooBar"}
      },
      {
          $unwind: "$user_rating"
      },
      {
        $match: {"name": "FooBar"}
      },
        {
          $group: {
            _id: {
              "name": "$name",
              "rating": "$user_rating.user_rating"
            },
            averageRating: {$avg: "$user_rating.user_rating"},
            countRating: {$sum: 1}
        }
      },
      {
        $group: {
          _id: "$_id.name",
          countRating: {"$sum": "$totalRatings"},
          averageRating: {"$avg": "$averageRating"},
          "rating": {
            "$push": {
              "num": "$_id.rating",
              "count": "$totalRatings"
            }
          },
        }
      }]);

Can anyone help get the overall average here?
Thanks!!

Body:
db.collection.aggregate([
      { $match: {"name": "FooBar"} },
      { $unwind: "$user_rating" },
      {
          $group: {
              _id : "$name",
              avg: {$avg: "$user_rating.user_rating" },
              ratings: {$push: "$user_rating.user_rating" }
          }
      },
      { $unwind: "$ratings" },
      {
          $group: {
              _id: { name: "$_id", num: "$ratings", avg: "$avg" },
              count: { $sum: 1 }
          }
      },
      {
          $group: {
              _id: { name: "$_id.name", avg: "$_id.avg" },
              ratings: { $push: { num: "$_id.num", count: "$count" }}
          }
      },
      { $project: {_id:0, name:"$_id.name", averageRating: "$_id.avg", ratings: 1}}
 ])

I have used additional grouping here to calculate the total average rating. Then I unwind results and pass calculated avg value in grouping key.

Output:

{
    "name" : "FooBar",
    "averageRating" : 4.2,
    "ratings" : [
        {
            "num" : 3,
            "count" : 2
        },
        {
            "num" : 5,
            "count" : 3
        }
    ]
}


问:
Static Resource not found when usercontrol is created from code-behind
I am working on refactoring an application to use property injection.  This has required me to create the views from the code behind like such.  Originally everything was created in XAML and bindings were set to the view models by static resources.  This gave no control over injecting the service for getting data into the view model.

This is the App.xaml.cs:

```<code>public App()
{
    this.MainWindow = new MainWindow(new MainWindowViewModel(new DbDataService()));
    MainWindow.Show();

}
</code>```

MainWindowViewModel is set as the datacontext.
App.xaml contains this resource for viewing the product type class in a listbox:

```<code>  <DataTemplate x:Key="DataTemplate" DataType="{x:Type classes:Product}">
</code>```

The MainWindow has a tab for each view.  I have a tab's view created like this in MainWindow's constructor:

```<code> ProductsTab.Content = new MainView(mainWindowViewModel);
</code>```

When I do this, I get the following error in the MainView on this line:

```<code><dxe:ListBoxEdit  Grid.Column="0" ItemTemplate="{StaticResource DataTemplate}" ...etc... />
</code>```

"'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '37' and line position '31'."

What I have tried:
I have tried creating the Tab's view in XAML and setting its data context to the parents, however, I still got this exception.
I have tried changing my static resources to dynamic resources, which causes no error at runtime, but the list box does not display the information correctly.

What I need to know:
How to use static/dynamic resources with decency injection.
If there is a better approach to this problem, such as creating the templates in code and injecting them into the views?

Some of my concerns:
I want to add dependency injection to this application, however, I feel like the approach I'm using not only breaks the resources but breaks the MVVM pattern.

答:
Try to create and call your MainWindow in the OnStartup method of your App class:

```<code>public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        this.MainWindow = new MainWindow(new MainWindowViewModel(new DbDataService()));
        MainWindow.Show();
    }
}
</code>```

This should work provided that you define the "DataTemplate" resource in your App.xaml (or in a ResourceDictionary that you merge from App.xaml).

Body:
I am working on refactoring an application to use property injection.  This has required me to create the views from the code behind like such.  Originally everything was created in XAML and bindings were set to the view models by static resources.  This gave no control over injecting the service for getting data into the view model.

This is the App.xaml.cs:

public App()
{
    this.MainWindow = new MainWindow(new MainWindowViewModel(new DbDataService()));
    MainWindow.Show();

}

MainWindowViewModel is set as the datacontext.
App.xaml contains this resource for viewing the product type class in a listbox:

  <DataTemplate x:Key="DataTemplate" DataType="{x:Type classes:Product}">

The MainWindow has a tab for each view.  I have a tab's view created like this in MainWindow's constructor:

 ProductsTab.Content = new MainView(mainWindowViewModel);

When I do this, I get the following error in the MainView on this line:

<dxe:ListBoxEdit  Grid.Column="0" ItemTemplate="{StaticResource DataTemplate}" ...etc... />

"'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '37' and line position '31'."

What I have tried:
I have tried creating the Tab's view in XAML and setting its data context to the parents, however, I still got this exception.
I have tried changing my static resources to dynamic resources, which causes no error at runtime, but the list box does not display the information correctly.

What I need to know:
How to use static/dynamic resources with decency injection.
If there is a better approach to this problem, such as creating the templates in code and injecting them into the views?

Some of my concerns:
I want to add dependency injection to this application, however, I feel like the approach I'm using not only breaks the resources but breaks the MVVM pattern.

Body:
Try to create and call your MainWindow in the OnStartup method of your App class:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        this.MainWindow = new MainWindow(new MainWindowViewModel(new DbDataService()));
        MainWindow.Show();
    }
}

This should work provided that you define the "DataTemplate" resource in your App.xaml (or in a ResourceDictionary that you merge from App.xaml).


问:
MonoDevelop 2.4: Help finding a dll
I am trying to build a MonoDevelop 2.4 add-in but I need the dll with the namespace of: MonoDevelop.Projects.Gui. Does anyone know what dll this namespace is stored in? I was told that the namespace was in MonoDevelop.Ide.dll but when I added the dll to the MonoDevelop project the namespace did not resolve.</p>

答: This namespace doesn't exist anymore in MonoDevelop 2.4. The classes that were there have been moved to MonoDevelop.Ide.* namespaces. You can try looking in MonoDevelop.Ide, MonoDevelop.Ide.Gui, MonoDevelop.Ide.Projects or MonoDevelop.Ide.Projects.OptionPanels.</p>

Title: MonoDevelop 2.4: Help finding a dll


问:
Play multiple audio sounds in mobile devices with javascript
I am working on building a game which has different sounds.

I am using the below for playing them

```<code>var jackpot_audio_file = document.getElementById('jackpot_sound');
jackpot_audio_file.play();
</code>```

It works perfectly on desktop but not on mobile devices. Some play because I have a click then sound plays, but for the rest which do not need user to click anything didn't work.

I tried with simulated click with trigger('click') but it also didn't work.

答:
I know this is an old question, but I've faced the same issues and found a way around it.

As you may have realized, you can't trigger a sound to play by itself on mobile environments. For it to play, it is required a touch event by the user.

So, what I did the following:

1 - I declared all sounds I'm going to play beforehand

```<code>var sound1 = new Audio('file1.mp3');
var sound2 = new Audio('file1.mp3');
var sound3 = new Audio('file1.mp3');
</code>```

2 - I created a screen with a button that the user MUST click in order to proceeed to the game:

```<code><button onclick="proceeed()">proceeed</button>
</code>```

3 - declared a function to be called by this button, that will set all audios volume to zero, play them all, pause them all, and proceed to the game:

```<code>function proceed() {
    sound1.volume = 0;
    sound2.volume = 0;
    sound3.volume = 0;

    sound1.play();
    sound1.pause();
    sound2.play();
    sound2.pause();
    sound3.play();
    sound3.pause();

    sound1.volume = 1;
    sound2.volume = 1;
    sound3.volume = 1;

    startGame();
}
</code>```

This way all sounds are "played" with a touch event and loaded into memory. Next time in the application you want to play a sound, you just call

```<code>sound1.play();
</code>```

and the sound will be played, even if there're other sounds being played.

Still we can't make it play automatically, but we can "trick" the user into provinding us the event we need so sounds are freely available for playing. It allows you to have a background theme and play sound effects on top of it.

You can check the result here:

http://thechase.besaba.com (open it on a mobile device).

The source code can be found at: https://github.com/Vinas/theChase.

Hope this was useful!

Body:
I am working on building a game which has different sounds.

I am using the below for playing them

var jackpot_audio_file = document.getElementById('jackpot_sound');
jackpot_audio_file.play();

It works perfectly on desktop but not on mobile devices. Some play because I have a click then sound plays, but for the rest which do not need user to click anything didn't work.

I tried with simulated click with trigger('click') but it also didn't work.

Body:
I know this is an old question, but I've faced the same issues and found a way around it.

As you may have realized, you can't trigger a sound to play by itself on mobile environments. For it to play, it is required a touch event by the user.

So, what I did the following:

1 - I declared all sounds I'm going to play beforehand

var sound1 = new Audio('file1.mp3');
var sound2 = new Audio('file1.mp3');
var sound3 = new Audio('file1.mp3');

2 - I created a screen with a button that the user MUST click in order to proceeed to the game:

<button onclick="proceeed()">proceeed</button>

3 - declared a function to be called by this button, that will set all audios volume to zero, play them all, pause them all, and proceed to the game:

function proceed() {
    sound1.volume = 0;
    sound2.volume = 0;
    sound3.volume = 0;

    sound1.play();
    sound1.pause();
    sound2.play();
    sound2.pause();
    sound3.play();
    sound3.pause();

    sound1.volume = 1;
    sound2.volume = 1;
    sound3.volume = 1;

    startGame();
}

This way all sounds are "played" with a touch event and loaded into memory. Next time in the application you want to play a sound, you just call

sound1.play();

and the sound will be played, even if there're other sounds being played.

Still we can't make it play automatically, but we can "trick" the user into provinding us the event we need so sounds are freely available for playing. It allows you to have a background theme and play sound effects on top of it.

You can check the result here:

http://thechase.besaba.com (open it on a mobile device).

The source code can be found at: https://github.com/Vinas/theChase.

Hope this was useful!