问:
Compiling C and sqlite3
I'm having some trouble incorporating sqlite3 into a program I'm writing. I've been scouring the internet over the past few days attempting to find a solution. I'm using the MinGW compiler and have already tried:

Ensuring the C:\MinGW\bin directory is included in both the user and system environment Path variables with no spaces and separated with a semi-colon

Using the command prompt and entering "C:\MinGW\bin\gcc shell.c sqlite3.c -lpthread -ldl" in the same directory of all related files which returns the result "c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -ldl
collect2.exe: error: ld returned 1 exit status"

Fresh install of MinGW and eclipse

If it helps this is the code I'm testing this with, I can't get the includes to show up as code but they are all in carets in order, iostream, stdio.h, and sqlite3.h
It returns the error "fatal error: sqlite3.h: No such file or directory". I have all of the include files in the same directory as the .cpp source as well.

```<code>int main(int argc, char* argv[])
{
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    rc = sqlite3_open("text.db", &db);
    return 0;
}
</code>```

Title: Compiling C and sqlite3

Body:
I'm having some trouble incorporating sqlite3 into a program I'm writing. I've been scouring the internet over the past few days attempting to find a solution. I'm using the MinGW compiler and have already tried:

Ensuring the C:\MinGW\bin directory is included in both the user and system environment Path variables with no spaces and separated with a semi-colon

Using the command prompt and entering "C:\MinGW\bin\gcc shell.c sqlite3.c -lpthread -ldl" in the same directory of all related files which returns the result "c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -ldl
collect2.exe: error: ld returned 1 exit status"

Fresh install of MinGW and eclipse

If it helps this is the code I'm testing this with, I can't get the includes to show up as code but they are all in carets in order, iostream, stdio.h, and sqlite3.h
It returns the error "fatal error: sqlite3.h: No such file or directory". I have all of the include files in the same directory as the .cpp source as well.

int main(int argc, char* argv[])
{
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    rc = sqlite3_open("text.db", &db);
    return 0;
}

Body:
#include <stdio.h>
#include "sqlite3.h"

int main(int argc, char* argv[])
{
    sqlite3 *db;
    char *zErrMsg = 0;
    int rc;
    rc = sqlite3_open("text.db", &db);
    return 0;
}

Compile and test result:

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$ mingw32-gcc -o test main.c sqlite3.c -I./

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$ ll
total 8485
-rw-r--r-- 1 w00343520 1049089     192 六月  8 10:38 main.c
-rw-r--r-- 1 w00343520 1049089  236938 五月 26 00:15 shell.c
-rw-r--r-- 1 w00343520 1049089 7130198 五月 26 00:15 sqlite3.c
-rw-r--r-- 1 w00343520 1049089  498184 五月 26 00:15 sqlite3.h
-rw-r--r-- 1 w00343520 1049089   30199 五月 26 00:15 sqlite3ext.h
-rwxr-xr-x 1 w00343520 1049089  785640 六月  8 10:38 test.exe*

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$ ./test.exe

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$ ll
total 8485
-rw-r--r-- 1 w00343520 1049089     192 六月  8 10:38 main.c
-rw-r--r-- 1 w00343520 1049089  236938 五月 26 00:15 shell.c
-rw-r--r-- 1 w00343520 1049089 7130198 五月 26 00:15 sqlite3.c
-rw-r--r-- 1 w00343520 1049089  498184 五月 26 00:15 sqlite3.h
-rw-r--r-- 1 w00343520 1049089   30199 五月 26 00:15 sqlite3ext.h
-rwxr-xr-x 1 w00343520 1049089  785640 六月  8 10:38 test.exe*
-rw-r--r-- 1 w00343520 1049089       0 六月  8 10:41 text.db

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$

The test result for shell.c:

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$ mingw32-gcc -o sqlite shell.c sqlite3.c -I./

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$ ./sqlite.exe

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$ ./sqlite.exe --help
Usage: D:\Download\sqlite-amalgamation-3190200\sqlite-amalgamation-3190200\sqlite.exe [OPTIONS] FILENAME [SQL]
FILENAME is the name of an SQLite database. A new database is created
if the file does not previously exist.
OPTIONS include:
   -ascii               set output mode to 'ascii'
   -bail                stop after hitting an error
   -batch               force batch I/O
   -column              set output mode to 'column'
   -cmd COMMAND         run "COMMAND" before reading stdin
   -csv                 set output mode to 'csv'
   -echo                print commands before execution
   -init FILENAME       read/process named file
   -[no]header          turn headers on or off
   -help                show this message
   -html                set output mode to HTML
   -interactive         force interactive I/O
   -line                set output mode to 'line'
   -list                set output mode to 'list'
   -lookaside SIZE N    use N entries of SZ bytes for lookaside memory
   -mmap N              default mmap size set to N
   -newline SEP         set output row separator. Default: '\n'
   -nullvalue TEXT      set text string for NULL values. Default ''
   -pagecache SIZE N    use N slots of SZ bytes each for page cache memory
   -scratch SIZE N      use N slots of SZ bytes each for scratch memory
   -separator SEP       set output column separator. Default: '|'
   -stats               print memory stats before each finalize
   -version             show SQLite version
   -vfs NAME            use NAME as the default VFS

w00343520@wuhy1w001184171 MINGW64 /d/Download/sqlite-amalgamation-3190200/sqlite-amalgamation-3190200
$


来源: stackexchange

问:
Remove legend in multiple plots?
I want to make multiplots containing 5 barcharts (with 2 colomns and 3 rows) I want the legend is appeared in the rows 3, column 2. And also, I want to change label from (A, B, C..) into (m/z=450.02 RT 9.52, m/z 500.07 RT 10, ...)  that will appear in the up-right position of each plot.
Also, I want to add error bar in the first chart with data SD, but I couldn't add them in the plot.
Please help me to solve this plots. Thank you!

Here's my console:

```<code>data <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
               intensity = c(7378298.69217025,9009027.95021888,11106773.0180047,3010750.725502,25794620.5038354),
               sd = c(2554669.97449261,1054643.80319534,4936955.54885355, 1606982.34241596, 9975537.82883142))
</code>```

head(data)

```<code>data1 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(1089586.025,
                              1622944.618,
                              1466859.571,
                              1213772.715,
                              9310160.875))
data2 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(1196693.956,
                              1742096.027,
                              1545728.252,
                              1307935.409,
                              9569069.002))

data2 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(1196693.956,
                              1742096.027,
                              1545728.252,
                              1307935.409,
                              9569069.002))
data3 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(106964005.1,
                              92622841.82,
                              122723308,
                              159793488.3,
                              153196930.7))
data4 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(770606573.5,
                              613182573.3,
                              780913983.6,
                              829523587.7,
                              809287616.6))
</code>```

making plot

```<code>    p <-ggplot(data, aes(group, y=intensity)) +
 geom_bar(stat="identity", aes(fill =group ))+theme(legend.position = "none")
 theme_minimal()+
 theme(axis.title.x=element_blank(),
 axis.text.x=element_blank(),
 axis.ticks.x=element_blank())

        p1 <-ggplot(data1, aes(group, y=intensity)) +
    geom_bar(stat="identity", aes(fill =group ))+
   theme_minimal()+
  theme(axis.title.x=element_blank(),
       axis.text.x=element_blank(),
       axis.ticks.x=element_blank())
     p2 <-ggplot(data2, aes(group, y=intensity)) +
   geom_bar(stat="identity", aes(fill =group ))+
  theme_minimal()+
  theme(axis.title.x=element_blank(),
          axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
    p3 <-ggplot(data3, aes(group, y=intensity)) +
  geom_bar(stat="identity", aes(fill =group ))+
  theme_minimal()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
    p4 <-ggplot(data4, aes(group, y=intensity)) +
  geom_bar(stat="identity", aes(fill =group ))+
  theme_minimal()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
    library(grid)
plot_grid(p,p1,p2,p3,p4, labels=c("A", "B","C","D","E"), ncol = 2, nrow = 3)
</code>```

答:
```<code>data0 <- data

library(plyr)
all<- ldply(0:4, function(x){
          tmp <- get(paste0("data", x))
          tmp$gp <- x
          tmp
       })

ggplot(all, aes(group, intensity, fill=group)) +
  geom_bar(stat="identity", aes(fill =group )) +
  geom_errorbar(data=all[all$gp==0, ], aes(
                ymin=intensity-sd, ymax=intensity+sd)) +
  facet_wrap(~gp, scales="free", ncol=2) +
  theme_minimal()+
  theme(legend.position = "bottom",
        axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        strip.background = element_blank(),
        strip.text.x = element_blank())
</code>```

ContentLicense: CC BY-SA 3.0

Title: Remove legend in multiple plots?

Body:
I want to make multiplots containing 5 barcharts (with 2 colomns and 3 rows) I want the legend is appeared in the rows 3, column 2. And also, I want to change label from (A, B, C..) into (m/z=450.02 RT 9.52, m/z 500.07 RT 10, ...)  that will appear in the up-right position of each plot.
Also, I want to add error bar in the first chart with data SD, but I couldn't add them in the plot.
Please help me to solve this plots. Thank you!

Here's my console:

data <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
               intensity = c(7378298.69217025,9009027.95021888,11106773.0180047,3010750.725502,25794620.5038354),
               sd = c(2554669.97449261,1054643.80319534,4936955.54885355, 1606982.34241596, 9975537.82883142))

head(data)

data1 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(1089586.025,
                              1622944.618,
                              1466859.571,
                              1213772.715,
                              9310160.875))
data2 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(1196693.956,
                              1742096.027,
                              1545728.252,
                              1307935.409,
                              9569069.002))

data2 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(1196693.956,
                              1742096.027,
                              1545728.252,
                              1307935.409,
                              9569069.002))
data3 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(106964005.1,
                              92622841.82,
                              122723308,
                              159793488.3,
                              153196930.7))
data4 <- data.frame(group = c("B. mamane+SAHAall","B. mamane+SAHAprod","Untreated B. mamane","B. mamane+VSall","B. mamane+VSprod"),
                intensity = c(770606573.5,
                              613182573.3,
                              780913983.6,
                              829523587.7,
                              809287616.6))

