问:
Why does creating a list of lists produce unexpected behavior?
EDIT: This question is about why the behavior is what it is, not how to get around it, which is what the alleged duplicate is about.

I've used the following notation to create lists of a certain size in different cases. For example:

```<code>>>> [None] * 5
[None, None, None, None, None]
>>>
</code>```

This appears to work as expected and is shorter than:

```<code>>>> [None for _ in range(5)]
[None, None, None, None, None]
>>>
</code>```

I then tried to create an list of lists using the same approach:

```<code>>>> [[]] * 5
[[], [], [], [], []]
>>>
</code>```

Fair enough. It seems to work as expected.

However, while going through the debugger, I noticed that all the sub-list buckets had the same value, even though I had added only a single item. For example:

```<code>>>> t = [[]] * 5
>>> t
[[], [], [], [], []]
>>> t[1].append(4)
>>> t
[[4], [4], [4], [4], [4]]
>>> t[0] is t[1]
True
>>>
</code>```

I was not expecting all top-level array elements to be references to a single sub-list; I expected 5 independent sub-lists.

For that, I had to write code like so:

```<code>>>> t = [[] for _ in range(5)]
>>> t
[[], [], [], [], []]
>>> t[2].append(4)
>>> t
[[], [], [4], [], []]
>>> t[0] is t[1]
False
>>>
</code>```

I'm clearly missing something, probably a historical fact or simply a different way in which the consistency here is viewed.

Can someone explain why two different code snippets that one would reasonably expect to be equivalent to each other actually end up implicitly producing different and non-obvious (IMO) results, especially given Python's zen of always being explicit and obvious?

Please note that I'm already aware of this question, which is different to what I'm asking.

I'm simply looking for a detailed explanation/justification. If there're historical, technical, and/or theoretical reasons for this behavior, then please be sure to include a reference or two.

答:
When you do the following:

```<code>[[]]*n
</code>```

You are first creating a list, then using the * operator with an int n. This takes whatever objects are in your list, and creates n- many repetitions of it.

But since in Python, explicit is better than implicit, you don't implicitly make a copy of those objects. Indeed, this is consistent with the semantics of Python.

Try to name a single case where Python implicitly makes a copy.

Furthermore, it is consistent with the addition on the list:

```<code>l = [1, [], 'a']

l2 = l + l + l

l[1].append('foo')

print(l2)
</code>```

And the output:

```<code>[1, ['foo'], 'a', 1, ['foo'], 'a', 1, ['foo'], 'a']
</code>```

Now, as noted in the comments, coming from C++ it makes sense that the above would be surprising, but if one is used to Python, the above is what one would expect.

On the other hand:

```<code>[[] for _ in range(5)]
</code>```

Is a list comprehension. It is equivalent to:

```<code>lst = []
for _ in range(5):
    lst.append([])
</code>```

Here, clearly, every time you are in the loop you create a new list. That is how literal syntax works.

As an aside, I almost never use the * operator on lists, except for one particular idiom I am fond of:

```<code>>>> x = list(range(1, 22))
>>> it_by_three = [iter(x)]*3
>>> for a,b,c in zip(*it_by_three):
...    print(a, b, c)
...
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21
</code>```

Body:
EDIT: This question is about why the behavior is what it is, not how to get around it, which is what the alleged duplicate is about.

I've used the following notation to create lists of a certain size in different cases. For example:

>>> [None] * 5
[None, None, None, None, None]
>>>

This appears to work as expected and is shorter than:

>>> [None for _ in range(5)]
[None, None, None, None, None]
>>>

I then tried to create an list of lists using the same approach:

>>> [[]] * 5
[[], [], [], [], []]
>>>

Fair enough. It seems to work as expected.

However, while going through the debugger, I noticed that all the sub-list buckets had the same value, even though I had added only a single item. For example:

>>> t = [[]] * 5
>>> t
[[], [], [], [], []]
>>> t[1].append(4)
>>> t
[[4], [4], [4], [4], [4]]
>>> t[0] is t[1]
True
>>>

I was not expecting all top-level array elements to be references to a single sub-list; I expected 5 independent sub-lists.

For that, I had to write code like so:

>>> t = [[] for _ in range(5)]
>>> t
[[], [], [], [], []]
>>> t[2].append(4)
>>> t
[[], [], [4], [], []]
>>> t[0] is t[1]
False
>>>

I'm clearly missing something, probably a historical fact or simply a different way in which the consistency here is viewed.

Can someone explain why two different code snippets that one would reasonably expect to be equivalent to each other actually end up implicitly producing different and non-obvious (IMO) results, especially given Python's zen of always being explicit and obvious?

Please note that I'm already aware of this question, which is different to what I'm asking.

I'm simply looking for a detailed explanation/justification. If there're historical, technical, and/or theoretical reasons for this behavior, then please be sure to include a reference or two.

Body:
When you do the following:

[[]]*n

You are first creating a list, then using the * operator with an int n. This takes whatever objects are in your list, and creates n- many repetitions of it.

But since in Python, explicit is better than implicit, you don't implicitly make a copy of those objects. Indeed, this is consistent with the semantics of Python.

Try to name a single case where Python implicitly makes a copy.

Furthermore, it is consistent with the addition on the list:

l = [1, [], 'a']

l2 = l + l + l

l[1].append('foo')

print(l2)

And the output:

[1, ['foo'], 'a', 1, ['foo'], 'a', 1, ['foo'], 'a']

Now, as noted in the comments, coming from C++ it makes sense that the above would be surprising, but if one is used to Python, the above is what one would expect.

On the other hand:

[[] for _ in range(5)]

Is a list comprehension. It is equivalent to:

lst = []
for _ in range(5):
    lst.append([])

Here, clearly, every time you are in the loop you create a new list. That is how literal syntax works.

As an aside, I almost never use the * operator on lists, except for one particular idiom I am fond of:

>>> x = list(range(1, 22))
>>> it_by_three = [iter(x)]*3
>>> for a,b,c in zip(*it_by_three):
...    print(a, b, c)
...
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
19 20 21


来源: stackexchange

问:
Flattening Multiple Arrays
I am trying to model cultural dissemination. In the program, I have five characteristics and nine potential outcomes per characteristic. </p>

```<code>dimension <- 10
characteristics <- 5

world <- array(0, dim=c(dimension, dimension, characteristics))

for (i in 1:dimension){
  for (j in 1:dimension){
    for (k in 1:characteristics){
      world[i,j,k] <- sample(c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), 1)
    }
  }
}
</code>```

<p>I would like to be able to flatten the array and create a unique identifier for each potential variation. For example, a world where each array[1,1]=(0,0,0,0,0)=1 all the way to: (9,9,9,9,9)=10^5. Also, this: (1,0,0,0,0)!=(0,0,1,0,0) etc. Any suggestions on how to flatten the dimensions would be greatly appreciated. </p>

答:
Can you provide an example with the desired shape?  How 'flat' do you want it?  This stacks the five characteristics on top of each other, resulting in a 10*5 rows and 10+1 columns (the extra column denotes the 'characteristic').

```<code>library(magrittr)
lst_ds <- purrr::map(seq_len(characteristics), ~tibble::as_tibble(world[,,.]))
ds <- lst_ds %>%
  dplyr::bind_rows(.id = "characteristic")
</code>```

produces:

```<code># A tibble: 50 x 11
   characteristic    V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
            <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1              1     3     3     1     6     3     6     9     7     0     0
 2              1     7     4     8     8     8     9     7     2     4     4
 3              1     0     6     7     2     7     5     1     1     7     4
 4              1     0     6     3     4     5     1     9     3     1     3
 5              1     1     5     2     1     1     9     6     8     3     2
 6              1     6     5     6     5     4     3     2     0     6     1
 7              1     2     7     1     4     4     4     8     1     1     0
 8              1     0     7     6     1     3     9     0     8     6     1
 9              1     1     2     4     8     1     9     2     8     1     5
10              1     2     9     1     6     8     0     3     1     6     2
11              2     6     2     7     7     0     1     1     2     9     0
12              2     0     0     7     5     7     4     9     1     4     6
# ... with 38 more rows
</code>```

ContentLicense: CC BY-SA 3.0

Title: Flattening Multiple Arrays

Body:
I am trying to model cultural dissemination. In the program, I have five characteristics and nine potential outcomes per characteristic.

dimension <- 10
characteristics <- 5

world <- array(0, dim=c(dimension, dimension, characteristics))

for (i in 1:dimension){
  for (j in 1:dimension){
    for (k in 1:characteristics){
      world[i,j,k] <- sample(c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), 1)
    }
  }
}

I would like to be able to flatten the array and create a unique identifier for each potential variation. For example, a world where each array[1,1]=(0,0,0,0,0)=1 all the way to: (9,9,9,9,9)=10^5. Also, this: (1,0,0,0,0)!=(0,0,1,0,0) etc. Any suggestions on how to flatten the dimensions would be greatly appreciated.

Body:
Can you provide an example with the desired shape?  How 'flat' do you want it?  This stacks the five characteristics on top of each other, resulting in a 10*5 rows and 10+1 columns (the extra column denotes the 'characteristic').

library(magrittr)
lst_ds <- purrr::map(seq_len(characteristics), ~tibble::as_tibble(world[,,.]))
ds <- lst_ds %>%
  dplyr::bind_rows(.id = "characteristic")

produces:

# A tibble: 50 x 11
   characteristic    V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
            <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1              1     3     3     1     6     3     6     9     7     0     0
 2              1     7     4     8     8     8     9     7     2     4     4
 3              1     0     6     7     2     7     5     1     1     7     4
 4              1     0     6     3     4     5     1     9     3     1     3
 5              1     1     5     2     1     1     9     6     8     3     2
 6              1     6     5     6     5     4     3     2     0     6     1
 7              1     2     7     1     4     4     4     8     1     1     0
 8              1     0     7     6     1     3     9     0     8     6     1
 9              1     1     2     4     8     1     9     2     8     1     5
10              1     2     9     1     6     8     0     3     1     6     2
11              2     6     2     7     7     0     1     1     2     9     0
12              2     0     0     7     5     7     4     9     1     4     6
# ... with 38 more rows


问:
SQL OrderBy two columns as one
I have a table that has two columns: Height and Width

What is the easiest way to sort this table incrementally based on either Height or Width

In other words, it would pick the smallest value from Height and Width for each row and sort it based on this number?

Thanks in advance!

答:
If you want to only sort on whichever column value is smallest and ignore the other column:</p>

```<code>SELECT
    *
FROM
    SomeTable
ORDER BY
    CASE
        WHEN Height < Width THEN Height
        ELSE Width
    END
</code>```

Title: SQL OrderBy two columns as one

Body:
If you want to only sort on whichever column value is smallest and ignore the other column:

SELECT
    *
FROM
    SomeTable
ORDER BY
    CASE
        WHEN Height < Width THEN Height
        ELSE Width
    END


问:
More efficient na.aggregate for grouped by maximum in R
I have a data frame that is roughly 20,000 x 300 in size that I am currently using na.aggregate from the zoo package to fill in the maximum by group for every column. If there is all NA's in the group it should return NA.  I am trying to find a more efficient solution for this chunk of my code to speed it up.  Here is a toy data frame as well as an attempt at a dplyr solution that was about ~10x slower than the na.aggregate version:

