问:
Firebase url to json version of the database data
I have created a firebase database and added some data to the database.

It has given me a url like this:

```<code>https://my-app-name.firebaseio.com/
</code>```

My question is...does firebase provide a url to a json version of my database data if so what is it?

答:
As soon as you add data into your Firebase Realtime database, each node becomes a JSON particular version of your database. Let's say you have a node named users, your URL will be:

```<code>https://my-app-name.firebaseio.com/users/
</code>```

To download the JSON file, simply go to your Firebase Console, choose your project, select your database, click the users node and download the JSON file from the right side, using Export JOSN option.

Body:
I have created a firebase database and added some data to the database.

It has given me a url like this:

https://my-app-name.firebaseio.com/

My question is...does firebase provide a url to a json version of my database data if so what is it?

Body:
As soon as you add data into your Firebase Realtime database, each node becomes a JSON particular version of your database. Let's say you have a node named users, your URL will be:

https://my-app-name.firebaseio.com/users/

To download the JSON file, simply go to your Firebase Console, choose your project, select your database, click the users node and download the JSON file from the right side, using Export JOSN option.


来源: stackexchange

问:
How would you tail call optimize this Clojure function that builds a tree?
I have some maps

```<code>(def m1 [{:a 1, :b 2, :c 0}
         {:a 1, :b 3, :c 0}
         {:a 1, :b 0, :c 2}
         {:a 1, :b 3, :c 1}
         {:a 1, :b 0, :c 3}])
</code>```

which I can recursively group with this function

```<code>(defn group [ks coll]
  (if (empty? ks) coll
      (let [gs (group-by #(select-keys % [(first ks)]) coll)]
        (map (fn [[k v]] {k (group (rest ks) v)}) (dissoc gs {})))))
</code>```

to produce the expected result:

```<code>(group [:a :b :c] m1)
</code>```

=>

```<code>({{:a 1} ({{:b 2} ({{:c 0} [{:a 1, :b 2, :c 0}]})}
          {{:b 3} ({{:c 0} [{:a 1, :b 3, :c 0}]}
                   {{:c 1} [{:a 1, :b 3, :c 1}]})}
          {{:b 0} ({{:c 2} [{:a 1, :b 0, :c 2}]}
                   {{:c 3} [{:a 1, :b 0, :c 3}]})})})
</code>```

How could you rewrite a function like this that has map in the last position as it needs to follow multiple paths, to be tail call optimized using recur?

答:
Your original algorithm requires that the current siblings of the node are preserved as context when recurring, so that we can return to processing those siblings after recurring to the bottom. With a slight modification, we can build a full path to one node at a time, depth-first, disregarding the relationships of nodes. This allows more simple tail-call recursion.

```<code>(defn group [ks coll]
  (group-recur ks coll ks [] {}))

(defn- group-recur [ks coll recur-keys path acc]
  (if (empty? coll)
    acc
    (if (empty? recur-keys)
      (recur ks (rest coll) ks [] (assoc-in acc path (first coll)))
      (let [node (first coll)
            rk   (first recur-keys)
            k    (select-keys node [rk])
            p    (conj path k)]
        (recur ks coll (rest recur-keys) p acc)))))
</code>```

Here's an online Repl to try it out.

ContentLicense: CC BY-SA 3.0

Body:
I have some maps

(def m1 [{:a 1, :b 2, :c 0}
         {:a 1, :b 3, :c 0}
         {:a 1, :b 0, :c 2}
         {:a 1, :b 3, :c 1}
         {:a 1, :b 0, :c 3}])

which I can recursively group with this function