making plot

    p <-ggplot(data, aes(group, y=intensity)) +
 geom_bar(stat="identity", aes(fill =group ))+theme(legend.position = "none")
 theme_minimal()+
 theme(axis.title.x=element_blank(),
 axis.text.x=element_blank(),
 axis.ticks.x=element_blank())

        p1 <-ggplot(data1, aes(group, y=intensity)) +
    geom_bar(stat="identity", aes(fill =group ))+
   theme_minimal()+
  theme(axis.title.x=element_blank(),
       axis.text.x=element_blank(),
       axis.ticks.x=element_blank())
     p2 <-ggplot(data2, aes(group, y=intensity)) +
   geom_bar(stat="identity", aes(fill =group ))+
  theme_minimal()+
  theme(axis.title.x=element_blank(),
          axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
    p3 <-ggplot(data3, aes(group, y=intensity)) +
  geom_bar(stat="identity", aes(fill =group ))+
  theme_minimal()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
    p4 <-ggplot(data4, aes(group, y=intensity)) +
  geom_bar(stat="identity", aes(fill =group ))+
  theme_minimal()+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())
    library(grid)
plot_grid(p,p1,p2,p3,p4, labels=c("A", "B","C","D","E"), ncol = 2, nrow = 3)


问:
Removing specific parts of the image in openCV
I am doing some image processing and need to do the following task in images ::

Image

From here I want to remove eyes, eyebrows, lips etc such that the smoothness of the image is not lost (eg, if the eyes are removed then the area should be replaced with neighboring colors).

I have the details(Points) of the area covering the part that needs to be flatten(eyes etc).Shown below::

答:
A Python version, using simple threshold to select facial features (because I don't have those green contours), then inpainting, as mentioned in Phann's answer:

```<code>import cv2
import numpy as np

def get_inpainted(img):
    gs = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gs, 70, 1, cv2.THRESH_BINARY)
    mask_features = 1 - thresh #1 for the dark pixels, 0 everywhere else
    #enlarge the mask a little bit...
    mask_features = cv2.dilate(mask_features, np.ones((8, 8), np.uint8))
    return cv2.inpaint(img, mask_features, 8, cv2.INPAINT_NS)

img_source = cv2.imread("test_images/face.jpg")
img_dest = img_source[:]

#manually select two areas of interest
img_dest[158:276, 34:213] = get_inpainted(img_source[158:276, 34:213]) #eyebrows to nostrils
img_dest[278:343, 68:190] = get_inpainted(img_source[278:343, 68:190]) #mouth

cv2.imwrite("test_images/face_inp.jpg", img_dest)
</code>```

And so we turn the guy from your first picture (left) into a faceless scary dude (right):

Body:
A Python version, using simple threshold to select facial features (because I don't have those green contours), then inpainting, as mentioned in Phann's answer:

import cv2
import numpy as np

def get_inpainted(img):
    gs = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gs, 70, 1, cv2.THRESH_BINARY)
    mask_features = 1 - thresh #1 for the dark pixels, 0 everywhere else
    #enlarge the mask a little bit...
    mask_features = cv2.dilate(mask_features, np.ones((8, 8), np.uint8))
    return cv2.inpaint(img, mask_features, 8, cv2.INPAINT_NS)

img_source = cv2.imread("test_images/face.jpg")
img_dest = img_source[:]

#manually select two areas of interest
img_dest[158:276, 34:213] = get_inpainted(img_source[158:276, 34:213]) #eyebrows to nostrils
img_dest[278:343, 68:190] = get_inpainted(img_source[278:343, 68:190]) #mouth

cv2.imwrite("test_images/face_inp.jpg", img_dest)

And so we turn the guy from your first picture (left) into a faceless scary dude (right):


问:
SQL Server Merging two records into one
I have this table:

```<code>--------------------------------
|ID|SN|SEC|Qty|DONE_CON|DONE_BY|
|--+--+---+---+--------+-------|
|1A|1A|ETC|124|YES     |       |
|2B|1A|CON|   |        |David  |
|1H|1H|ETC|764|YES     |       |
|2R|1H|CON|   |        |Maria  |
--------------------------------
</code>```

What I want to do is to get all the CON as the SEC and show its ID, Qty and DONE_BY values.

My problem is Qty will come from its reference record (RF column).

Example:

CON record with ID 2B has 1A as its RF. So the Qty will be 124.

CON record with ID 2R has 1H as its RF. So the Qty will be 764.

Final Output should look like this:

```<code>----------------
|ID|Qty|DONE_BY|
|--+---+-------|
|2B|124|David  |
|2R|764|Maria  |
----------------
</code>```

Currently, I only have this query:

```<code>SELECT ID, Qty, DONE_BY FROM TBL_TEST WHERE SEC='CON'
</code>```

Please, help me. Thank you in advance.

答:
Try this query --</p>

```<code>SELECT T1.ID
    ,T2.Qty
    ,T1.DONE_BY
FROM tblSample T1
INNER JOIN tblSample T2 ON T1.SN = T2.ID
AND T1.Sec = N'CON'
</code>```

Title: SQL Server Merging two records into one

Body:
I have this table:

--------------------------------
|ID|SN|SEC|Qty|DONE_CON|DONE_BY|
|--+--+---+---+--------+-------|
|1A|1A|ETC|124|YES     |       |
|2B|1A|CON|   |        |David  |
|1H|1H|ETC|764|YES     |       |
|2R|1H|CON|   |        |Maria  |
--------------------------------

What I want to do is to get all the CON as the SEC and show its ID, Qty and DONE_BY values.

My problem is Qty will come from its reference record (RF column).

Example:

CON record with ID 2B has 1A as its RF. So the Qty will be 124.

CON record with ID 2R has 1H as its RF. So the Qty will be 764.

Final Output should look like this:

----------------
|ID|Qty|DONE_BY|
|--+---+-------|
|2B|124|David  |
|2R|764|Maria  |
----------------

Currently, I only have this query:

SELECT ID, Qty, DONE_BY FROM TBL_TEST WHERE SEC='CON'

Please, help me. Thank you in advance.

Body:
Try this query --

SELECT T1.ID
    ,T2.Qty
    ,T1.DONE_BY
FROM tblSample T1
INNER JOIN tblSample T2 ON T1.SN = T2.ID
AND T1.Sec = N'CON'


问:
php/sql- How do I use LIKE operator on variable to pull results from database?
As question said, I want to use the LIKE Operator so whenever user inputs something, like "M", it returns all database entries starting with "m" rather then anything named just "M". This is my code

```<code>$strSymbolName = @$_REQUEST["searchSymbol"];
//searchSymbol is the variable with user Input inside

if(!empty($strSymbolName))
{ // process the form
 // Establish dbserver connection and default database

$db = $objDBUtil->Open();
 // Run a Query to get company name

$query = "SELECT symSymbol, symName FROM symbols " .
 "WHERE symSymbol =" . $objDBUtil->DBQuotes($strSymbolName);
//Retrieves company symbol and name from database. Stores this in result

$result = $db->query($query);`
</code>```

What I thought of doing was using the LIKE operator on the WHERE statement, so something like-

```<code>WHERE symSymbol LIKE = " . $objDBUtil->DBQuotes($strSymbolName);
</code>```

But this didn't work...How would I apply the LIKE operator here?

答:
Use the % wildcard after the string you want to look for.

```<code>$query = "SELECT symSymbol, symName FROM symbols WHERE symSymbol LIKE ".$objDBUtil->DBQuotes($strSymbolName)."%";
</code>```

A bit more on the % and other wildcards: https://www.w3schools.com/sql/sql_wildcards.asp

Excerpt from above link:

WHERE CustomerName LIKE 'a%'        || Finds any values that starts
  with "a"

WHERE CustomerName LIKE '%a'        || Finds any values that ends with
  "a"

WHERE CustomerName LIKE '%or%'    || Finds any values that have "or"
  in any position

WHERE CustomerName LIKE '_r%'       || Finds any values that have "r"
  in the second position

WHERE CustomerName LIKE 'a_%_%' || Finds any values that starts with
  "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'          || Finds any values that starts
  with "a" and ends with "o"

Body:
As question said, I want to use the LIKE Operator so whenever user inputs something, like "M", it returns all database entries starting with "m" rather then anything named just "M". This is my code

$strSymbolName = @$_REQUEST["searchSymbol"];
//searchSymbol is the variable with user Input inside

if(!empty($strSymbolName))
{ // process the form
 // Establish dbserver connection and default database

$db = $objDBUtil->Open();
 // Run a Query to get company name

$query = "SELECT symSymbol, symName FROM symbols " .
 "WHERE symSymbol =" . $objDBUtil->DBQuotes($strSymbolName);
//Retrieves company symbol and name from database. Stores this in result

$result = $db->query($query);`

What I thought of doing was using the LIKE operator on the WHERE statement, so something like-

WHERE symSymbol LIKE = " . $objDBUtil->DBQuotes($strSymbolName);

But this didn't work...How would I apply the LIKE operator here?

Body:
Use the % wildcard after the string you want to look for.

$query = "SELECT symSymbol, symName FROM symbols WHERE symSymbol LIKE ".$objDBUtil->DBQuotes($strSymbolName)."%";

A bit more on the % and other wildcards: https://www.w3schools.com/sql/sql_wildcards.asp

Excerpt from above link:

WHERE CustomerName LIKE 'a%'        || Finds any values that starts
  with "a"

WHERE CustomerName LIKE '%a'        || Finds any values that ends with
  "a"

WHERE CustomerName LIKE '%or%'    || Finds any values that have "or"
  in any position

WHERE CustomerName LIKE '_r%'       || Finds any values that have "r"
  in the second position

WHERE CustomerName LIKE 'a_%_%' || Finds any values that starts with
  "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o'          || Finds any values that starts
  with "a" and ends with "o"


问:
Generic method and JSON
I wrote generic method which returns list of some objects, for example Orders. My question is why in second, non-generic method it returns correct list of Orders and the first method (generic) returns list of linkedHashMaps instead of Orders?

Generic:

```<code> private <T> List<T> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<T>> mapType = new TypeReference<List<T>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}
</code>```

Non-generic:

```<code>private List<Order> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<Order>> mapType = new TypeReference<List<Order>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}
</code>```

Generic method returns that:
LinkedHashMap

答:
The problem is that the generic type variable T is not bound to any concrete type, so the compiler sees it as Object. So:

```<code>TypeReference<List<T>> mapType = new TypeReference<List<T>>() {};
</code>```

is actually:

```<code>TypeReference<List<Object>> mapType = new TypeReference<List<Object>>() {};
</code>```

And when the ObjectMapper can't gather info about the concrete type of the object to deserialize, it defaults to LinkedHashMap.

If you want to be able to deserialize to a generic type at runtime, you should pass the TypeReference type token as an argument to your mapObjectsToList method:

```<code>// Make this a singleton, i.e. don't create a new instance on every call!
ObjectMapper objectMapper = new ObjectMapper();

private <T> List<T> mapObjectsToList(
        String objectsListInJson,
        TypeReference<List<T>> mapType) throws IOException {

    return objectMapper.readValue(objectsListInJson, mapType);
}
</code>```

And then use the above method as follows:

```<code>List<Order> orders = mapObjectsToList(
    stringWithTheJSON,
    new TypeReference<List<Order>> {});
</code>```

On a side note, I've moved the ObjectMapper objectMapper = new ObjectMapper() statement outside the method. There should be only one ObjectMapper instance in the whole application, unless you require different configuration for serializing/deserializing.

Title: Generic method and JSON

Body:
I wrote generic method which returns list of some objects, for example Orders. My question is why in second, non-generic method it returns correct list of Orders and the first method (generic) returns list of linkedHashMaps instead of Orders?

Generic:

 private <T> List<T> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<T>> mapType = new TypeReference<List<T>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}

