问:
Prometheus metrics not showing up using prometheus go client
I am using prometheus golang client. The code snippet is below. The build for the same is working okay.

The issue is that only go metrics are shown. xyz_* metrics are missing. I call the initMetrics() as first thing in the main() func.

```<code>// Declaring prometheus metric counters
var (

  metric_prefix = "xyz_"

  xyzAPICallsCounter = prometheus.NewCounterVec(
    prometheus.CounterOpts{
      Name: metric_prefix + "api_calls_total" ,
      Help: "Number of calls to xyz endpoint",
    },
    []string{
      // Type of api call. Present values
      "type",
      // Method can be "add", "delete", "getall", "get", "create", "ensure"
      "method",
      // Status is success or failed
      "status",
    },
  )

)

    func initMetrics(){
    prometheus.MustRegister(xyzAPICallsCounter)
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
    }
</code>```

Edit: I changed the initMetrics() function to below and now there are no metrics at all and the below error message.

```<code>func initMetrics(){
  var registry = prometheus.NewRegistry()
  registry.MustRegister(
    xyzAPICallsCounter,
  )
  http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
  log.Fatal(http.ListenAndServe(":8080", nil))
}
</code>```

答:
CounterVec is a collection of counters and is not exported until it has counters in it.

See the code docs and example for more info.

Body:
I am using prometheus golang client. The code snippet is below. The build for the same is working okay.

The issue is that only go metrics are shown. xyz_* metrics are missing. I call the initMetrics() as first thing in the main() func.

// Declaring prometheus metric counters
var (

  metric_prefix = "xyz_"

  xyzAPICallsCounter = prometheus.NewCounterVec(
    prometheus.CounterOpts{
      Name: metric_prefix + "api_calls_total" ,
      Help: "Number of calls to xyz endpoint",
    },
    []string{
      // Type of api call. Present values
      "type",
      // Method can be "add", "delete", "getall", "get", "create", "ensure"
      "method",
      // Status is success or failed
      "status",
    },
  )

)

    func initMetrics(){
    prometheus.MustRegister(xyzAPICallsCounter)
    http.Handle("/metrics", promhttp.Handler())
    http.ListenAndServe(":8080", nil)
    }

Edit: I changed the initMetrics() function to below and now there are no metrics at all and the below error message.

func initMetrics(){
  var registry = prometheus.NewRegistry()
  registry.MustRegister(
    xyzAPICallsCounter,
  )
  http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{}))
  log.Fatal(http.ListenAndServe(":8080", nil))
}


来源: stackexchange

问:
jQuery version not supported on Android 7.0?
I am using a simple PHP-based file manager system that uses jQuery 1.8.2 on the original code to construct the tables. I can easily open the webpage using any windows browsers, but when I use my android tablet (Samsung Galaxy Tab S2 , SM-T710) using Android 7.0, I cannot open the webpage. But when I try to open the webpage using another tablet with same specifications but equipped with Android 6.0.1, I have no problem opening the page with full functionality.

I managed to obtain android log files containing the following error:

```<code>12-01 17:08:09.453 22534 22534 I chromium: [INFO:CONSOLE(99)] "Uncaught ReferenceError: jQuery is not defined"
</code>```

I know that the problem lies with jQuery version that I am using, but I do not know what versions are being supported by android and how to narrow down the options.

I have tried different browsers and all devices, and the results do not change. It either works on all browsers on the device or none of them. Also tried a couple of jQuery version manually but could not get it to work.

I would appreciate any help on the matter.

答:
I found a quick fix to the problem.

The original code, as referenced in the original post, uses the following line to include the jQuery library:

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</code>```

But the quick fix that I found to the problem, is to download the jQuery library itself and put it in the folder and include it in the library call line. Hence I downloaded the latest version (3.2.1) from jQuery Website and changed the above line to the following:

```<code><script src="jquery-3.2.1.min.js"></script>
</code>```

In this way, I am statically calling the library and including it with the webpage itself. I know it is not efficient in any way, but it fixed my problem and the issue is resolved.

ContentLicense: CC BY-SA 3.0

Body:
I am using a simple PHP-based file manager system that uses jQuery 1.8.2 on the original code to construct the tables. I can easily open the webpage using any windows browsers, but when I use my android tablet (Samsung Galaxy Tab S2 , SM-T710) using Android 7.0, I cannot open the webpage. But when I try to open the webpage using another tablet with same specifications but equipped with Android 6.0.1, I have no problem opening the page with full functionality.

I managed to obtain android log files containing the following error:

12-01 17:08:09.453 22534 22534 I chromium: [INFO:CONSOLE(99)] "Uncaught ReferenceError: jQuery is not defined"

I know that the problem lies with jQuery version that I am using, but I do not know what versions are being supported by android and how to narrow down the options.

I have tried different browsers and all devices, and the results do not change. It either works on all browsers on the device or none of them. Also tried a couple of jQuery version manually but could not get it to work.

I would appreciate any help on the matter.

Body:
I found a quick fix to the problem.

The original code, as referenced in the original post, uses the following line to include the jQuery library:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

But the quick fix that I found to the problem, is to download the jQuery library itself and put it in the folder and include it in the library call line. Hence I downloaded the latest version (3.2.1) from jQuery Website and changed the above line to the following:

<script src="jquery-3.2.1.min.js"></script>

In this way, I am statically calling the library and including it with the webpage itself. I know it is not efficient in any way, but it fixed my problem and the issue is resolved.


问:
Generated Spring Boot project - maven dependencies without versions
I am new in the Spring and Maven so I start from Spring's starter page. When I run project, project works fine, problem is pom.xml file of that project contains dependencies without version attributes. Can you explain me what that mean? Is it ok or should I define custom versions to use?

Here is pom file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.customApp</groupId>
    <artifactId>myApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>myApp</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

答:
For dependencies that live in the parent then it will use the version that the parent is using.

Not the one you wrote, that is the version of the parent, but the version of that dependency that this version of the parent contains.

Example: V1.0 of the parent contains version 2.1 of dependency1 and version 3.6 of dependency2 and V2.0 of the parent contains version 3.0 of dependency1 and version 4.0 of dependency2

Otherwise: What will the version be when I don't specify it in the Maven's pom.xml?

Since you say your project is running fine then it means the version numbers are coming form the parent.

Body:
I am new in the Spring and Maven so I start from Spring's starter page. When I run project, project works fine, problem is pom.xml file of that project contains dependencies without version attributes. Can you explain me what that mean? Is it ok or should I define custom versions to use?

Here is pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.customApp</groupId>
    <artifactId>myApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>myApp</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>


问:
difference between socket programming and Http programming
What is the difference between socket programming and Http programming? can anyone help please?</p>

答:
HTTP Connection

HTTP connection is a protocol that runs on a socket.

HTTP connection is a higher-level abstraction of a network connection.

With HTTP connection the implementation takes care of all these higher-level details and simply send HTTP request (some header
  information) and receive HTTP response from the server.

Socket Connection

Socket is used to transport data between systems. It simply connects two systems together, an IP address is the address of the
  machine over an IP based network.

With socket connection you can design your own protocol for network connection between two systems.

With Socket connection you need to take care of all the lower-level details of a TCP/IP connection.


问:
How can I find where a JavaScript function is defined in Firefox Quantum's debugger?
If I know the name of a JavaScript function, or if I have a reference to a function (eg. in a callback) how can I find where that function is defined, when using the Firefox Quantum debugger.

In Firebug/Firefox debugger I used to be able to type the function name into the JS console, and it would print a little bit of info and I could click on that output and be taken to the function definition.

Now in Firefox Quantum if I click on the function name it expands in the console to show info about the function object.

The Chrome debugger still works the way Firebug/Firefox used to, but I end up needing to debug/test in both browsers.

答:
In your debugger tab hit ctrl + shift + f.
This will open a search window where you can type in the funtion name.
This way you will get every location the name appears. Now you just have to look out for a line like: function <name> () {

Or you type function <name> right away.


问:
Logic: is ( A && !(B || C)) || ( B || C ) the same as ( A || B || C )?
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

```<code>#if ( A && !(B || C)) || ( B || C )
</code>```

is this the same as?

```<code>#if ( A || B || C )
</code>```

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

```<code>#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)
</code>```

答: Yes, the two expressions are equivalent.  (I just wrote a couple of functions to test all eight possibilities.)</p>

ContentLicense: CC BY-SA 2.5

Body:
I've encountered some obj-c code and I'm wondering if there's a way to simplify it:

#if ( A && !(B || C)) || ( B || C )

is this the same as?

#if ( A || B || C )

If not, is there another way to formulate it that would be easier to read?

[edit]
I tried the truth table before asking the question, but thought I had to be missing something because I doubted that Foundation.framework/Foundation.h would employ this more complex form.   Is there a good reason for it?

Here's the original code (from Foundation.h):

#if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) || (TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)


问:
Position image on page with title using ImageMagick or similar command line tool
I have a landscape image foo.png which I'd like to lay out on a page like this:

```<code>+--------------+
|              |
|  title text  |
|              |
|  +--------+  |
|  |foo.png |  |
|  |        |  |
|  +--------+  |
|              |
|              |
+--------------+
</code>```

I've got the image positioned properly on the page with:

convert -background white -page letter+20+300 -resize 572x572 foo.png -layers flatten laid-out.png

However, I can't find the right use of -annotate, -draw text or label: to get that title text to show up in the right place.

The eventual goal is to script this for about a hundred images, so I need a command-line solution.

答:
It looks like you'd do well to take advantage of ImageMagick's "-gravity" setting here. This might not be exactly what you're looking for, but notice how "-gravity" works to locate the overlay image with "-composite", and the text is located with "-annotate" using a command like this...

```<code>convert foo.png -resize 572x572 \
   -size 612x792 xc:white +swap -gravity center -composite \
   -gravity north -pointsize 24 -annotate +0+100 "Title Text" laid-out.png