```<code>library(zoo)
library(dplyr)
library(microbenchmark)

# toy data frame
DF <- tibble(group=c(rep("A",4),rep("B",2),rep("C",3)),
             Col1=rep(NA_real_,9),
             Col2=c(5,3,2,NA,NA,NA,1,2,NA),
             Col3=c(NA,NA,NA,NA,1,NA,2,3,NA))

# na.aggregate solution
na.agg <- function(DF){

  agg.max <- suppressWarnings(na.aggregate(DF,DF$group,FUN=max))
  agg.max[,2:ncol(agg.max)] <- apply(agg.max[,2:ncol(agg.max)],2,as.numeric)

  return(agg.max)
}

# dplyr solution
dplyr.agg <- function(DF){

  Sol.2 <- DF %>%
    group_by(group) %>%
    mutate_all(funs(case_when(
      all(is.na(.))~NA_real_,
      is.na(.)~max(.,na.rm=TRUE),
      TRUE ~ as.numeric(I(.)))))
}

# Timing test
res <- microbenchmark(na.agg(DF),dplyr.agg(DF))

print(res)

Unit: milliseconds
          expr       min        lq      mean    median        uq       max neval
    na.agg(DF)  1.698281  1.879652  2.122334  2.063809  2.297201  3.763934   100
 dplyr.agg(DF) 10.730040 11.553523 12.484254 12.068044 12.778734 21.239836   100
</code>```

Is there an rcpp, data.table or better dplyr solution that is quicker??

答:
There's plenty more speed to be eeked out of na.agg yet. Don't do na.aggregate over the entire DF, as the inclusion of the group column means everything gets converted to a character, which will slow things down. Run it on DF[-1] excluding group and you don't even need the as.numeric conversion post-hoc.

```<code>na.agg2 <- function(DF) {
  DF[-1] <- na.aggregate(DF[-1], DF$group, FUN=function(x) if(all(is.na(x))) NA else max(x) )
  DF
}
</code>```

This markedly reduces the execution speed compared to your current na.agg:

```<code>microbenchmark(na.agg(DF),na.agg2(DF))
#Unit: milliseconds
#        expr      min       lq     mean   median       uq       max neval
#  na.agg(DF) 2.127476 2.145621 2.232542 2.163216 2.216366  3.433873   100
# na.agg2(DF) 1.047977 1.055675 1.560371 1.062455 1.080783 49.378785   100
</code>```

Using data.table seems to be speedier again:

```<code>DT <- copy(DF)
DT <- as.data.table(DT)
DT[,
  lapply(.SD, function(x) if(all(is.na(x))) NA_real_ else
                             replace(x,is.na(x),max(x,na.rm=TRUE))),
  by=group
]
</code>```

Body:
I have a data frame that is roughly 20,000 x 300 in size that I am currently using na.aggregate from the zoo package to fill in the maximum by group for every column. If there is all NA's in the group it should return NA.  I am trying to find a more efficient solution for this chunk of my code to speed it up.  Here is a toy data frame as well as an attempt at a dplyr solution that was about ~10x slower than the na.aggregate version:

library(zoo)
library(dplyr)
library(microbenchmark)

# toy data frame
DF <- tibble(group=c(rep("A",4),rep("B",2),rep("C",3)),
             Col1=rep(NA_real_,9),
             Col2=c(5,3,2,NA,NA,NA,1,2,NA),
             Col3=c(NA,NA,NA,NA,1,NA,2,3,NA))

# na.aggregate solution
na.agg <- function(DF){

  agg.max <- suppressWarnings(na.aggregate(DF,DF$group,FUN=max))
  agg.max[,2:ncol(agg.max)] <- apply(agg.max[,2:ncol(agg.max)],2,as.numeric)

  return(agg.max)
}

# dplyr solution
dplyr.agg <- function(DF){

  Sol.2 <- DF %>%
    group_by(group) %>%
    mutate_all(funs(case_when(
      all(is.na(.))~NA_real_,
      is.na(.)~max(.,na.rm=TRUE),
      TRUE ~ as.numeric(I(.)))))
}

# Timing test
res <- microbenchmark(na.agg(DF),dplyr.agg(DF))

print(res)

Unit: milliseconds
          expr       min        lq      mean    median        uq       max neval
    na.agg(DF)  1.698281  1.879652  2.122334  2.063809  2.297201  3.763934   100
 dplyr.agg(DF) 10.730040 11.553523 12.484254 12.068044 12.778734 21.239836   100

Is there an rcpp, data.table or better dplyr solution that is quicker??

Body:
There's plenty more speed to be eeked out of na.agg yet. Don't do na.aggregate over the entire DF, as the inclusion of the group column means everything gets converted to a character, which will slow things down. Run it on DF[-1] excluding group and you don't even need the as.numeric conversion post-hoc.

na.agg2 <- function(DF) {
  DF[-1] <- na.aggregate(DF[-1], DF$group, FUN=function(x) if(all(is.na(x))) NA else max(x) )
  DF
}

This markedly reduces the execution speed compared to your current na.agg:

microbenchmark(na.agg(DF),na.agg2(DF))
#Unit: milliseconds
#        expr      min       lq     mean   median       uq       max neval
#  na.agg(DF) 2.127476 2.145621 2.232542 2.163216 2.216366  3.433873   100
# na.agg2(DF) 1.047977 1.055675 1.560371 1.062455 1.080783 49.378785   100

Using data.table seems to be speedier again:

DT <- copy(DF)
DT <- as.data.table(DT)
DT[,
  lapply(.SD, function(x) if(all(is.na(x))) NA_real_ else
                             replace(x,is.na(x),max(x,na.rm=TRUE))),
  by=group
]


问:
BeautifulSoup4 attribute error
i've been going at this for hours now! i keep getting an error, all i'm trying to do is scrape the name of the product, brand, price, and shipping price, i have successfully scraped all, only issue is when i try and scrape the price and get it to loop through every one of the items on the webpage! i have a separate file in which i successfully scraped the price! This is my code trying to put everything together, and this is the error i get! please help!</p>

```<code># coding=utf-8
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

url = 'https://www.newegg.com/Product/ProductList.aspx?Submit=Property&N=100007709%2050001419%2050001315%2050001402%2050001312%2050001669%2050012150%2050001561%2050001314%2050001471%20600566292%20600566291%20600565504%20601201888%20601204369%20601210955%20601203793%204814%20601296707&IsNodeId=1&cm_sp=Cat_video-Cards_1-_-Visnav-_-Gaming-Video-Cards_1'

# This grabs the webpage and downloads it!
uClient = uReq(url)

# This is so i can read everything out of the url!
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")

# Grabs each product!
containers = page_soup.findAll("div", {"class": {"item-container", "item-action"}})

# set up the loop to get the brand of the item!
for container in containers:

    brand_container = container.findAll("a", {"class":"item-brand"})
    brand = container.div.div.a.img["title"]

    title_container = container.findAll("a", {"class":"item-title"})
    product_name = title_container[0].text

    price_container = container.findAll("li", {"class":"price-current"})
    price = container.strong.text

    shipping_container = page_soup.findAll("li", {"class": "price-ship"})
    shipping = shipping_container[0].text.strip()

    print("Product_name: " + product_name)
    print("Brand: " + brand)
    print("Price: " + price)
    print("Shipping: " + shipping)
</code>```

答:
The AttributeError is raised because a tag does not have the subtag you are looking for (e.g. container does not have a .div).  The cause is because of this line:

```<code>containers = page_soup.findAll("div", {"class": {"item-container", "item-action"}})
</code>```

You are making containers all item-container divs and item-action divs.  The item-action divs are not the containers you want to iterate through.  If you change that line to:

```<code>containers = page_soup.findAll("div", {"class": {"item-container"}})
</code>```

then it should parse correctly.

Finally you should change

```<code>brand = container.div.div.a.img["title"]
</code>```

to:

```<code>brand = brand_container.img["title"]
</code>```

Title: BeautifulSoup4 attribute error

Body:
i've been going at this for hours now! i keep getting an error, all i'm trying to do is scrape the name of the product, brand, price, and shipping price, i have successfully scraped all, only issue is when i try and scrape the price and get it to loop through every one of the items on the webpage! i have a separate file in which i successfully scraped the price! This is my code trying to put everything together, and this is the error i get! please help!

# coding=utf-8
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

url = 'https://www.newegg.com/Product/ProductList.aspx?Submit=Property&N=100007709%2050001419%2050001315%2050001402%2050001312%2050001669%2050012150%2050001561%2050001314%2050001471%20600566292%20600566291%20600565504%20601201888%20601204369%20601210955%20601203793%204814%20601296707&IsNodeId=1&cm_sp=Cat_video-Cards_1-_-Visnav-_-Gaming-Video-Cards_1'

# This grabs the webpage and downloads it!
uClient = uReq(url)

# This is so i can read everything out of the url!
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")

# Grabs each product!
containers = page_soup.findAll("div", {"class": {"item-container", "item-action"}})

# set up the loop to get the brand of the item!
for container in containers:

    brand_container = container.findAll("a", {"class":"item-brand"})
    brand = container.div.div.a.img["title"]

    title_container = container.findAll("a", {"class":"item-title"})
    product_name = title_container[0].text

    price_container = container.findAll("li", {"class":"price-current"})
    price = container.strong.text

    shipping_container = page_soup.findAll("li", {"class": "price-ship"})
    shipping = shipping_container[0].text.strip()

    print("Product_name: " + product_name)
    print("Brand: " + brand)
    print("Price: " + price)
    print("Shipping: " + shipping)

Body:
The AttributeError is raised because a tag does not have the subtag you are looking for (e.g. container does not have a .div).  The cause is because of this line:

containers = page_soup.findAll("div", {"class": {"item-container", "item-action"}})

You are making containers all item-container divs and item-action divs.  The item-action divs are not the containers you want to iterate through.  If you change that line to:

containers = page_soup.findAll("div", {"class": {"item-container"}})

then it should parse correctly.

Finally you should change

brand = container.div.div.a.img["title"]

to:

brand = brand_container.img["title"]


问:
Two Tables relation with a WHERE clause condition if exists or not exists
the query is

```<code>$query = "SELECT a.title, a.content, SUM(b.rating) as rating FROM posts a, ratings b WHERE a.id = :id AND a.id = b.pid GROUP BY b.author ORDER BY rating";
</code>```

depends on these table

```<code>                 posts                                       ratings
  [ id  -  title   -   content -  author ]            [ pid  -  rating  -  author ]
   --------------------------------------              ---------------------------
  [ 1  -  title1  -  content1 -  author1 ]            [  1    -   8   -   author1 ]
  [ 2  -  title1  -  content2 -  author2 ]            [  1    -   5   -   author1 ]
  [ 3  -  title1  -  content4 -  author3 ]            [  1    -   9   -   author2 ]
  [ 4  -  title4  -  content4 -  author4 ]            [  1    -   6   -   author4 ]
  [ 5  -  title5  -  content5 -  author5 ]            [  5    -   3   -   author5 ]
</code>```

Now i'm trying to ORDER posts by the SUM of all the ratings WHERE the a.id = b.pid AND a.author = b.author But it doesnt work ordered as it is supposed to be, And if there is no rating at all, the entire query values become empty since the clause WHERE a.id = p.id is empty, And i want to make it as a SUM = 0, How can i fix this exactly?