(defn group [ks coll]
  (if (empty? ks) coll
      (let [gs (group-by #(select-keys % [(first ks)]) coll)]
        (map (fn [[k v]] {k (group (rest ks) v)}) (dissoc gs {})))))

to produce the expected result:

(group [:a :b :c] m1)

=>

({{:a 1} ({{:b 2} ({{:c 0} [{:a 1, :b 2, :c 0}]})}
          {{:b 3} ({{:c 0} [{:a 1, :b 3, :c 0}]}
                   {{:c 1} [{:a 1, :b 3, :c 1}]})}
          {{:b 0} ({{:c 2} [{:a 1, :b 0, :c 2}]}
                   {{:c 3} [{:a 1, :b 0, :c 3}]})})})

How could you rewrite a function like this that has map in the last position as it needs to follow multiple paths, to be tail call optimized using recur?

Body:
Your original algorithm requires that the current siblings of the node are preserved as context when recurring, so that we can return to processing those siblings after recurring to the bottom. With a slight modification, we can build a full path to one node at a time, depth-first, disregarding the relationships of nodes. This allows more simple tail-call recursion.

(defn group [ks coll]
  (group-recur ks coll ks [] {}))

(defn- group-recur [ks coll recur-keys path acc]
  (if (empty? coll)
    acc
    (if (empty? recur-keys)
      (recur ks (rest coll) ks [] (assoc-in acc path (first coll)))
      (let [node (first coll)
            rk   (first recur-keys)
            k    (select-keys node [rk])
            p    (conj path k)]
        (recur ks coll (rest recur-keys) p acc)))))

Here's an online Repl to try it out.


问:
How do I make it so my code continuously asks parts 1., 2., and 3. and Choice:? After a third attempt the scanner just closes
```<code>import java.lang.Math;
import java.util.Scanner;

public class Temperature {

    static int fahrenheit;
    static int celsius;

    public static int Celsius(int fahrenheit) {

        fahrenheit = (int) (5.0 / 9.0 * (fahrenheit - 32));
        return fahrenheit;

    }

    public static int Fahrenheit(int fahrenheit) {
        fahrenheit = (int) (9.0 / 5.0 * celsius + 32);
        return fahrenheit;
    }

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        Scanner scan = new Scanner(System.in);
        System.out.println("1. Fahrenheit to Celsius");
        System.out.println("2. Celsius to Fahrenheit");
        System.out.println("3. Exit");
        System.out.println("Choice:");

        int choice = scan.nextInt();

        switch (choice) {

        case 1:
            System.out.println("Enter temperature: ");
            fahrenheit = scan.nextInt();
            System.out.println(fahrenheit + " Fahrenheit is " + Celsius(fahrenheit) + " Celsius");
            System.out.println("1. Fahrenheit to Celsius");
            System.out.println("2. Celsius to Fahrenheit");
            System.out.println("3. Exit");
            System.out.println("Choice:");
            choice = scan.nextInt();

        case 2:

            System.out.println("Enter temperature: ");
            celsius = scan.nextInt();
            System.out.println(celsius + " Celsius is " + Fahrenheit(celsius) + " Fahrenheit");
            System.out.println("1. Fahrenheit to Celsius");
            System.out.println("2. Celsius to Fahrenheit");
            System.out.println("3. Exit");
            System.out.println("Choice:");
            choice = scan.nextInt();

        case 3:
            break;

        }
</code>```

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
1
Enter temperature:
100
100 Fahrenheit is 37 Celsius

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
2
Enter temperature:
0
0 Celsius is 32 Fahrenheit

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
1

After the third attempt, the code doesn't run anymore no matter which choice I input. I want it so it continues to ask as long as the input is either 1 or 2.

答:
Just put while-loop or do-while a around your switch-case as likewise,

```<code>while(choice!= 3) {
     switch (choice) {
      .....
     }
}
</code>```

OR

```<code>do {
     switch(choice) {
       ......
     }
} while (choice != 3)
</code>```

This will lets you to continuously iterate as many time as you want unless you enter 3.

you can even put the following condition in order to make more secure,

```<code>while ( choice >= 3 ) //not recommended but you can.
</code>```

Body:
import java.lang.Math;
import java.util.Scanner;

public class Temperature {

    static int fahrenheit;
    static int celsius;

    public static int Celsius(int fahrenheit) {

        fahrenheit = (int) (5.0 / 9.0 * (fahrenheit - 32));
        return fahrenheit;

    }

    public static int Fahrenheit(int fahrenheit) {
        fahrenheit = (int) (9.0 / 5.0 * celsius + 32);
        return fahrenheit;
    }

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        Scanner scan = new Scanner(System.in);
        System.out.println("1. Fahrenheit to Celsius");
        System.out.println("2. Celsius to Fahrenheit");
        System.out.println("3. Exit");
        System.out.println("Choice:");

        int choice = scan.nextInt();

        switch (choice) {

        case 1:
            System.out.println("Enter temperature: ");
            fahrenheit = scan.nextInt();
            System.out.println(fahrenheit + " Fahrenheit is " + Celsius(fahrenheit) + " Celsius");
            System.out.println("1. Fahrenheit to Celsius");
            System.out.println("2. Celsius to Fahrenheit");
            System.out.println("3. Exit");
            System.out.println("Choice:");
            choice = scan.nextInt();

        case 2:

            System.out.println("Enter temperature: ");
            celsius = scan.nextInt();
            System.out.println(celsius + " Celsius is " + Fahrenheit(celsius) + " Fahrenheit");
            System.out.println("1. Fahrenheit to Celsius");
            System.out.println("2. Celsius to Fahrenheit");
            System.out.println("3. Exit");
            System.out.println("Choice:");
            choice = scan.nextInt();

        case 3:
            break;

        }

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
1
Enter temperature:
100
100 Fahrenheit is 37 Celsius

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
2
Enter temperature:
0
0 Celsius is 32 Fahrenheit

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
1

After the third attempt, the code doesn't run anymore no matter which choice I input. I want it so it continues to ask as long as the input is either 1 or 2.

Body:
Just put while-loop or do-while a around your switch-case as likewise,

while(choice!= 3) {
     switch (choice) {
      .....
     }
}

OR

do {
     switch(choice) {
       ......
     }
} while (choice != 3)

This will lets you to continuously iterate as many time as you want unless you enter 3.

you can even put the following condition in order to make more secure,

while ( choice >= 3 ) //not recommended but you can.


问:
Pass multiple arguments to macro
I wrote a SAS code that allows me to increment a dataset (ds1) with information (var1, var2, var3...) from another dataset (ds2), based on a common key:

```<code>proc sql;
    create table ds1 as
    select a.*, b.var1, b.var2, b.var3, b.var4...
    from ds1 as a left join ds2 as b
    on a.key1 = b.key2;
quit;
</code>```

I want to transform this code into a macro, so I can reuse it. If I had only one information variable (var1), it would be easy:

```<code>%macro increment(ds1, key1, ds2, key2, varinfo);
    proc sql;
        create table &ds1. as
        select a.*, b.&varinfo.
        from &ds1. as a left join &ds2. as b
        on a.&key1. = b.&key2.;
    quit;
%mend;
</code>```

However, I may want to pass multiple information variables:

```<code>%increment(ds1, key1, ds2, key2, var1 var2 var3 var4 var5 var6 var7);
</code>```

How do I rewrite the macro so it works with this "parameter array"?

Thank you!

答:
One option is to simply pass it along as you suggest - that will work fine.

```<code>%macro increment(ds1, key1, ds2, key2, varinfo);
    proc sql;
        create table &ds1. as
        select a.*
            %do i = 1 %to %sysfunc(countw(&varinfo.));
              ,b.%scan(&varinfo.,&i.)
            %end;
        from &ds1. as a left join &ds2. as b
        on a.&key1. = b.&key2.;
    quit;
%mend;

%increment(ds1, key1, ds2, key2, var1 var2 var3 var4 var5 var6 var7);
</code>```

Another option, which won't really work any differently in practice but is a more direct answer to the question-as-asked, is to use parmbuff option in the macro declaration, which creates a sort of dummy macro variable out of any parameters after the known ones.  But I don't recommend it in this case since you can just use a single parameter.

Title: Pass multiple arguments to macro

Body:
I wrote a SAS code that allows me to increment a dataset (ds1) with information (var1, var2, var3...) from another dataset (ds2), based on a common key:

proc sql;
    create table ds1 as
    select a.*, b.var1, b.var2, b.var3, b.var4...
    from ds1 as a left join ds2 as b
    on a.key1 = b.key2;
quit;

I want to transform this code into a macro, so I can reuse it. If I had only one information variable (var1), it would be easy:

%macro increment(ds1, key1, ds2, key2, varinfo);
    proc sql;
        create table &ds1. as
        select a.*, b.&varinfo.
        from &ds1. as a left join &ds2. as b
        on a.&key1. = b.&key2.;
    quit;
%mend;

However, I may want to pass multiple information variables:

%increment(ds1, key1, ds2, key2, var1 var2 var3 var4 var5 var6 var7);

How do I rewrite the macro so it works with this "parameter array"?

Thank you!

Body:
One option is to simply pass it along as you suggest - that will work fine.

%macro increment(ds1, key1, ds2, key2, varinfo);
    proc sql;
        create table &ds1. as
        select a.*
            %do i = 1 %to %sysfunc(countw(&varinfo.));
              ,b.%scan(&varinfo.,&i.)
            %end;
        from &ds1. as a left join &ds2. as b
        on a.&key1. = b.&key2.;
    quit;
%mend;

%increment(ds1, key1, ds2, key2, var1 var2 var3 var4 var5 var6 var7);

Another option, which won't really work any differently in practice but is a more direct answer to the question-as-asked, is to use parmbuff option in the macro declaration, which creates a sort of dummy macro variable out of any parameters after the known ones.  But I don't recommend it in this case since you can just use a single parameter.


问:
The type javax.servlet.ServletContext and javax.servlet.ServletException cannot be resolved
I'm trying to include Spring Security to my web project, i'm following this tutorial http://docs.spring.io/spring-security/site/docs/current/guides/html5//helloworld.html

I've done everything in the tutorial with the given maven project and works fine. But when i'm trying to include it to my project a compilation error appear. Specifically when i extends from AbstractSecurityWebApplicationInitializer appear the given error

Multiple markers at this line

The type javax.servlet.ServletContext cannot be resolved. It is indirectly referenced from required .class files

The type javax.servlet.ServletException cannot be resolved. It is indirectly referenced from required .class files

The POM.xml

```<code><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>spring.primefaces</groupId>
<artifactId>primefaces.testwebapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringPrimefacesWebApp</name>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>
<dependencies>
    <!-- JSF 2.2 core and implementation -->
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.11</version>
    </dependency>
    <!-- Prime Faces -->
    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>5.2</version>
    </dependency>
    <!-- Spring security -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.0.1.RELEASE</version>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.1.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
</code>```

Thanks for the help!

Using mvn clean install -U

答:
try setting the updated parent, like this:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.6.RELEASE</version>
    <relativePath></relativePath>
</parent>
</code>```

this solved for me.

Body:
I'm trying to include Spring Security to my web project, i'm following this tutorial http://docs.spring.io/spring-security/site/docs/current/guides/html5//helloworld.html

I've done everything in the tutorial with the given maven project and works fine. But when i'm trying to include it to my project a compilation error appear. Specifically when i extends from AbstractSecurityWebApplicationInitializer appear the given error

Multiple markers at this line

The type javax.servlet.ServletContext cannot be resolved. It is indirectly referenced from required .class files

The type javax.servlet.ServletException cannot be resolved. It is indirectly referenced from required .class files

The POM.xml

<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>spring.primefaces</groupId>
<artifactId>primefaces.testwebapp</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>SpringPrimefacesWebApp</name>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>
<dependencies>

    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-api</artifactId>
        <version>2.2.11</version>
    </dependency>
    <dependency>
        <groupId>com.sun.faces</groupId>
        <artifactId>jsf-impl</artifactId>
        <version>2.2.11</version>
    </dependency>

    <dependency>
        <groupId>org.primefaces</groupId>
        <artifactId>primefaces</artifactId>
        <version>5.2</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.0.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.0.1.RELEASE</version>
    </dependency>
</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-framework-bom</artifactId>
            <version>4.1.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Thanks for the help!

Using mvn clean install -U

Body:
try setting the updated parent, like this:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.6.RELEASE</version>
    <relativePath></relativePath>
</parent>

this solved for me.


问:
Best practice for Bash start-up files on a Mac
As I understand it, the order that start-up files are read by the bash shell on a Mac are...

~/.bash_profile

~/.bash_login

~/.profile

..and once one file in this list is found, the contents of the other is ignored.

That being said, is there a best practice for which of these files should be my one true Bash start-up file?

On one hand, if .bash_profile will take precedence over any other potential start-up file, then that should be used, because you can be sure that 100% of the time the info in that start-up file is being run.

On the other hand, if .profile is the file that exists on Mac systems by default, and .bash_profile needs to be manually created, then perhaps that should be used, and there will never be a reason to create a .bash_profile file.

Thoughts?

答:
It depends on whether you use shells other than bash, and whether you use bash-only features in your profile.  If you use other sh-style shells (sh, ksh, zsh, etc but not csh or tcsh), don't use bash-only features and want the same setup no matter what shell you're in, you should use .profile.  If you want to use bash-only features, use .bash_profile.  If you want to use multiple shells but also use bash-only features, put the common stuff in .profile and the bash-only stuff in .bash_profile, then add if [ -f ~/.profile ]; then . ~/.profile; fi to .bash_profile.

If you only ever use bash, but don't rely on any bash-only features in your profile, then it doesn't really matter.

There's actually another complication: login bash shells source either .bash_profile, .bash_login, or .profile; non-login interactive bash shells (e.g. subshells) source .bashrc instead.  I tend to want the same setup in both login and non-login shells, so I put all the interesting stuff in .bashrc, and then if [ -f ~/.bashrc ]; then . ~/.bashrc; fi in .bash_profile.  If I also used other shells, I'd probably put most of it in .profile instead, and have .bashrc source that instead.

ContentLicense: CC BY-SA 2.5


问:
Scrollview in two Linearlayouts?
I have 4 TextViews in my Activity and i am using LinearLayout with vertical orientation. Top one TextView is kind of header (no need to scroll) next one is some kind of description which i want to make scrollable. 3rd one is again a heading (no scroll needed) and 4th is description (need to scroll).
I tried but only top TextView (header) and 2nd TextView (description) is being showed on the screen. Description is scrollable but the problem is, other two TextView are hidden.
Its kind of silly question to ask but i am kind of stuck here because i am new to android. Here is my xml.

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?android:attr/actionBarSize"
android:orientation="vertical"
android:padding="15dp"

>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#d0f7c9"
    android:orientation="vertical"
    android:padding="10dp"

    >

    <TextView
        android:id="@+id/tvTitle"
        style="?android:attr/listSeparatorTextViewStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="20dp" />

</LinearLayout>

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#b3cff4"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvShow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="20dp" />
    </LinearLayout>
</ScrollView>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Program Output"
    android:textColor="@color/black"
    android:textSize="25dp" />

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#d2b3f4">

        <TextView
            android:id="@+id/tvOutput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="20dp" />

    </LinearLayout>

</ScrollView>
</code>```

答:
You can try like this,</p>

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#d0f7c9"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvTitle"
            style="?android:attr/listSeparatorTextViewStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Top Title"
            android:textColor="#ffffff"
            android:textSize="20dp"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#b3cff4">

            <TextView
                android:id="@+id/tvShow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:textSize="20dp"/>
        </ScrollView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvTitle1"
            style="?android:attr/listSeparatorTextViewStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Seconf Title"
            android:textColor="#ffffff"
            android:textSize="20dp"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#b3cff4">

            <TextView
                android:id="@+id/tvShow1"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:textSize="20dp"/>
        </ScrollView>
    </LinearLayout>

</LinearLayout>
</code>```

Title: Scrollview in two Linearlayouts?

Body:
I have 4 TextViews in my Activity and i am using LinearLayout with vertical orientation. Top one TextView is kind of header (no need to scroll) next one is some kind of description which i want to make scrollable. 3rd one is again a heading (no scroll needed) and 4th is description (need to scroll).
I tried but only top TextView (header) and 2nd TextView (description) is being showed on the screen. Description is scrollable but the problem is, other two TextView are hidden.
Its kind of silly question to ask but i am kind of stuck here because i am new to android. Here is my xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?android:attr/actionBarSize"
android:orientation="vertical"
android:padding="15dp"

>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#d0f7c9"
    android:orientation="vertical"
    android:padding="10dp"

    >

    <TextView
        android:id="@+id/tvTitle"
        style="?android:attr/listSeparatorTextViewStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="#ffffff"
        android:textSize="20dp" />

</LinearLayout>

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#b3cff4"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvShow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="20dp" />
    </LinearLayout>
</ScrollView>

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Program Output"
    android:textColor="@color/black"
    android:textSize="25dp" />

<ScrollView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#d2b3f4">

        <TextView
            android:id="@+id/tvOutput"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:textSize="20dp" />

    </LinearLayout>

</ScrollView>

Body:
You can try like this,

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#d0f7c9"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvTitle"
            style="?android:attr/listSeparatorTextViewStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Top Title"
            android:textColor="#ffffff"
            android:textSize="20dp"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#b3cff4">

            <TextView
                android:id="@+id/tvShow"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:textSize="20dp"/>
        </ScrollView>
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tvTitle1"
            style="?android:attr/listSeparatorTextViewStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Seconf Title"
            android:textColor="#ffffff"
            android:textSize="20dp"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#b3cff4">

            <TextView
                android:id="@+id/tvShow1"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:textSize="20dp"/>
        </ScrollView>
    </LinearLayout>

</LinearLayout>


问:
Extract PHP method in Visual Studio Code
Is there a way in Visual Studio Code to extract the selected lines to a PHP function?

I saw there is a way to do it for C#, but I did not find a way for PHP.

答:
No, not builtin at least.

Features like extract method have to be implemented per-language. Try filing a feature request against the PHP extension: https://github.com/felixfbecker/php-language-server/issues

ContentLicense: CC BY-SA 4.0


问:
How to make a Input be taken as a variable in VBScript?
I want to be able to take an input and use it within my VBScript.</p>

```<code>@echo off
set var=Input
echo "%var%"
pause
</code>```

答:
I'm thinking you mean this...</p>

```<code>%%%var%%%
</code>```

Body:
I want to be able to take an input and use it within my VBScript.

@echo off
set var=Input
echo "%var%"
pause

Body:
I'm thinking you mean this...

%%%var%%%


问:
Challenge JavaScript grab image URL from HTML class
This question differs from other questions before, in that here we have a
 STYLE inside a CLASS name. That made it a little more complicated to me.

I want to alert() ONLY the url of a image showing in the website, that is accessible with its class name:

```<code>    <div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>
</code>```

I tried by doing:

```<code>alert( (document.querySelector('.image-container-image').textContent) );
</code>```

Tried other different ways, but still no luck.

My output should be an alert showing the following url:
  "https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg"

Your guidance is very much appreciated.

答:
JavaScript (ES6), <s>121</s> 89 bytes

One-liner, code-golf style:

alert(document.querySelector('.image-container-image').style.backgroundImage.slice(5,-2))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);"></div></code>```

101 bytes alternative

getComputedStyle() works, even if the background-image exists in an external stylesheet:

alert(getComputedStyle(document.querySelector('.image-container-image')).backgroundImage.slice(5,-2))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.image-container-image{background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);}</code>```

```

Body:
This question differs from other questions before, in that here we have a
 STYLE inside a CLASS name. That made it a little more complicated to me.

I want to alert() ONLY the url of a image showing in the website, that is accessible with its class name:

I tried by doing:

alert( (document.querySelector('.image-container-image').textContent) );

Tried other different ways, but still no luck.

My output should be an alert showing the following url:
  "https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg"

Your guidance is very much appreciated.

Body:
JavaScript (ES6), <s>121</s> 89 bytes

One-liner, code-golf style:

alert(document.querySelector('.image-container-image').style.backgroundImage.slice(5,-2))

<div class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);"></div>

101 bytes alternative

getComputedStyle() works, even if the background-image exists in an external stylesheet:

alert(getComputedStyle(document.querySelector('.image-container-image')).backgroundImage.slice(5,-2))

.image-container-image{background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);}