</code>```

That starts by reading in "foo.png" and resizing it. Then it sets the size of the desired canvas, creates a white canvas of that size, sets the gravity to center, swaps the overlay image with the canvas to get them in the correct order, and composites "foo.png" centered on the canvas.

Then it changes the gravity setting to north, sets the pointsize of the text, and annotates the image with the text located "+0+100". That's zero pixels from center left to right, and 100 pixels down from the top.

A couple experiments should help you find settings to suit your need.

Body:
I have a landscape image foo.png which I'd like to lay out on a page like this:

+--------------+
|              |
|  title text  |
|              |
|  +--------+  |
|  |foo.png |  |
|  |        |  |
|  +--------+  |
|              |
|              |
+--------------+

I've got the image positioned properly on the page with:

convert -background white -page letter+20+300 -resize 572x572 foo.png -layers flatten laid-out.png

However, I can't find the right use of -annotate, -draw text or label: to get that title text to show up in the right place.

The eventual goal is to script this for about a hundred images, so I need a command-line solution.

Body:
It looks like you'd do well to take advantage of ImageMagick's "-gravity" setting here. This might not be exactly what you're looking for, but notice how "-gravity" works to locate the overlay image with "-composite", and the text is located with "-annotate" using a command like this...

convert foo.png -resize 572x572 \
   -size 612x792 xc:white +swap -gravity center -composite \
   -gravity north -pointsize 24 -annotate +0+100 "Title Text" laid-out.png

That starts by reading in "foo.png" and resizing it. Then it sets the size of the desired canvas, creates a white canvas of that size, sets the gravity to center, swaps the overlay image with the canvas to get them in the correct order, and composites "foo.png" centered on the canvas.

Then it changes the gravity setting to north, sets the pointsize of the text, and annotates the image with the text located "+0+100". That's zero pixels from center left to right, and 100 pixels down from the top.

A couple experiments should help you find settings to suit your need.


问:
Pandas groupby quantile values
I tried to calculate specific quantile values from a data frame, as shown in the code below. There was no problem when calculate it in separate lines.

When attempting to run last 2 lines, I get the following error:

```<code>AttributeError: 'SeriesGroupBy' object has no attribute 'quantile(0.25)'
</code>```

How can I fix this?

```<code>import pandas as pd
df = pd.DataFrame(
    {
        'x': [0, 1, 0, 1, 0, 1, 0, 1],
        'y': [7, 6, 5, 4, 3, 2, 1, 0],
        'number': [25000, 35000, 45000, 50000, 60000, 70000, 65000, 36000]
    }
)
f = {'number': ['median', 'std', 'quantile']}
df1 = df.groupby('x').agg(f)
df.groupby('x').quantile(0.25)
df.groupby('x').quantile(0.75)

# code below with problem:
f = {'number': ['median', 'std', 'quantile(0.25)', 'quantile(0.75)']}
df1 = df.groupby('x').agg(f)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Pandas groupby quantile values

Body:
I tried to calculate specific quantile values from a data frame, as shown in the code below. There was no problem when calculate it in separate lines.

When attempting to run last 2 lines, I get the following error:

AttributeError: 'SeriesGroupBy' object has no attribute 'quantile(0.25)'

How can I fix this?

import pandas as pd
df = pd.DataFrame(
    {
        'x': [0, 1, 0, 1, 0, 1, 0, 1],
        'y': [7, 6, 5, 4, 3, 2, 1, 0],
        'number': [25000, 35000, 45000, 50000, 60000, 70000, 65000, 36000]
    }
)
f = {'number': ['median', 'std', 'quantile']}
df1 = df.groupby('x').agg(f)
df.groupby('x').quantile(0.25)
df.groupby('x').quantile(0.75)

# code below with problem:
f = {'number': ['median', 'std', 'quantile(0.25)', 'quantile(0.75)']}
df1 = df.groupby('x').agg(f)

Body:
I prefer def functions

def q1(x):
    return x.quantile(0.25)

def q3(x):
    return x.quantile(0.75)

f = {'number': ['median', 'std', q1, q3]}
df1 = df.groupby('x').agg(f)
df1
Out[1643]:
  number
  median           std     q1     q3
x
0  52500  17969.882211  40000  61250
1  43000  16337.584481  35750  55000


问:
bunifu material textbox mode password is not working
I want to create a login page based C# desktop application. I use the bunifu toolbox to create a login page design. But when I want to create a password field using the bunifumaterialtextbox, the textbox does not show any changes / it only displays alphabet. It looks like the ispassword contained in the textbox properties is not working. So what should I do so that this texbox can display the correct password (not displaying alphabeth) when the program is run ?. I apologize for any errors in this question. </p>

答:
I'm new using the Bunifu framework tool and I had the same problem then you. The solution I found was to invoke the _TextBox method which I suppose that gives you all the normal TextBox controls.

My code was something like this:
txtPassword._TextBox.PasswordChar = '*';

I loaded this code inside the Form_Load code block. It worked for me, hope that be useful for you too. Good luck!


问:
Write single value on firebase database without deleting the existing ones
I'am trying to add a single value my database without deleting the existing ones because I need them all. The structure is something like that /user/fav_post/{post_id_1,post_id_2,...}. The "fav_post" initially is empty and as the time goes by the user adds more fav_posts.

One way that solves this problem is downloading all favorite posts, putting them in a HashMap, add the new post and the push them to the database but this does not seem very optimal.

So what I am trying to achieve is to have all the favorite posts and to display them to the user.

```<code> mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .setValue(postID);
</code>```

Edit: The end result should be like

Ther end result I want to be like that
root

```<code>-User

--FavPosts

---postID1(String)
</code>```

And when the user favorites another post the result should be like that:

```<code>root
-User

--FavPosts

---postID1(String)

---postID2(String)
</code>```