It is supposed to shows values like this if the id is 1 when echoed

```<code>author1, author2, author4
</code>```

but instead it just shows at randomized ORDER and if the ratings table is empty, no values are called at all.

答:
Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

It is a little difficult to figure out what you want.  But you seem to have a big focus on authors, even though authors play a minimal role in your query.  This is what you are describing:

```<code>SELECT p.author, SUM(r.rating) as sumrating
FROM posts p LEFT JOIN
     ratings r
     ON p.id = r.pid AND p.author = r.author
WHERE a.id = :id
GROUP BY p.author
ORDER BY sumrating;
</code>```

It doesn't seem particularly useful to me.

Body:
the query is

$query = "SELECT a.title, a.content, SUM(b.rating) as rating FROM posts a, ratings b WHERE a.id = :id AND a.id = b.pid GROUP BY b.author ORDER BY rating";

depends on these table

                 posts                                       ratings
  [ id  -  title   -   content -  author ]            [ pid  -  rating  -  author ]
   --------------------------------------              ---------------------------
  [ 1  -  title1  -  content1 -  author1 ]            [  1    -   8   -   author1 ]
  [ 2  -  title1  -  content2 -  author2 ]            [  1    -   5   -   author1 ]
  [ 3  -  title1  -  content4 -  author3 ]            [  1    -   9   -   author2 ]
  [ 4  -  title4  -  content4 -  author4 ]            [  1    -   6   -   author4 ]
  [ 5  -  title5  -  content5 -  author5 ]            [  5    -   3   -   author5 ]

Now i'm trying to ORDER posts by the SUM of all the ratings WHERE the a.id = b.pid AND a.author = b.author But it doesnt work ordered as it is supposed to be, And if there is no rating at all, the entire query values become empty since the clause WHERE a.id = p.id is empty, And i want to make it as a SUM = 0, How can i fix this exactly?

It is supposed to shows values like this if the id is 1 when echoed

author1, author2, author4

but instead it just shows at randomized ORDER and if the ratings table is empty, no values are called at all.

Body:
Never use commas in the FROM clause.  Always use proper, explicit JOIN syntax.

It is a little difficult to figure out what you want.  But you seem to have a big focus on authors, even though authors play a minimal role in your query.  This is what you are describing:

SELECT p.author, SUM(r.rating) as sumrating
FROM posts p LEFT JOIN
     ratings r
     ON p.id = r.pid AND p.author = r.author
WHERE a.id = :id
GROUP BY p.author
ORDER BY sumrating;

It doesn't seem particularly useful to me.


问:
Make sure Java will not close OutputStream before PrinWriter.print() finishes
I'm developing a distributed system that receives requests via Socket and writes the results back using OutputStream.

I'm facing problems because I have to return a very large string, but Java just keeps the execution of the code after I call the method print() without it finished printing:

```<code>public void attendRequisition(Socket clientSocket) {
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());

    pw.print(getResults());

    pw.close()
}
</code>```

Some information:

I need to close the connection after sending the results.

Without the close() instruction, the whole printing process takes about 3~5 seconds to finishes

I'm using telnet to test this method, and I can see the message coming and being cut becase of Java running the close() instruction

I can't count with receiving client's feedback

I believe this is happening because Java thinks the method print() finished executing, but what might be happening is that Java sends the message to the JVM, and JVM send it to the network adapter, and since the message is very large, close() method is called before the network adapter is able to send the entire message.

What I need is a way to make sure Java will only run the instruction close() after the printing process finished and the client received the entire message.

UPDATE: I was able to get it working properly by adding a Thread.sleep(). By doing this, the SO has enough time to send the message before Java closes the connection. But I don't want to use this solution, it implicates on too many problems.

答:
I can see the message coming and being cut becase of Java running the close() instruction

No you can't. You can see the message being cut, unless you're wrong about how long it is, but you're jumping to conclusions about the reason. Java does not close the PrintWriter before it has finished sending. It flushes the writer to the socket send buffer, blocking if necessary, and then closes the underlying socket, which buffers a FIN behind the data. All the data gets sent, and all the data gets received, before the FIN arrives, which signals end of stream to the receiver.

Possibly you are unaware that PrintWriter swallows exceptions and therefore should really not be used over a network.

Body:
I'm developing a distributed system that receives requests via Socket and writes the results back using OutputStream.

I'm facing problems because I have to return a very large string, but Java just keeps the execution of the code after I call the method print() without it finished printing:

public void attendRequisition(Socket clientSocket) {
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());

    pw.print(getResults());

    pw.close()
}

Some information:

I need to close the connection after sending the results.

Without the close() instruction, the whole printing process takes about 3~5 seconds to finishes

I'm using telnet to test this method, and I can see the message coming and being cut becase of Java running the close() instruction

I can't count with receiving client's feedback

I believe this is happening because Java thinks the method print() finished executing, but what might be happening is that Java sends the message to the JVM, and JVM send it to the network adapter, and since the message is very large, close() method is called before the network adapter is able to send the entire message.

What I need is a way to make sure Java will only run the instruction close() after the printing process finished and the client received the entire message.

UPDATE: I was able to get it working properly by adding a Thread.sleep(). By doing this, the SO has enough time to send the message before Java closes the connection. But I don't want to use this solution, it implicates on too many problems.


问:
does not work recurring paypal sandbox
my php code generates html form which is submitting automatically with redirection of customers:

```<code>    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" name="vm_paypal_form" id="vmPaymentForm" accept-charset="UTF-8">
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="cmd" value="_xclick-subscriptions" />
<input type="hidden" name="business" value="bolpav@example.com" />
<input type="hidden" name="custom" value="otmjboutim6sl98u6olis61nm7" /
><input type="hidden" name="currency_code" value="USD" />
<input type="hidden" name="return" value="http://example.com/devportal/index.php?option=com_virtuemart&view=vmplg&task=pluginresponsereceived&on=3L99030&pm=1&Itemid=166&lang=" />
<input type="hidden" name="notify_url" value="http://example.com/devportal/index.php?option=com_virtuemart&view=vmplg&task=notify&tmpl=component&lang=" />
<input type="hidden" name="cancel_return" value="http://example.com/devportal/index.php?option=com_virtuemart&view=vmplg&task=pluginUserPaymentCancel&on=3L99030&pm=1&Itemid=166&lang=" />
<input type="hidden" name="rm" value="1" />
<input type="hidden" name="bn" value="VirtueMart_Cart_PPA" />
<input type="hidden" name="no_shipping" value="1" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="image_url" value="http://example.com/devportal/images/virtuemart/vendor/" />
<input type="hidden" name="item_name" value="Order Number: 3L99030" />
<input type="hidden" name="lc" value="EN" />
<input type="hidden" name="a3" value="105" />
<input type="hidden" name="p3" value="1" />
<input type="hidden" name="t3" value="M" />
<input type="hidden" name="src" value="1" />
<input type="hidden" name="srt" value="52" />
<input type="hidden" name="sra" value="1" />
<input type="submit"  value="Please wait while redirecting to PayPal" />
</form>
</code>```

After this form is submited i see page with order number, price and  message : ". To complete your checkout using PayPal, please log in." After i click Login button then it redirects me to login page . But after i login then it open dasboard and forgets about payment . So payment procedure gets broken.  I am using Sanbox business account for seller and sandbox personal account for customer. Can anybody help?

答: It seems to be a known issue at PayPal's end. The engineering team is working on this for a fix. Will update here once it gets fixed.</p>

Title: does not work recurring paypal sandbox

Body:
my php code generates html form which is submitting automatically with redirection of customers:

    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" name="vm_paypal_form" id="vmPaymentForm" accept-charset="UTF-8">
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="cmd" value="_xclick-subscriptions" />
<input type="hidden" name="business" value="bolpav@example.com" />
<input type="hidden" name="custom" value="otmjboutim6sl98u6olis61nm7" /
><input type="hidden" name="currency_code" value="USD" />
<input type="hidden" name="return" value="http://example.com/devportal/index.php?option=com_virtuemart&view=vmplg&task=pluginresponsereceived&on=3L99030&pm=1&Itemid=166&lang=" />
<input type="hidden" name="notify_url" value="http://example.com/devportal/index.php?option=com_virtuemart&view=vmplg&task=notify&tmpl=component&lang=" />
<input type="hidden" name="cancel_return" value="http://example.com/devportal/index.php?option=com_virtuemart&view=vmplg&task=pluginUserPaymentCancel&on=3L99030&pm=1&Itemid=166&lang=" />
<input type="hidden" name="rm" value="1" />
<input type="hidden" name="bn" value="VirtueMart_Cart_PPA" />
<input type="hidden" name="no_shipping" value="1" />
<input type="hidden" name="no_note" value="1" />
<input type="hidden" name="image_url" value="http://example.com/devportal/images/virtuemart/vendor/" />
<input type="hidden" name="item_name" value="Order Number: 3L99030" />
<input type="hidden" name="lc" value="EN" />
<input type="hidden" name="a3" value="105" />
<input type="hidden" name="p3" value="1" />
<input type="hidden" name="t3" value="M" />
<input type="hidden" name="src" value="1" />
<input type="hidden" name="srt" value="52" />
<input type="hidden" name="sra" value="1" />
<input type="submit"  value="Please wait while redirecting to PayPal" />
</form>

After this form is submited i see page with order number, price and  message : ". To complete your checkout using PayPal, please log in." After i click Login button then it redirects me to login page . But after i login then it open dasboard and forgets about payment . So payment procedure gets broken.  I am using Sanbox business account for seller and sandbox personal account for customer. Can anybody help?


问:
Parse query string into an array
How can I turn a string below into an array?

```<code>pg_id=2&parent_id=2&document&video
</code>```

This is the array I am looking for,

```<code>array(
    'pg_id' => 2,
    'parent_id' => 2,
    'document' => ,
    'video' =>
)
</code>```

答:
You can use the PHP string function parse_str() followed by foreach loop.

```<code>$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
  echo "$key => $value<br>";
}
print_r($my_arr);
</code>```

Title: Parse query string into an array

Body:
How can I turn a string below into an array?

pg_id=2&parent_id=2&document&video

This is the array I am looking for,

array(
    'pg_id' => 2,
    'parent_id' => 2,
    'document' => ,
    'video' =>
)

Body:
You can use the PHP string function parse_str() followed by foreach loop.

$str="pg_id=2&parent_id=2&document&video";
parse_str($str,$my_arr);
foreach($my_arr as $key=>$value){
  echo "$key => $value<br>";
}
print_r($my_arr);


问:
Can anyone recommend an Image Gallery with a good programming API?
What is the best solution/API for this? On my site users upload image, tag then and more. Instead of displaying the normal page where it shows the image and info (date, desc, user comments, etc) I want it to go to the next/prev image. Preferably with preloading. This code could be done either in flash or javascript, but I would need a way to give the user a link so they can pass it to someone else to continue at the same point.

Another thing I would like to support is a 'gallery' mode where it displays thumbs of multiple images and allows scrolling through them.

Is there an API I should use or should I hand-roll gallery and slideshow code?

答: Flickr seems to have a comprehensive API.  (But I have no experience with it.)</p>