Non-generic:

private List<Order> mapObjectsToList(String objectsListInJson) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    TypeReference<List<Order>> mapType = new TypeReference<List<Order>>() {
    };
    return objectMapper.readValue(objectsListInJson, mapType);
}

Generic method returns that:
LinkedHashMap

Body:
The problem is that the generic type variable T is not bound to any concrete type, so the compiler sees it as Object. So:

TypeReference<List<T>> mapType = new TypeReference<List<T>>() {};

is actually:

TypeReference<List<Object>> mapType = new TypeReference<List<Object>>() {};

And when the ObjectMapper can't gather info about the concrete type of the object to deserialize, it defaults to LinkedHashMap.

If you want to be able to deserialize to a generic type at runtime, you should pass the TypeReference type token as an argument to your mapObjectsToList method:

// Make this a singleton, i.e. don't create a new instance on every call!
ObjectMapper objectMapper = new ObjectMapper();

private <T> List<T> mapObjectsToList(
        String objectsListInJson,
        TypeReference<List<T>> mapType) throws IOException {

    return objectMapper.readValue(objectsListInJson, mapType);
}

And then use the above method as follows:

List<Order> orders = mapObjectsToList(
    stringWithTheJSON,
    new TypeReference<List<Order>> {});

On a side note, I've moved the ObjectMapper objectMapper = new ObjectMapper() statement outside the method. There should be only one ObjectMapper instance in the whole application, unless you require different configuration for serializing/deserializing.


问:
JavaScript file inclusion. Should I not link in ?
I'm watching Douglas Crockfords "Theory of the DOM" and he mentioned that the location of my script tags can greatly affect the load time of my applications.  Furthermore, he asserts that a script tag should be included as far towards the bottom of the document body as possible.

Is this accurate?

OR

Is this video out of date? (which he actually sites as a reason he didn't lecture on the DOM sooner).

答:
Google agrees with Crockford:

Defer JavaScript loading

It's also (one of) the reason(s) why the Google Analytics trackers are to be placed at the bottom.

Yahoo! as well:

Best Practices for Speeding Up your Website (Section "Put Scripts at the Bottom")

And other SO users agree as well:

Is "Put Scripts at the bottom" correct?

ContentLicense: CC BY-SA 2.5

Title: JavaScript file inclusion. Should I not link in <head>?


问:
How to use Nominatim API through PHP to retrieve latitude and longitude?
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.

```<code>function geocode($address){

    // url encode the address
    $address = urlencode($address);

    $url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';

    // get the json response
    $resp_json = file_get_contents($url);

    // decode the json
    $resp = json_decode($resp_json, true);

        // get the important data
        $lati = $resp['lat'];
        $longi = $resp['lon'];

            // put the data in the array
            $data_arr = array();

            array_push(
                $data_arr,
                    $lati,
                    $longi
                );

            return $data_arr;

}
</code>```

The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:

[[DATE] America/New_York] PHP Notice:  Undefined index: title in [...php] on line [...]

[[DATE] America/New_York] PHP Notice:  Undefined variable: area in [...php] on line [...]

What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.

Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).

Would really appreciate any help with this, thank you!

Edit

This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result

答:
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.

The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:

```<code>$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
</code>```

Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.

```<code>// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
</code>```

In full, with some abbreviation of the array building at the end for simplicity:

```<code>function geocode($address){

    // url encode the address
    $address = urlencode($address);

    $url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";

    // get the json response
    $resp_json = file_get_contents($url);

    // decode the json
    $resp = json_decode($resp_json, true);

    return array($resp[0]['lat'], $resp[0]['lon']);

}
</code>```

Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.

Body:
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.

function geocode($address){

    // url encode the address
    $address = urlencode($address);

    $url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';

    // get the json response
    $resp_json = file_get_contents($url);

    // decode the json
    $resp = json_decode($resp_json, true);

        // get the important data
        $lati = $resp['lat'];
        $longi = $resp['lon'];

            // put the data in the array
            $data_arr = array();

            array_push(
                $data_arr,
                    $lati,
                    $longi
                );

            return $data_arr;

}

The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:

[[DATE] America/New_York] PHP Notice:  Undefined index: title in [...php] on line [...]

[[DATE] America/New_York] PHP Notice:  Undefined variable: area in [...php] on line [...]

What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.

Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).

Would really appreciate any help with this, thank you!

Edit

This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result

Body:
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.

The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:

$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";

Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.

// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];

In full, with some abbreviation of the array building at the end for simplicity:

function geocode($address){

    // url encode the address
    $address = urlencode($address);

    $url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";

    // get the json response
    $resp_json = file_get_contents($url);

    // decode the json
    $resp = json_decode($resp_json, true);

    return array($resp[0]['lat'], $resp[0]['lon']);

}

Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.


问:
Accessing a class' member variable from another class
Consider this example:

```<code>public class FirstClass {
    public static int x;

   public static void main(String[] args){
     x = 5;
     SecondClass sc = new SecondClass();
   }

   public int getX(){
     return x;
   }

}
//assume class SecondClass is in another File
public class SecondClass{}
</code>```

I want to access variable x from class SecondClass and as far as I know there are two ways I can do this.

In SecondClass class I can simply do FirstClass.x ---> do stuff. IntelliJ allows me to do this since x has public visibility.

I make the constructor of SecondClass take a FirstClass fc as a parameter and then do this.fc = fc;  while having declared it as a member variable after class declaration. Then, in the main I change the instance of SecondClass to  SecondClass sc = new SecondClass(this);  And now I can have access in SecondClass through fc.getX();

What is the difference between the two as I have never seen an explanation in this scenario ?

Apologies if my example is not abstract enough but I tried to make it as much as possible.

Thanks in advance.

答:
```<code>public class FirstClass {
    int x;
    ......
    public int getX(){
        return x;
    }
}
</code>```

There is no maggic. it's by java specification.
Controlling Access to Members of a Class

The four access levels are −

Visible to the package, the default. No modifiers are needed.

Visible to the class only (private)

Visible to the world (public)

Visible to the package and all subclasses (protected)

your case  int x; has default access. All classes in some package have access to it.

public int getX()

you can get x variable everywhere by in your project.

FirstClass fc = new FirstClass();
int value = fc.getX();

You should use exactly this (call method instead of direct x) approach in 90% cases outside of your class and 10% getX() - inside class. There might be cases with testing , some extra logic for getX() -- but it's in common practice , not in your case

Body:
Consider this example:

public class FirstClass {
    public static int x;

   public static void main(String[] args){
     x = 5;
     SecondClass sc = new SecondClass();
   }

   public int getX(){
     return x;
   }

}
//assume class SecondClass is in another File
public class SecondClass{}

I want to access variable x from class SecondClass and as far as I know there are two ways I can do this.

In SecondClass class I can simply do FirstClass.x ---> do stuff. IntelliJ allows me to do this since x has public visibility.

I make the constructor of SecondClass take a FirstClass fc as a parameter and then do this.fc = fc;  while having declared it as a member variable after class declaration. Then, in the main I change the instance of SecondClass to  SecondClass sc = new SecondClass(this);  And now I can have access in SecondClass through fc.getX();

What is the difference between the two as I have never seen an explanation in this scenario ?

Apologies if my example is not abstract enough but I tried to make it as much as possible.

Thanks in advance.

Body:
public class FirstClass {
    int x;
    ......
    public int getX(){
        return x;
    }
}

There is no maggic. it's by java specification.
Controlling Access to Members of a Class

The four access levels are −

Visible to the package, the default. No modifiers are needed.

Visible to the class only (private)

Visible to the world (public)

Visible to the package and all subclasses (protected)

your case  int x; has default access. All classes in some package have access to it.

public int getX()

you can get x variable everywhere by in your project.

FirstClass fc = new FirstClass();
int value = fc.getX();

You should use exactly this (call method instead of direct x) approach in 90% cases outside of your class and 10% getX() - inside class. There might be cases with testing , some extra logic for getX() -- but it's in common practice , not in your case


问:
How to use events in yii2?
I've been through the documentation and all the articles on Yii2 events found using Google. Can someone provide me a good example of how events can be used in Yii2 and where it may seem logical?

答:
By default Yii2 already provide some event declaration, You can read more about explanation on BaseActiveRecord.  </p>

<p>You can use this variable as same as declaring it manually. </p>

```<code>public function init()
{
    parent::init();

    $this->on(self::EVENT_AFTER_INSERT, [$this, 'exampleMethodHere']);
}
</code>```

Title: How to use events in yii2?

Body:
By default Yii2 already provide some event declaration, You can read more about explanation on BaseActiveRecord.

You can use this variable as same as declaring it manually.

public function init()
{
    parent::init();

    $this->on(self::EVENT_AFTER_INSERT, [$this, 'exampleMethodHere']);
}


问:
Google Sheets API - How to get repeating column number?
I want to update my google docs spreadsheet using API.

I have the following table

Is it possible to make query to insert value in D3 without mentioning exact coordinate ? The problem is that I have about 10 repeating sections and sometimes they can be changed, so I need a way to find range of, for example, section two and then find coordinate of column with name inside of section two.

Is it possible ?

答:
This should be possible with Google Apps Script for Sheets.

The flow I'd go at it would probably be something like:

Get all top row values (e.g. Section One, Section Two, and so on).

Identify the values where value is Name.

Proceed with what else you need.