答:
What you're looking for is a set: an unordered collection of unique values. In the Firebase Database you'd store the post Id as a key and (since Firebase doesn't allow you to store a key without a value) true as the value.

So:

```<code>root: {
  User: {
    FavPosts: {
      postID1: true,
      postID2: true
    }
  }
}
</code>```

You'd set these values with:

```<code> mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .child(postID)
       .setValue(true);
</code>```

Body:
I'am trying to add a single value my database without deleting the existing ones because I need them all. The structure is something like that /user/fav_post/{post_id_1,post_id_2,...}. The "fav_post" initially is empty and as the time goes by the user adds more fav_posts.

One way that solves this problem is downloading all favorite posts, putting them in a HashMap, add the new post and the push them to the database but this does not seem very optimal.

So what I am trying to achieve is to have all the favorite posts and to display them to the user.

 mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .setValue(postID);

Edit: The end result should be like

Ther end result I want to be like that
root

-User

--FavPosts

---postID1(String)

And when the user favorites another post the result should be like that:

root
-User

--FavPosts

---postID1(String)

---postID2(String)

Body:
What you're looking for is a set: an unordered collection of unique values. In the Firebase Database you'd store the post Id as a key and (since Firebase doesn't allow you to store a key without a value) true as the value.

So:

root: {
  User: {
    FavPosts: {
      postID1: true,
      postID2: true
    }
  }
}

You'd set these values with:

 mDatabase.child("USERS")
       .child(currentUser.getUid())
       .child("favorites")
       .child(postID)
       .setValue(true);


问:
Should I use multiple databases for single project
I am working on a site which provides coupons for online shopping sites.
It provides discount coupons for shopping sites in India.
But now the client wants to provide coupons for USA stores also.
But offers available for Indian users are not useful for the USA users and vice versa.

Therefore there will be two versions of the site. One is for the Indian users and other is for the USA users.

But if a user from India searches for an offer which is not available in India but is available in the USA. Then it should appear in search results.

Now I am thinking of creating a new database for the USA users with exact same schema as that of the database for current users(Indian users).

But I would like to get advice from an expert.

答:
In the long run you might want to add more countries so I would do it by adding a country table kind of thing and something like offer_valid for offerid country id which would make a single offer valid for one country or more.
Creating multiple databases would make the maintenance hectic.</p>


问:
Alternative for Xephyr in wayland
I'm searching for a tool to test my codes, I always do it using Xephyr for Xorg.
Now Is there any alternative for Xephyr in Wayland?</p>

答:
Wayland environments like Gnome 3 or KDE 5 use a rootless Xwayland to support X applications; Xephyr still works then.

For pure Wayland environments there is currently no nested X server available, afaik. Xpra may support this as soon as it is ported to GTK3 and python 3. But that port is not ready yet.

For now, you can run Xwayland as a Wayland client (not rootless in this case). With given environment variables WAYLAND_DISPLAY and XDG_RUNTIME_DIR, you can run Xwayland :1 and start X applications with DISPLAY=:1 xterm.

Xwayland appears as a fullscreen borderless window. Unfortunately, it is not possible to set another screen size for Xwayland. In Gnome 3 you can move it around with SUPER+LeftMouseButton,  other Wayland compositors may have a different setup to move borderless clients. Instead of moving Xwayland window, you can use ALT+Tab in many desktop environments to switch to the hidden applications.

Title: Alternative for Xephyr in wayland


问:
How to perform a git merge in a Jenkins pipeline?
When Jenkins builds a non-master git branch, I want to merge in master automatically at a specific point. I don't want to use the git plugin's auto merge feature.

However, I've added the stage:

```<code>stage('Merge master') {
  sh 'git merge master'
}
</code>```

But I get an error:

```<code>merge: master - not something we can merge
</code>```

Jenkins seems to be checking out my branch in a weird way that prevents me being able to then merge master. What do I need to do to merge master into my branch?

答:
When Jenkins cloned your repo, it didn't checkout a local master branch

The following script should allow you to test a merge of master.

```<code>git fetch --all
git checkout master
git checkout branch-name
git merge master
</code>```

Body:
When Jenkins builds a non-master git branch, I want to merge in master automatically at a specific point. I don't want to use the git plugin's auto merge feature.

However, I've added the stage:

stage('Merge master') {
  sh 'git merge master'
}

But I get an error:

merge: master - not something we can merge

Jenkins seems to be checking out my branch in a weird way that prevents me being able to then merge master. What do I need to do to merge master into my branch?

Body:
When Jenkins cloned your repo, it didn't checkout a local master branch

The following script should allow you to test a merge of master.

git fetch --all
git checkout master
git checkout branch-name
git merge master


问:
Microsoft.Azure.Search (sdk v3.0.3) don't return all the facets correctly
When I use Microsoft.Azure.Search (v3.0.3)'s "SearchAsync" and "Search" methods to return the indexed items, the sdk doesn't return all the facets.

However; when I try the same thing using Postman, it returns all the facets correctly.

Could this be a bug of the sdk (I believe it is as a direct call to an sdk method doesn't return the all the facets correctly - but couldn't find any records about this possible bug)? If yes, is there a fix for this for the sdk? Any help is appreciated.

UPDATE:
After spending some more time, I have found out that the bug is not .NET SDK Specific.

Both .NET SDK and REST API appear to have this problem and none of them returns all the facets. Can you please tell me is there a known bug for this and what is the fix for it?

Please see the following example;

There must be 2 Coaching facets but only 1 is returning from the Azure Search Service.

The new search query(facet specialisms added)

```<code>https://MYPROJECT-search.search.windows.net/indexes/myproject-directory-qa/docs?api-version=2016-09-01&$count=true&facet=specialisms&$filter=listingType eq 'Therapist'
 "Coaching:Development coaching", --> This doesn't return as a facet.
 "Coaching:Executive coaching", -->This returns fine.

  "@search.facets": {
        "specialisms@odata.type": "#Collection(Microsoft.Azure.Search.V2016_09_01.QueryResultFacet)",
        "specialisms": [
            {
                "count": 5,
                "value": "Anxiety, depression and trauma:Depression"
            },
            {
                "count": 4,
                "value": "Addiction, self-harm and eating disorders:Obsessions"
            },
            {
                "count": 4,
                "value": "Anxiety, depression and trauma:Post-traumatic stress"
            },
            {
                "count": 4,
                "value": "Coaching:Executive coaching"
            },
            {
                "count": 4,
                "value": "Identity, culture and spirituality:Self esteem"
            },
            {
                "count": 4,
                "value": "Relationships, family and children:Pregnancy related issues"
            },
            {
                "count": 4,
                "value": "Stress and work:Redundancy"
            },
            {
                "count": 3,
                "value": "Addiction, self-harm and eating disorders:Eating disorders"
            },
            {
                "count": 3,
                "value": "Anxiety, depression and trauma:Bereavement"
            },
            {
                "count": 3,
                "value": "Anxiety, depression and trauma:Loss"
            }
        ]
    },

{
            "@search.score": 1,
            "contactId": "df394997-6e94-e711-80ed-3863bb34db00",
            "location": {
                "type": "Point",
                "coordinates": [
                    -2.58586,
                    51.47873
                ],
                "crs": {
                    "type": "name",
                    "properties": {
                        "name": "EPSG:4326"
                    }
                }
            },
            "profileImageUrl": "https://myprojectwebqa.blob.core.windows.net/profileimage/3e31457c-5113-4062-b960-30f038ce7bfc.jpg",
            "locationText": "Bristol",
            "listingType": "Therapist",
            "disabledAccess": true,
            "flexibleHours": true,
            "offersConcessionaryRates": false,
            "homeVisits": true,
            "howIWillWork": "<p>Some test data</p>",
            "specialisms": [
                "Health related issues:Asperger syndrome",
                "Health related issues:Chronic fatigue syndrome/ME",
                "Addiction, self-harm and eating disorders:Addictions",
                "Addiction, self-harm and eating disorders:Eating disorders",
                "Addiction, self-harm and eating disorders:Obsessions",
                "Anxiety, depression and trauma:Bereavement",
                "Anxiety, depression and trauma:Depression",
                "Anxiety, depression and trauma:Loss",
                "Coaching:Development coaching",
                "Coaching:Executive coaching",
                "Identity, culture and spirituality:Self esteem",
                "Identity, culture and spirituality:Sexuality",
                "Relationships, family and children:Infertility",
                "Relationships, family and children:Relationships",
                "Stress and work:Redundancy"
            ],
            "clientele": [
                "Adults",
                "Children",
                "Groups"
            ],
            "approaches": [
                "CBT",
                "Cognitive",
                "Psychoanalytic",
                "Psychosynthesis"
            ],
            "sessionTypes": [
                "Home visits",
                "Long-term face to face work"
            ],
            "hourlyRate": 50,
            "fullName": "Test Name",
            "id": "ZWUwNGIyNjYtYjQ5Ny1lNzExLTgwZTktMzg2M2JiMzY0MGI4"
        }
</code>```

Please see details below;

答:
For my case I have found out that by default the Azure Search Service returns 10 of the facets. That is why I couldn't see all my facets.

After updating my search query as follows, I have fixed my problem and now I can see all my facets in the search results - please see the facet bit updated to this; facet=specialisms, count:9999.

```<code> https://MYPROJECTNAME-search.search.windows.net/indexes/MYPROJECTNAME-directory-qa/docs?api-version=2016-09-01&$count=true&facet=specialisms, count:9999&facet=clientele, count:9999&$filter=listingType eq 'Therapist'
</code>```

For the Microsoft documentation, please see the following link.

"max # of facet terms; default is 10"

https://learn.microsoft.com/en-us/rest/api/searchservice/search-documents

Body:
When I use Microsoft.Azure.Search (v3.0.3)'s "SearchAsync" and "Search" methods to return the indexed items, the sdk doesn't return all the facets.

However; when I try the same thing using Postman, it returns all the facets correctly.

Could this be a bug of the sdk (I believe it is as a direct call to an sdk method doesn't return the all the facets correctly - but couldn't find any records about this possible bug)? If yes, is there a fix for this for the sdk? Any help is appreciated.

UPDATE:
After spending some more time, I have found out that the bug is not .NET SDK Specific.

Both .NET SDK and REST API appear to have this problem and none of them returns all the facets. Can you please tell me is there a known bug for this and what is the fix for it?

Please see the following example;

There must be 2 Coaching facets but only 1 is returning from the Azure Search Service.

The new search query(facet specialisms added)

https://MYPROJECT-search.search.windows.net/indexes/myproject-directory-qa/docs?api-version=2016-09-01&$count=true&facet=specialisms&$filter=listingType eq 'Therapist'
 "Coaching:Development coaching", --> This doesn't return as a facet.
 "Coaching:Executive coaching", -->This returns fine.

  "@search.facets": {
        "specialisms@odata.type": "#Collection(Microsoft.Azure.Search.V2016_09_01.QueryResultFacet)",
        "specialisms": [
            {
                "count": 5,
                "value": "Anxiety, depression and trauma:Depression"
            },
            {
                "count": 4,
                "value": "Addiction, self-harm and eating disorders:Obsessions"
            },
            {
                "count": 4,
                "value": "Anxiety, depression and trauma:Post-traumatic stress"
            },
            {
                "count": 4,
                "value": "Coaching:Executive coaching"
            },
            {
                "count": 4,
                "value": "Identity, culture and spirituality:Self esteem"
            },
            {
                "count": 4,
                "value": "Relationships, family and children:Pregnancy related issues"
            },
            {
                "count": 4,
                "value": "Stress and work:Redundancy"
            },
            {
                "count": 3,
                "value": "Addiction, self-harm and eating disorders:Eating disorders"
            },
            {
                "count": 3,
                "value": "Anxiety, depression and trauma:Bereavement"
            },
            {
                "count": 3,
                "value": "Anxiety, depression and trauma:Loss"
            }
        ]
    },

{
            "@search.score": 1,
            "contactId": "df394997-6e94-e711-80ed-3863bb34db00",
            "location": {
                "type": "Point",
                "coordinates": [
                    -2.58586,
                    51.47873
                ],
                "crs": {
                    "type": "name",
                    "properties": {
                        "name": "EPSG:4326"
                    }
                }
            },
            "profileImageUrl": "https://myprojectwebqa.blob.core.windows.net/profileimage/3e31457c-5113-4062-b960-30f038ce7bfc.jpg",
            "locationText": "Bristol",
            "listingType": "Therapist",
            "disabledAccess": true,
            "flexibleHours": true,
            "offersConcessionaryRates": false,
            "homeVisits": true,
            "howIWillWork": "
Some test data
",
            "specialisms": [
                "Health related issues:Asperger syndrome",
                "Health related issues:Chronic fatigue syndrome/ME",
                "Addiction, self-harm and eating disorders:Addictions",
                "Addiction, self-harm and eating disorders:Eating disorders",
                "Addiction, self-harm and eating disorders:Obsessions",
                "Anxiety, depression and trauma:Bereavement",
                "Anxiety, depression and trauma:Depression",
                "Anxiety, depression and trauma:Loss",
                "Coaching:Development coaching",
                "Coaching:Executive coaching",
                "Identity, culture and spirituality:Self esteem",
                "Identity, culture and spirituality:Sexuality",
                "Relationships, family and children:Infertility",
                "Relationships, family and children:Relationships",
                "Stress and work:Redundancy"
            ],
            "clientele": [
                "Adults",
                "Children",
                "Groups"
            ],
            "approaches": [
                "CBT",
                "Cognitive",
                "Psychoanalytic",
                "Psychosynthesis"
            ],
            "sessionTypes": [
                "Home visits",
                "Long-term face to face work"
            ],
            "hourlyRate": 50,
            "fullName": "Test Name",
            "id": "ZWUwNGIyNjYtYjQ5Ny1lNzExLTgwZTktMzg2M2JiMzY0MGI4"
        }

Please see details below;

Body:
For my case I have found out that by default the Azure Search Service returns 10 of the facets. That is why I couldn't see all my facets.

After updating my search query as follows, I have fixed my problem and now I can see all my facets in the search results - please see the facet bit updated to this; facet=specialisms, count:9999.

 https://MYPROJECTNAME-search.search.windows.net/indexes/MYPROJECTNAME-directory-qa/docs?api-version=2016-09-01&$count=true&facet=specialisms, count:9999&facet=clientele, count:9999&$filter=listingType eq 'Therapist'

For the Microsoft documentation, please see the following link.

"max # of facet terms; default is 10"

https://learn.microsoft.com/en-us/rest/api/searchservice/search-documents


问:
numpy.ndarray: converting to a "normal" class
[Python 3]

I like ndarray but I find it annoying to use.

Here's one problem I face. I want to write class Array that will inherit much of the functionality of ndarray, but has only one way to be instantiated: as a zero-filled array of a certain size. I was hoping to write:

```<code>class Array(numpy.ndarray):
  def __init__(size):
    # What do here?
</code>```

I'd like to call super().__init__ with some parameters to create a zero-filled array, but it won't work since ndarray uses a global function numpy.zeros (rather than a constructor) to create a zero-filled array.

Questions:

Why does ndarray use global (module) functions instead of constructors in many cases? It is a big annoyance if I'm trying to reuse them in an object-oriented setting.

What's the best way to define class Array that I need? Should I just manually populate ndarray with zeroes, or is there any way to reuse the zeros function?

答:
Inheritance of ndarray is little bit tricky. ndarray does not even have method __init(self, )___, so it can't be called from subclass, but there are reasons for that. Please see numpy documentation of subclassing.

By the way could you be more specific of your particular needs? It's still quite easy to cook up a class (utilizing ndarray) for your own needs, but a subclass of ndarray to pass all the numpy machinery is quite different issue.

It seems that I can't comment my own post, odd

@Philipp: It will be called by Python, but not by numpy. There are three ways to instantiate ndarray, and the guidelines how to handle all cases is given on that doc.

Body:
[Python 3]

I like ndarray but I find it annoying to use.

Here's one problem I face. I want to write class Array that will inherit much of the functionality of ndarray, but has only one way to be instantiated: as a zero-filled array of a certain size. I was hoping to write:

class Array(numpy.ndarray):
  def __init__(size):
    # What do here?

I'd like to call super().__init__ with some parameters to create a zero-filled array, but it won't work since ndarray uses a global function numpy.zeros (rather than a constructor) to create a zero-filled array.

Questions:

Why does ndarray use global (module) functions instead of constructors in many cases? It is a big annoyance if I'm trying to reuse them in an object-oriented setting.

What's the best way to define class Array that I need? Should I just manually populate ndarray with zeroes, or is there any way to reuse the zeros function?


问:
Pass Array Into View Codeigniter Mikrotik
```<code>Array ( [0] => Array ( [.id] => *0 [name] => default [as] => 64578 [router-id] => 0.0.0.0 [redistribute-connected] => false [redistribute-static] => false [redistribute-rip] => false [redistribute-ospf] => false [redistribute-other-bgp] => false [out-filter] => [client-to-client-reflection] => true [ignore-as-path-len] => false [routing-table] => [default] => true [disabled] => false ) )
</code>```

how To loop and pass array above into the view in Codeigniter, please help !

From Comment.

```<code>if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true) {

    $this->routerosapi->write("/interface/eoip/print",false);

    $READ = $this->routerosapi->read(false);

    $data['eoip'] = $this->routerosapi->parseResponse($READ);

    $this->load->view('mikrotik/interface_eoip', $data);

    // $this->mikrotik_model->insert_pool($data);

}
</code>```

答:
Well, let's assume for a moment that you store your array to a variable called $myArray. You could then just do the following:

```<code>$data["myArray"] = $myArray;
$this->load->view("path_to_your_view", $data);
</code>```

The second parameter is sent to you view but it is exploded and every named index in the array becomes it's own variable in the view. So, in the view, you could just:

```<code>foreach($myArray as $key=>$value){
    echo "<p>$key has a value of $value.</p>";
}
</code>```

That's all there is to it. It's pretty simple...

Body:
Array ( [0] => Array ( [.id] => *0 [name] => default [as] => 64578 [router-id] => 0.0.0.0 [redistribute-connected] => false [redistribute-static] => false [redistribute-rip] => false [redistribute-ospf] => false [redistribute-other-bgp] => false [out-filter] => [client-to-client-reflection] => true [ignore-as-path-len] => false [routing-table] => [default] => true [disabled] => false ) )

how To loop and pass array above into the view in Codeigniter, please help !

From Comment.

if ($this->mikrotikext->mikrotik_connect($ip,$username,$password,$port) == true) {

    $this->routerosapi->write("/interface/eoip/print",false);

    $READ = $this->routerosapi->read(false);

    $data['eoip'] = $this->routerosapi->parseResponse($READ);

    $this->load->view('mikrotik/interface_eoip', $data);

    // $this->mikrotik_model->insert_pool($data);

}

Body:
Well, let's assume for a moment that you store your array to a variable called $myArray. You could then just do the following:

$data["myArray"] = $myArray;
$this->load->view("path_to_your_view", $data);

The second parameter is sent to you view but it is exploded and every named index in the array becomes it's own variable in the view. So, in the view, you could just:

foreach($myArray as $key=>$value){
    echo "<p>$key has a value of $value.</p>";
}

That's all there is to it. It's pretty simple...


问:
Compute the square root of 3 in C++
How can I compute the square root of 3 in C++ using the following relation?

Here is what I tried:

```<code>#include <iostream>
#include <cmath>

int main(void)
{
    double prevRes(1);
    double res(1 + 1./2);
    short i(2);

    while (abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;

        res = i + 1 / res;

        i = 3 - i;
    }

    std::cout << res << std::endl;

    return 0;
}
</code>```

The program runs forever.

答:
Use the built in sqrt function.</p>

```<code>#include <cstdio>
#include <cmath>

int main ()
{
    double param, result;
    param = 1024.0;
    result = sqrt (param);
    printf ("sqrt(%f) = %f\n", param, result );
    return 0;
}
</code>```

Title: Compute the square root of 3 in C++

Body:
How can I compute the square root of 3 in C++ using the following relation?

Here is what I tried:

#include <iostream>
#include <cmath>

int main(void)
{
    double prevRes(1);
    double res(1 + 1./2);
    short i(2);

    while (abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;

        res = i + 1 / res;

        i = 3 - i;
    }

    std::cout << res << std::endl;

    return 0;
}

The program runs forever.

Body:
Use the built in sqrt function.

#include <cstdio>
#include <cmath>

int main ()
{
    double param, result;
    param = 1024.0;
    result = sqrt (param);
    printf ("sqrt(%f) = %f\n", param, result );
    return 0;
}


问:
Mac terminal : trying to add to /etc/shells
This one works

```<code>$ cat /etc/shells
# List of acceptable shells for chpass(1).
# Ftpd will not allow users to connect who are not using
# one of these shells.

/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh
</code>```

But this one does not :

```<code>sudo -s 'echo /usr/local/bin/zsh >> /etc/shells'
/bin/bash: echo /usr/local/bin/zsh >> /etc/shells: No such file or directory
</code>```

答:
The only thing you really need sudo for is to open the protected file for writing. You can use the tee command to append to the file.

```<code>echo /usr/local/bin/zsh | sudo tee -a /etc/shells > /dev/null
</code>```

Body:
This one works

$ cat /etc/shells
# List of acceptable shells for chpass(1).
# Ftpd will not allow users to connect who are not using
# one of these shells.

/bin/bash
/bin/csh
/bin/ksh
/bin/sh
/bin/tcsh
/bin/zsh

But this one does not :

sudo -s 'echo /usr/local/bin/zsh >> /etc/shells'
/bin/bash: echo /usr/local/bin/zsh >> /etc/shells: No such file or directory

Body:
The only thing you really need sudo for is to open the protected file for writing. You can use the tee command to append to the file.

echo /usr/local/bin/zsh | sudo tee -a /etc/shells > /dev/null


问:
MATLAB index within groups
Given a vector A of group numbers (such as the one returned by findgroups), how to return a vector B of the same length containing indices of elements within groups of A?

For example, if A = [1 1 1 2 2 2 1 1 2 2] then B = [1 2 3 1 2 3 4 5 4 5].

Add 1

My own solution to this is

```<code>s = splitapply(@(x) {x, [1:numel(x)]'}, [1:numel(A)]', A(:))
B(vertcat(s{:,1})) = vertcat(s{:,2})
</code>```

but it seems somewhat convoluted.

答:
Here's a way that avoids loops:</p>

```<code>s = bsxfun(@eq, A(:).', unique(A(:))); % Or, in recent versions, s = A==unique(A).';
t = cumsum(s,2);
B = reshape(t(s), size(A));
</code>```

Title: MATLAB index within groups

Body:
Given a vector A of group numbers (such as the one returned by findgroups), how to return a vector B of the same length containing indices of elements within groups of A?

For example, if A = [1 1 1 2 2 2 1 1 2 2] then B = [1 2 3 1 2 3 4 5 4 5].

Add 1

My own solution to this is

s = splitapply(@(x) {x, [1:numel(x)]'}, [1:numel(A)]', A(:))
B(vertcat(s{:,1})) = vertcat(s{:,2})

but it seems somewhat convoluted.

Body:
Here's a way that avoids loops:

s = bsxfun(@eq, A(:).', unique(A(:))); % Or, in recent versions, s = A==unique(A).';
t = cumsum(s,2);
B = reshape(t(s), size(A));


问:
Choose dynamically a property of the component
Consider the following simple code:

```<code>export class TestComponent {
    mobileMessage: string;
    private mobileValidationMessages:ISchemeObject = {
        required: "Mobile is required",
        pattern:  "Mobile format is not correct"
    }

    setMessage(controlName: string): void {
        const x = <any>(controlName + "Message");
        this[x] = "Something";
    }
}
</code>```

With the above I want to call setMessage() with any argument I like, e.g.
setMessage("mobile") and be able to change mobileMessage. However, Typescript is complaining and does not allow me to do that. How may I achieve that?

答:
You could restrict the string to keys of the class itself to make it more type safe</p>

```<code>export class TestComponent {

  mobileMessage: string

  setMessage(messageProp: keyof this): void {
      this[messageProp] = 'Something'
  }

  example(): void {
    this.setMessage('mobileMessage')
  }

}
</code>```

Body:
Consider the following simple code:

export class TestComponent {
    mobileMessage: string;
    private mobileValidationMessages:ISchemeObject = {
        required: "Mobile is required",
        pattern:  "Mobile format is not correct"
    }

    setMessage(controlName: string): void {
        const x = <any>(controlName + "Message");
        this[x] = "Something";
    }
}

With the above I want to call setMessage() with any argument I like, e.g.
setMessage("mobile") and be able to change mobileMessage. However, Typescript is complaining and does not allow me to do that. How may I achieve that?

Body:
You could restrict the string to keys of the class itself to make it more type safe

export class TestComponent {

  mobileMessage: string

  setMessage(messageProp: keyof this): void {
      this[messageProp] = 'Something'
  }

  example(): void {
    this.setMessage('mobileMessage')
  }

}


问:
Android set DatePicker to a certain date
I have 3 strings containing day, month and year values. For example:

```<code>String mday = "02";
String mmonth="07";
String myear="2013";
</code>```

I need to set the DatePicker in my activity to a month from the date above. I do not mean just add 1 to the mmonth value... in case of day 31 I would end up with an invalid date.
So I need some way to increment the date (the valid way) and set the DatePicker with it's value.
I am aware that setting the datePicker with Int values is done like this:

```<code>DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);
// where iYear,iMonth and iDay are integers
</code>```

But how do I obtain the integer values of day,month and year of an incremented DATE by one month?

So between the first values (strings) and final values of incremented date(integers) what are the steps that I must make?

I assume I would have to use a Calendar.
So my code should look like this:

```<code>Integer iYear, iMonth, iDay = 0;
String mday = "02";
String mmonth="07";
String myear="2013";

Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(myear), Integer.parseInt(mmonth), Integer.parseInt(mday));
cal.add(Calendar.MONTH, 1);
// here I should get the values from cal inside the iYear, iMonth, iDay, but I do not seem to succeed.

DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);
</code>```

if I do:

```<code>datepicker.init(cal.YEAR, cal.MONTH, cal.DATE, null);
</code>```

then application crashes.
What should I do?
How to set this incremented by a month date into my DatePicker?

UPDATE
I changed my test code to this:

```<code>    Calendar cal = Calendar.getInstance();
    cal.set(2013, 05, 23);
    cal.add(Calendar.MONTH, 1);

    int xxday = cal.get(Calendar.DATE);
    int xxmonth = cal.get(Calendar.MONTH);
    int xxyear = cal.get(Calendar.YEAR);

    datepicker.init(xxyear, xxmonth, xxday, null);
</code>```

but Now the datePicker is set to one month from NOW instead of one month from the wanted date So instead of (2013-06-23) I have (2013-09-23). I assume it's because of

```<code>    int xxmonth = cal.get(Calendar.MONTH);
</code>```

how can I get the real month from a Calendar cal; ?

答:
use this tuto to create your DatePickerDialog then use this code inside DatePickerDialog
https://developer.android.com/guide/topics/ui/dialogs.html</p>

```<code>@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String mday = "02";
    String mmonth="07";
    String myear="2013";
    //convert them to int
    int mDay=Integer.valueOf(mday);
    int mMonth=Integer.valueOf(mmonth);
    int mYear=Integer.valueOf(myear);

    return new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
            String d=convertToCompletDate(i2,i1,i);
            mListener.onDatePicked(d);

        }
    },mYear,mMonth,mDay);
}
</code>```

Body:
I have 3 strings containing day, month and year values. For example:

String mday = "02";
String mmonth="07";
String myear="2013";

I need to set the DatePicker in my activity to a month from the date above. I do not mean just add 1 to the mmonth value... in case of day 31 I would end up with an invalid date.
So I need some way to increment the date (the valid way) and set the DatePicker with it's value.
I am aware that setting the datePicker with Int values is done like this:

DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);
// where iYear,iMonth and iDay are integers

But how do I obtain the integer values of day,month and year of an incremented DATE by one month?

So between the first values (strings) and final values of incremented date(integers) what are the steps that I must make?

I assume I would have to use a Calendar.
So my code should look like this:

Integer iYear, iMonth, iDay = 0;
String mday = "02";
String mmonth="07";
String myear="2013";

Calendar cal = Calendar.getInstance();
cal.set(Integer.parseInt(myear), Integer.parseInt(mmonth), Integer.parseInt(mday));
cal.add(Calendar.MONTH, 1);
// here I should get the values from cal inside the iYear, iMonth, iDay, but I do not seem to succeed.

DatePicker datepicker = (DatePicker) findViewById(R.id.datePicker1);
datepicker.init(iYear, iMonth, iDay, null);

if I do:

datepicker.init(cal.YEAR, cal.MONTH, cal.DATE, null);

then application crashes.
What should I do?
How to set this incremented by a month date into my DatePicker?

UPDATE
I changed my test code to this:

    Calendar cal = Calendar.getInstance();
    cal.set(2013, 05, 23);
    cal.add(Calendar.MONTH, 1);

    int xxday = cal.get(Calendar.DATE);
    int xxmonth = cal.get(Calendar.MONTH);
    int xxyear = cal.get(Calendar.YEAR);

    datepicker.init(xxyear, xxmonth, xxday, null);

but Now the datePicker is set to one month from NOW instead of one month from the wanted date So instead of (2013-06-23) I have (2013-09-23). I assume it's because of

    int xxmonth = cal.get(Calendar.MONTH);

how can I get the real month from a Calendar cal; ?

Body:
use this tuto to create your DatePickerDialog then use this code inside DatePickerDialog
https://developer.android.com/guide/topics/ui/dialogs.html

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    String mday = "02";
    String mmonth="07";
    String myear="2013";
    //convert them to int
    int mDay=Integer.valueOf(mday);
    int mMonth=Integer.valueOf(mmonth);
    int mYear=Integer.valueOf(myear);

    return new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
            String d=convertToCompletDate(i2,i1,i);
            mListener.onDatePicked(d);

        }
    },mYear,mMonth,mDay);
}