LastEditorDisplayName: Eddie

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Jon Ericson


问:
Insert a button in the grouping header
Any help would be appreciable.I want to know how to insert a button in the grouping header without using "Ext.ux.grid.RowActions".I am in need of how to put a button in simply by renderer or something like that..Please help me to figure out this.</p>

答:
Ext JS uses tables in it's markup to display buttons. If you want an Ext JS format button, rather than just a normal button, you could conceivably include the relevant markup in the groupTextTpl attribute of the Ext.grid.GroupingView object associated with the grouped grid, for example:

```<code>...
groupTextTpl: 'Item: {gvalue} ({[values.rs.length]} Sub Item{[values.rs.length > 1 ? "s" : ""]}) <table cellspacing="0" class="x-btn  x-btn-text-icon" id="ext-comp-1005" style="width: auto;"><tbody class="x-btn-small x-btn-icon-small-left"><tr><td class="x-btn-tl"><i> </i></td><td class="x-btn-tc"></td><td class="x-btn-tr"><i> </i></td></tr><tr><td class="x-btn-ml"><i> </i></td><td class="x-btn-mc"><em unselectable="on" class=""><button type="button" id="ext-gen40" class=" x-btn-text my-action">My Action</button></em></td><td class="x-btn-mr"><i> </i></td></tr><tr><td class="x-btn-bl"><i> </i></td><td class="x-btn-bc"></td><td class="x-btn-br"><i> </i></td></tr></tbody></table>',
...
</code>```

This will create a button in the grouping header.

Title: Insert a button in the grouping header

Body:
Ext JS uses tables in it's markup to display buttons. If you want an Ext JS format button, rather than just a normal button, you could conceivably include the relevant markup in the groupTextTpl attribute of the Ext.grid.GroupingView object associated with the grouped grid, for example:

...
groupTextTpl: 'Item: {gvalue} ({[values.rs.length]} Sub Item{[values.rs.length > 1 ? "s" : ""]}) <table cellspacing="0" class="x-btn  x-btn-text-icon" id="ext-comp-1005" style="width: auto;"><tbody class="x-btn-small x-btn-icon-small-left"><tr><td class="x-btn-tl"><i>&nbsp;</i></td><td class="x-btn-tc"></td><td class="x-btn-tr"><i>&nbsp;</i></td></tr><tr><td class="x-btn-ml"><i>&nbsp;</i></td><td class="x-btn-mc"><em unselectable="on" class=""><button type="button" id="ext-gen40" class=" x-btn-text my-action">My Action</button></em></td><td class="x-btn-mr"><i>&nbsp;</i></td></tr><tr><td class="x-btn-bl"><i>&nbsp;</i></td><td class="x-btn-bc"></td><td class="x-btn-br"><i>&nbsp;</i></td></tr></tbody></table>',
...

This will create a button in the grouping header.


问:
Javascript: Open link in new page and run script
I require the ability to open a new window

```<code>window.open(url,'_blank');
</code>```

Then run a javascript script such as

```<code>window.open(url,'_blank').ready("javascript in here");
</code>```

But I don't know how to do it, is there a way that I can do this?

The description is short but I think that's all that needs to be said

答:
I don't know exactly what your use case is, but browser extensions allow you to run arbitrary JavaScript code in webpages (content_scripts for Chrome, for example).

The downside is that the user need to install the extension.

Body:
I require the ability to open a new window

window.open(url,'_blank');

Then run a javascript script such as

window.open(url,'_blank').ready("javascript in here");

But I don't know how to do it, is there a way that I can do this?

The description is short but I think that's all that needs to be said


问:
Recreating PyCharm launcher in Ubuntu
I installed pycharm normally via bin/pycharm.sh, but the mistake I made was doing bash pycharm.sh while the pycharm directory has inside the Downloads folder.

I later on moved the directory to /opt/Pycharm/. This is causing the once functioning unity launcher (which was added when PyCharm was initially installed) to fail every time I attempt to use it (as expected).

How can I re-add pycharm.sh as a lauchable app from the unity launcher? I know the location of the pycharm.sh file. I've tried to add it to /usr/bin/ but that does not change anything.

I can still launch pycharm via bash /usr/opt/Pycharm/bin/Pycharm.sh. But this is tedious.

UPDATE

I have tried making a new .desktop file for pycharm, using the following script:

```<code>[Desktop Entry]
Encoding=UTF-8
Name=PyCharm
Exec=/opt/Pycharm-3.0.1/bin/pycharm.sh
Icon=/opt/Pycharm-3.0.1/bin/PyCharm_32.png
Type=Application
Categories=Development;
StartupWMClass=PyCharm
</code>```

However, I get a "Unable to save Pycharm.desktop" error when I try to save the file inside /usr/share/applications/pycharm.desktop. Any help regarding this would be deeply appreciated.

答:
I just wanted to add, I just installed PyCharm Edu for Ubuntu 16.04 LTS today, and the way to create a desktop entry is very easy. When PyCharm Edu opens up, before entering any project, click on configure, and there should be a create Desktop Entry option. Select it, and it will create a PyCharm Edu.desktop file in the following directory:

```<code>/usr/local/share/applications
</code>```

Now traverse to that destination, and click the newly created PyCharm Edu.desktop file to launch PyCharm Edu. After that, you would just need to lock to launcher. It should work.

I know I am very late, but I hope I've helped those of us on Ubuntu 16.04 LTS who are trying to configure a desktop entry for this specific application.

Title: Recreating PyCharm launcher in Ubuntu

Body:
I installed pycharm normally via bin/pycharm.sh, but the mistake I made was doing bash pycharm.sh while the pycharm directory has inside the Downloads folder.

I later on moved the directory to /opt/Pycharm/. This is causing the once functioning unity launcher (which was added when PyCharm was initially installed) to fail every time I attempt to use it (as expected).

How can I re-add pycharm.sh as a lauchable app from the unity launcher? I know the location of the pycharm.sh file. I've tried to add it to /usr/bin/ but that does not change anything.

I can still launch pycharm via bash /usr/opt/Pycharm/bin/Pycharm.sh. But this is tedious.

UPDATE

I have tried making a new .desktop file for pycharm, using the following script:

[Desktop Entry]
Encoding=UTF-8
Name=PyCharm
Exec=/opt/Pycharm-3.0.1/bin/pycharm.sh
Icon=/opt/Pycharm-3.0.1/bin/PyCharm_32.png
Type=Application
Categories=Development;
StartupWMClass=PyCharm

However, I get a "Unable to save Pycharm.desktop" error when I try to save the file inside /usr/share/applications/pycharm.desktop. Any help regarding this would be deeply appreciated.

Body:
I just wanted to add, I just installed PyCharm Edu for Ubuntu 16.04 LTS today, and the way to create a desktop entry is very easy. When PyCharm Edu opens up, before entering any project, click on configure, and there should be a create Desktop Entry option. Select it, and it will create a PyCharm Edu.desktop file in the following directory:

/usr/local/share/applications

Now traverse to that destination, and click the newly created PyCharm Edu.desktop file to launch PyCharm Edu. After that, you would just need to lock to launcher. It should work.

I know I am very late, but I hope I've helped those of us on Ubuntu 16.04 LTS who are trying to configure a desktop entry for this specific application.


问:
How to get the MouseEvent coordinates for an element that has CSS3 Transform?
I want to detect where a MouseEvent has occurred, in coordinates relative to the clicked element. Why? Because I want to add an absolutely positioned child element at the clicked location.

I know how to detect it when no CSS3 transformations exist (see description below). However, when I add a CSS3 Transform, then my algorithm breaks, and I don't know how to fix it.

I'm not using any JavaScript library, and I want to understand how things work in plain JavaScript. So, please, don't answer with "just use jQuery".

By the way, I want a solution that works for all MouseEvents, not just "click". Not that it matters, because I believe all mouse events share the same properties, thus the same solution should work for all of them.

Background information

According to DOM Level 2 specification, a MouseEvent has few properties related to getting the event coordinates:

screenX and screenY return the screen coordinates (the origin is the top-left corner of user's monitor)

clientX and clientY return the coordinates relative the document viewport.

Thus, in order to find the position of the MouseEvent relative to the clicked element content, I must do this math:

```<code>ev.clientX - this.getBoundingClientRect().left - this.clientLeft + this.scrollLeft
</code>```

ev.clientX is the coordinate relative to the document viewport

this.getBoundingClientRect().left is the position of the element relative to the document viewport

this.clientLeft is the amount of border (and scrollbar) between the element boundary and the inner coordinates

this.scrollLeft is the amount of scrolling inside the element

getBoundingClientRect(), clientLeft and scrollLeft are specified at CSSOM View Module.

Experiment without CSS Transform (it works)

Confusing? Try the following piece of JavaScript and HTML. Upon clicking, a red dot should appear exactly where the click has happened. This version is "quite simple" and works as expected.

```<code>function click_handler(ev) {
    var rect = this.getBoundingClientRect();
    var left = ev.clientX - rect.left - this.clientLeft + this.scrollLeft;
    var top = ev.clientY - rect.top - this.clientTop + this.scrollTop;

    var dot = document.createElement('div');
    dot.setAttribute('style', 'position:absolute; width: 2px; height: 2px; top: '+top+'px; left: '+left+'px; background: red;');
    this.appendChild(dot);
}

document.getElementById("experiment").addEventListener('click', click_handler, false);

<div id="experiment" style="border: 5px inset #AAA; background: #CCC; height: 400px; position: relative; overflow: auto;">
    <div style="width: 900px; height: 2px;"></div>
    <div style="height: 900px; width: 2px;"></div>
</div>
</code>```

Experiment adding a CSS Transform (it fails)

Now, try adding a CSS transform:

```<code>#experiment {
    transform: scale(0.5);
    -moz-transform: scale(0.5);
    -o-transform: scale(0.5);
    -webkit-transform: scale(0.5);
    /* Note that this is a very simple transformation. */
    /* Remember to also think about more complex ones, as described below. */
}
</code>```

The algorithm doesn't know about the transformations, and thus calculates a wrong position. What's more, the results are different between Firefox 3.6 and Chrome 12. Opera 11.50 behaves just like Chrome.

In this example, the only transformation was scaling, so I could multiply the scaling factor to calculate the correct coordinate. However, if we think about arbitrary transformations (scale, rotate, skew, translate, matrix), and even nested transformations (a transformed element inside another transformed element), then we really need a better way to calculate the coordinates.

答:
I am working on a polyfill to transfrom DOM coordinates. The GeometryUtils api is not available yet (@see https://drafts.csswg.org/cssom-view/). I created a "simple" code in 2014 to transform coordinates, like localToGlobal, globalToLocal and localToLocal. Its not finished yet, but its working :) I think I will finish it in the coming months (05.07.2017), so if you still need a API to accomplish coordinate transformation give it a try: https://github.com/jsidea/jsidea jsidea core library. Its not stable yet (pre alpha).
You can use it like that:

Create your transform instance:

```<code>var transformer = jsidea.geom.Transform.create(yourElement);
</code>```

The box model you want to transform to (default:"border", will be replaced by ENUM's later on):

```<code>var toBoxModel = "border";
</code>```

The box model where your input coordinates coming from (default:"border"):

```<code>var fromBoxModel = "border";
</code>```

Transform your global coordinates (here {x:50, y:100, z: 0}) to local space. The resulting point has 4 components: x, y, z and w.

```<code>var local = transformer.globalToLocal(50, 100, 0, toBoxModel, fromBoxModel);
</code>```

I have implemented some other functions like localToGlobal and localToLocal.
If you want to give a try, just download the release build and use the jsidea.min.js.

Download the first release here: Download TypeScript code

Feel free to change the code, I never put it under any license :)

Body:
I want to detect where a MouseEvent has occurred, in coordinates relative to the clicked element. Why? Because I want to add an absolutely positioned child element at the clicked location.

I know how to detect it when no CSS3 transformations exist (see description below). However, when I add a CSS3 Transform, then my algorithm breaks, and I don't know how to fix it.

I'm not using any JavaScript library, and I want to understand how things work in plain JavaScript. So, please, don't answer with "just use jQuery".

By the way, I want a solution that works for all MouseEvents, not just "click". Not that it matters, because I believe all mouse events share the same properties, thus the same solution should work for all of them.

Background information

According to DOM Level 2 specification, a MouseEvent has few properties related to getting the event coordinates:

screenX and screenY return the screen coordinates (the origin is the top-left corner of user's monitor)

clientX and clientY return the coordinates relative the document viewport.

Thus, in order to find the position of the MouseEvent relative to the clicked element content, I must do this math:

ev.clientX - this.getBoundingClientRect().left - this.clientLeft + this.scrollLeft

ev.clientX is the coordinate relative to the document viewport

this.getBoundingClientRect().left is the position of the element relative to the document viewport

this.clientLeft is the amount of border (and scrollbar) between the element boundary and the inner coordinates

this.scrollLeft is the amount of scrolling inside the element

getBoundingClientRect(), clientLeft and scrollLeft are specified at CSSOM View Module.

Experiment without CSS Transform (it works)

Confusing? Try the following piece of JavaScript and HTML. Upon clicking, a red dot should appear exactly where the click has happened. This version is "quite simple" and works as expected.

function click_handler(ev) {
    var rect = this.getBoundingClientRect();
    var left = ev.clientX - rect.left - this.clientLeft + this.scrollLeft;
    var top = ev.clientY - rect.top - this.clientTop + this.scrollTop;

    var dot = document.createElement('div');
    dot.setAttribute('style', 'position:absolute; width: 2px; height: 2px; top: '+top+'px; left: '+left+'px; background: red;');
    this.appendChild(dot);
}

document.getElementById("experiment").addEventListener('click', click_handler, false);

Experiment adding a CSS Transform (it fails)

Now, try adding a CSS transform:

#experiment {
    transform: scale(0.5);
    -moz-transform: scale(0.5);
    -o-transform: scale(0.5);
    -webkit-transform: scale(0.5);
    /* Note that this is a very simple transformation. */
    /* Remember to also think about more complex ones, as described below. */
}

The algorithm doesn't know about the transformations, and thus calculates a wrong position. What's more, the results are different between Firefox 3.6 and Chrome 12. Opera 11.50 behaves just like Chrome.

In this example, the only transformation was scaling, so I could multiply the scaling factor to calculate the correct coordinate. However, if we think about arbitrary transformations (scale, rotate, skew, translate, matrix), and even nested transformations (a transformed element inside another transformed element), then we really need a better way to calculate the coordinates.

Body:
I am working on a polyfill to transfrom DOM coordinates. The GeometryUtils api is not available yet (@see https://drafts.csswg.org/cssom-view/). I created a "simple" code in 2014 to transform coordinates, like localToGlobal, globalToLocal and localToLocal. Its not finished yet, but its working :) I think I will finish it in the coming months (05.07.2017), so if you still need a API to accomplish coordinate transformation give it a try: https://github.com/jsidea/jsidea jsidea core library. Its not stable yet (pre alpha).
You can use it like that:

Create your transform instance:

var transformer = jsidea.geom.Transform.create(yourElement);

The box model you want to transform to (default:"border", will be replaced by ENUM's later on):

var toBoxModel = "border";

The box model where your input coordinates coming from (default:"border"):

var fromBoxModel = "border";

Transform your global coordinates (here {x:50, y:100, z: 0}) to local space. The resulting point has 4 components: x, y, z and w.

var local = transformer.globalToLocal(50, 100, 0, toBoxModel, fromBoxModel);

I have implemented some other functions like localToGlobal and localToLocal.
If you want to give a try, just download the release build and use the jsidea.min.js.

Download the first release here: Download TypeScript code

Feel free to change the code, I never put it under any license :)


问:
Symfony - Sonata "Admin service "app.admin.post" not found in admin pool."
I get the following error while trying to access the dashboard.

An exception has been thrown during the rendering of a template ("Admin service "app.admin.post" not found in admin pool.")

I use this tutorial ""5.3.2. Using the config.yml"" and I have no idea why I have this error
https://symfony.com/doc/current/bundles/SonataAdminBundle/reference/dashboard.html

```<code>sonata_admin:
templates:
    dashboard: SonataAdminBundle:Core:dashboard.html.twig
dashboard:
    groups:
        app.admin.group.content:
            label: app.admin.group.content
            label_catalogue: AppBundle
            items:
                - app.admin.post

        app.admin.group.blog:
            items: ~
            item_adds:
                - sonata.admin.page
            roles: [ ROLE_ONE, ROLE_TWO ]

        app.admin.group.misc: ~
</code>```

答:
Did you declared the services following the same tutorial?

```<code>services:
    app.admin.post:
        class: AppBundle\Admin\PostAdmin
        tags:
            - name: sonata.admin
              manager_type: orm
              group: "app.admin.group.content"
              label: "app.admin.model.post"
              label_catalogue: "AppBundle"
        arguments:
            - ~
            - AppBundle\Entity\Post
            - ~
</code>```

Remember that you have to declare them into app/config/services.yml or almost into your src/{whateverBundle}}/Resources/services.yml

Body:
I get the following error while trying to access the dashboard.

An exception has been thrown during the rendering of a template ("Admin service "app.admin.post" not found in admin pool.")

I use this tutorial ""5.3.2. Using the config.yml"" and I have no idea why I have this error
https://symfony.com/doc/current/bundles/SonataAdminBundle/reference/dashboard.html

sonata_admin:
templates:
    dashboard: SonataAdminBundle:Core:dashboard.html.twig
dashboard:
    groups:
        app.admin.group.content:
            label: app.admin.group.content
            label_catalogue: AppBundle
            items:
                - app.admin.post

        app.admin.group.blog:
            items: ~
            item_adds:
                - sonata.admin.page
            roles: [ ROLE_ONE, ROLE_TWO ]

        app.admin.group.misc: ~

Body:
Did you declared the services following the same tutorial?

services:
    app.admin.post:
        class: AppBundle\Admin\PostAdmin
        tags:
            - name: sonata.admin
              manager_type: orm
              group: "app.admin.group.content"
              label: "app.admin.model.post"
              label_catalogue: "AppBundle"
        arguments:
            - ~
            - AppBundle\Entity\Post
            - ~

Remember that you have to declare them into app/config/services.yml or almost into your src/{whateverBundle}}/Resources/services.yml


问:
Passing large amounts of data between webpages
I have a page where the user inputs a list of (potentially) thousands of strings, which then leads to a page that uses this list. I tried to just use a query parameter to pass the strings to the latter page, but according to another StackOverflow post that would exceed several browsers' URL length limits, although it worked just fine on Chrome, Firefox and Safari when I tested it. Are there any alternatives to passing massive a query parameter?

Note: One alternative would be to switch to a single-page app but I'd like to avoid that much complexity if it's possible.

答:
URL has a length limit which is not standardized. It depends on which browser and which version of the browser you're using. You're probably safe with about 2000 characters of total URL length.

If you want to avoid that, instead of issuing a GET request to a different page, you should create a POST request which has no limits.

The other alternative is using SPA where you're not actually sending anything over the HTTP and send the data in-memory instead.


答: Save the data in localstorage or some client db like indexedDB, then retrieve it on the other page.</p>

Title: Passing large amounts of data between webpages

Body:
I have a page where the user inputs a list of (potentially) thousands of strings, which then leads to a page that uses this list. I tried to just use a query parameter to pass the strings to the latter page, but according to another StackOverflow post that would exceed several browsers' URL length limits, although it worked just fine on Chrome, Firefox and Safari when I tested it. Are there any alternatives to passing massive a query parameter?

Note: One alternative would be to switch to a single-page app but I'd like to avoid that much complexity if it's possible.


问:
tail call optimization for xslt recursive template
BackGround

We are using nginx with ngx_http_xslt_module enabled.This will help us in applying stylesheets to responses.

This module internally uses libxslt processor to apply xslt transformations.It has a configurable depth(maxdepth) of recursion beyond which it will signal an infinite recursion error.

Issue

At a depth of 3000 the below xslt transformation when applied to a document is failing with infinite recursion error.As per other answers that I have seen,the below xslt template is tail call optimised and some processors optimise the code.Wanted to confirm from xslt perspective if the below xslt function is really tail optimized and if libxslt does tail call optimization.

The escapeQuote xslt template when converted to code however is not tail call optimized.

```<code>"currentresult" + escapeQuote(sub-string(str))
</code>```

The below is xslt template to escape double quotes.

```<code> <xsl:template name="escapeQuote">
  <xsl:param name="pText" select="normalize-space(.)"/>
  <xsl:if test="string-length($pText) >0">
   <xsl:value-of select="substring-before(concat($pText, '"'), '"')"/>
   <xsl:if test="contains($pText, '"')">
    <xsl:text>\"</xsl:text>
    <xsl:call-template name="escapeQuote">
      <xsl:with-param name="pText" select="substring-after($pText, '"')"/>
    </xsl:call-template>
   </xsl:if>
  </xsl:if>
</xsl:template>
</code>```

This is in XSLT 1.0.

答:
libxslt does not do tail-call optimisation.  You should instead use the EXSLT functions that are included with libxslt.  The str:replace function is not technically conformant to the specification, but is sufficiently correct for your needs.  Specifically (assuming you are trying to change " to \"):

```<code><xsl:template xmlns:str="http://exslt.org/strings" name="escapeQuote">
  <xsl:param name="pText" select="normalize-space(.)"/>
  <xsl:value-of select="str:replace($pText,'"','\"')"/>
</xsl:template>
</code>```

Obviously you can ditch the template all together and just insert the relevant XPath if that works better for you.

Body:
BackGround

We are using nginx with ngx_http_xslt_module enabled.This will help us in applying stylesheets to responses.

This module internally uses libxslt processor to apply xslt transformations.It has a configurable depth(maxdepth) of recursion beyond which it will signal an infinite recursion error.

Issue

At a depth of 3000 the below xslt transformation when applied to a document is failing with infinite recursion error.As per other answers that I have seen,the below xslt template is tail call optimised and some processors optimise the code.Wanted to confirm from xslt perspective if the below xslt function is really tail optimized and if libxslt does tail call optimization.

The escapeQuote xslt template when converted to code however is not tail call optimized.

"currentresult" + escapeQuote(sub-string(str))

The below is xslt template to escape double quotes.

 <xsl:template name="escapeQuote">
  <xsl:param name="pText" select="normalize-space(.)"/>
  <xsl:if test="string-length($pText) >0">
   <xsl:value-of select="substring-before(concat($pText, '"'), '"')"/>
   <xsl:if test="contains($pText, '"')">
    <xsl:text>\"</xsl:text>
    <xsl:call-template name="escapeQuote">
      <xsl:with-param name="pText" select="substring-after($pText, '"')"/>
    </xsl:call-template>
   </xsl:if>
  </xsl:if>
</xsl:template>

This is in XSLT 1.0.

Body:
libxslt does not do tail-call optimisation.  You should instead use the EXSLT functions that are included with libxslt.  The str:replace function is not technically conformant to the specification, but is sufficiently correct for your needs.  Specifically (assuming you are trying to change " to \"):

<xsl:template xmlns:str="http://exslt.org/strings" name="escapeQuote">
  <xsl:param name="pText" select="normalize-space(.)"/>
  <xsl:value-of select="str:replace($pText,'&quot;','\&quot;')"/>
</xsl:template>

Obviously you can ditch the template all together and just insert the relevant XPath if that works better for you.


问:
Get current image of kubernetes deployment
How can I use kubectl or the API to retrieve the current image for containers in a pod or deployment?

For example, in a deployment created with the below configuration, I want to retrieve the value eu.gcr.io/test0/brain:latest.

```<code>apiVersion: v1
   kind: Deployment
   metadata:
     name: flags
   spec:
     replicas: 6
     template:
       metadata:
      labels:
        app: flags
       spec:
         containers:
         - name: flags
           image: eu.gcr.io/test0/brain:latest
</code>```

答:
From kubectl 1.6 the -o wide option does this, so

```<code>kubectl get deployments -o wide
</code>```

will show the current image in the output.

Body:
How can I use kubectl or the API to retrieve the current image for containers in a pod or deployment?

For example, in a deployment created with the below configuration, I want to retrieve the value eu.gcr.io/test0/brain:latest.

apiVersion: v1
   kind: Deployment
   metadata:
     name: flags
   spec:
     replicas: 6
     template:
       metadata:
      labels:
        app: flags
       spec:
         containers:
         - name: flags
           image: eu.gcr.io/test0/brain:latest

Body:
From kubectl 1.6 the -o wide option does this, so

kubectl get deployments -o wide

will show the current image in the output.


问:
Jquery ajax get xml parse error
I want get a XML from this url usin Jquery ajax https://sisa.msal.gov.ar/sisa/services/rest/puco/44003375

Via browser I can see this:

```<code>This XML file does not appear to have any style information associated with it. The document tree is shown below.
<puco>
 <resultado>OK</resultado>
 <coberturaSocial>O.S.P. CIUDAD AUT</coberturaSocial>
<denominacion>AGOSTINO RODRIGO LEONARDO</denominacion>
<nrodoc>44003375</nrodoc>
<rnos>901001</rnos>
<tipodoc>DNI</tipodoc>
</puco>
</code>```

But when doing:

```<code>var id=44003375;
$.ajax({
    type : "GET",
    url  : 'https://sisa.msal.gov.ar/sisa/services/rest/puco/'+id,
    dataType :"JSONP",
    jsonp: true,
    success : function(xhr){
      alert(JSON.stringify(xhr));
    },
    error : function(httpReq,status,exception){
      var clientid = $(httpReq).text();
      alert(JSON.stringify(httpReq));
    }
 });
</code>```

Return "Parse error"... how I can get via ajax what the browser shows?

答:
I resolved, but with PHP</p>

```<code><?php
  $response = file_get_contents('https://sisa.msal.gov.ar/sisa/services/rest/puco/44003375');
  $response = new SimpleXMLElement($response);
  dd($response);
?>
</code>```

Title: Jquery ajax get xml parse error

Body:
I want get a XML from this url usin Jquery ajax https://sisa.msal.gov.ar/sisa/services/rest/puco/44003375

Via browser I can see this:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<puco>
 <resultado>OK</resultado>
 <coberturaSocial>O.S.P. CIUDAD AUT</coberturaSocial>
<denominacion>AGOSTINO RODRIGO LEONARDO</denominacion>
<nrodoc>44003375</nrodoc>
<rnos>901001</rnos>
<tipodoc>DNI</tipodoc>
</puco>

But when doing:

var id=44003375;
$.ajax({
    type : "GET",
    url  : 'https://sisa.msal.gov.ar/sisa/services/rest/puco/'+id,
    dataType :"JSONP",
    jsonp: true,
    success : function(xhr){
      alert(JSON.stringify(xhr));
    },
    error : function(httpReq,status,exception){
      var clientid = $(httpReq).text();
      alert(JSON.stringify(httpReq));
    }
 });

Return "Parse error"... how I can get via ajax what the browser shows?

Body:
I resolved, but with PHP

<?php
  $response = file_get_contents('https://sisa.msal.gov.ar/sisa/services/rest/puco/44003375');
  $response = new SimpleXMLElement($response);
  dd($response);
?>


问:
Java - How to increase the robot delay above 60'000 milliseconds?
Im trying to make an Auto Typer but i cant go above 60'000 milliseconds between each message, is it possible to go above that?

Code:

```<code>import java.awt.AWTException;
import java.awt.Robot;
import static java.awt.event.KeyEvent.*;

public class Runnah implements Runnable {

    private MainGUI gui;

    // A new robot
    private Robot robot;

    private boolean toggle;

    private static boolean enter;

    public Runnah(MainGUI c) throws AWTException {
        // Creates the Robot
        this.robot = new Robot();
        // Sets the current GUI
        gui = c;
        toggle = true;
        enter = false;
    }

    public Runnah(Robot robot) {
        this.robot = robot;
    }

    private void typeNow(int... key) {
        typeNow(key, 0, key.length);
    }

    private void typeNow(int[] key, int offset, int length) {
        if (length == 0) {
            return;
        }

        // Presses and releases the key that is passed into typeNow
        robot.keyPress(key[offset]);
        typeNow(key, offset + 1, length - 1);
        robot.keyRelease(key[offset]);
    }

    // GIANT SWITCH STATEMENT FOR EVERY CHARACTER ON THE KEYBOARD
    public void typeThis(char let) {
        switch (let) {
        case 'a':
            typeNow(VK_A);
            break;
        case 'b':
            typeNow(VK_B);
            break;
        case 'c':
            typeNow(VK_C);
            break;
        case 'd':
            typeNow(VK_D);
            break;
        case 'e':
            typeNow(VK_E);
            break;
        case 'f':
            typeNow(VK_F);
            break;
        case 'g':
            typeNow(VK_G);
            break;
        case 'h':
            typeNow(VK_H);
            break;
        case 'i':
            typeNow(VK_I);
            break;
        case 'j':
            typeNow(VK_J);
            break;
        case 'k':
            typeNow(VK_K);
            break;
        case 'l':
            typeNow(VK_L);
            break;
        case 'm':
            typeNow(VK_M);
            break;
        case 'n':
            typeNow(VK_N);
            break;
        case 'o':
            typeNow(VK_O);
            break;
        case 'p':
            typeNow(VK_P);
            break;
        case 'q':
            typeNow(VK_Q);
            break;
        case 'r':
            typeNow(VK_R);
            break;
        case 's':
            typeNow(VK_S);
            break;
        case 't':
            typeNow(VK_T);
            break;
        case 'u':
            typeNow(VK_U);
            break;
        case 'v':
            typeNow(VK_V);
            break;
        case 'w':
            typeNow(VK_W);
            break;
        case 'x':
            typeNow(VK_X);
            break;
        case 'y':
            typeNow(VK_Y);
            break;
        case 'z':
            typeNow(VK_Z);
            break;
        case 'A':
            typeNow(VK_SHIFT, VK_A);
            break;
        case 'B':
            typeNow(VK_SHIFT, VK_B);
            break;
        case 'C':
            typeNow(VK_SHIFT, VK_C);
            break;
        case 'D':
            typeNow(VK_SHIFT, VK_D);
            break;
        case 'E':
            typeNow(VK_SHIFT, VK_E);
            break;
        case 'F':
            typeNow(VK_SHIFT, VK_F);
            break;
        case 'G':
            typeNow(VK_SHIFT, VK_G);
            break;
        case 'H':
            typeNow(VK_SHIFT, VK_H);
            break;
        case 'I':
            typeNow(VK_SHIFT, VK_I);
            break;
        case 'J':
            typeNow(VK_SHIFT, VK_J);
            break;
        case 'K':
            typeNow(VK_SHIFT, VK_K);
            break;
        case 'L':
            typeNow(VK_SHIFT, VK_L);
            break;
        case 'M':
            typeNow(VK_SHIFT, VK_M);
            break;
        case 'N':
            typeNow(VK_SHIFT, VK_N);
            break;
        case 'O':
            typeNow(VK_SHIFT, VK_O);
            break;
        case 'P':
            typeNow(VK_SHIFT, VK_P);
            break;
        case 'Q':
            typeNow(VK_SHIFT, VK_Q);
            break;
        case 'R':
            typeNow(VK_SHIFT, VK_R);
            break;
        case 'S':
            typeNow(VK_SHIFT, VK_S);
            break;
        case 'T':
            typeNow(VK_SHIFT, VK_T);
            break;
        case 'U':
            typeNow(VK_SHIFT, VK_U);
            break;
        case 'V':
            typeNow(VK_SHIFT, VK_V);
            break;
        case 'W':
            typeNow(VK_SHIFT, VK_W);
            break;
        case 'X':
            typeNow(VK_SHIFT, VK_X);
            break;
        case 'Y':
            typeNow(VK_SHIFT, VK_Y);
            break;
        case 'Z':
            typeNow(VK_SHIFT, VK_Z);
            break;
        case '`':
            typeNow(VK_BACK_QUOTE);
            break;
        case '0':
            typeNow(VK_0);
            break;
        case '1':
            typeNow(VK_1);
            break;
        case '2':
            typeNow(VK_2);
            break;
        case '3':
            typeNow(VK_3);
            break;
        case '4':
            typeNow(VK_4);
            break;
        case '5':
            typeNow(VK_5);
            break;
        case '6':
            typeNow(VK_6);
            break;
        case '7':
            typeNow(VK_7);
            break;
        case '8':
            typeNow(VK_8);
            break;
        case '9':
            typeNow(VK_9);
            break;
        case '-':
            typeNow(VK_MINUS);
            break;
        case '=':
            typeNow(VK_EQUALS);
            break;
        case '~':
            typeNow(VK_SHIFT, VK_BACK_QUOTE);
            break;
        case '!':
            typeNow(VK_SHIFT, VK_1);
            break;
        case '@':
            typeNow(VK_SHIFT, VK_2);
            break;
        case '#':
            typeNow(VK_SHIFT, VK_3);
            break;
        case '$':
            typeNow(VK_SHIFT, VK_4);
            break;
        case '%':
            typeNow(VK_SHIFT, VK_5);
            break;
        case '^':
            typeNow(VK_SHIFT, VK_6);
            break;
        case '&':
            typeNow(VK_SHIFT, VK_7);
            break;
        case '*':
            typeNow(VK_SHIFT, VK_8);
            break;
        case '(':
            typeNow(VK_SHIFT, VK_9);
            break;
        case ')':
            typeNow(VK_SHIFT, VK_0);
            break;
        case '_':
            typeNow(VK_SHIFT, VK_MINUS);
            break;
        case '+':
            typeNow(VK_SHIFT, VK_EQUALS);
            break;
        case '\t':
            typeNow(VK_TAB);
            break;
        case '\n':
            typeNow(VK_ENTER);
            break;
        case '[':
            typeNow(VK_OPEN_BRACKET);
            break;
        case ']':
            typeNow(VK_CLOSE_BRACKET);
            break;
        case '\\':
            typeNow(VK_BACK_SLASH);
            break;
        case '{':
            typeNow(VK_SHIFT, VK_OPEN_BRACKET);
            break;
        case '}':
            typeNow(VK_SHIFT, VK_CLOSE_BRACKET);
            break;
        case '|':
            typeNow(VK_SHIFT, VK_BACK_SLASH);
            break;
        case ';':
            typeNow(VK_SEMICOLON);
            break;
        case ':':
            typeNow(VK_SHIFT, VK_SEMICOLON);
            break;
        case '\'':
            typeNow(VK_QUOTE);
            break;
        case '"':
            typeNow(VK_SHIFT, VK_QUOTE);
            break;
        case ',':
            typeNow(VK_COMMA);
            break;
        case '<':
            typeNow(VK_SHIFT, VK_COMMA);
            break;
        case '.':
            typeNow(VK_PERIOD);
            break;
        case '>':
            typeNow(VK_SHIFT, VK_PERIOD);
            break;
        case '/':
            typeNow(VK_SLASH);
            break;
        case '?':
            typeNow(VK_SHIFT, VK_SLASH);
            break;
        case ' ':
            typeNow(VK_SPACE);
            break;
        default:
            throw new IllegalArgumentException("Derp! That chatacter doesn't work " + let);
        }
    }

    public void setToggle() {
        toggle = false;
    }

    // Enables/Disables the enter key
    public void setEnter(boolean a) {
        enter = a;
    }

    @Override
    public void run() {

        int seconds = 1;

        // Get the input from the textField in the GUI
        String temp = gui.getInput();

        // Turns it into an array of chars
        char[] test = new char[temp.length()];

        for (int i = 0; i < temp.length(); i++) {
            test[i] = temp.charAt(i);
        }

        // Sets the seconds to the entered seconds * 1000
        // Becase .delay() runs in Milliseconds
        try {
            seconds = gui.getSeconds() * 1000;
        } catch (Exception e) {

        }

        while (!Thread.currentThread().isInterrupted()) {

            robot.delay(seconds);

            for (int i = 0; i < temp.length(); i++) {
                typeThis(test[i]);
            }

            if (enter) {
                typeNow(VK_ENTER);
            }
        }
        toggle = true;
    }

}
</code>```

答:
Fixed.

Original Version :

```<code>    try {
        seconds = gui.getSeconds() * 1000;
    } catch (Exception e) {

    }

    while (!Thread.currentThread().isInterrupted()) {

        robot.delay(seconds);

        for (int i = 0; i < temp.length(); i++) {
            typeThis(test[i]);
        }

        if (enter) {
            typeNow(VK_ENTER);
        }
    }