With that said, I'm sure you're well aware (seeing as you're a well-rep user :) ) that asking for codes or anything similar is off-topic or could be considered too broad here in Stack Overflow.


问:
Mysql Select and count rows with multiple same values
I am trying to create a query that allows me to select the data like shown below

```<code>id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 1
2  | 1          | Ahri       | 2
5  | 1          | Ahri       | 2
3  | 1          | Ahri       | 3
4  | 1          | Ahri       | 2
6  | 1          | Teemo      | 1
7  | 1          | Warwick    | 4
8  | 1          | Warwick    | 4
</code>```

It should count the Counter_Lane and then the Counter_Type with the most should be shown for that name as shown below how it should show the data:

```<code>id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 2
2  | 1          | Teemo      | 1
3  | 1          | Warwick    | 4
</code>```

I have tried the following code and its the closest I have came for over 3 hours now, so could someone help please.

```<code>SELECT
    a.Counter_Type, Champion_For, a.Counter_Lane, a.Champion_Name, COUNT(*) as Amount, sum(vote_type = 'up') as Upvotes, sum(vote_type = 'down') as Downvotes, sum(vote_type = 'up')-sum(vote_type = 'down') as Totalvotes
FROM Champion_Counters_Data a
JOIN ( SELECT c.Counter_Lane, c.Champion_Name, COUNT(*) magnitude
FROM Champion_Counters_Data c
WHERE
    Champion_For = "Aatrox" AND Counter_Type = 1 GROUP BY Champion_Name, Counter_Lane ORDER BY magnitude) b ON a.Champion_Name = b.Champion_Name AND b.Counter_Lane = a.Counter_Lane
GROUP BY Champion_Name
</code>```

答:
```<code>SELECT * FROM your_table  GROUP BY MAX(Counter_Lane)
</code>```

This query is based on the output you want from the table you have given.

Body:
I am trying to create a query that allows me to select the data like shown below

id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 1
2  | 1          | Ahri       | 2
5  | 1          | Ahri       | 2
3  | 1          | Ahri       | 3
4  | 1          | Ahri       | 2
6  | 1          | Teemo      | 1
7  | 1          | Warwick    | 4
8  | 1          | Warwick    | 4

It should count the Counter_Lane and then the Counter_Type with the most should be shown for that name as shown below how it should show the data:

id  Counter_Type Champion_Name Counter_Lane
---|------------|------------|--------------
1  | 1          | Ahri       | 2
2  | 1          | Teemo      | 1
3  | 1          | Warwick    | 4

I have tried the following code and its the closest I have came for over 3 hours now, so could someone help please.

SELECT
    a.Counter_Type, Champion_For, a.Counter_Lane, a.Champion_Name, COUNT(*) as Amount, sum(vote_type = 'up') as Upvotes, sum(vote_type = 'down') as Downvotes, sum(vote_type = 'up')-sum(vote_type = 'down') as Totalvotes
FROM Champion_Counters_Data a
JOIN ( SELECT c.Counter_Lane, c.Champion_Name, COUNT(*) magnitude
FROM Champion_Counters_Data c
WHERE
    Champion_For = "Aatrox" AND Counter_Type = 1 GROUP BY Champion_Name, Counter_Lane ORDER BY magnitude) b ON a.Champion_Name = b.Champion_Name AND b.Counter_Lane = a.Counter_Lane
GROUP BY Champion_Name

Body:
SELECT * FROM your_table  GROUP BY MAX(Counter_Lane)

This query is based on the output you want from the table you have given.


问:
Geo Fencing - point inside/outside polygon
I would like to determine a polygon and implement an algorithm which would check if a point is inside or outside the polygon.

Does anyone know if there is any example available of any similar algorithm?

答:
I add one detail to help people who live in the... south of earth!!
If you're in Brazil (that's my case), our GPS coord are all negatives.
And all these algo give wrong results.

The easiest way if to use the absolute values of the Lat and Long of all point. And in that case Jan Kobersky's algo is perfect.


问:
Other Users Cannot Connect to SQL Data Connection
I have been banging my head for hours now trying to figure out this issue.  Currently, I have an Excel 2013 file that I created with a few pivot charts.  The pivot charts are connected to SQL Server 2012.  I personally can refresh the data without any issues on my end, however whenever someone else tries to
open the database connection they receive the following error.  I have tested this on multiple users and each one experiences the same error.  Any suggestions on what's going on here?

答:
Either your users need to instal the same SQL Server driver you use, or you need to change yours to match their drivers:

https://support.microsoft.com/en-us/help/2022518/error-message-class-not-registered-when-you-update-powerpivot-data


问:
How to get app signing time based on APK file
I am working on a project that analyzing APK files for detecting malware apps, and I wonder how to extract the SIGNING TIME rather than PACKAGING TIME. This is one feature I read from a paper and it seems surprising useful.</p>

答:
There are at least three ways I know of to get something like the signing time. There first is to use keytool:

```<code>$ keytool -printcert -jarfile sample.apk
Signer #1:

Signature:

Owner: CN=GService inc, OU=G Service inc, O=G, L=New York, ST=New York, C=US
Issuer: CN=GService inc, OU=G Service inc, O=G, L=New York, ST=New York, C=US
Serial number: 6f30f864
Valid from: Thu Dec 17 04:12:27 PST 2015 until: Wed Dec 12 04:12:27 PST 2035
Certificate fingerprints:
     MD5:  4D:36:65:14:59:5B:74:8F:2C:9D:92:30:F6:1D:90:8A
     SHA1: A8:85:7B:72:4C:EE:55:83:09:D5:AC:5D:1A:02:80:C5:F6:83:2B:40
     SHA256: 04:A7:24:9F:35:D5:8D:7E:F6:0F:73:81:35:5D:23:16:0D:FC:EA:61:C4:15:61:CC:06:8D:36:D9:C6:55:12:B7
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: C1 C5 19 32 72 47 46 C5   01 CC 4B AF 12 40 3D D2  ...2rGF...K..@=.
0010: B5 52 45 5E                                        .RE^
]
]
</code>```

This gets you the likely time the certificate was created: Thu Dec 17 04:12:27 PST 2015.

The second is to use jarsigner:

```<code>$ jarsigner -verify -verbose sample.apk

sm      4284 Wed Apr 13 11:03:18 PDT 2016 AndroidManifest.xml
sm      9193 Wed Apr 13 11:03:18 PDT 2016 res/drawable-hdpi-v4/ic_launcher.png
sm      5057 Wed Apr 13 11:03:18 PDT 2016 res/drawable-mdpi-v4/ic_launcher.png
sm     14068 Wed Apr 13 11:03:18 PDT 2016 res/drawable-xhdpi-v4/ic_launcher.png
sm      1408 Wed Apr 13 11:03:18 PDT 2016 resources.arsc
sm     20388 Wed Apr 13 11:03:18 PDT 2016 classes.dex
s        523 Wed Apr 13 11:03:18 PDT 2016 META-INF/MANIFEST.MF
         576 Wed Apr 13 11:03:18 PDT 2016 META-INF/CERT.SF
        1368 Wed Apr 13 11:03:18 PDT 2016 META-INF/CERT.RSA

  s = signature was verified
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope
</code>```

This gets you what appears to be the last modified times of all the entries in the APK. They're all the same in this APK, but they're sometimes different. All the last modified times probably have to be greater than the "valid from" date.

The third option is programmatically using JarFile in Java:

```<code>private static void printCertInfo(String jarPath) throws Exception {
    // verify = true is key here
    JarFile apkFile = new JarFile(jarPath, true);
    JarEntry androidManifestEntry = apkFile.getJarEntry("AndroidManifest.xml");
    if (androidManifestEntry == null) {
        System.err.println("APK has no AndroidManifest.xml");
        System.exit(-1);
    }

    // Need to fully read stream to verify cert
    System.out.println("Android manifest probably signed: " + androidManifestEntry.getLastModifiedTime());

    ByteStreams.copy(apkFile.getInputStream(androidManifestEntry), ByteStreams.nullOutputStream());
    // Assuming only signed with a single cert (not always true, but you get the idea)
    X509Certificate cert = (X509Certificate) androidManifestEntry.getCertificates()[0];
    System.out.println("Android manifest cert probably created: " + cert.getNotBefore());
    System.out.println("Full cert: " + cert.toString());
}
</code>```

You might think you could use androidManifestEntry.getCodeSigners()[0].getTimestamp() but it's always null and I'm not sure what it is. The above code gives this output:

```<code>Android manifest probably signed: 2016-04-13T18:03:18Z
Android manifest cert probably created: Thu Dec 17 04:12:27 PST 2015
Full cert: [
[
  Version: V3
  Subject: CN=GService inc, OU=G Service inc, O=G, L=New York, ST=New York, C=US
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

  // ** SNIP -- you get the idea **
</code>```

Body:
There are at least three ways I know of to get something like the signing time. There first is to use keytool:

$ keytool -printcert -jarfile sample.apk
Signer #1:

Signature:

Owner: CN=GService inc, OU=G Service inc, O=G, L=New York, ST=New York, C=US
Issuer: CN=GService inc, OU=G Service inc, O=G, L=New York, ST=New York, C=US
Serial number: 6f30f864
Valid from: Thu Dec 17 04:12:27 PST 2015 until: Wed Dec 12 04:12:27 PST 2035
Certificate fingerprints:
     MD5:  4D:36:65:14:59:5B:74:8F:2C:9D:92:30:F6:1D:90:8A
     SHA1: A8:85:7B:72:4C:EE:55:83:09:D5:AC:5D:1A:02:80:C5:F6:83:2B:40
     SHA256: 04:A7:24:9F:35:D5:8D:7E:F6:0F:73:81:35:5D:23:16:0D:FC:EA:61:C4:15:61:CC:06:8D:36:D9:C6:55:12:B7
     Signature algorithm name: SHA256withRSA
     Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: C1 C5 19 32 72 47 46 C5   01 CC 4B AF 12 40 3D D2  ...2rGF...K..@=.
0010: B5 52 45 5E                                        .RE^
]
]

This gets you the likely time the certificate was created: Thu Dec 17 04:12:27 PST 2015.

The second is to use jarsigner:

$ jarsigner -verify -verbose sample.apk

sm      4284 Wed Apr 13 11:03:18 PDT 2016 AndroidManifest.xml
sm      9193 Wed Apr 13 11:03:18 PDT 2016 res/drawable-hdpi-v4/ic_launcher.png
sm      5057 Wed Apr 13 11:03:18 PDT 2016 res/drawable-mdpi-v4/ic_launcher.png
sm     14068 Wed Apr 13 11:03:18 PDT 2016 res/drawable-xhdpi-v4/ic_launcher.png
sm      1408 Wed Apr 13 11:03:18 PDT 2016 resources.arsc
sm     20388 Wed Apr 13 11:03:18 PDT 2016 classes.dex
s        523 Wed Apr 13 11:03:18 PDT 2016 META-INF/MANIFEST.MF
         576 Wed Apr 13 11:03:18 PDT 2016 META-INF/CERT.SF
        1368 Wed Apr 13 11:03:18 PDT 2016 META-INF/CERT.RSA

  s = signature was verified
  m = entry is listed in manifest
  k = at least one certificate was found in keystore
  i = at least one certificate was found in identity scope