问:
How can I keep a container running on Kubernetes?
I'm now trying to run a simple container with shell (/bin/bash) on a Kubernetes cluster.

I thought that there was a way to keep a container running on a Docker container by using pseudo-tty and detach option (-td option on docker run command).

For example,

```<code>$ sudo docker run -td ubuntu:latest
</code>```

Is there an option like this in Kubernetes?

I've tried running a container by using a kubectl run-container command like:

```<code>kubectl run-container test_container ubuntu:latest --replicas=1
</code>```

But the container exits for a few seconds (just like launching with the docker run command without options I mentioned above). And ReplicationController launches it again repeatedly.

Is there a way to keep a container running on Kubernetes like the -td options in the docker run command?

答: In my case, a pod with an initContainer failed to initialize. Running docker ps -a and then docker logs exited-container-id-here gave me a log message which kubectl logs podname didn't display. Mystery solved :-)

Body:
I'm now trying to run a simple container with shell (/bin/bash) on a Kubernetes cluster.

I thought that there was a way to keep a container running on a Docker container by using pseudo-tty and detach option (-td option on docker run command).

For example,

$ sudo docker run -td ubuntu:latest

Is there an option like this in Kubernetes?

I've tried running a container by using a kubectl run-container command like:

kubectl run-container test_container ubuntu:latest --replicas=1