</code>```

Fixed Version :

```<code>    try {
        seconds = gui.getSeconds() * 1000;
    } catch (Exception e) {

    }
    System.out.print(seconds);
    while (!Thread.currentThread().isInterrupted()) {

        if (seconds <= 60000) {
            robot.delay(seconds);
        } else {
            try {
                int newTime = seconds - 60000;
                robot.delay(60000);
                Thread.sleep(newTime);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        for (int i = 0; i < temp.length(); i++) {
            typeThis(test[i]);
        }

        if (enter) {
            typeNow(VK_ENTER);
        }
    }
</code>```

Allows you to go above 60'000 ms delay.

Body:
Im trying to make an Auto Typer but i cant go above 60'000 milliseconds between each message, is it possible to go above that?

Code:

import java.awt.AWTException;
import java.awt.Robot;
import static java.awt.event.KeyEvent.*;

public class Runnah implements Runnable {

    private MainGUI gui;

    // A new robot
    private Robot robot;

    private boolean toggle;

    private static boolean enter;

    public Runnah(MainGUI c) throws AWTException {
        // Creates the Robot
        this.robot = new Robot();
        // Sets the current GUI
        gui = c;
        toggle = true;
        enter = false;
    }

    public Runnah(Robot robot) {
        this.robot = robot;
    }

    private void typeNow(int... key) {
        typeNow(key, 0, key.length);
    }

    private void typeNow(int[] key, int offset, int length) {
        if (length == 0) {
            return;
        }

        // Presses and releases the key that is passed into typeNow
        robot.keyPress(key[offset]);
        typeNow(key, offset + 1, length - 1);
        robot.keyRelease(key[offset]);
    }

    // GIANT SWITCH STATEMENT FOR EVERY CHARACTER ON THE KEYBOARD
    public void typeThis(char let) {
        switch (let) {
        case 'a':
            typeNow(VK_A);
            break;
        case 'b':
            typeNow(VK_B);
            break;
        case 'c':
            typeNow(VK_C);
            break;
        case 'd':
            typeNow(VK_D);
            break;
        case 'e':
            typeNow(VK_E);
            break;
        case 'f':
            typeNow(VK_F);
            break;
        case 'g':
            typeNow(VK_G);
            break;
        case 'h':
            typeNow(VK_H);
            break;
        case 'i':
            typeNow(VK_I);
            break;
        case 'j':
            typeNow(VK_J);
            break;
        case 'k':
            typeNow(VK_K);
            break;
        case 'l':
            typeNow(VK_L);
            break;
        case 'm':
            typeNow(VK_M);
            break;
        case 'n':
            typeNow(VK_N);
            break;
        case 'o':
            typeNow(VK_O);
            break;
        case 'p':
            typeNow(VK_P);
            break;
        case 'q':
            typeNow(VK_Q);
            break;
        case 'r':
            typeNow(VK_R);
            break;
        case 's':
            typeNow(VK_S);
            break;
        case 't':
            typeNow(VK_T);
            break;
        case 'u':
            typeNow(VK_U);
            break;
        case 'v':
            typeNow(VK_V);
            break;
        case 'w':
            typeNow(VK_W);
            break;
        case 'x':
            typeNow(VK_X);
            break;
        case 'y':
            typeNow(VK_Y);
            break;
        case 'z':
            typeNow(VK_Z);
            break;
        case 'A':
            typeNow(VK_SHIFT, VK_A);
            break;
        case 'B':
            typeNow(VK_SHIFT, VK_B);
            break;
        case 'C':
            typeNow(VK_SHIFT, VK_C);
            break;
        case 'D':
            typeNow(VK_SHIFT, VK_D);
            break;
        case 'E':
            typeNow(VK_SHIFT, VK_E);
            break;
        case 'F':
            typeNow(VK_SHIFT, VK_F);
            break;
        case 'G':
            typeNow(VK_SHIFT, VK_G);
            break;
        case 'H':
            typeNow(VK_SHIFT, VK_H);
            break;
        case 'I':
            typeNow(VK_SHIFT, VK_I);
            break;
        case 'J':
            typeNow(VK_SHIFT, VK_J);
            break;
        case 'K':
            typeNow(VK_SHIFT, VK_K);
            break;
        case 'L':
            typeNow(VK_SHIFT, VK_L);
            break;
        case 'M':
            typeNow(VK_SHIFT, VK_M);
            break;
        case 'N':
            typeNow(VK_SHIFT, VK_N);
            break;
        case 'O':
            typeNow(VK_SHIFT, VK_O);
            break;
        case 'P':
            typeNow(VK_SHIFT, VK_P);
            break;
        case 'Q':
            typeNow(VK_SHIFT, VK_Q);
            break;
        case 'R':
            typeNow(VK_SHIFT, VK_R);
            break;
        case 'S':
            typeNow(VK_SHIFT, VK_S);
            break;
        case 'T':
            typeNow(VK_SHIFT, VK_T);
            break;
        case 'U':
            typeNow(VK_SHIFT, VK_U);
            break;
        case 'V':
            typeNow(VK_SHIFT, VK_V);
            break;
        case 'W':
            typeNow(VK_SHIFT, VK_W);
            break;
        case 'X':
            typeNow(VK_SHIFT, VK_X);
            break;
        case 'Y':
            typeNow(VK_SHIFT, VK_Y);
            break;
        case 'Z':
            typeNow(VK_SHIFT, VK_Z);
            break;
        case '`':
            typeNow(VK_BACK_QUOTE);
            break;
        case '0':
            typeNow(VK_0);
            break;
        case '1':
            typeNow(VK_1);
            break;
        case '2':
            typeNow(VK_2);
            break;
        case '3':
            typeNow(VK_3);
            break;
        case '4':
            typeNow(VK_4);
            break;
        case '5':
            typeNow(VK_5);
            break;
        case '6':
            typeNow(VK_6);
            break;
        case '7':
            typeNow(VK_7);
            break;
        case '8':
            typeNow(VK_8);
            break;
        case '9':
            typeNow(VK_9);
            break;
        case '-':
            typeNow(VK_MINUS);
            break;
        case '=':
            typeNow(VK_EQUALS);
            break;
        case '~':
            typeNow(VK_SHIFT, VK_BACK_QUOTE);
            break;
        case '!':
            typeNow(VK_SHIFT, VK_1);
            break;
        case '@':
            typeNow(VK_SHIFT, VK_2);
            break;
        case '#':
            typeNow(VK_SHIFT, VK_3);
            break;
        case '$':
            typeNow(VK_SHIFT, VK_4);
            break;
        case '%':
            typeNow(VK_SHIFT, VK_5);
            break;
        case '^':
            typeNow(VK_SHIFT, VK_6);
            break;
        case '&':
            typeNow(VK_SHIFT, VK_7);
            break;
        case '*':
            typeNow(VK_SHIFT, VK_8);
            break;
        case '(':
            typeNow(VK_SHIFT, VK_9);
            break;
        case ')':
            typeNow(VK_SHIFT, VK_0);
            break;
        case '_':
            typeNow(VK_SHIFT, VK_MINUS);
            break;
        case '+':
            typeNow(VK_SHIFT, VK_EQUALS);
            break;
        case '\t':
            typeNow(VK_TAB);
            break;
        case '\n':
            typeNow(VK_ENTER);
            break;
        case '[':
            typeNow(VK_OPEN_BRACKET);
            break;
        case ']':
            typeNow(VK_CLOSE_BRACKET);
            break;
        case '\\':
            typeNow(VK_BACK_SLASH);
            break;
        case '{':
            typeNow(VK_SHIFT, VK_OPEN_BRACKET);
            break;
        case '}':
            typeNow(VK_SHIFT, VK_CLOSE_BRACKET);
            break;
        case '|':
            typeNow(VK_SHIFT, VK_BACK_SLASH);
            break;
        case ';':
            typeNow(VK_SEMICOLON);
            break;
        case ':':
            typeNow(VK_SHIFT, VK_SEMICOLON);
            break;
        case '\'':
            typeNow(VK_QUOTE);
            break;
        case '"':
            typeNow(VK_SHIFT, VK_QUOTE);
            break;
        case ',':
            typeNow(VK_COMMA);
            break;
        case '<':
            typeNow(VK_SHIFT, VK_COMMA);
            break;
        case '.':
            typeNow(VK_PERIOD);
            break;
        case '>':
            typeNow(VK_SHIFT, VK_PERIOD);
            break;
        case '/':
            typeNow(VK_SLASH);
            break;
        case '?':
            typeNow(VK_SHIFT, VK_SLASH);
            break;
        case ' ':
            typeNow(VK_SPACE);
            break;
        default:
            throw new IllegalArgumentException("Derp! That chatacter doesn't work " + let);
        }
    }

    public void setToggle() {
        toggle = false;
    }

    // Enables/Disables the enter key
    public void setEnter(boolean a) {
        enter = a;
    }

    @Override
    public void run() {

        int seconds = 1;

        // Get the input from the textField in the GUI
        String temp = gui.getInput();

        // Turns it into an array of chars
        char[] test = new char[temp.length()];

        for (int i = 0; i < temp.length(); i++) {
            test[i] = temp.charAt(i);
        }

        // Sets the seconds to the entered seconds * 1000
        // Becase .delay() runs in Milliseconds
        try {
            seconds = gui.getSeconds() * 1000;
        } catch (Exception e) {

        }

        while (!Thread.currentThread().isInterrupted()) {

            robot.delay(seconds);

            for (int i = 0; i < temp.length(); i++) {
                typeThis(test[i]);
            }

            if (enter) {
                typeNow(VK_ENTER);
            }
        }
        toggle = true;
    }

}