This gets you what appears to be the last modified times of all the entries in the APK. They're all the same in this APK, but they're sometimes different. All the last modified times probably have to be greater than the "valid from" date.

The third option is programmatically using JarFile in Java:

private static void printCertInfo(String jarPath) throws Exception {
    // verify = true is key here
    JarFile apkFile = new JarFile(jarPath, true);
    JarEntry androidManifestEntry = apkFile.getJarEntry("AndroidManifest.xml");
    if (androidManifestEntry == null) {
        System.err.println("APK has no AndroidManifest.xml");
        System.exit(-1);
    }

    // Need to fully read stream to verify cert
    System.out.println("Android manifest probably signed: " + androidManifestEntry.getLastModifiedTime());

    ByteStreams.copy(apkFile.getInputStream(androidManifestEntry), ByteStreams.nullOutputStream());
    // Assuming only signed with a single cert (not always true, but you get the idea)
    X509Certificate cert = (X509Certificate) androidManifestEntry.getCertificates()[0];
    System.out.println("Android manifest cert probably created: " + cert.getNotBefore());
    System.out.println("Full cert: " + cert.toString());
}

You might think you could use androidManifestEntry.getCodeSigners()[0].getTimestamp() but it's always null and I'm not sure what it is. The above code gives this output:

Android manifest probably signed: 2016-04-13T18:03:18Z
Android manifest cert probably created: Thu Dec 17 04:12:27 PST 2015
Full cert: [
[
  Version: V3
  Subject: CN=GService inc, OU=G Service inc, O=G, L=New York, ST=New York, C=US
  Signature Algorithm: SHA256withRSA, OID = 1.2.840.113549.1.1.11

  // ** SNIP -- you get the idea **


问:
Been at this awhile
So I have a json file converted from xml. I'm trying to use jq in a bash script to work through this problem.

current at command line jq -r '.users.user[0].id."#text"' cosmology18.json works great and shows the output perfect

however in bash i've had to use substitutions to try to get this to work with no resolve.

first I got part of it to work the first part to read user data

```<code>  baselineresult=$(jq -r '.users.user[1].cpid."#text"' $1)
</code>```

would allow me to echo out the data received perfectly

however when i try to add $basecount which increases each time i couldn't get it to work so i constructed this crazy method in which I had to use substitutions to get the $basecount into the [ ] of the user.

```<code>  bracea="["
  braceb="]"
  dquote='"'
  squote="'"
  pound="#"
  echo test of command is jq -r "${squote}.users.user${bracea}${basecount}${braceb}.cpid.${dquote}#text${dquote}${squote} $1"

  baselineresult=$(jq -r "${squote}.users.user${bracea}${basecount}${braceb}.cpid.${dquote}${pound}text${dquote}${squote} $1")
  echo $baselineresult
</code>```

the command matches the one i entered at command line to work.

however i get this:

test of command is jq -r '.users.user[0].cpid."#text"' cosmology18.json
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at , line 1:
'.users.user[0].cpid."#text"' cosmology18.json
jq: 1 compile error

any ideas.. been at this for 8 hours now.
I can't seem to find this illegal character as the output is identical to the one id use at command line of jq -r '.users.user[0].id."#text"' cosmology18.json

答:
The problem is that you don't know what's bash syntax and what's jq syntax, so you're merging them both together.

Here's an example of what jq expects:

```<code>.users.user[1].cpid."#text"
</code>```

Here's what you're giving it:

```<code>'.users.user[1].cpid."#text"' filename
</code>```

jq is never supposed to see the single quotes, in your working command they're bash syntax to specify which string to pass to jq. Instead, you try to give single quotes to jq which has no idea what that means.

Similarly, the space followed by the filename is bash syntax to specify that you want to pass a second argument. Instead, you try to give them to jq in its first argument, which it does not expect.

To jq, this command is indistinguishable from your original (it results in an execve call with the exact same parameters). You can vary the variable to get different indices:

```<code>var=1
baselineresult=$(jq -r '.users.user['"$var"'].cpid."#text"' "$1")
</code>```

Title: Been at this awhile

Body:
So I have a json file converted from xml. I'm trying to use jq in a bash script to work through this problem.

current at command line jq -r '.users.user[0].id."#text"' cosmology18.json works great and shows the output perfect

however in bash i've had to use substitutions to try to get this to work with no resolve.

first I got part of it to work the first part to read user data

  baselineresult=$(jq -r '.users.user[1].cpid."#text"' $1)

would allow me to echo out the data received perfectly

however when i try to add $basecount which increases each time i couldn't get it to work so i constructed this crazy method in which I had to use substitutions to get the $basecount into the [ ] of the user.

  bracea="["
  braceb="]"
  dquote='"'
  squote="'"
  pound="#"
  echo test of command is jq -r "${squote}.users.user${bracea}${basecount}${braceb}.cpid.${dquote}#text${dquote}${squote} $1"

  baselineresult=$(jq -r "${squote}.users.user${bracea}${basecount}${braceb}.cpid.${dquote}${pound}text${dquote}${squote} $1")
  echo $baselineresult

the command matches the one i entered at command line to work.

however i get this:

test of command is jq -r '.users.user[0].cpid."#text"' cosmology18.json
jq: error: syntax error, unexpected INVALID_CHARACTER, expecting $end (Unix shell quoting issues?) at , line 1:
'.users.user[0].cpid."#text"' cosmology18.json
jq: 1 compile error

any ideas.. been at this for 8 hours now.
I can't seem to find this illegal character as the output is identical to the one id use at command line of jq -r '.users.user[0].id."#text"' cosmology18.json

Body:
The problem is that you don't know what's bash syntax and what's jq syntax, so you're merging them both together.

Here's an example of what jq expects:

.users.user[1].cpid."#text"

Here's what you're giving it:

'.users.user[1].cpid."#text"' filename

jq is never supposed to see the single quotes, in your working command they're bash syntax to specify which string to pass to jq. Instead, you try to give single quotes to jq which has no idea what that means.

Similarly, the space followed by the filename is bash syntax to specify that you want to pass a second argument. Instead, you try to give them to jq in its first argument, which it does not expect.

To jq, this command is indistinguishable from your original (it results in an execve call with the exact same parameters). You can vary the variable to get different indices:

var=1
baselineresult=$(jq -r '.users.user['"$var"'].cpid."#text"' "$1")


问:
How to do unit testing with django without hitting the database?
I am trying to test my models without actually accessing the database, but Django is apparently not able to create models when there are relationships and the associated instance is not in the database.

Is there a workaround around this?

EDIT

This is my code:

```<code>from django.contrib.auth import models as auth_models

from app.models import Question, Category

user1 = auth_models.User(username='foo', first_name='Foo', last_name='Oof', email='foo@oof.com')
category = Category(name='sample-category')
question = Question(author=user1, category=category, title='sample-title')
</code>```

Which gives:

```<code>$ python manage.py test app.unittests.test_models

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
    super(Command, self).execute(*args, **options)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
    failures = test_runner.run_tests(test_labels)
  File "venv2.7/local/lib/python2.7/site-packages/django/test/runner.py", line 209, in run_tests
    suite = self.build_suite(test_labels, extra_tests)
  File "venv2.7/local/lib/python2.7/site-packages/django/test/runner.py", line 121, in build_suite
    tests = self.test_loader.loadTestsFromName(label)
  File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
    module = __import__('.'.join(parts_copy))
  File "myapp/unittests/test_models.py", line 8, in <module>
    question = Question(author=user1, category=category, title='sample-title')
  File "venv2.7/local/lib/python2.7/site-packages/django/db/models/base.py", line 468, in __init__
    setattr(self, field.name, rel_obj)
  File "venv2.7/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 668, in __set__
    (value, self.field.rel.to._meta.object_name)
ValueError: Cannot assign "<User: foo>": "User" instance isn't saved in the database.
</code>```

答:
Try to use factories; DjangoModelFactory and factory boy

factories.py

```<code>from factory import DjangoModelFactory, SubFactory
from factory import post_generation

class User(DjangoModelFactory):
    class Meta:
        model = 'authapp.User'

    name = 'test_user...'

class Category(DjangoModelFactory):
    class Meta:
        model = 'yourapp.Category'

    @post_generation
    def create_questions(self, create, **kwargs):
        count = 3

        make_items = getattr(Question, 'create' if create else 'build')
        items = [make_items(category=self) for i in range(count)]

        # for build you have to add questions to django's object cache
        if not create:
            self._prefetched_objects_cache = {'question': items}

class Question(DjangoModelFactory):
    class Meta:
        model = 'yourapp.Question'

    category = SubFactory(Category)
    user = SubFactory(User)
</code>```

tests.py:

```<code>category = Category.build()
</code>```

This will create a category and 3 questions with a user. You can also not use SunFactories and create them separately, just use .build();
When using .build() you will not to hit database - build does call object's init() method but is not hitting a save() method

https://factoryboy.readthedocs.io/en/latest/

Body:
I am trying to test my models without actually accessing the database, but Django is apparently not able to create models when there are relationships and the associated instance is not in the database.

Is there a workaround around this?

EDIT

This is my code:

from django.contrib.auth import models as auth_models

from app.models import Question, Category

user1 = auth_models.User(username='foo', first_name='Foo', last_name='Oof', email='foo@oof.com')
category = Category(name='sample-category')
question = Question(author=user1, category=category, title='sample-title')

Which gives:

$ python manage.py test app.unittests.test_models

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 30, in run_from_argv
    super(Command, self).run_from_argv(argv)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 74, in execute
    super(Command, self).execute(*args, **options)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "venv2.7/local/lib/python2.7/site-packages/django/core/management/commands/test.py", line 90, in handle
    failures = test_runner.run_tests(test_labels)
  File "venv2.7/local/lib/python2.7/site-packages/django/test/runner.py", line 209, in run_tests
    suite = self.build_suite(test_labels, extra_tests)
  File "venv2.7/local/lib/python2.7/site-packages/django/test/runner.py", line 121, in build_suite
    tests = self.test_loader.loadTestsFromName(label)
  File "/usr/lib/python2.7/unittest/loader.py", line 91, in loadTestsFromName
    module = __import__('.'.join(parts_copy))
  File "myapp/unittests/test_models.py", line 8, in <module>
    question = Question(author=user1, category=category, title='sample-title')
  File "venv2.7/local/lib/python2.7/site-packages/django/db/models/base.py", line 468, in __init__
    setattr(self, field.name, rel_obj)
  File "venv2.7/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 668, in __set__
    (value, self.field.rel.to._meta.object_name)
ValueError: Cannot assign "<User: foo>": "User" instance isn't saved in the database.

Body:
Try to use factories; DjangoModelFactory and factory boy

factories.py

from factory import DjangoModelFactory, SubFactory
from factory import post_generation

class User(DjangoModelFactory):
    class Meta:
        model = 'authapp.User'

    name = 'test_user...'

class Category(DjangoModelFactory):
    class Meta:
        model = 'yourapp.Category'

    @post_generation
    def create_questions(self, create, **kwargs):
        count = 3

        make_items = getattr(Question, 'create' if create else 'build')
        items = [make_items(category=self) for i in range(count)]

        # for build you have to add questions to django's object cache
        if not create:
            self._prefetched_objects_cache = {'question': items}

class Question(DjangoModelFactory):
    class Meta:
        model = 'yourapp.Question'

    category = SubFactory(Category)
    user = SubFactory(User)

tests.py:

category = Category.build()

This will create a category and 3 questions with a user. You can also not use SunFactories and create them separately, just use .build();
When using .build() you will not to hit database - build does call object's init() method but is not hitting a save() method

https://factoryboy.readthedocs.io/en/latest/


问:
How do I get python to read only every other line from a file that contains a poem
I know the code for reading every line is

```<code>f=open ('poem.txt','r')
for line in f:
    print line
</code>```

how do you have python read only even-numbered lines from the original file. Assuming 1-based numbering of lines.

答:
From Nick Bastin's comment:</p>

```<code>with open('poem.txt', 'r') as f:
    for count, line in enumerate(f, start=1):
        if count % 2 == 0:
            print line
</code>```

Body:
I know the code for reading every line is

f=open ('poem.txt','r')
for line in f:
    print line

how do you have python read only even-numbered lines from the original file. Assuming 1-based numbering of lines.

Body:
From Nick Bastin's comment:

with open('poem.txt', 'r') as f:
    for count, line in enumerate(f, start=1):
        if count % 2 == 0:
            print line


问:
How can i convert this string to datetime in sql?
I have a field whose values look like 2017-06-07T12:16:40.000Z

I have been trying to find any ways to convert it to look like 2017-06-07 12:16

答:
This website could be very helpful to you:

https://www.w3schools.com/sql

For your requirement, you could use:

```<code>ALTER TABLE <table> MODIFY <column> DATETIME;
</code>```

and then

```<code>UPDATE <table>
SET column = YYYY-MM-DD HH:MI:SS
WHERE <condition>;
</code>```

Hope this helped. Please tell me if it solved your problem.

Body:
This website could be very helpful to you:

https://www.w3schools.com/sql

For your requirement, you could use:

ALTER TABLE <table> MODIFY <column> DATETIME;

and then

UPDATE <table>
SET column = YYYY-MM-DD HH:MI:SS
WHERE <condition>;

Hope this helped. Please tell me if it solved your problem.


问:
Creating a customized installer for a java application
I want create a installer which will ask to select a path for file(access) during the installation process and then a folder will be created and the path which was selected by the user will add to a new text file inside the newly created folder.I have checked installer creating programs like INNO setup.But they are providing very few default actions.Can any one direct me in the correct direction.?</p>

答: You can probably use something like INNO and use default action to call scripts/code which can be as complex as you want. I guess the only benefit of using the existing installer/packaging framework is UI for individual developers. Apart from the UI you anyways have to write your processes and actions. </p>


问:
How can I call a Function with a href?
I´m trying to call a function into a href, my function is on functions.php
and my href is on views/something.php

so, this is my function:

```<code>function discount($connection, $us){
    $discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
    $discount->execute();
    return $discount;
}
</code>```

and my link button is on an
 (not in a form):

```<code><?php foreach ($total_notu as $notu) : ?>
    <li><a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
  <?php endforeach; ?>
</code>```

(Do not pay attention to the foreach)

答:
You'll need to change this to use an ajax call or form post to call the PHP function.

Here's a really basic example which should point you in the right direction

discount.php

```<code><?php

    // Load $connection from somewhere

    // Get user, it's better to get this from a cookie or session rather than GET
    $user = $_GET['user']

    $discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
    $discount->bindParam(':user', $user);
    $result = $discount->execute();

    // Throw error if something went wrong with the update, this will cause $.ajax to use the error function
    if (!$result) {
        http_response_code(500);
    }
</code>```

html, assuming $notu[0] contains the user id

```<code><?php foreach ($total_notu as $notu) : ?>
    <li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>
</code>```

js, requires jquery

```<code>function callDiscount(user_id)
{
    // Perform ajax call to discount.php
    $.ajax({
        url: '/discount.php?user=' + user_id,
        error: function() {
            alert('An error occurred');
        },
        success: function(data) {
            // Redirect user to notificaciones.php
            document.location = '/notificaciones.php';
        }
    });

    // Prevent link click doing anything
    return false;
}
</code>```

Title: How can I call a Function with a href?

Body:
I´m trying to call a function into a href, my function is on functions.php
and my href is on views/something.php

so, this is my function:

function discount($connection, $us){
    $discount = $conexion->prepare("UPDATE postule SET seen = 1 WHERE id = $us");
    $discount->execute();
    return $discount;
}

and my link button is on an
 (not in a form):

<?php foreach ($total_notu as $notu) : ?>

<a onClick="<?php discount() ?>" href="notificaciones.php"> Notificaciones <?php echo "$notu[0]"; ?>

  <?php endforeach; ?>

(Do not pay attention to the foreach)

Body:
You'll need to change this to use an ajax call or form post to call the PHP function.

Here's a really basic example which should point you in the right direction

discount.php

<?php

    // Load $connection from somewhere

    // Get user, it's better to get this from a cookie or session rather than GET
    $user = $_GET['user']

    $discount = $connection->prepare("UPDATE postule SET seen = 1 WHERE id = :user");
    $discount->bindParam(':user', $user);
    $result = $discount->execute();

    // Throw error if something went wrong with the update, this will cause $.ajax to use the error function
    if (!$result) {
        http_response_code(500);
    }

html, assuming $notu[0] contains the user id

<?php foreach ($total_notu as $notu) : ?>
    <li><a onClick="return callDiscount('<?php echo "$notu[0]"; ?>');" href="#"> Notificaciones <span class="badge "><?php echo "$notu[0]"; ?></span></a></li>
<?php endforeach; ?>

js, requires jquery

function callDiscount(user_id)
{
    // Perform ajax call to discount.php
    $.ajax({
        url: '/discount.php?user=' + user_id,
        error: function() {
            alert('An error occurred');
        },
        success: function(data) {
            // Redirect user to notificaciones.php
            document.location = '/notificaciones.php';
        }
    });

    // Prevent link click doing anything
    return false;
}


问:
Simple Rails validation issue with non-user defined inputs
Background

I'm using the acts_as_list gem in a rails app

my posts table has a position column

position is assigned in a before_create callback in my model:

This is the code for my Post model:

```<code>class Post < ActiveRecord::Base
  acts_as_list
  before_create :set_position
  attr_accessible :title, :description, :category_id
  validates :position, :presence => true, :uniqueness => true

  protected
    def set_position
      self.position = Post.all.size + 1
    end
end
</code>```

My Problem:
I don't want users to be able to set the position, so I've removed the position field from the Post form.  When I submit a new post, the validation fails, and I'm told that position can't be blank.

I realise that my validation is failing because the user is not inputting the position themselves, but I have set the position in the before_filter, so how can I get rails to use that information when it is performing the validation?

Bonus Question
The form submits when I remove the validation, but I was wondering why this works because I don't pass position to attr_accessible?  I pass a number of other symbols to it like so:  attr_accessible :title, :description, :category_id but I don't pass :position. Is there likely to be any problems there? Should position be attr_protected?

答:
First question

```<code>before_validation :set_position, :on => :create
</code>```

Bonus question.
You probably got mass assigment warrning (check your logs)
When you remove validation rails dont return any error on :position so they save what was in attr_accesible (probably the position will be null in DB)

Body:
Background

I'm using the acts_as_list gem in a rails app

my posts table has a position column

position is assigned in a before_create callback in my model:

This is the code for my Post model:

class Post < ActiveRecord::Base
  acts_as_list
  before_create :set_position
  attr_accessible :title, :description, :category_id
  validates :position, :presence => true, :uniqueness => true

  protected
    def set_position
      self.position = Post.all.size + 1
    end
end

My Problem:
I don't want users to be able to set the position, so I've removed the position field from the Post form.  When I submit a new post, the validation fails, and I'm told that position can't be blank.

I realise that my validation is failing because the user is not inputting the position themselves, but I have set the position in the before_filter, so how can I get rails to use that information when it is performing the validation?

Bonus Question
The form submits when I remove the validation, but I was wondering why this works because I don't pass position to attr_accessible?  I pass a number of other symbols to it like so:  attr_accessible :title, :description, :category_id but I don't pass :position. Is there likely to be any problems there? Should position be attr_protected?

Body:
First question

before_validation :set_position, :on => :create

Bonus question.
You probably got mass assigment warrning (check your logs)
When you remove validation rails dont return any error on :position so they save what was in attr_accesible (probably the position will be null in DB)


问:
Inconvenience when accessing a value of a vector - Octave
I have a problem accessing the element of a vector in octave:

```<code>>> den = [1 2 1 2]
>> poles = roots(den)
>> poles =

  -2.00000 + 0.00000i
   0.00000 + 1.00000i
   0.00000 - 1.00000i
>> poles(2)
ans = 4.1633e-016 + 1.0000e+000i
</code>```

Instead of returning 0 + 1i, it returns 4.1633e-016 + 1.0000e + 000i. Why?

how can I solve that?

答:
What you see in the first result is correct. The precision of presentation is up to 5 digit precision. In the second call to see the result is presented in scientific format, so you can see the real value of the what you see in a limited format of the presentation.

I should have mentioned that sometimes you get a very small value, which means zero, but because of some error in computation you've gotten a very small value instead of zero. You can use format long E before your code to get the results in a detail scientific format.

Body:
I have a problem accessing the element of a vector in octave:

>> den = [1 2 1 2]
>> poles = roots(den)
>> poles =

  -2.00000 + 0.00000i
   0.00000 + 1.00000i
   0.00000 - 1.00000i
>> poles(2)
ans = 4.1633e-016 + 1.0000e+000i

Instead of returning 0 + 1i, it returns 4.1633e-016 + 1.0000e + 000i. Why?

how can I solve that?


问:
Selenium WebDriver - Missing 'text' parameter (IndexOutOfBounds) - SendKeys
I'm trying to run a test on google's website and when I send the text I'm saying the following message:

Missing 'text' parameter (IndexOutOfBounds)

Code:
browser.FindElement(By.Name("q")).SendKeys("a");

What I do not understand is that until yesterday the code was running normally.

Can someone help me solve this error?

tks!

Version:
geckodriver-v0.16.0-win64
Selenium Client & WebDriver  - C#   3.4.0
Firefox 53.0v

答:
@Kayh and @NickBaker
There is still an issue: how did that work?

https://github.com/mozilla/geckodriver/issues/511

I am using Firefox 53.0.3 (32-bit), geckodriver 0.16.1 to drive browser with Selenium 3.4.0 but still getting

System.InvalidOperationException : Missing 'text' parameter (IndexOutOfBounds)

EDIT:
https://github.com/mozilla/geckodriver/issues/511 fixed now on 02 July 2017. Combination of Selenium client binding 3.4.3, geckodriver 0.17, Firefox 54 works now.


问:
Assign custom attribute of angular directive in a Html Helper element Razor
Here I am writing an angular custom directive attribute as below

```<code>var app = angular.module('myApp', ['ui.bootstrap']);

    app.directive('myDirective', function () {
        return {
            restrict: 'A',
            link: function (scope, el) {
                el.bind('blur', function () {
                    alert('hi');
                });
            }
        }
    });
</code>```

And I have an view  in which i am using razor .So my question is how to inject this directive attribute to my htmlHelper element.My Html Helper element is as follows

```<code>  @Html.TextBoxFor(m => m.Name, new { @class = "form-control testcss", required = "true", ng_model = "Name", uib_popover = "I have a title!", popover_toggle = "focus" })
</code>```

When i simply inject the attribute  as "my_directive" it shows "Invalid anonymous type memeber declarator".

Appreciate your help.Thanks!!

答:
I had a similar problem.  You can solve this by adding @my_directive="" to the list in the anonymous class.  It seems when declared with an empty value, it will just add the attribute with no value (so, it will render as input type="text" my-directive id="myID"...).

Hope that helps!
Steve

Body:
Here I am writing an angular custom directive attribute as below

var app = angular.module('myApp', ['ui.bootstrap']);

    app.directive('myDirective', function () {
        return {
            restrict: 'A',
            link: function (scope, el) {
                el.bind('blur', function () {
                    alert('hi');
                });
            }
        }
    });

And I have an view  in which i am using razor .So my question is how to inject this directive attribute to my htmlHelper element.My Html Helper element is as follows

  @Html.TextBoxFor(m => m.Name, new { @class = "form-control testcss", required = "true", ng_model = "Name", uib_popover = "I have a title!", popover_toggle = "focus" })

When i simply inject the attribute  as "my_directive" it shows "Invalid anonymous type memeber declarator".

Appreciate your help.Thanks!!


问:
Return a value of 0 or 0.00 along with where clause MySQL
While I was debugging and seeing some test with my query, I noticed that some of my results have NULL values. I want to return them or see them as a value of 0 or 0.00 according to their type just like the Senior.

I tried it with a case statement but it didn't get the result I wanted which is 0.

This is determined through where clause according to type.

Here's my query:

```<code>SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED,
(SELECT (CASE WHEN

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else
SUM(gndsale.AMOUNT) END)
from gndsale where gndsale.ID= b.ID and
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR DISCOUNT`

FROM
gndsale a INNER JOIN emp b ON a.ID= b.ID WHERE a.type = "22" and STR_TO_DATE(a.DOB,
'%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31' GROUP BY DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')
</code>```

Here is my result:

I want to make that Null Value as 0

答:
try this:</p>

```<code>select EMPLOYEE,`Date`,DECLARED,case when SENIOR_DISCOUNT is null then 0 else SENIOR_DISCOUNT end as `SENIOR DISCOUNT` from
(SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED,
(SELECT (CASE WHEN

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else
SUM(gndsale.AMOUNT) END)
from gndsale where gndsale.ID= b.ID and
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR_DISCOUNT`

FROM
gndsale a INNER JOIN emp b ON a.ID= b.ID WHERE a.type = "22" and STR_TO_DATE(a.DOB,
'%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31' GROUP BY DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')) as a
</code>```

Body:
While I was debugging and seeing some test with my query, I noticed that some of my results have NULL values. I want to return them or see them as a value of 0 or 0.00 according to their type just like the Senior.

I tried it with a case statement but it didn't get the result I wanted which is 0.

This is determined through where clause according to type.

Here's my query:

SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED,
(SELECT (CASE WHEN

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else
SUM(gndsale.AMOUNT) END)
from gndsale where gndsale.ID= b.ID and
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR DISCOUNT`

FROM
gndsale a INNER JOIN emp b ON a.ID= b.ID WHERE a.type = "22" and STR_TO_DATE(a.DOB,
'%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31' GROUP BY DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')

Here is my result:

I want to make that Null Value as 0

Body:
try this:

select EMPLOYEE,`Date`,DECLARED,case when SENIOR_DISCOUNT is null then 0 else SENIOR_DISCOUNT end as `SENIOR DISCOUNT` from
(SELECT a.ID as EMPLOYEE, a.DOB as Date, a.AMOUNT as DECLARED,
(SELECT (CASE WHEN

SUM(gndsale.AMOUNT) and gndsale.ID IS NULL then "0" and gndsale.typeid = "10" else
SUM(gndsale.AMOUNT) END)
from gndsale where gndsale.ID= b.ID and
gndsale.typeid = "10" and gndsale.DOB = a.DOB)  as `SENIOR_DISCOUNT`

FROM
gndsale a INNER JOIN emp b ON a.ID= b.ID WHERE a.type = "22" and STR_TO_DATE(a.DOB,
'%m/%d/%Y') BETWEEN '2017-05-01' AND '2017-05-31' GROUP BY DECLARED order by STR_TO_DATE(a.DOB, '%m/%d/%Y')) as a


问:
Searching xml in Clojure
I have the following sample xml:

```<code><data>
  <products>
    <product>
      <section>Red Section</section>
      <images>
        <image>img.jpg</image>
        <image>img2.jpg</image>
      </images>
    </product>
    <product>
      <section>Blue Section</section>
      <images>
        <image>img.jpg</image>
        <image>img3.jpg</image>
      </images>
    </product>
    <product>
      <section>Green Section</section>
      <images>
        <image>img.jpg</image>
        <image>img2.jpg</image>
      </images>
    </product>
  </products>
</data>
</code>```

I know how to parse it in Clojure

```<code>(require '[clojure.xml :as xml])
(def x (xml/parse 'location/of/that/xml'))
</code>```

This returns a nested map describing the xml

```<code>{:tag :data,
 :attrs nil,
 :content [
     {:tag :products,
      :attrs nil,
      :content [
          {:tag :product,
           :attrs nil,
           :content [] ..
</code>```

This structure can of course be traversed with standard Clojure functions, but it may turn out to be really verbose, especially if compared to, for instance, querying it with XPath. Is there any helper to traverse and search such structure? How can I, for example

get a list of all <product>

get only the product whose <images> tag contains an <image> with text "img2.jpg"

get the product whose section is "Red Section"

Thanks

答:
The Tupelo library can easily solve problems like this using tupelo.forest tree data structure. Please see this question for more information.  API docs can be found here.

Here we load your xml data and convert it first into enlive and then the native tree structure used by tupelo.forest.  Libs & data def:

```<code>(ns tst.tupelo.forest-examples
  (:use tupelo.forest tupelo.test )
  (:require
    [clojure.data.xml :as dx]
    [clojure.java.io :as io]
    [clojure.set :as cs]
    [net.cgrand.enlive-html :as en-html]
    [schema.core :as s]
    [tupelo.core :as t]
    [tupelo.string :as ts]))
(t/refer-tupelo)

(def xml-str-prod "<data>
                    <products>
                      <product>
                        <section>Red Section</section>
                        <images>
                          <image>img.jpg</image>
                          <image>img2.jpg</image>
                        </images>
                      </product>
                      <product>
                        <section>Blue Section</section>
                        <images>
                          <image>img.jpg</image>
                          <image>img3.jpg</image>
                        </images>
                      </product>
                      <product>
                        <section>Green Section</section>
                        <images>
                          <image>img.jpg</image>
                          <image>img2.jpg</image>
                        </images>
                      </product>
                    </products>
                  </data> " )
</code>```

and initialization code:

```<code>(dotest
  (with-forest (new-forest)
    (let [enlive-tree          (->> xml-str-prod
                                 java.io.StringReader.
                                 en-html/html-resource
                                 first)
          root-hid             (add-tree-enlive enlive-tree)
          tree-1               (hid->hiccup root-hid)
</code>```

The hid suffix stands for "Hex ID" which is unique hex value that acts like a pointer to a node/leaf in the tree. At this stage we have just loaded the data in the forest data structure, creating tree-1 which looks like:

```<code>[:data
 [:tupelo.forest/raw "\n                    "]
 [:products
  [:tupelo.forest/raw "\n                      "]
  [:product
   [:tupelo.forest/raw "\n                        "]
   [:section "Red Section"]
   [:tupelo.forest/raw "\n                        "]
   [:images
    [:tupelo.forest/raw "\n                          "]
    [:image "img.jpg"]
    [:tupelo.forest/raw "\n                          "]
    [:image "img2.jpg"]
    [:tupelo.forest/raw "\n                        "]]
   [:tupelo.forest/raw "\n                      "]]
  [:tupelo.forest/raw "\n                      "]
  [:product
   [:tupelo.forest/raw "\n                        "]
   [:section "Blue Section"]
   [:tupelo.forest/raw "\n                        "]
   [:images
    [:tupelo.forest/raw "\n                          "]
    [:image "img.jpg"]
    [:tupelo.forest/raw "\n                          "]
    [:image "img3.jpg"]
    [:tupelo.forest/raw "\n                        "]]
   [:tupelo.forest/raw "\n                      "]]
  [:tupelo.forest/raw "\n                      "]
  [:product
   [:tupelo.forest/raw "\n                        "]
   [:section "Green Section"]
   [:tupelo.forest/raw "\n                        "]
   [:images
    [:tupelo.forest/raw "\n                          "]
    [:image "img.jpg"]
    [:tupelo.forest/raw "\n                          "]
    [:image "img2.jpg"]
    [:tupelo.forest/raw "\n                        "]]
   [:tupelo.forest/raw "\n                      "]]
  [:tupelo.forest/raw "\n                    "]]
 [:tupelo.forest/raw "\n                   "]]
</code>```

We next remove any blank strings with this code:

```<code>blank-leaf-hid?      (fn [hid] (and (leaf-hid? hid) ; ensure it is a leaf node
                                 (let [value (hid->value hid)]
                                      (and (string? value)
                                        (or (zero? (count value)) ; empty string
                                          (ts/whitespace? value)))))) ; all whitespace string

blank-leaf-hids      (keep-if blank-leaf-hid? (all-hids))
>>                   (apply remove-hid blank-leaf-hids)
tree-2               (hid->hiccup root-hid)
</code>```

to produce a much nicer result tree (hiccup format)

```<code>[:data
 [:products
  [:product
   [:section "Red Section"]
   [:images [:image "img.jpg"] [:image "img2.jpg"]]]
  [:product
   [:section "Blue Section"]
   [:images [:image "img.jpg"] [:image "img3.jpg"]]]
  [:product
   [:section "Green Section"]
   [:images [:image "img.jpg"] [:image "img2.jpg"]]]]]
</code>```

The following code then computes the answers to the three questions above:

```<code>product-hids         (find-hids root-hid [:** :product])
product-trees-hiccup (mapv hid->hiccup product-hids)

img2-paths           (find-paths-leaf root-hid [:data :products :product :images :image] "img2.jpg")
img2-prod-paths      (mapv #(drop-last 2 %) img2-paths)
img2-prod-hids       (mapv last img2-prod-paths)
img2-trees-hiccup    (mapv hid->hiccup img2-prod-hids)

red-sect-paths       (find-paths-leaf root-hid [:data :products :product :section] "Red Section")
red-prod-paths       (mapv #(drop-last 1 %) red-sect-paths)
red-prod-hids        (mapv last red-prod-paths)
red-trees-hiccup     (mapv hid->hiccup red-prod-hids)]
</code>```

with results:

```<code> (is= product-trees-hiccup
   [[:product
     [:section "Red Section"]
     [:images
      [:image "img.jpg"]
      [:image "img2.jpg"]]]
    [:product
     [:section "Blue Section"]
     [:images
      [:image "img.jpg"]
      [:image "img3.jpg"]]]
    [:product
     [:section "Green Section"]
     [:images
      [:image "img.jpg"]
      [:image "img2.jpg"]]]] )

(is= img2-trees-hiccup
  [[:product
    [:section "Red Section"]
    [:images
     [:image "img.jpg"]
     [:image "img2.jpg"]]]
   [:product
    [:section "Green Section"]
    [:images
     [:image "img.jpg"]
     [:image "img2.jpg"]]]])

(is= red-trees-hiccup
  [[:product
    [:section "Red Section"]
    [:images
     [:image "img.jpg"]
     [:image "img2.jpg"]]]]))))
</code>```

The full example can be found in the forest-examples unit test.

Title: Searching xml in Clojure

Body:
I have the following sample xml:

<data>
  <products>
    <product>

Red Section

      <images>
        <image>img.jpg</image>
        <image>img2.jpg</image>
      </images>
    </product>
    <product>

Blue Section

      <images>
        <image>img.jpg</image>
        <image>img3.jpg</image>
      </images>
    </product>
    <product>

Green Section

      <images>
        <image>img.jpg</image>
        <image>img2.jpg</image>
      </images>
    </product>
  </products>
</data>

I know how to parse it in Clojure

(require '[clojure.xml :as xml])
(def x (xml/parse 'location/of/that/xml'))

This returns a nested map describing the xml

{:tag :data,
 :attrs nil,
 :content [
     {:tag :products,
      :attrs nil,
      :content [
          {:tag :product,
           :attrs nil,
           :content [] ..

This structure can of course be traversed with standard Clojure functions, but it may turn out to be really verbose, especially if compared to, for instance, querying it with XPath. Is there any helper to traverse and search such structure? How can I, for example

get a list of all <product>

get only the product whose <images> tag contains an <image> with text "img2.jpg"

get the product whose section is "Red Section"

Thanks

Body:
The Tupelo library can easily solve problems like this using tupelo.forest tree data structure. Please see this question for more information.  API docs can be found here.

Here we load your xml data and convert it first into enlive and then the native tree structure used by tupelo.forest.  Libs & data def:

(ns tst.tupelo.forest-examples
  (:use tupelo.forest tupelo.test )
  (:require
    [clojure.data.xml :as dx]
    [clojure.java.io :as io]
    [clojure.set :as cs]
    [net.cgrand.enlive-html :as en-html]
    [schema.core :as s]
    [tupelo.core :as t]
    [tupelo.string :as ts]))
(t/refer-tupelo)

(def xml-str-prod "<data>
                    <products>
                      <product>
                        <section>Red Section</section>
                        <images>
                          <image>img.jpg</image>
                          <image>img2.jpg</image>
                        </images>
                      </product>
                      <product>
                        <section>Blue Section</section>
                        <images>
                          <image>img.jpg</image>
                          <image>img3.jpg</image>
                        </images>
                      </product>
                      <product>
                        <section>Green Section</section>
                        <images>
                          <image>img.jpg</image>
                          <image>img2.jpg</image>
                        </images>
                      </product>
                    </products>
                  </data> " )

and initialization code:

(dotest
  (with-forest (new-forest)
    (let [enlive-tree          (->> xml-str-prod
                                 java.io.StringReader.
                                 en-html/html-resource
                                 first)
          root-hid             (add-tree-enlive enlive-tree)
          tree-1               (hid->hiccup root-hid)

The hid suffix stands for "Hex ID" which is unique hex value that acts like a pointer to a node/leaf in the tree. At this stage we have just loaded the data in the forest data structure, creating tree-1 which looks like:

[:data
 [:tupelo.forest/raw "\n                    "]
 [:products
  [:tupelo.forest/raw "\n                      "]
  [:product
   [:tupelo.forest/raw "\n                        "]
   [:section "Red Section"]
   [:tupelo.forest/raw "\n                        "]
   [:images
    [:tupelo.forest/raw "\n                          "]
    [:image "img.jpg"]
    [:tupelo.forest/raw "\n                          "]
    [:image "img2.jpg"]
    [:tupelo.forest/raw "\n                        "]]
   [:tupelo.forest/raw "\n                      "]]
  [:tupelo.forest/raw "\n                      "]
  [:product
   [:tupelo.forest/raw "\n                        "]
   [:section "Blue Section"]
   [:tupelo.forest/raw "\n                        "]
   [:images
    [:tupelo.forest/raw "\n                          "]
    [:image "img.jpg"]
    [:tupelo.forest/raw "\n                          "]
    [:image "img3.jpg"]
    [:tupelo.forest/raw "\n                        "]]
   [:tupelo.forest/raw "\n                      "]]
  [:tupelo.forest/raw "\n                      "]
  [:product
   [:tupelo.forest/raw "\n                        "]
   [:section "Green Section"]
   [:tupelo.forest/raw "\n                        "]
   [:images
    [:tupelo.forest/raw "\n                          "]
    [:image "img.jpg"]
    [:tupelo.forest/raw "\n                          "]
    [:image "img2.jpg"]
    [:tupelo.forest/raw "\n                        "]]
   [:tupelo.forest/raw "\n                      "]]
  [:tupelo.forest/raw "\n                    "]]
 [:tupelo.forest/raw "\n                   "]]

We next remove any blank strings with this code:

blank-leaf-hid?      (fn [hid] (and (leaf-hid? hid) ; ensure it is a leaf node
                                 (let [value (hid->value hid)]
                                      (and (string? value)
                                        (or (zero? (count value)) ; empty string
                                          (ts/whitespace? value)))))) ; all whitespace string

blank-leaf-hids      (keep-if blank-leaf-hid? (all-hids))
>>                   (apply remove-hid blank-leaf-hids)
tree-2               (hid->hiccup root-hid)

to produce a much nicer result tree (hiccup format)

[:data
 [:products
  [:product
   [:section "Red Section"]
   [:images [:image "img.jpg"] [:image "img2.jpg"]]]
  [:product
   [:section "Blue Section"]
   [:images [:image "img.jpg"] [:image "img3.jpg"]]]
  [:product
   [:section "Green Section"]
   [:images [:image "img.jpg"] [:image "img2.jpg"]]]]]

The following code then computes the answers to the three questions above:

product-hids         (find-hids root-hid [:** :product])
product-trees-hiccup (mapv hid->hiccup product-hids)

img2-paths           (find-paths-leaf root-hid [:data :products :product :images :image] "img2.jpg")
img2-prod-paths      (mapv #(drop-last 2 %) img2-paths)
img2-prod-hids       (mapv last img2-prod-paths)
img2-trees-hiccup    (mapv hid->hiccup img2-prod-hids)

red-sect-paths       (find-paths-leaf root-hid [:data :products :product :section] "Red Section")
red-prod-paths       (mapv #(drop-last 1 %) red-sect-paths)
red-prod-hids        (mapv last red-prod-paths)
red-trees-hiccup     (mapv hid->hiccup red-prod-hids)]

with results:

 (is= product-trees-hiccup
   [[:product
     [:section "Red Section"]
     [:images
      [:image "img.jpg"]
      [:image "img2.jpg"]]]
    [:product
     [:section "Blue Section"]
     [:images
      [:image "img.jpg"]
      [:image "img3.jpg"]]]
    [:product
     [:section "Green Section"]
     [:images
      [:image "img.jpg"]
      [:image "img2.jpg"]]]] )

(is= img2-trees-hiccup
  [[:product
    [:section "Red Section"]
    [:images
     [:image "img.jpg"]
     [:image "img2.jpg"]]]
   [:product
    [:section "Green Section"]
    [:images
     [:image "img.jpg"]
     [:image "img2.jpg"]]]])

(is= red-trees-hiccup
  [[:product
    [:section "Red Section"]
    [:images
     [:image "img.jpg"]
     [:image "img2.jpg"]]]]))))

The full example can be found in the forest-examples unit test.