But the container exits for a few seconds (just like launching with the docker run command without options I mentioned above). And ReplicationController launches it again repeatedly.

Is there a way to keep a container running on Kubernetes like the -td options in the docker run command?


问:
Java preprocess phase
I'm writing a Java application that needs a lot of static data that is stored in many enum types. Since I would like an user-friendly way to customize this data using for example xml or json files but I'm not allowed to do it directly with enums I was looking for a way to elegantly do it.

Maybe a good solution would be to have a separate java program that reads the xml files and produces the java sources that are then compiled with the remaining part of the sources. My doubs is how to automatize this process in a stand alone way (eg ant?) and how to integrate it seamlessly with eclipse so that it is autOmatically done when I'm working with the project.. Does anything similar to what I'm looking already exists? Any suggestion to solve my problem?

Thanks!

答:
Create a project whose sole job is to generate java from your sources.
Make sure that the generation phase is done by Ant.

Now, wrap this project into eclipse and use a custom ant builder, that calls the target in your already existing build.xml.

This is a standard part of our dev infrastructure, so this definitely works.

Title: Java preprocess phase


问:
displaying a vector of deques in columns
I'm trying to display a vector of deques (std::vector<std::deque<int>> v) like this

```<code>v.at(0).at(0) v.at(1).at(0) v.at(2).at(0) v.at(3).at(0)
v.at(0).at(1) v.at(1).at(1) v.at(2).at(1) v.at(3).at(1)
v.at(0).at(2) v.at(1).at(2) v.at(2).at(2) v.at(3).at(2)
              v.at(1).at(3)               v.at(3).at(3)
                                          v.at(3).at(4)
</code>```