<div class='image-container-image'></div>


问:
Read appsettings json values in .NET Core Test Project
My Web application needs to read the Document DB keys from appsettings.json file. I have created a class with the key names and reading the Config section in ConfigureServices() as:

```<code>public Startup(IHostingEnvironment env) {
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddSession();
    Helpers.GetConfigurationSettings(services, Configuration);
    DIBuilder.AddDependency(services, Configuration);
}
</code>```

I'm looking for the ways to read the Key values in Test project.

答:
Copy the appSettings.json to your Test project root directory and mark its property as Content and Copy if newer.

```<code>var builder = new ConfigurationBuilder()
  .SetBasePath(Directory.GetCurrentDirectory())
  .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
  .AddEnvironmentVariables();
ConfigurationManager.Configuration = builder.Build();
</code>```

ConfigurationManager is a class and it has a static property Configuration. This way the whole application can just access it as ConfigurationManager.Configuration[<key>]

Body:
My Web application needs to read the Document DB keys from appsettings.json file. I have created a class with the key names and reading the Config section in ConfigureServices() as:

public Startup(IHostingEnvironment env) {
    var builder = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    Configuration = builder.Build();
}

public IConfigurationRoot Configuration { get; }

public void ConfigureServices(IServiceCollection services) {
    services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
    services.AddSession();
    Helpers.GetConfigurationSettings(services, Configuration);
    DIBuilder.AddDependency(services, Configuration);
}

I'm looking for the ways to read the Key values in Test project.

Body:
Copy the appSettings.json to your Test project root directory and mark its property as Content and Copy if newer.

var builder = new ConfigurationBuilder()
  .SetBasePath(Directory.GetCurrentDirectory())
  .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
  .AddEnvironmentVariables();
ConfigurationManager.Configuration = builder.Build();

ConfigurationManager is a class and it has a static property Configuration. This way the whole application can just access it as ConfigurationManager.Configuration[<key>]


问:
Can't access nested object in blade template
I'm using Laravel, Eloquent for queries, and Blade for templating.