Body:
Fixed.

Original Version :

    try {
        seconds = gui.getSeconds() * 1000;
    } catch (Exception e) {

    }

    while (!Thread.currentThread().isInterrupted()) {

        robot.delay(seconds);

        for (int i = 0; i < temp.length(); i++) {
            typeThis(test[i]);
        }

        if (enter) {
            typeNow(VK_ENTER);
        }
    }

Fixed Version :

    try {
        seconds = gui.getSeconds() * 1000;
    } catch (Exception e) {

    }
    System.out.print(seconds);
    while (!Thread.currentThread().isInterrupted()) {

        if (seconds <= 60000) {
            robot.delay(seconds);
        } else {
            try {
                int newTime = seconds - 60000;
                robot.delay(60000);
                Thread.sleep(newTime);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        for (int i = 0; i < temp.length(); i++) {
            typeThis(test[i]);
        }

        if (enter) {
            typeNow(VK_ENTER);
        }
    }

Allows you to go above 60'000 ms delay.


问:
Serializing a proxy
I am trying to serialize an invocation handler to a file. I am only trying to serialize the following part as it is the only part of the program that will change:

```<code> public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }
</code>```

I get the following error
run:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
    at jdkproxydemo.JdkProxyDemo.main(JdkProxyDemo.java:69)
C:\Users\ACK\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

Here is the full code:

```<code>public class JdkProxyDemo {

interface If {
    int originalMethod(String s);
}

static class Original implements If {
    public int originalMethod(String s) {
        System.out.println(s);
        return 0;
    }
}

public static class Handler implements InvocationHandler, Serializable {

    private final If original;

    public Handler(If original) {
        this.original = original;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }
}

public static void main(String[] args) throws FileNotFoundException, IOException{

      ///  OutputStream file = null;

        Original original = new Original();
        Handler handler = new Handler(original);
        If f = (If) Proxy.newProxyInstance(If.class.getClassLoader(),new Class[] { If.class },handler);
                OutputStream file = new FileOutputStream("quarks.ser");
  OutputStream buffer = new BufferedOutputStream(file);
   ObjectOutput output = new ObjectOutputStream(buffer);
   output.writeObject(handler.invoke(f,handler.original,"a"));
   output.close();
}
</code>```

}

What is the best way to achieve this result, serializing a proxy object?

答:
Let's check this:

```<code>output.writeObject(handler.invoke(f,handler.original,"a"));
</code>```

Here you are not serializing the proxy f but the result of a method call:

```<code>handler.invoke(f,handler.original,"a")
</code>```

Also the method invoke requires an array of arguments, so you need to pass an array not a string.

```<code>handler.invoke(f,handler.original,new Object[]{"a"})
</code>```

And handler.original is not a method ... it should be If.class.getMethods()[0]

```<code>handler.invoke(f,If.class.getMethods()[0],new Object[]{"a"})
</code>```

But since it is a proxy of If it could be written:

```<code>f.originalMethod("a")
</code>```

But method returns always null:

```<code>public Object invoke(Object proxy, Method method, Object[] args) {
    // [...]
    return null;
}
</code>```

So in fact you are trying to serialize null which is pointless.

EDIT (after comment)

The proxy can be serialized provided only that the handler is itself serializable.

```<code>public interface Adder {

    int add(int x, int y);
}
</code>```

The handler must be a Serializable object

```<code>public class AdderHandler implements InvocationHandler, Serializable {

    private int factor;

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        int a = (Integer) args[0];
        int b = (Integer) args[1];
        return (a+b)*factor;
    }

    public static Adder newInstance(int factor){
        Class[] clazz = new Class[]{Adder.class};
        AdderHandler h = new AdderHandler(factor);

        return (Adder) Proxy.newProxyInstance(AdderHandler.class.getClassLoader(), clazz, h);
    }

    public AdderHandler(int factor) {
        super();
        this.factor = factor;
    }
}
</code>```

Since the Proxy has only 1 field (the handler) ...

```<code>public class TestAdder {

    @Test
    public void testSerialization() throws Exception {
        Adder adder = AdderHandler.newInstance(2);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(bos);){
            oos.writeObject(adder);
        }

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        try(ObjectInputStream ois = new ObjectInputStream(bis);){

            Adder adder2 = (Adder) ois.readObject();
            int result = adder2.add(1, 3);
            assertEquals(8, result);
        }
    }

}
</code>```

Title: Serializing a proxy

Body:
I am trying to serialize an invocation handler to a file. I am only trying to serialize the following part as it is the only part of the program that will change:

 public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }

I get the following error
run:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: <any>
    at jdkproxydemo.JdkProxyDemo.main(JdkProxyDemo.java:69)
C:\Users\ACK\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 1 second)

Here is the full code:

public class JdkProxyDemo {

interface If {
    int originalMethod(String s);
}

static class Original implements If {
    public int originalMethod(String s) {
        System.out.println(s);
        return 0;
    }
}

public static class Handler implements InvocationHandler, Serializable {

    private final If original;

    public Handler(If original) {
        this.original = original;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        System.out.println("BEFORE");
        method.invoke(original, args);
        System.out.println("AFTER");
        //System.out.println(method);
        return null;

    }
}

public static void main(String[] args) throws FileNotFoundException, IOException{

      ///  OutputStream file = null;

        Original original = new Original();
        Handler handler = new Handler(original);
        If f = (If) Proxy.newProxyInstance(If.class.getClassLoader(),new Class[] { If.class },handler);
                OutputStream file = new FileOutputStream("quarks.ser");
  OutputStream buffer = new BufferedOutputStream(file);
   ObjectOutput output = new ObjectOutputStream(buffer);
   output.writeObject(handler.invoke(f,handler.original,"a"));
   output.close();
}

}

What is the best way to achieve this result, serializing a proxy object?

Body:
Let's check this:

output.writeObject(handler.invoke(f,handler.original,"a"));

Here you are not serializing the proxy f but the result of a method call:

handler.invoke(f,handler.original,"a")

Also the method invoke requires an array of arguments, so you need to pass an array not a string.

handler.invoke(f,handler.original,new Object[]{"a"})

And handler.original is not a method ... it should be If.class.getMethods()[0]

handler.invoke(f,If.class.getMethods()[0],new Object[]{"a"})

But since it is a proxy of If it could be written:

f.originalMethod("a")

But method returns always null:

public Object invoke(Object proxy, Method method, Object[] args) {
    // [...]
    return null;
}

So in fact you are trying to serialize null which is pointless.

EDIT (after comment)

The proxy can be serialized provided only that the handler is itself serializable.

public interface Adder {

    int add(int x, int y);
}

The handler must be a Serializable object

public class AdderHandler implements InvocationHandler, Serializable {

    private int factor;

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        int a = (Integer) args[0];
        int b = (Integer) args[1];
        return (a+b)*factor;
    }

    public static Adder newInstance(int factor){
        Class[] clazz = new Class[]{Adder.class};
        AdderHandler h = new AdderHandler(factor);

        return (Adder) Proxy.newProxyInstance(AdderHandler.class.getClassLoader(), clazz, h);
    }

    public AdderHandler(int factor) {
        super();
        this.factor = factor;
    }
}

Since the Proxy has only 1 field (the handler) ...

public class TestAdder {

    @Test
    public void testSerialization() throws Exception {
        Adder adder = AdderHandler.newInstance(2);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (ObjectOutputStream oos = new ObjectOutputStream(bos);){
            oos.writeObject(adder);
        }

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        try(ObjectInputStream ois = new ObjectInputStream(bis);){

            Adder adder2 = (Adder) ois.readObject();
            int result = adder2.add(1, 3);
            assertEquals(8, result);
        }
    }

}


问:
Error while trying to run project: Access is denied
Trying to Start a Winform solution With Debugging in Visual Studio 2017 causes this error:

Error while trying to run project: Access is denied.

Running Without Debugging works and starts the project without the error.

This guy reported the same issue with a WPF project to Microsoft Developer Community (beta testing) but there is no solution: https://developercommunity.visualstudio.com/content/problem/39737/error-while-trying-to-run-project-unable-to-start-3.html

A ProcessMonitor Trace reveals its an Access Denied in the Registry:

```<code>39:45.7
devenv.exe
RegCreateKey    \REGISTRY\A\{3883977B-E889-4804-9494-B5A8BC8E3F1D}\Software\Microsoft\VisualStudio\15.0_8708a912\DialogPage
ACCESS DENIED
Desired Access: Maximum Allowed
</code>```

Since its an Application Hive Registry Key it cannot be changed in RegEdit. UPDATE: You can change this, see my updated answer.

How can I debug projects?

Note: Answering my own question to help others in the future.

答:
Right click on the Winform or WPF Project > Properties > Debug tab > tick Enable native code debugging.

UPDATE:
 Use this answer to  fix the Registry A Hive in VS2017 (it has its own registry):

https://stackoverflow.com/a/45579640/495455

Body:
Trying to Start a Winform solution With Debugging in Visual Studio 2017 causes this error:

Error while trying to run project: Access is denied.

Running Without Debugging works and starts the project without the error.

This guy reported the same issue with a WPF project to Microsoft Developer Community (beta testing) but there is no solution: https://developercommunity.visualstudio.com/content/problem/39737/error-while-trying-to-run-project-unable-to-start-3.html

A ProcessMonitor Trace reveals its an Access Denied in the Registry:

39:45.7
devenv.exe
RegCreateKey    \REGISTRY\A\{3883977B-E889-4804-9494-B5A8BC8E3F1D}\Software\Microsoft\VisualStudio\15.0_8708a912\DialogPage
ACCESS DENIED
Desired Access: Maximum Allowed

Since its an Application Hive Registry Key it cannot be changed in RegEdit. UPDATE: You can change this, see my updated answer.

How can I debug projects?

Note: Answering my own question to help others in the future.