The first part of the vector is fixed at 7, the size of the actual columns are dynamic however depending on what the user chooses to do.

I was attempting something like

```<code>int row = 0;
int column;

for (column = 0; column < v.at(row).size(); column++){
      cout << "v["<< row <<"]["<< column << "]" << v.at(row).at(column) << "\t";
  while (row < v.size()){
    cout << endl;
    row++;
  }
}
</code>```

I'm getting errors like

```<code>libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
make: *** [Pile.h] Abort trap: 6
</code>```

Having one of those blah brain days. Can someone help me print this out the way I want it?

答:
Here is a demonstrative program that shows one of approaches to the task.

```<code>#include <iostream>
#include <iomanip>
#include <vector>
#include <deque>
#include <algorithm>

int main()
{
    std::vector<std::deque<int>> v =
    {
        { 0, 1, 2 },
        { 0, 1, 2, 3 },
        { 0, 1, 2 },
        { 0, 1, 2, 3, 4 }
    };

    size_t n = std::max_element( v.begin(), v.end(),
                                 []( const auto &x, const auto &y )
                                 {
                                    return x.size() < y.size();
                                 } )->size();

    for ( size_t i = 0; i < n; i++)
    {
        for ( size_t j = 0; j < v.size(); j++ )
        {
            std::cout << std::setw( 4 );
            if ( i < v[j].size() )
            {
                std::cout << v[j][i];
            }
            else
            {
                std::cout << "";
            }
        }

        std::cout << std::endl;
    }

    return 0;
}
</code>```

Its output is

```<code>   0   0   0   0
   1   1   1   1
   2   2   2   2
       3       3
               4
</code>```

Body:
I'm trying to display a vector of deques (std::vector<std::deque<int>> v) like this

v.at(0).at(0) v.at(1).at(0) v.at(2).at(0) v.at(3).at(0)
v.at(0).at(1) v.at(1).at(1) v.at(2).at(1) v.at(3).at(1)
v.at(0).at(2) v.at(1).at(2) v.at(2).at(2) v.at(3).at(2)
              v.at(1).at(3)               v.at(3).at(3)
                                          v.at(3).at(4)

The first part of the vector is fixed at 7, the size of the actual columns are dynamic however depending on what the user chooses to do.

I was attempting something like

int row = 0;
int column;

for (column = 0; column < v.at(row).size(); column++){
      cout << "v["<< row <<"]["<< column << "]" << v.at(row).at(column) << "\t";
  while (row < v.size()){
    cout << endl;
    row++;
  }
}

I'm getting errors like

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
make: *** [Pile.h] Abort trap: 6

Having one of those blah brain days. Can someone help me print this out the way I want it?

Body:
Here is a demonstrative program that shows one of approaches to the task.

#include <iostream>
#include <iomanip>
#include <vector>
#include <deque>
#include <algorithm>

int main()
{
    std::vector<std::deque<int>> v =
    {
        { 0, 1, 2 },
        { 0, 1, 2, 3 },
        { 0, 1, 2 },
        { 0, 1, 2, 3, 4 }
    };

    size_t n = std::max_element( v.begin(), v.end(),
                                 []( const auto &x, const auto &y )
                                 {
                                    return x.size() < y.size();
                                 } )->size();

    for ( size_t i = 0; i < n; i++)
    {
        for ( size_t j = 0; j < v.size(); j++ )
        {
            std::cout << std::setw( 4 );
            if ( i < v[j].size() )
            {
                std::cout << v[j][i];
            }
            else
            {
                std::cout << "";
            }
        }

        std::cout << std::endl;
    }

    return 0;
}

Its output is

   0   0   0   0
   1   1   1   1
   2   2   2   2
       3       3
               4