Here are the models I'm working with:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class DistrictCharge extends Model
{
    protected $fillable = [ 'plan_year', 'location_id', 'meal_id', 'charge_id', 'price' ];

    public function plan_year() {
        return $this->belongsTo('App\PlanYear', 'plan_year');
    }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class PlanYear extends Model
{
    protected $fillable = [ 'year', 'start_date', 'end_date' ];

    public $primaryKey = 'year';
}
</code>```

Relevant controller code:

```<code>public function index()
{
    $district_charges = DistrictCharge::with('plan_year')->get();

    return view('district-charges/index', compact(
        'district_charges',
    ));
}
</code>```

In my template, when I do this:

```<code>{{ $district_charges[0] }}
</code>```

I get this (indented for readability):

```<code>{
    "id":1,
    "created_at":"2017-01-23 21:33:53",
    "updated_at":"2017-01-23 21:33:53",
    "plan_year": {
        "year":2016,
        "start_date":"2015-07-01",
        "end_date":"2016-06-30",
        "created_at":"2017-01-23 21:03:08",
        "updated_at":"2017-01-23 21:03:08"
    },
    "location_id":"2",
    "meal_id":"1",
    "charge_id":"4",
    "price":"175"
}
</code>```

This makes sense; the plan_year field is populated with the contents of the database entry it refers to, exactly as I want. But when I do this:

```<code>{{ $district_charges[0]->plan_year }}
</code>```

I just get 2016, a non-object. This is a problem because I queried in order to populate the plan_year field because I need the start_date and end_date fields that it comes with for my view. When I try to access these properties in my view I just get a 'trying to get properties of a non-object' error. I'm not that familiar with Laravel, Eloquent, or Blade, so any help would be great.

Edit:

Table structure as requested:

```<code>district_charges
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| created_at  | timestamp        | YES  |     | NULL    |                |
| updated_at  | timestamp        | YES  |     | NULL    |                |
| plan_year   | int(11)          | NO   |     | NULL    |                |
| location_id | int(11)          | NO   |     | NULL    |                |
| meal_id     | int(11)          | NO   |     | NULL    |                |
| charge_id   | int(11)          | NO   |     | NULL    |                |
| price       | int(11)          | NO   |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

plan_years
+------------+-----------+------+-----+---------+-------+
| Field      | Type      | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+-------+
| year       | int(11)   | NO   |     | NULL    |       |
| start_date | date      | NO   |     | NULL    |       |
| end_date   | date      | NO   |     | NULL    |       |
| created_at | timestamp | YES  |     | NULL    |       |
| updated_at | timestamp | YES  |     | NULL    |       |
+------------+-----------+------+-----+---------+-------+
</code>```

What I'm not getting is why I can see the contents of the variable I want when I output the whole thing in a template, but when I selectively output just parts of it, it says it doesn't exist.

答:
You don't have any id in the table, so put the following class member in your PlanYear model

```<code>protected $primaryKey = 'year';
</code>```

Also, change your relation method to be without an underscore - for example, year()

Body:
I'm using Laravel, Eloquent for queries, and Blade for templating.

Here are the models I'm working with:

namespace App;

use Illuminate\Database\Eloquent\Model;

class DistrictCharge extends Model
{
    protected $fillable = [ 'plan_year', 'location_id', 'meal_id', 'charge_id', 'price' ];

    public function plan_year() {
        return $this->belongsTo('App\PlanYear', 'plan_year');
    }
}

namespace App;

use Illuminate\Database\Eloquent\Model;

class PlanYear extends Model
{
    protected $fillable = [ 'year', 'start_date', 'end_date' ];

    public $primaryKey = 'year';
}

Relevant controller code:

public function index()
{
    $district_charges = DistrictCharge::with('plan_year')->get();

    return view('district-charges/index', compact(
        'district_charges',
    ));
}

In my template, when I do this:

{{ $district_charges[0] }}

I get this (indented for readability):

{
    "id":1,
    "created_at":"2017-01-23 21:33:53",
    "updated_at":"2017-01-23 21:33:53",
    "plan_year": {
        "year":2016,
        "start_date":"2015-07-01",
        "end_date":"2016-06-30",
        "created_at":"2017-01-23 21:03:08",
        "updated_at":"2017-01-23 21:03:08"
    },
    "location_id":"2",
    "meal_id":"1",
    "charge_id":"4",
    "price":"175"
}

This makes sense; the plan_year field is populated with the contents of the database entry it refers to, exactly as I want. But when I do this:

{{ $district_charges[0]->plan_year }}

I just get 2016, a non-object. This is a problem because I queried in order to populate the plan_year field because I need the start_date and end_date fields that it comes with for my view. When I try to access these properties in my view I just get a 'trying to get properties of a non-object' error. I'm not that familiar with Laravel, Eloquent, or Blade, so any help would be great.

Edit:

Table structure as requested:

district_charges
+-------------+------------------+------+-----+---------+----------------+
| Field       | Type             | Null | Key | Default | Extra          |
+-------------+------------------+------+-----+---------+----------------+
| id          | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| created_at  | timestamp        | YES  |     | NULL    |                |
| updated_at  | timestamp        | YES  |     | NULL    |                |
| plan_year   | int(11)          | NO   |     | NULL    |                |
| location_id | int(11)          | NO   |     | NULL    |                |
| meal_id     | int(11)          | NO   |     | NULL    |                |
| charge_id   | int(11)          | NO   |     | NULL    |                |
| price       | int(11)          | NO   |     | NULL    |                |
+-------------+------------------+------+-----+---------+----------------+

plan_years
+------------+-----------+------+-----+---------+-------+
| Field      | Type      | Null | Key | Default | Extra |
+------------+-----------+------+-----+---------+-------+
| year       | int(11)   | NO   |     | NULL    |       |
| start_date | date      | NO   |     | NULL    |       |
| end_date   | date      | NO   |     | NULL    |       |
| created_at | timestamp | YES  |     | NULL    |       |
| updated_at | timestamp | YES  |     | NULL    |       |
+------------+-----------+------+-----+---------+-------+

What I'm not getting is why I can see the contents of the variable I want when I output the whole thing in a template, but when I selectively output just parts of it, it says it doesn't exist.

Body:
You don't have any id in the table, so put the following class member in your PlanYear model

protected $primaryKey = 'year';

Also, change your relation method to be without an underscore - for example, year()


问:
How to round a time down to the nearest 15 minutes in Ruby?
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

```<code>t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
</code>```

答:
Since Ruby allows arithmetic (in seconds) on Times, you can just do this:</p>

```<code>t = Time.new
rounded_t = t-t.sec-t.min%15*60
</code>```

OwnerDisplayName: Readonly

Body:
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)

Body:
Since Ruby allows arithmetic (in seconds) on Times, you can just do this:

t = Time.new
rounded_t = t-t.sec-t.min%15*60

OwnerDisplayName: Chuck


答:
If you do not want the program to end put it in a while loop:</p>

```<code>   Scanner scan = new Scanner(System.in);
   System.out.println("1. Fahrenheit to Celsius");
   System.out.println("2. Celsius to Fahrenheit");
   System.out.println("3. Exit");
   System.out.println("Choice:");

   int choice = scan.nextInt();

   do {
     switch (choice) {
        ...
         }
      } while (choice!= 3);
</code>```

Title: How do I make it so my code continuously asks parts 1., 2., and 3. and Choice:? After a third attempt the scanner just closes

Body:
import java.lang.Math;
import java.util.Scanner;

public class Temperature {

    static int fahrenheit;
    static int celsius;

    public static int Celsius(int fahrenheit) {

        fahrenheit = (int) (5.0 / 9.0 * (fahrenheit - 32));
        return fahrenheit;

    }

    public static int Fahrenheit(int fahrenheit) {
        fahrenheit = (int) (9.0 / 5.0 * celsius + 32);
        return fahrenheit;
    }

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        Scanner scan = new Scanner(System.in);
        System.out.println("1. Fahrenheit to Celsius");
        System.out.println("2. Celsius to Fahrenheit");
        System.out.println("3. Exit");
        System.out.println("Choice:");

        int choice = scan.nextInt();

        switch (choice) {

        case 1:
            System.out.println("Enter temperature: ");
            fahrenheit = scan.nextInt();
            System.out.println(fahrenheit + " Fahrenheit is " + Celsius(fahrenheit) + " Celsius");
            System.out.println("1. Fahrenheit to Celsius");
            System.out.println("2. Celsius to Fahrenheit");
            System.out.println("3. Exit");
            System.out.println("Choice:");
            choice = scan.nextInt();

        case 2:

            System.out.println("Enter temperature: ");
            celsius = scan.nextInt();
            System.out.println(celsius + " Celsius is " + Fahrenheit(celsius) + " Fahrenheit");
            System.out.println("1. Fahrenheit to Celsius");
            System.out.println("2. Celsius to Fahrenheit");
            System.out.println("3. Exit");
            System.out.println("Choice:");
            choice = scan.nextInt();

        case 3:
            break;

        }

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
1
Enter temperature:
100
100 Fahrenheit is 37 Celsius

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
2
Enter temperature:
0
0 Celsius is 32 Fahrenheit

Fahrenheit to Celsius

Celsius to Fahrenheit

Exit
Choice:
1

After the third attempt, the code doesn't run anymore no matter which choice I input. I want it so it continues to ask as long as the input is either 1 or 2.

Body:
If you do not want the program to end put it in a while loop:

   Scanner scan = new Scanner(System.in);
   System.out.println("1. Fahrenheit to Celsius");
   System.out.println("2. Celsius to Fahrenheit");
   System.out.println("3. Exit");
   System.out.println("Choice:");

   int choice = scan.nextInt();

   do {
     switch (choice) {
        ...
         }
      } while (choice!= 3);


答:
Enclose it in a do-while loop</p>

```<code>do {
    switch(choice) {
       ...
    }
}while(choice != 3);
</code>```

Body:
Enclose it in a do-while loop

do {
    switch(choice) {
       ...
    }
}while(choice != 3);


问:
add values with PHP
I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.

So far I've been able to display both entries for value by using the following.

```<code>function showTotal() {

global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if (!$result) {

die('Query FAILED' . mysqli_error());

} else if (isset($failed)) {

echo "Failed";

}

while ($row = mysqli_fetch_assoc($result)) {

$value = $row['value'];

echo "$value";

            }
                }
</code>```

What I really want is these values added together rather than displaying alongside each other.

Thanks
James

答:
While I personally would opt to go with the solution offered by @jm, PHP does offer another way with its array_sum(), as follows:

```<code><?php

$value = 0;

while ($row[] = mysqli_fetch_assoc($result)) {}

echo array_sum($row['value']);
</code>```

See Manual

Note: you could change the fetching of the result by using mysqli_fetch_all, if you have the MySQL native driver; see here.

Title: add values with PHP

Body:
I have a database table with two fields both id and value and I'd like to add the two entries for value together and then echo out the total of the sum.

So far I've been able to display both entries for value by using the following.

function showTotal() {

global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if (!$result) {

die('Query FAILED' . mysqli_error());

} else if (isset($failed)) {

echo "Failed";

}

while ($row = mysqli_fetch_assoc($result)) {

$value = $row['value'];

echo "$value";

            }
                }

What I really want is these values added together rather than displaying alongside each other.

Thanks
James

Body:
While I personally would opt to go with the solution offered by @jm, PHP does offer another way with its array_sum(), as follows:

<?php

$value = 0;

while ($row[] = mysqli_fetch_assoc($result)) {}

echo array_sum($row['value']);

See Manual

Note: you could change the fetching of the result by using mysqli_fetch_all, if you have the MySQL native driver; see here.


问:
count the number of items in a shell variable
I have a shell variable sampleDir:

```<code>sampleDir=/home/sample*
echo $sampleDir
</code>```

will give:

```<code>/home/sample_001 /home/sample_002 /home/sample_003
</code>```

(note there are sub-directories under the sample_*** ones)

If I would like to count how much of these items are in this $sampleDir variable, what would be a best way please? (Expect to return 3)

答:
As posed, you are trying to count the number of spaces in your string and add one. There are a number of good ways of doing this. The shortest to type is probably something along the lines of

```<code>COUNT=$(grep -o ' ' <<< "$sampleDir" | wc -l)
((COUNT++))
</code>```

The problem with this approach is that you can not have spaces anywhere in the file names. A better way might be to just store the name of the directory you are interested in and run a command like find on that:

```<code>sampleRoot=/home
find "$sampleRoot" -name 'sample*' | wc -l
</code>```

Body:
I have a shell variable sampleDir:

sampleDir=/home/sample*
echo $sampleDir

will give:

/home/sample_001 /home/sample_002 /home/sample_003

(note there are sub-directories under the sample_*** ones)

If I would like to count how much of these items are in this $sampleDir variable, what would be a best way please? (Expect to return 3)

Body:
As posed, you are trying to count the number of spaces in your string and add one. There are a number of good ways of doing this. The shortest to type is probably something along the lines of

COUNT=$(grep -o ' ' <<< "$sampleDir" | wc -l)
((COUNT++))

The problem with this approach is that you can not have spaces anywhere in the file names. A better way might be to just store the name of the directory you are interested in and run a command like find on that:

sampleRoot=/home
find "$sampleRoot" -name 'sample*' | wc -l


问:
Outlook web addIn dropdown menu
I have created the Outlook Web Add-in project and trying th create the dropdown menu by following the link under

```<code>https://github.com/officedev/outlook-add-in-command-demo
</code>```

It seems that dropdown menu just take static list. What i want to do is i have webservices which is returning some destination and link of that destionation . I want to display the list of all those destination under the dropdown and by clicking one of it, it opens the link into task pane.
Any tips ? how to display from webservice in dropdown menu.

答: It is not currently possible to dynamically populate the dropdowns, your best bet would be to have a single taskpane action, then render a selector page that dynamically shows the available options, then navigate to the page associated with that option. Feel free to upvote this User Voice suggestion to let us know that this feature is important to you.</p>

Title: Outlook web addIn dropdown menu

Body:
I have created the Outlook Web Add-in project and trying th create the dropdown menu by following the link under

https://github.com/officedev/outlook-add-in-command-demo

It seems that dropdown menu just take static list. What i want to do is i have webservices which is returning some destination and link of that destionation . I want to display the list of all those destination under the dropdown and by clicking one of it, it opens the link into task pane.
Any tips ? how to display from webservice in dropdown menu.


答:
You should have a menu method, for example:

```<code>public static void showMenu() {
    System.out.println("1. Fahrenheit to Celsius");
    System.out.println("2. Celsius to Fahrenheit");
    System.out.println("3. Exit");
    System.out.println("Choice:");
}
</code>```

On your main method have a call to this method inside a do-while loop:

```<code>public static void main(String args[]) {
    //Add your Scanner code here, your variables, etc
    do {
        showMenu();
        choice = scan.nextInt();

        switch (choice) {
            case 1:
                System.out.println("Enter temperature: ");
                fahrenheit = scan.nextInt();
                System.out.println(fahrenheit + " Fahrenheit is " + Celsius(fahrenheit) + " Celsius");
                break;
            case 2:
                //Do the same for method 1 but for Celsius
    } while (choice != 3);
}
</code>```

And, you're done!

Body:
You should have a menu method, for example:

public static void showMenu() {
    System.out.println("1. Fahrenheit to Celsius");
    System.out.println("2. Celsius to Fahrenheit");
    System.out.println("3. Exit");
    System.out.println("Choice:");
}

On your main method have a call to this method inside a do-while loop:

public static void main(String args[]) {
    //Add your Scanner code here, your variables, etc
    do {
        showMenu();
        choice = scan.nextInt();

        switch (choice) {
            case 1:
                System.out.println("Enter temperature: ");
                fahrenheit = scan.nextInt();
                System.out.println(fahrenheit + " Fahrenheit is " + Celsius(fahrenheit) + " Celsius");
                break;
            case 2:
                //Do the same for method 1 but for Celsius
    } while (choice != 3);
}

And, you're done!


问:
Objectify doesn't work inside createThreadForCurrentRequest()
This is a follow-up question to an answer here.

I have the following code in a servlet:

```<code>createThreadForCurrentRequest(() => {
    // do stuff
}).start();
</code>```

But when I run it locally, I received this exception:

```<code>Exception in thread "Thread-17" java.lang.IllegalStateException: You have not started an Objectify context. You are probably missing the ObjectifyFilter. If you are not running in the context of an http request, see the ObjectifyService.run() method.
</code>```

Where do I do wrong?

To paraphrase: How do I run Objectify inside thread spawned by createThreadForCurrentRequest()?

EDIT 1: By request, here's the web.xml:

```<code><?xml version="1.0" encoding="utf-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="true">

    <absolute-ordering/>

    <!-- Register Objectify model -->
    <listener>
        <listener-class>foo.ObjectifyListener</listener-class>
    </listener>

    <filter>
        <filter-name>objectify</filter-name>
        <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>objectify</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>bar</servlet-name>
        <servlet-class>foo.BarServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>bar</servlet-name>
        <url-pattern>/foo/bar/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

EDIT 2:

I use the new (currently in beta) Java 8 runtime.

答:
You can create a unit of work (exactly the same way the filter does) like this:

```<code>ObjectifyService.run(() -> {
    ofy().load()...etc
});
</code>```

Also see the begin() method, which is pretty much the same thing (you can use try-with-resources instead of passing a closure).

Body:
This is a follow-up question to an answer here.

I have the following code in a servlet:

createThreadForCurrentRequest(() => {
    // do stuff
}).start();

But when I run it locally, I received this exception:

Exception in thread "Thread-17" java.lang.IllegalStateException: You have not started an Objectify context. You are probably missing the ObjectifyFilter. If you are not running in the context of an http request, see the ObjectifyService.run() method.

Where do I do wrong?

To paraphrase: How do I run Objectify inside thread spawned by createThreadForCurrentRequest()?

EDIT 1: By request, here's the web.xml:

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         metadata-complete="true">

    <absolute-ordering/>

    <listener>
        <listener-class>foo.ObjectifyListener</listener-class>
    </listener>

    <filter>
        <filter-name>objectify</filter-name>
        <filter-class>com.googlecode.objectify.ObjectifyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>objectify</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>bar</servlet-name>
        <servlet-class>foo.BarServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>bar</servlet-name>
        <url-pattern>/foo/bar/</url-pattern>
    </servlet-mapping>

</web-app>

EDIT 2:

I use the new (currently in beta) Java 8 runtime.

Body:
You can create a unit of work (exactly the same way the filter does) like this:

ObjectifyService.run(() -> {
    ofy().load()...etc
});

Also see the begin() method, which is pretty much the same thing (you can use try-with-resources instead of passing a closure).


问:
MongoDB client throws a FileNotFoundException in mscorlib
I'm using Visual Studio .NET 4.6 and Robomongo has no problem connecting to my database

My imports for MongoDB

```<code>using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson;
</code>```

The code that's executing:

```<code>MongoClient client = new MongoClient("mongodb://localhost");
MongoServer server = client.GetServer();
MongoDatabase mongoDatabase = server.GetDatabase("GameCollection");
</code>```

The full error message:

An unhandled exception of type 'System.IO.FileNotFoundException'
  occurred in mscorlib.dll

Additional information: Could not load file or assembly
  'System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The system cannot find the file specified.

答:
In my case I already had System.Runtime.InteropServices.RuntimeInformation installed, yet it kept giving me the same error.   Either complaining that 4.0.0.0 was not found, or if I updated the app.config to 4.3, it complained that 4.3.0.0 was missing.

However, after uninstalling and reinstalleding several packages it started working, and even though version 4.3 of the System.Runtime.InteropServices.RuntimeInformation was installed, it required the app.config to have 4.0.1.0

```<code><dependentAssembly>
    <assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
  </dependentAssembly>
</code>```

I have no idea why, but it finally works for me.

Body:
I'm using Visual Studio .NET 4.6 and Robomongo has no problem connecting to my database

My imports for MongoDB

using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Bson;

The code that's executing:

MongoClient client = new MongoClient("mongodb://localhost");
MongoServer server = client.GetServer();
MongoDatabase mongoDatabase = server.GetDatabase("GameCollection");

The full error message:

An unhandled exception of type 'System.IO.FileNotFoundException'
  occurred in mscorlib.dll

Additional information: Could not load file or assembly
  'System.Runtime.InteropServices.RuntimeInformation, Version=4.0.0.0,
  Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
  dependencies. The system cannot find the file specified.

Body:
In my case I already had System.Runtime.InteropServices.RuntimeInformation installed, yet it kept giving me the same error.   Either complaining that 4.0.0.0 was not found, or if I updated the app.config to 4.3, it complained that 4.3.0.0 was missing.

However, after uninstalling and reinstalleding several packages it started working, and even though version 4.3 of the System.Runtime.InteropServices.RuntimeInformation was installed, it required the app.config to have 4.0.1.0

<dependentAssembly>
    <assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
  </dependentAssembly>

I have no idea why, but it finally works for me.


问:
java.io.filenotfoundexception: /home/ljh/.android/analytics.settings (permission denied)
When I started Android studio, I got

could not initialize analytics, treating as opt-out. java.io.filenotfoundexception: /home/ljh/.android/analytics.settings (permission denied)

What should I do? My OS is Ubuntu 32bit

答:
Solution is to install these 32 bit libraries on your ubuntu box

```<code>sudo dpkg --add-architecture i386
sudo apt-get -qqy update
sudo apt-get -qqy install libncurses5:i386 libstdc++6:i386 zlib1g:i386
</code>```

Following are compile errors which are solved by issuing above commands :

```<code>:CordovaLib:generateReleaseResources
:CordovaLib:packageReleaseResources
   Building Cordova app for Android          \
:CordovaLib:generateReleaseBuildConfig
 FAILEDding Cordova app for Android          \

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':CordovaLib:processReleaseResources'.
> com.android.ide.common.process.ProcessException: Failed to execute aapt
</code>```

stack trace may also show these errors

```<code>BUILD FAILED

Total time: 37.372 secs
%% Command finished with error code 1: /home/stens/src/github.com/loudthink/loudspeed/.meteor/local/cordova-build/platforms/android/gradlew cdvBuildRelease,-b,/home/stens/src/github.com/loudthink/loudspeed/.meteor/local/cordova-build/platforms/android/build.gradle,-Dorg.gradle.daemon=true,-Dorg.gradle.jvmargs=-Xmx2048m,-Pandroid.useDeprecatedNdk=true
=> Errors executing Cordova commands:

   While building Cordova app for platform Android:
   Error: /home/stens/src/github.com/loudthink/loudspeed/.meteor/local/cordova-build/platforms/android/gradlew: Command failed with exit code 1
   Error output:
   Could not initialize analytics, treating as opt-out.
   java.io.FileNotFoundException: /home/stens/.android/analytics.settings (No such file or directory)
</code>```

Body:
Solution is to install these 32 bit libraries on your ubuntu box

sudo dpkg --add-architecture i386
sudo apt-get -qqy update
sudo apt-get -qqy install libncurses5:i386 libstdc++6:i386 zlib1g:i386

Following are compile errors which are solved by issuing above commands :

:CordovaLib:generateReleaseResources
:CordovaLib:packageReleaseResources
   Building Cordova app for Android          \
:CordovaLib:generateReleaseBuildConfig
 FAILEDding Cordova app for Android          \

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':CordovaLib:processReleaseResources'.
> com.android.ide.common.process.ProcessException: Failed to execute aapt

stack trace may also show these errors

BUILD FAILED

Total time: 37.372 secs
%% Command finished with error code 1: /home/stens/src/github.com/loudthink/loudspeed/.meteor/local/cordova-build/platforms/android/gradlew cdvBuildRelease,-b,/home/stens/src/github.com/loudthink/loudspeed/.meteor/local/cordova-build/platforms/android/build.gradle,-Dorg.gradle.daemon=true,-Dorg.gradle.jvmargs=-Xmx2048m,-Pandroid.useDeprecatedNdk=true
=> Errors executing Cordova commands:

   While building Cordova app for platform Android:
   Error: /home/stens/src/github.com/loudthink/loudspeed/.meteor/local/cordova-build/platforms/android/gradlew: Command failed with exit code 1
   Error output:
   Could not initialize analytics, treating as opt-out.
   java.io.FileNotFoundException: /home/stens/.android/analytics.settings (No such file or directory)


问:
in bash, sed, how can I search/replace this: var = ["blabla, doodoo"]; by var blabla = [blabla, doodoo"];
In bash, sed, how can I search/replace this line :

```<code>var = ["bla bla, doodoo"];
</code>```

with

```<code>var blabla = ["bla bla, doodoo"];
</code>```

blabla and doodoo can be anything (one or more words each) -

I want to copy the section between [" and , and paste it after = .

And more, I need to remove any spaces in the copied part...

Any help would be appreciated!

答:
With GNU awk for the 3rd arg to match(), gensub() and \s:</p>

```<code>$ awk 'match($0,/(.*var\s*)(=\s*\["([^,]+)(.*))/,a) {$0 = a[1] gensub(/\s/,"","g",a[3]) " " a[2]} 1' file
var blabla = ["bla bla, doodoo"];
</code>```

Body:
In bash, sed, how can I search/replace this line :

var = ["bla bla, doodoo"];

with

var blabla = ["bla bla, doodoo"];

blabla and doodoo can be anything (one or more words each) -

I want to copy the section between [" and , and paste it after = .

And more, I need to remove any spaces in the copied part...

Any help would be appreciated!

Body:
With GNU awk for the 3rd arg to match(), gensub() and \s:

$ awk 'match($0,/(.*var\s*)(=\s*\["([^,]+)(.*))/,a) {$0 = a[1] gensub(/\s/,"","g",a[3]) " " a[2]} 1' file
var blabla = ["bla bla, doodoo"];


问:
Entering data from form into database: sqlalchemy.orm.exc.UnmappedInstanceError
Please ignore my hack job, I'm just trying to get data from a form inserted into SQL Server. </p>

```<code>@app.route("/contact", methods = ['GET', 'POST'])
def contact():
   form = PayRoll_Form()

   if request.method == 'POST':
       if form.validate() == False:
           flash('All fields are required.')
           return render_template('contact.html', form = form)
       else:
           N = engine.execute(PayRoll.insert(),
               Name = request.form['Name'],
               CreateUserPK = request.form['CreateUserPK'],
               PeriodStart = request.form['PeriodStart'],
               PeriodStop = request.form['PeriodStop'],
               DueDate = request.form['DueDate'])
           session.add(N)
           session.commit()
           flash('Submited')
           return redirect("/contact")
   if request.method == 'GET':
       return render_template('contact.html', form = form)
if __name__ == '__main__':
    app.run(debug=True,port=5000)
</code>```

答: You seem to be mixing possible implementations here; the line N = engine.execute(... actually executes the INSERT against the DB directly. Trying to add the result to the current session and commit that session doesn't make sense. You would only use those methods if you had an ORM object that you made changes to (or created) and wanted to have committed, but you've already done this in the line referenced above.

Body:
Please ignore my hack job, I'm just trying to get data from a form inserted into SQL Server.

@app.route("/contact", methods = ['GET', 'POST'])
def contact():
   form = PayRoll_Form()

   if request.method == 'POST':
       if form.validate() == False:
           flash('All fields are required.')
           return render_template('contact.html', form = form)
       else:
           N = engine.execute(PayRoll.insert(),
               Name = request.form['Name'],
               CreateUserPK = request.form['CreateUserPK'],
               PeriodStart = request.form['PeriodStart'],
               PeriodStop = request.form['PeriodStop'],
               DueDate = request.form['DueDate'])
           session.add(N)
           session.commit()
           flash('Submited')
           return redirect("/contact")
   if request.method == 'GET':
       return render_template('contact.html', form = form)
if __name__ == '__main__':
    app.run(debug=True,port=5000)


问:
TFS Release Artifacts - How to Link Version Control Artifacts?
I am trying to setup some powershell scripts to be available on my TFS Release Agent.

From what I have learned thus far the way to do this is to link an artifact up and reference the artifact link in a PowerShell Task in TFS RM.

What I have trouble with is that TFS RM Artifacts will only allow me to download the entire Team Project in Version control while I only want powershell scripts in a specific subfolder downloaded to the agent.

I get an error message that says:

Field (Source Repository) Artifacts should have valid values

So, how do I link a SUBfolder of TFS as a downloadable artifact????

I there a custom task I can use to accomplish this instead?

I have yet to find one in the MarketPLace that downloads raw files in TFS Version Control binding and workspace free to execute on the Release agent server.

答: You can't. Publish an artifact as part of your build process. You can easily control the exact folders/files that are published.</p>


答:
You have the .style.backgroundImage on elements. You can use this with the substring function to get the url.

```<code>st =document.querySelector('.image-container-image').style.backgroundImage;
url = st.substring(5, st.length -2);
</code>```

url would become https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg

EDIT If you want to you can change this to one line of code.

alert(document.querySelector('.image-container-image').style.backgroundImage.substring(5, document.querySelector('.image-container-image').style.backgroundImage.length -2))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);"></div></code>```

Title: Challenge JavaScript grab image URL from HTML class

Body:
This question differs from other questions before, in that here we have a
 STYLE inside a CLASS name. That made it a little more complicated to me.

I want to alert() ONLY the url of a image showing in the website, that is accessible with its class name:

I tried by doing:

alert( (document.querySelector('.image-container-image').textContent) );

Tried other different ways, but still no luck.

My output should be an alert showing the following url:
  "https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg"

Your guidance is very much appreciated.

Body:
You have the .style.backgroundImage on elements. You can use this with the substring function to get the url.

st =document.querySelector('.image-container-image').style.backgroundImage;
url = st.substring(5, st.length -2);

url would become https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg

EDIT If you want to you can change this to one line of code.

alert(document.querySelector('.image-container-image').style.backgroundImage.substring(5, document.querySelector('.image-container-image').style.backgroundImage.length -2))

<div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);"></div>


问:
Getting text from XPath but want elements?
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

```<code><node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>
</code>```

I wish to copy the content of node 2 including the tags, which is:

```<code><node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>
</code>```

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

答:
```<code>./node1/node()
</code>```

or:

```<code>./node1/node2/../node()
</code>```

When you want the whole HTML node, end the Xpath with /node().

Body:
I am new to XPath so please bear with me. Basic question.

I want to select text, including the elements as well.  Example input below:

<node1>
    <node2>
        <node3>A1</node3>
        <node3>A2</node3>
        <node3>A3</node3>
        <node3>A4</node3>
    </node2>
</node1>

I wish to copy the content of node 2 including the tags, which is:

<node2>
    <node3>A1</node3>
    <node3>A2</node3>
    <node3>A3</node3>
    <node3>A4</node3>
</node2>

However, if I use the XPath /node1/node2/, I only get values A1 A2 A3 A4 (not the node2 and node3 tags).

Body:
./node1/node()

or:

./node1/node2/../node()

When you want the whole HTML node, end the Xpath with /node().


问:
C# convert datetime to WCF datetime format
I parse c# object that has DateTime property with JsonNet and then I post it to the server. But it returns that the date format is wrong. It request to be with format like this:

```<code>"/Date(1327572000000-1000)/"
</code>```

How can I convert c# DateTime to this format?

答:
This is how WCF essentially serializes DateTime values (note that non-UTC values include information about current time zone)

```<code>public static string MsJson(DateTime value)
{
    long unixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
    long ticks = (value.ToUniversalTime().Ticks - unixEpochTicks) / 10000;

    if (value.Kind == DateTimeKind.Utc)
    {
        return String.Format("/Date({0})/", ticks);
    }
    else
    {
        TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
        string sign = ts.Ticks < 0 ? "-" : "+";
        int hours = Math.Abs(ts.Hours);
        string hs = (hours < 10)
            ? "0" + hours
            : hours.ToString(CultureInfo.InvariantCulture);
        int minutes = Math.Abs(ts.Minutes);
        string ms = (minutes < 10)
            ? "0" + minutes
            : minutes.ToString(CultureInfo.InvariantCulture);
        return string.Format("/Date({0}{1}{2}{3})/", ticks, sign, hs, ms);
    }
}
</code>```

Body:
I parse c# object that has DateTime property with JsonNet and then I post it to the server. But it returns that the date format is wrong. It request to be with format like this:

"/Date(1327572000000-1000)/"

How can I convert c# DateTime to this format?

Body:
This is how WCF essentially serializes DateTime values (note that non-UTC values include information about current time zone)

public static string MsJson(DateTime value)
{
    long unixEpochTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
    long ticks = (value.ToUniversalTime().Ticks - unixEpochTicks) / 10000;

    if (value.Kind == DateTimeKind.Utc)
    {
        return String.Format("/Date({0})/", ticks);
    }
    else
    {
        TimeSpan ts = TimeZone.CurrentTimeZone.GetUtcOffset(value.ToLocalTime());
        string sign = ts.Ticks < 0 ? "-" : "+";
        int hours = Math.Abs(ts.Hours);
        string hs = (hours < 10)
            ? "0" + hours
            : hours.ToString(CultureInfo.InvariantCulture);
        int minutes = Math.Abs(ts.Minutes);
        string ms = (minutes < 10)
            ? "0" + minutes
            : minutes.ToString(CultureInfo.InvariantCulture);
        return string.Format("/Date({0}{1}{2}{3})/", ticks, sign, hs, ms);
    }
}


问:
How to effectively work with multiple files in Vim
I've started using Vim to develop Perl scripts and am starting to find it very powerful.

One thing I like is to be able to open multiple files at once with:

```<code>vi main.pl maintenance.pl
</code>```

and then hop between them with:

```<code>:n
:prev
</code>```

and see which file are open with:

```<code>:args
</code>```

And to add a file, I can say:

```<code>:n test.pl
</code>```

which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type :args I only have test.pl open.

So how can I add and remove files in my args list?

答:
To change all buffers to tab view.

```<code> :tab sball
</code>```

will open all the buffers to tab view. Then we can use any tab related commands

```<code>gt or :tabn           "    go to next tab
gT or :tabp or :tabN  "    go to previous tab
</code>```

details at :help tab-page-commands.

We can instruct vim to open ,as tab view, multiple files by vim -p file1 file2.
alias vim='vim -p' will be useful.

The same thing can also be achieved by having following autocommand in ~/.vimrc

```<code> au VimEnter * if !&diff | tab all | tabfirst | endif
</code>```

Anyway to answer the question:
To add to arg list: arga file,

To delete from arg list: argd pattern

More at :help arglist

OwnerDisplayName: Edward Tanguay

Body:
I've started using Vim to develop Perl scripts and am starting to find it very powerful.

One thing I like is to be able to open multiple files at once with:

vi main.pl maintenance.pl

and then hop between them with:

:n
:prev

and see which file are open with:

:args

And to add a file, I can say:

:n test.pl

which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type :args I only have test.pl open.

So how can I add and remove files in my args list?

Body:
To change all buffers to tab view.

 :tab sball

will open all the buffers to tab view. Then we can use any tab related commands

gt or :tabn           "    go to next tab
gT or :tabp or :tabN  "    go to previous tab

details at :help tab-page-commands.

We can instruct vim to open ,as tab view, multiple files by vim -p file1 file2.
alias vim='vim -p' will be useful.

The same thing can also be achieved by having following autocommand in ~/.vimrc

 au VimEnter * if !&diff | tab all | tabfirst | endif

Anyway to answer the question:
To add to arg list: arga file,

To delete from arg list: argd pattern

More at :help arglist


问:
Get CMake to not be silent about sources it doesn't understand?
Suppose you have a very simple CMakeLists.txt

```<code>add_executable(silent T.cpp A.asm)
</code>```

CMake will happily generate a C++ target for building silent, with T.cpp in it, but will silently drop any and all reference to A.asm, because it doesn't know what to do with the suffix.

Is there any way to get CMake to loudly complain about this source file it doesn't understand (to aid in porting a Makefile to CMake).

答:
CMake doesn't just drop unknown files in add_executable().

If alongside with

```<code>add_executable(silent T.cpp A.asm)
</code>```

you have

```<code>add_custom_command(OUTPUT A.asm COMMAND <...>
    DEPENDS <dependees>)
</code>```

then whenever <dependees> changed CMake will rerun command for create A.asm before compiling the executable.

Note, that automatical headers scanning doesn't provide such functionality: if your executable includes foo.h then executable will be rebuilt only when foo.h itself is changed. Any custom command creating this header will be ignored.

However, you may change behavior of add_executable by redefining it. See @Florian's answer for example of such redefinition.

Body:
Suppose you have a very simple CMakeLists.txt

add_executable(silent T.cpp A.asm)

CMake will happily generate a C++ target for building silent, with T.cpp in it, but will silently drop any and all reference to A.asm, because it doesn't know what to do with the suffix.

Is there any way to get CMake to loudly complain about this source file it doesn't understand (to aid in porting a Makefile to CMake).

Body:
CMake doesn't just drop unknown files in add_executable().

If alongside with

add_executable(silent T.cpp A.asm)

you have

add_custom_command(OUTPUT A.asm COMMAND <...>
    DEPENDS <dependees>)

then whenever <dependees> changed CMake will rerun command for create A.asm before compiling the executable.

Note, that automatical headers scanning doesn't provide such functionality: if your executable includes foo.h then executable will be rebuilt only when foo.h itself is changed. Any custom command creating this header will be ignored.

However, you may change behavior of add_executable by redefining it. See @Florian's answer for example of such redefinition.


问:
Challenge JavaScript grab image URL from HTML class
This question differs from other questions before, in that here we have a
 STYLE inside a CLASS name. That made it a little more complicated to me.

I want to alert() ONLY the url of a image showing in the website, that is accessible with its class name:

```<code>    <div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>
</code>```

I tried by doing:

```<code>alert( (document.querySelector('.image-container-image').textContent) );
</code>```

Tried other different ways, but still no luck.

My output should be an alert showing the following url:
  "https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg"

Your guidance is very much appreciated.

答:
Here is the solution:

// Get the image, style and the url from it
var img = document.getElementsByClassName('image-container-image')[0],
    style = img.currentStyle || window.getComputedStyle(img, false),
    bi = style.backgroundImage.slice(4, -1);

// For IE we need to remove quotes to the proper url
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Display the url to the user
alert('Image URL: ' + bi);```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div></code>```

Body:
Here is the solution:

// Get the image, style and the url from it
var img = document.getElementsByClassName('image-container-image')[0],
    style = img.currentStyle || window.getComputedStyle(img, false),
    bi = style.backgroundImage.slice(4, -1);

// For IE we need to remove quotes to the proper url
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Display the url to the user
alert('Image URL: ' + bi);

 <div  class='image-container-image' style="background-image:url(https://lh4.googleusercontent.com/-2h9xCStgaCM/AAAAAAAAAAI/AAAAAAAAhjs/TNS6opAJ52g/photo.jpg);">
</div>


答: If you have braces in your regular expression, nginx requires it to be quoted. It's mentioned for the rewrite directive, but I think it's applicable for most nginx directives that accept a regular expression.

Title: Nginx regex in location path or server_name

Body:
I am trying to use regex with nginx to allow requests containing some conditions without success.

for example one of the errors ginx: [emerg] pcre_compile() failed: missing ) in "(^/(unsafe)\/([0-9]" in /etc/nginx/sites-enabled/file.conf:33.

The regex should be ok according to https://regex101.com/, so I guess the issue with the nginx and this regex, so I need some help how to do it.

Regex:

^(http|https):\/\/(my[.]domain[.]com)\/(unsafe)\/([0-9]{0,4})x([0-9]{0,4})\/((ch)|[a-z0-9]{0,32})\/(([3_]+[a-z0-9]{0,32}\.jpg)|([c_1_]+[a-z0-9]{0,32}\.jpg)|([a-z0-9]{0,32}\.jpg)|(fb\/[0-9]{0,6}.jpg)|([a-z0-9]{0,6}\/[0-9]{0,6}.jpg))

Urls:

https://my.domain.com/unsafe/1530x55/7550/3_c892b2c2de030f40.jpg
https://my.domain.com/unsafe/1030x1345/71b0c5d3f50/c_1_c8928dc3e030f40.jpg
https://my.domain.com/unsafe/1030x4443/79481b0c5d3f50/c892333e030f40.jpg
https://my.domain.com/unsafe/0x0/ch/fb/157233.jpg
https://my.domain.com/unsafe/0x0/ch/6chars/123456.jpg

1.

server_name ~^(my[.]domain[.]com)\/(unsafe)\/([0-9]{0,4})x([0-9]{0,4})\/((ch)|[a-z0-9]{0,32})\/(([3_]+[a-z0-9]{0,32}\.jpg)|([c_1_]+[a-z0-9]{0,32}\.jpg)|([a-z0-9]{0,32}\.jpg)|(fb\/[0-9]{0,6}.jpg)|([a-z0-9]{0,6}\/[0-9]{0,6}.jpg));

or:

location ~ (/(unsafe)\/([0-9]{0,4})x([0-9]{0,4})\/((ch)|[a-z0-9]{0,32})\/(([3_]+[a-z0-9]{0,32}\.jpg)|([c_1_]+[a-z0-9]{0,32}\.jpg)|([a-z0-9]{0,32}\.jpg)|(fb\/[0-9]{0,6}.jpg)|([a-z0-9]{0,6}\/[0-9]{0,6}.jpg))) {
     empty
}

Thanks


问:
Collapse Relationships Neo4j?
Is it possible to "collapse" relationships in neo4j? I'm trying to graph relationships between people, and they can be related in multiple different ways - a shared course, jointly authored paper, RT or tweet mention. Right now I'm modeling people, courses, papers, and tweets all as nodes. But what I'm really interested in is modeling the person-person relationships that go through these intermediary nodes. Is it possible to graph the implicit relationship (person-course-person) explicit (person-person), while still keeping the course as a node? Something like this http://catalhoyuk.stanford.edu/network/teams/ - slide 2 and 3.

Any other data modeling suggestions welcome as well.

答:
Yes, you can do it. The query

```<code>MATCH(a:Person)-->(:Course)<--(b:Person)
CREATE (a)-[:IMPLICIT_RELATIONSHIP]->(b)
</code>```

will crate a relationship with type :IMPLICIT_RELATIONSHIP between all people that are related to the same course. But probably you don't need it since you can transverse from a to b and from b to a without this extra and not necessary relationship. Also if you want a virtual relationship at query time to use in a projection you can use the APOC procedure apoc.create.vRelationship.

The APOC procedures docs says:

Virtual Nodes and Relationships don’t exist in the graph, they are
  only returned to the UI/user for representing a graph projection. They
  can be visualized or processed otherwise. Please note that they have
  negative id’s.

Title: Collapse Relationships Neo4j?

Body:
Yes, you can do it. The query

MATCH(a:Person)-->(:Course)<--(b:Person)
CREATE (a)-[:IMPLICIT_RELATIONSHIP]->(b)

will crate a relationship with type :IMPLICIT_RELATIONSHIP between all people that are related to the same course. But probably you don't need it since you can transverse from a to b and from b to a without this extra and not necessary relationship. Also if you want a virtual relationship at query time to use in a projection you can use the APOC procedure apoc.create.vRelationship.

The APOC procedures docs says:

Virtual Nodes and Relationships don’t exist in the graph, they are
  only returned to the UI/user for representing a graph projection. They
  can be visualized or processed otherwise. Please note that they have
  negative id’s.


问:
.Htaccess rewrite to username
I'm a beginner in php and primarily with htaccess part. It's pretty darn confusing.

So I have this file :-

```<code>www.domain.com/profile.php?username=my_username
</code>```

How can I make the above accessible using only :-

```<code>wwww.domain.com/my_username
</code>```

Any kind of directions would be helpful

Something that I tried :-

```<code>RewriteEngine on
RewriteRule ^/([0-9]+)$ /profile.php?username=$1
</code>```

答:
The .htaccess file has to be given permission by apache to modify/override settings, depending on your host this might not be enabled by default.

As others have mentioned .htaccess isn't part of PHP it's a file that tells apache how to deal with certain request and what parts of the server are allow to be accessed along with other functionality.

You can achieve your desired result with rewritecond just make sure the Rewrite Engine is enabled.

Here is some more information about .htaccess https://code.tutsplus.com/tutorials/the-ultimate-guide-to-htaccess-files--net-4757

Title: .Htaccess rewrite to username

Body:
I'm a beginner in php and primarily with htaccess part. It's pretty darn confusing.

So I have this file :-

www.domain.com/profile.php?username=my_username

How can I make the above accessible using only :-

wwww.domain.com/my_username

Any kind of directions would be helpful

Something that I tried :-

RewriteEngine on
RewriteRule ^/([0-9]+)$ /profile.php?username=$1


问:
Can't compile asm hello world with gcc
This is the code in hello.s

```<code>.data

hello_str:
    .string "Hello, world!\n"

    .set hello_str_length, . - hello_str - 1

.text

.globl  main

.type   main, @function

main:
    movl    $4, %eax

    movl    $1, %ebx

    movl    $hello_str, %ecx

    movl    $hello_str_length, %edx

    int     $0x80

    movl    $1, %eax
    movl    $0, %ebx
    int     $0x80

    .size   main, . - main
</code>```

I run gcc hello.s -o hello and get this error:

```<code>/usr/bin/ld: /tmp/cc6ILJpd.o: relocation R_X86_64_32 against '.data' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
</code>```

collect2: error: ld returned 1 exit status

Then I've tried running gcc hello.s -fPIC -o hello, but it didn't do anything, the error is the same.

What am I doing wrong? Ubuntu 17.04, GCC 6.3.0.

答:
You're trying to compile i386 code in amd64 mode, which doesn't work. Try this instead:

```<code>gcc -m32 hellos. -o hello
</code>```

...to force i386 mode.

Edit: I recognised this because I know what i386 and amd64 code looks like, but a better clue is in the relocation name, R_X86_64_32. X86_64 is another name for the amd64 architecture; so what this is saying is that it's a 32 bit relocation for the X86_64 architecture. Given that you're not writing code for that architecture, that's a reasonable sign that it's the wrong compiler.

Title: Can't compile asm hello world with gcc

Body:
This is the code in hello.s

.data

hello_str:
    .string "Hello, world!\n"

    .set hello_str_length, . - hello_str - 1

.text

.globl  main

.type   main, @function

main:
    movl    $4, %eax

    movl    $1, %ebx

    movl    $hello_str, %ecx

    movl    $hello_str_length, %edx

    int     $0x80

    movl    $1, %eax
    movl    $0, %ebx
    int     $0x80

    .size   main, . - main

I run gcc hello.s -o hello and get this error:

/usr/bin/ld: /tmp/cc6ILJpd.o: relocation R_X86_64_32 against '.data' can not be used when making a shared object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output

collect2: error: ld returned 1 exit status

Then I've tried running gcc hello.s -fPIC -o hello, but it didn't do anything, the error is the same.

What am I doing wrong? Ubuntu 17.04, GCC 6.3.0.

Body:
You're trying to compile i386 code in amd64 mode, which doesn't work. Try this instead:

gcc -m32 hellos. -o hello

...to force i386 mode.

Edit: I recognised this because I know what i386 and amd64 code looks like, but a better clue is in the relocation name, R_X86_64_32. X86_64 is another name for the amd64 architecture; so what this is saying is that it's a 32 bit relocation for the X86_64 architecture. Given that you're not writing code for that architecture, that's a reasonable sign that it's the wrong compiler.


问:
Silverlight TextBlock Binding to SelectedItem in ComboBox
I have a ComboBox that is bound to a collection of CLR objects. Each item in the ComboBox is displayed via a DataTemplate. This DataTemplate contains an Image and a Title associated with the item. After a user clicks an item in the ComboBox, I want to display the selected items Title in another TextBlock in the screen.

My question is, how do I bind the Text property of the TextBlock to the Title property of the item selected in the comboBox?

Thank you!

答:
Assuming you called the ComboBox "ComboBox1"
You could use-</p>

```<code><TextBlock Text="{Binding ElementName=ComboBox1,Path=SelectedItem.Title}"/>
</code>```

Body:
Assuming you called the ComboBox "ComboBox1"
You could use-

<TextBlock Text="{Binding ElementName=ComboBox1,Path=SelectedItem.Title}"/>


问:
Test Services in Angular 4 which as setTimeout
I have a service in which has some dependency injected using the Injector (I have inherited this code and cant change the initialization for now) using setTimeout

```<code>@Injectable
export class MyService {
router:Router;
    constructor(private injector: Injector) {
      setTimeout(() => {
        debugger;
        this.router = injector.get(Router);
      });
    }

    public myMethod(){
      const someString = this.router.url.slice(1,someLength);
    }
}
</code>```

I need to test myMethod but when Ever I test this the setTimeout is called after the TestInExecution-> mymethod is called and gives an error

TypeError: Cannot read property 'url' of undefined as Router is not instantiated.

How to make sure that the router is injected properly before executing the test.

```<code>fit('Test My Service', fakeAsync(inject([Router, Location, MyService],
    (_router: Router, _location: Location, myService: MyService) => {
        let fixture = TestBed.createComponent(SomeComponent);
        //Wait for component to Initialize
        tick(500);
        fixture.detectChanges();
        fixture.whenStable().then(() => {
            _router.navigate(['/someCompoenet']).then(() => {
                expect(myService.myMethod()).toBe('Some String');
            });
        });
    })));
</code>```

答:
In the Angular documentation they use stubs to swap out the router. Could you not do that?

check out testing/router-stubs.ts here

Body:
I have a service in which has some dependency injected using the Injector (I have inherited this code and cant change the initialization for now) using setTimeout

@Injectable
export class MyService {
router:Router;
    constructor(private injector: Injector) {
      setTimeout(() => {
        debugger;
        this.router = injector.get(Router);
      });
    }

    public myMethod(){
      const someString = this.router.url.slice(1,someLength);
    }
}

I need to test myMethod but when Ever I test this the setTimeout is called after the TestInExecution-> mymethod is called and gives an error

TypeError: Cannot read property 'url' of undefined as Router is not instantiated.

How to make sure that the router is injected properly before executing the test.

fit('Test My Service', fakeAsync(inject([Router, Location, MyService],
    (_router: Router, _location: Location, myService: MyService) => {
        let fixture = TestBed.createComponent(SomeComponent);
        //Wait for component to Initialize
        tick(500);
        fixture.detectChanges();
        fixture.whenStable().then(() => {
            _router.navigate(['/someCompoenet']).then(() => {
                expect(myService.myMethod()).toBe('Some String');
            });
        });
    })));