问:
How to fix Error: laravel.log could not be opened?
I'm pretty new at laravel, in fact and I'm trying to create my very first project. for some reason I keep getting this error (I haven't even started coding yet)

```<code>Error in exception handler: The stream or file "/var/www/laravel/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/laravel/bootstrap/compiled.php:8423
</code>```

I've read this has something to do with permissions but chmod -R 775 storage didn't help at all.

答:
I wasn't too keen on changing my folder permissions to 777. Here's how I went about fixing this issue.

First, I changed the user who is running the web server on my local machine(I run nginx, but the principles apply everywhere):

```<code>$> sudo vim /etc/nginx/nginx.conf
user <my_user> #inside nginx.conf
service nginx reload
</code>```

Afterwards, I created another index.php file under the public/ folder to find out who was running my php-fpm version and where I would go about changing that:

```<code><?php
phpinfo();
?>
</code>```

Reloading the page, I found out that www-data was the user(under the environment section). I also found out I was running php 7.1. I proceeded to change the user:

```<code>$> sudo vim /etc/php/7.0/fpm/pool.d/www.conf
#Look for www-data or the following variables: user, group, listen.user, listen.group.
</code>```

Finally, I gave the following permissions to folders:

```<code>sudo chmod -R 775 ./storage/
</code>```

Now, I made sure that I was the owner of the folders by using a simple:

```<code>ls -al
</code>```

If you set the server and php-fpm users to yourself and the folders are owned by root for example, then you will keep encountering this issue. This can happen if you did a sudo laravel new <project> as root. In that case, make sure you use a recursive chown command on your project to change the user:group settings. In most default cases, www-data is the main setting for the server and php, in that case it's a matter of making sure the folder isn't out of www-data's reach.

My project is setup in my home directory. On Ubuntu 16.04 and Laravel 5.5.

Body:
I'm pretty new at laravel, in fact and I'm trying to create my very first project. for some reason I keep getting this error (I haven't even started coding yet)

Error in exception handler: The stream or file "/var/www/laravel/app/storage/logs/laravel.log" could not be opened: failed to open stream: Permission denied in /var/www/laravel/bootstrap/compiled.php:8423

I've read this has something to do with permissions but chmod -R 775 storage didn't help at all.

Body:
I wasn't too keen on changing my folder permissions to 777. Here's how I went about fixing this issue.

First, I changed the user who is running the web server on my local machine(I run nginx, but the principles apply everywhere):

$> sudo vim /etc/nginx/nginx.conf
user <my_user> #inside nginx.conf
service nginx reload

Afterwards, I created another index.php file under the public/ folder to find out who was running my php-fpm version and where I would go about changing that:

<?php
phpinfo();
?>

Reloading the page, I found out that www-data was the user(under the environment section). I also found out I was running php 7.1. I proceeded to change the user:

$> sudo vim /etc/php/7.0/fpm/pool.d/www.conf
#Look for www-data or the following variables: user, group, listen.user, listen.group.

Finally, I gave the following permissions to folders:

sudo chmod -R 775 ./storage/

Now, I made sure that I was the owner of the folders by using a simple:

ls -al

If you set the server and php-fpm users to yourself and the folders are owned by root for example, then you will keep encountering this issue. This can happen if you did a sudo laravel new <project> as root. In that case, make sure you use a recursive chown command on your project to change the user:group settings. In most default cases, www-data is the main setting for the server and php, in that case it's a matter of making sure the folder isn't out of www-data's reach.

My project is setup in my home directory. On Ubuntu 16.04 and Laravel 5.5.


答:
A solution can be using a loop to replace the values in A:

```<code>c = unique(A);
B= A;
for (idx = c)
    f = find(A == idx);
    B(f) = 1:length(f);
 end
</code>```

Title: MATLAB index within groups

Body:
A solution can be using a loop to replace the values in A:

c = unique(A);
B= A;
for (idx = c)
    f = find(A == idx);
    B(f) = 1:length(f);
 end


问:
How to prevent duplicate results with angularFire
I have firebase db like this :

```<code>    "cardsList" : {
            "tok_1BVGrNCM8UWO9kaul5P0MoQa" : {
              "cardHolder" : "John",
              "expMonth" : 12,
              "expYear" : 2020,
              "number" : "42** **** **** **43",
              "pin" : 1234
            },
              "tok_7BTErNCM8UWO9kaul5P0MoQa" : {
              "cardHolder" : "Eliott",
              "expMonth" : 12,
              "expYear" : 2020,
              "number" : "44** **** **** **49",
              "pin" : 1234
            }
}
</code>```

I get the results for each card in an array using this :

```<code>this.firebaseProvider.list('patientList/'+this.profileMember.idPatient+'/cardsList')
    .subscribe(cards=> cards.forEach(card=> {
      console.log(card.number)
      this.cardsList.push({'number': card.number})
      }))
</code>```

In my html I show the result with :

```<code><div *ngFor="let card of cardsList">
{{card.number}}
</div>
</code>```

The problem is that I get duplicate result each time one value on the database is updated (ex: carHolder is updated)

Ex :
BEFORE THE UPDATE

```<code>42** **** **** **43
44** **** **** **49
</code>```

AFTER THE UPDATE

```<code>42** **** **** **43
44** **** **** **49
42** **** **** **43
</code>```

How to prevent this?

Any help is welcome.

Alex.

答:
You can simply avoid it just by converting observable to promise like below.

```<code>import 'rxjs/add/operator/toPromise';

this.firebaseProvider.list('patientList/'+this.profileMember.idPatient+'/cardsList').toPromise().then(cards=> cards.forEach(card=> {
    this.cardsList.push({'number': card.number})
}))
</code>```

Body:
I have firebase db like this :

    "cardsList" : {
            "tok_1BVGrNCM8UWO9kaul5P0MoQa" : {
              "cardHolder" : "John",
              "expMonth" : 12,
              "expYear" : 2020,
              "number" : "42** **** **** **43",
              "pin" : 1234
            },
              "tok_7BTErNCM8UWO9kaul5P0MoQa" : {
              "cardHolder" : "Eliott",
              "expMonth" : 12,
              "expYear" : 2020,
              "number" : "44** **** **** **49",
              "pin" : 1234
            }
}

I get the results for each card in an array using this :

this.firebaseProvider.list('patientList/'+this.profileMember.idPatient+'/cardsList')
    .subscribe(cards=> cards.forEach(card=> {
      console.log(card.number)
      this.cardsList.push({'number': card.number})
      }))

In my html I show the result with :

{{card.number}}

The problem is that I get duplicate result each time one value on the database is updated (ex: carHolder is updated)

Ex :
BEFORE THE UPDATE

42** **** **** **43
44** **** **** **49

AFTER THE UPDATE

42** **** **** **43
44** **** **** **49
42** **** **** **43

How to prevent this?

Any help is welcome.

Alex.

Body:
You can simply avoid it just by converting observable to promise like below.

import 'rxjs/add/operator/toPromise';

this.firebaseProvider.list('patientList/'+this.profileMember.idPatient+'/cardsList').toPromise().then(cards=> cards.forEach(card=> {
    this.cardsList.push({'number': card.number})
}))


问:
Old value kept on ngModel change
Dealing with a table which need a filter by data, I've created the following screen:

What I need is to remove values outside the date start criteria of the filter so I've done this on my EsightComponent:

```<code>startDateChange($event, dt, col) {
  this.loading = true;
  this.eSightEndSubscription = this.eSightService.getByContractId(this.contractId).subscribe(
    res => {
      const filterResults = this.reads.filter((read) => {
        const iteratorDate = new Date(20 + read.timestamp.slice(-2), read.timestamp.slice(0, 2) - 1, 1);
        console.log(this.startDateFilter);
        return iteratorDate <= this.startDateFilter;
      }, this);

      this.processRightAnswer(filterResults);
    },
    error => {
      console.log('ERROR');
    },
    () => {
      this.loading = false;
    });
}
</code>```

And this is my view:

```<code><h4>Lecturas eSight <small>contrato {{ contractId }}</small></h4>

<p-calendar dateFormat="mm/yy" [(ngModel)]="startDateFilter" (onBlur)="startDateChange($event, dt, col)"></p-calendar>
<p-calendar [(ngModel)]="endDateFilter" (change)="startDateChange($event, dt, col)"></p-calendar>

<p-dataTable [value]="reads" [rows]="30" [paginator]="true" [loading]="loading" selectionMode="single" scrollable="true" #dt>
  <ng-container *ngFor="let col of cols; let i = index;">
    <p-column [field]="col.field" [header]="col.header" *ngIf="i === 0" [style]="{ 'width': '170px' }">
    </p-column>
    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length <= 10" [style]="{ 'width': '55px' }"></p-column>
    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length > 10" [style]="{ 'width': '170px' }"></p-column>
  </ng-container>
</p-dataTable>

<button class="btn btn-warning" (click)="onReturn()">Atrás</button>
</code>```

Based on tho way data binding principle, this.startDateFilter should catch changes on it, but it doesn't. If I select a date on the calendar, it always displays the previous value, not the selected new one. That is seen on console.log(this.startDateFilter) line.

I've checked I could use ngOnChanges to catch changes and to have access to both old and new values, but this hook just works for @Input() values and this is not my case.

I wish to retrieve the value selected by the user and not an old one.

Thanks.

答:
Based on DmitriyKhirniy's answer (thanks a lot!!!), what finally works is:</p>
```<code>$event.target.value
</code>```

Title: Old value kept on ngModel change

Body:
Dealing with a table which need a filter by data, I've created the following screen:

What I need is to remove values outside the date start criteria of the filter so I've done this on my EsightComponent:

startDateChange($event, dt, col) {
  this.loading = true;
  this.eSightEndSubscription = this.eSightService.getByContractId(this.contractId).subscribe(
    res => {
      const filterResults = this.reads.filter((read) => {
        const iteratorDate = new Date(20 + read.timestamp.slice(-2), read.timestamp.slice(0, 2) - 1, 1);
        console.log(this.startDateFilter);
        return iteratorDate <= this.startDateFilter;
      }, this);

      this.processRightAnswer(filterResults);
    },
    error => {
      console.log('ERROR');
    },
    () => {
      this.loading = false;
    });
}

And this is my view:

Lecturas eSight contrato {{ contractId }}

  <ng-container *ngFor="let col of cols; let i = index;">

    <p-column [field]="col.field" [header]="col.header" *ngIf="col.header.length <= 10" [style]="{ 'width': '55px' }">

 10" [style]="{ 'width': '170px' }">

  </ng-container>

<button class="btn btn-warning" (click)="onReturn()">Atrás</button>

Based on tho way data binding principle, this.startDateFilter should catch changes on it, but it doesn't. If I select a date on the calendar, it always displays the previous value, not the selected new one. That is seen on console.log(this.startDateFilter) line.

I've checked I could use ngOnChanges to catch changes and to have access to both old and new values, but this hook just works for @Input() values and this is not my case.

I wish to retrieve the value selected by the user and not an old one.

Thanks.

Body:
Based on DmitriyKhirniy's answer (thanks a lot!!!), what finally works is:

$event.target.value


问:
Public property of private class
I have a NavigationModel class which implements site navigation. Internally there is a private implementation of NavigationNode which I want to be able to declare within the NavigationModel but not outside of it. How would I accomplish this? When I do the following:

```<code>public class NavigationModel
{
    public List<NavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode
    {

    }
}
</code>```

The property tells me:

Inconsistent accessibility: property type
  'List' is less accessible than
  property 'NavigationModel.NavigationNodes'

答: NavigationNode needs to be public for this to work properly. Making it public still keeps the declaration internal to the containing class NavigationModel yet classes outside NavigationModel can reference it. </p>

Title: Public property of private class

Body:
I have a NavigationModel class which implements site navigation. Internally there is a private implementation of NavigationNode which I want to be able to declare within the NavigationModel but not outside of it. How would I accomplish this? When I do the following:

public class NavigationModel
{
    public List<NavigationNode> NavigationNodes { get; set; }
    public NavigationModel()
    {

    }

    private class NavigationNode
    {

    }
}

The property tells me:

Inconsistent accessibility: property type
  'List' is less accessible than
  property 'NavigationModel.NavigationNodes'


问:
Corda: Cannot connect to server(s)
I have downloaded the corda example project: spring-observable-stream and try to run it from IntelliJ. While started the server, It gives error:

W 11:01:55 1 AnnotationConfigEmbeddedWebApplicationContext.refresh - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nodeRPCConnection' defined in file [C:\Corda\spring-observable-stream\server\out\production\classes\net\corda\server\NodeRPCConnection.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [net.corda.server.NodeRPCConnection]: Constructor threw exception; nested exception is ActiveMQNotConnectedException[errorType=NOT_CONNECTED message=AMQ119007: Cannot connect to server(s). Tried with all available servers.]

答: You need to start the nodes before you start the servers. See the instructions here: https://docs.corda.net/tutorial-cordapp.html#running-the-example-cordapp.</p>

Title: Corda: Cannot connect to server(s)


答: Have you considered including the XML files in your jar, and loading them on startup into maps that use the enum as a key?</p>

Title: Java preprocess phase

Body:
I'm writing a Java application that needs a lot of static data that is stored in many enum types. Since I would like an user-friendly way to customize this data using for example xml or json files but I'm not allowed to do it directly with enums I was looking for a way to elegantly do it.

Maybe a good solution would be to have a separate java program that reads the xml files and produces the java sources that are then compiled with the remaining part of the sources. My doubs is how to automatize this process in a stand alone way (eg ant?) and how to integrate it seamlessly with eclipse so that it is autOmatically done when I'm working with the project.. Does anything similar to what I'm looking already exists? Any suggestion to solve my problem?

Thanks!


问:
Measuring elapsed time with the Time module
With the Time module in python is it possible to measure elapsed time? If so, how do I do that? </p>

<p>I need to do this so that if the cursor has been in a widget for a certain duration an event happens.  </p>

答:
For the best measure of elapsed time (since Python 3.3), use time.perf_counter().

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.

Update for Python 3.8

time.clock is now gone.

Body:
With the Time module in python is it possible to measure elapsed time? If so, how do I do that?

I need to do this so that if the cursor has been in a widget for a certain duration an event happens.


问:
Add View - Cannot retrieve Metadata
I am still new to MVC, but I am starting to get a feel for the general picture however I still mixup things like namespace, or using and I THINK that may be the case here where I am mis-referencing something.

Question: I am trying to add an EmployeeInfo View, with a List template, with Model class: EmployeeInfo, with data context class: MoviesEntities

The auto-generation will not execute. When I right-click in Controller's method EmployeeInfo. I select the option "Add View", fill in the information, then hit add and during the scaffolding load screen it gives me the error as follows.

There was an error running the selected code generator: 'Unable to
  retrieve metadata for 'WebApplication2.Models.EmployeeInfo'.'

My controller

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Entities;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class MoviesController : Controller
    {
        private MoviesEntities db = new MoviesEntities();

        // GET: /Movies/
        public ActionResult Index()
        {
            return View(db.Movies.ToList());
        }

        public ActionResult EmployeeInfo()
        {
            var query =
            from m in db.Movies
            join me in db.MovieEmployees
            on m.ID equals me.movieID
            join e in db.Employees
            on me.employeeID equals e.ID
            join r in db.Roles
            on me.roleID equals r.ID

            select new EmployeeInfo() {Name = e.Name, Role = r.RoleType, Birthday = e.Birthday };

            return View(query.Distinct().ToList());
          }
    }
}
</code>```

My context

```<code>//------------------------------------------------------------------------------
// <auto-generated> Built from database Movie </auto-generated>
//------------------------------------------------------------------------------

namespace WebApplication2.Entities
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using movieLayer;
    using WebApplication2.Models;

    public partial class MoviesEntities : DbContext
    {
        public MoviesEntities()
            : base("name=MoviesEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Employee> Employees { get; set; }
        public virtual DbSet<Location> Locations { get; set; }
        public virtual DbSet<Movie> Movies { get; set; }
        public virtual DbSet<MovieEmployee> MovieEmployees { get; set; }
        public virtual DbSet<Role> Roles { get; set; }
        public virtual DbSet<Show> Shows { get; set; }
        public virtual DbSet<sysdiagram> sysdiagrams { get; set; }

        public System.Data.Entity.DbSet<WebApplication2.Models.EmployeeInfo> EmployeeInfoes { get; set; }
    }
}
</code>```

Model of EmployeeInfo:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication2.Models

{
    public class EmployeeInfo
    {

        public EmployeeInfo() { }

        public string Name { get; set; }
        public string Role { get; set; }
        public DateTime Birthday { get; set; }
    }
}
</code>```

答:
Check your DataContextClass Option in Add View Pop winow and then correct the ConnectionString when adding your View from Controller

Refer Screenshot
.

Title: Add View - Cannot retrieve Metadata

Body:
I am still new to MVC, but I am starting to get a feel for the general picture however I still mixup things like namespace, or using and I THINK that may be the case here where I am mis-referencing something.

Question: I am trying to add an EmployeeInfo View, with a List template, with Model class: EmployeeInfo, with data context class: MoviesEntities

The auto-generation will not execute. When I right-click in Controller's method EmployeeInfo. I select the option "Add View", fill in the information, then hit add and during the scaffolding load screen it gives me the error as follows.

There was an error running the selected code generator: 'Unable to
  retrieve metadata for 'WebApplication2.Models.EmployeeInfo'.'

My controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using WebApplication2.Entities;
using WebApplication2.Models;

namespace WebApplication2.Controllers
{
    public class MoviesController : Controller
    {
        private MoviesEntities db = new MoviesEntities();

        // GET: /Movies/
        public ActionResult Index()
        {
            return View(db.Movies.ToList());
        }

        public ActionResult EmployeeInfo()
        {
            var query =
            from m in db.Movies
            join me in db.MovieEmployees
            on m.ID equals me.movieID
            join e in db.Employees
            on me.employeeID equals e.ID
            join r in db.Roles
            on me.roleID equals r.ID

            select new EmployeeInfo() {Name = e.Name, Role = r.RoleType, Birthday = e.Birthday };

            return View(query.Distinct().ToList());
          }
    }
}

My context

//------------------------------------------------------------------------------
// <auto-generated> Built from database Movie </auto-generated>
//------------------------------------------------------------------------------

namespace WebApplication2.Entities
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;
    using movieLayer;
    using WebApplication2.Models;

    public partial class MoviesEntities : DbContext
    {
        public MoviesEntities()
            : base("name=MoviesEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Employee> Employees { get; set; }
        public virtual DbSet<Location> Locations { get; set; }
        public virtual DbSet<Movie> Movies { get; set; }
        public virtual DbSet<MovieEmployee> MovieEmployees { get; set; }
        public virtual DbSet<Role> Roles { get; set; }
        public virtual DbSet<Show> Shows { get; set; }
        public virtual DbSet<sysdiagram> sysdiagrams { get; set; }

        public System.Data.Entity.DbSet<WebApplication2.Models.EmployeeInfo> EmployeeInfoes { get; set; }
    }
}

Model of EmployeeInfo:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WebApplication2.Models

{
    public class EmployeeInfo
    {

        public EmployeeInfo() { }

        public string Name { get; set; }
        public string Role { get; set; }
        public DateTime Birthday { get; set; }
    }
}


问:
How to Query across multiple tables
I have the following DB. Is this a proper query to get the first name of the authors loaned by Members ? or is there a more efficient way ?

```<code>select M.MemberNo, A.FirstName
from Person.Members as M
INNER JOIN Booking.Loans as L
on M.MemberNo = L.MemberNo
INNER JOIN Article.Copies as C
on L.ISBN = C.ISBN and L.CopyNo = C.CopyNo
INNER JOIN Article.Items as I
on C.ISBN = I.ISBN
INNER JOIN Article.Titles as T
on I.TitleID = T.TitleID
INNER JOIN Article.TitleAuthors as TA
on T.TitleID = TA.TitleID
INNER JOIN Article.Authors as A
on TA.AuthorID = A.AuthorID
;
go
</code>```

答:
The most direct way to get the names of authors of books that are lent out to members would be like this:

Get member loans (Booking.Loans)

Get books for member loans (Article.Items)

Get authors for the books for member loans (Article.TitleAuthors)

Get first names for authors for the books for member loans (Article.Authors)

```<code>select L.MemberNo, A.FirstName
FROM Booking.Loans as L
INNER JOIN Article.Items as I
on L.ISBN = I.ISBN
INNER JOIN Article.TitleAuthors as TA
on I.TitleID = TA.TitleID
INNER JOIN Article.Authors as A
on TA.AuthorID = A.AuthorID
</code>```

The advantage to joining all the tables like you have your original query is to ensure that each intermediary table was INSERTed into or DELETEd from correctly.

For example, your original query wouldn't return any rows for a member if they had a loan (i.e. a row in the Loans table) but for some reason didn't have an entry in the Members table.  If you can assume that (or don't care if) there will always be a row in the Members table if there is a row in the Loans table, then you can exclude the join to Person.Members.

You can apply this same logic to the other intermediary tables (Member, Copies, Title) too, if needed.  If you need a specific piece of data from one of the these tables, though, then you would need to include them in the joins.

Title: How to Query across multiple tables

Body:
I have the following DB. Is this a proper query to get the first name of the authors loaned by Members ? or is there a more efficient way ?

select M.MemberNo, A.FirstName
from Person.Members as M
INNER JOIN Booking.Loans as L
on M.MemberNo = L.MemberNo
INNER JOIN Article.Copies as C
on L.ISBN = C.ISBN and L.CopyNo = C.CopyNo
INNER JOIN Article.Items as I
on C.ISBN = I.ISBN
INNER JOIN Article.Titles as T
on I.TitleID = T.TitleID
INNER JOIN Article.TitleAuthors as TA
on T.TitleID = TA.TitleID
INNER JOIN Article.Authors as A
on TA.AuthorID = A.AuthorID
;
go

Body:
The most direct way to get the names of authors of books that are lent out to members would be like this:

Get member loans (Booking.Loans)

Get books for member loans (Article.Items)

Get authors for the books for member loans (Article.TitleAuthors)

Get first names for authors for the books for member loans (Article.Authors)

select L.MemberNo, A.FirstName
FROM Booking.Loans as L
INNER JOIN Article.Items as I
on L.ISBN = I.ISBN
INNER JOIN Article.TitleAuthors as TA
on I.TitleID = TA.TitleID
INNER JOIN Article.Authors as A
on TA.AuthorID = A.AuthorID

The advantage to joining all the tables like you have your original query is to ensure that each intermediary table was INSERTed into or DELETEd from correctly.

For example, your original query wouldn't return any rows for a member if they had a loan (i.e. a row in the Loans table) but for some reason didn't have an entry in the Members table.  If you can assume that (or don't care if) there will always be a row in the Members table if there is a row in the Loans table, then you can exclude the join to Person.Members.

You can apply this same logic to the other intermediary tables (Member, Copies, Title) too, if needed.  If you need a specific piece of data from one of the these tables, though, then you would need to include them in the joins.