问:
Project time tracker
I'm building a project time tracker and need some guidance on how to record weekly hours.

I essentially have two tables: projectTable and weeklyReportTable with a one to many relation.

ProtectTable will keeping a record of all projects being worked on along with other information, such as owner, status, etc...

weeklyReportTable is supposed to keep a track of weekly activity on the project and there can only be one entry per week per project. On a weekly basis users will log number of hours and an activity report of what happened during that week.

The UI to update project status will consist of panel listing all projects by the logged in user along with an input field to log hours and activity. There will be a widget that the user can use to move forward and backward to select the week they want to log activity against.

Question: what would be the best approach to ensure that there is only one entry per week per project in the weeklyReportTable? If a user tried to log activity on a project for a week that already exists I don't want to create a new record but rather update the existing one.

答: if u have a project start date, I'd assume you want to create it when project gets created, ahead of time, till end date. Otherwise, you can create it when they click on a specific week, but you might want to lock that portion to make sure that in case two users, cannot click it, causing a duplicate value. Or you can write a trigger on the before create to check for a duplicate but still I think you want to lock it since relationship has a different cardinality than expressed through UI. If u have a custom database, specify a unique index on date + project id, as long as you use the same date (monday of the week u r in), you should be good </p>

Title: Project time tracker


来源: stackexchange

问:
mysql query escape single quote
i have a problem with this following db::insert command.
I want to use array in a mysql query "in ()" section, but the commas has been escaped. How can i solve this problem?

```<code>$users = [435,1671,429];
$list = implode("','", $users);

DB::insert("insert into ".
    "rejections (calendar_id, user_id, note, status) ".
    "select id as calendar_id, ?, concat(?), concat(?) ".
    "from calendar ".
    "where DATE(_date) BETWEEN ? AND ? and user_id in (?)", [$admin, $note, $status, $start_date, $end_date, $list]
);
</code>```

mysql_log: 2019-05-30T16:28:51.221007Z 1815 Execute    insert into rejections (calendar_id, user_id, note, status) select id as calendar_id, 2416, concat('Comment'), concat(1) from calendar where DATE(_date) BETWEEN '2019-05-01' AND '2019-05-31' and user_id in ('435\',\'1671\',\'429')

答:
A fast (and dirty) fix could be to remove the single quotes in implode() and use FIND_IN_SET() instead of IN():

```<code>$users = [435,1671,429];
$list = implode(",", $users);

DB::insert("insert into ".
    "rejections (calendar_id, user_id, note, status) ".
    "select id as calendar_id, ?, concat(?), concat(?) ".
    "from calendar ".
    "where DATE(_date) BETWEEN ? AND ? and find_in_set(user_id, ?)"
, [$admin, $note, $status, $start_date, $end_date, $list]);
</code>```

Note that it might be slower, because an index on user_id can't be used.

If you want to use IN() in your query, you will need a placeholder for each user:

```<code>IN (?,?,?)
</code>```

and also bind every user ID

```<code>[$admin, $note, $status, $start_date, $end_date, $list[0], $list[1], $list[2]]
</code>```

Since you probably don't know the number uf users in advance, you can use something like this:

```<code>$users = [435,1671,429];

$usersPlaceholders = array_map(function($id) { return '?'; }, $users);
$usersPlaceholders = implode(',', $usersPlaceholders);
$params = array_merge([$admin, $note, $status, $start_date, $end_date], $users);

DB::insert("
    insert into rejections (calendar_id, user_id, note, status)
    select id as calendar_id, ?, concat(?), concat(?)
    from calendar
    where DATE(_date) BETWEEN ? AND ? and user_id in ($usersPlaceholders)
", $params);
</code>```

ContentLicense: CC BY-SA 4.0

Title: mysql query escape single quote

Body:
i have a problem with this following db::insert command.
I want to use array in a mysql query "in ()" section, but the commas has been escaped. How can i solve this problem?

$users = [435,1671,429];
$list = implode("','", $users);

DB::insert("insert into ".
    "rejections (calendar_id, user_id, note, status) ".
    "select id as calendar_id, ?, concat(?), concat(?) ".
    "from calendar ".
    "where DATE(_date) BETWEEN ? AND ? and user_id in (?)", [$admin, $note, $status, $start_date, $end_date, $list]
);

mysql_log: 2019-05-30T16:28:51.221007Z 1815 Execute    insert into rejections (calendar_id, user_id, note, status) select id as calendar_id, 2416, concat('Comment'), concat(1) from calendar where DATE(_date) BETWEEN '2019-05-01' AND '2019-05-31' and user_id in ('435\',\'1671\',\'429')

Body:
A fast (and dirty) fix could be to remove the single quotes in implode() and use FIND_IN_SET() instead of IN():

$users = [435,1671,429];
$list = implode(",", $users);

DB::insert("insert into ".
    "rejections (calendar_id, user_id, note, status) ".
    "select id as calendar_id, ?, concat(?), concat(?) ".
    "from calendar ".
    "where DATE(_date) BETWEEN ? AND ? and find_in_set(user_id, ?)"
, [$admin, $note, $status, $start_date, $end_date, $list]);

Note that it might be slower, because an index on user_id can't be used.

If you want to use IN() in your query, you will need a placeholder for each user:

IN (?,?,?)

and also bind every user ID

[$admin, $note, $status, $start_date, $end_date, $list[0], $list[1], $list[2]]

Since you probably don't know the number uf users in advance, you can use something like this:

$users = [435,1671,429];

$usersPlaceholders = array_map(function($id) { return '?'; }, $users);
$usersPlaceholders = implode(',', $usersPlaceholders);
$params = array_merge([$admin, $note, $status, $start_date, $end_date], $users);

DB::insert("
    insert into rejections (calendar_id, user_id, note, status)
    select id as calendar_id, ?, concat(?), concat(?)
    from calendar
    where DATE(_date) BETWEEN ? AND ? and user_id in ($usersPlaceholders)
", $params);


问:
Is if statement in for loop faster than one by one if statements in Java?
I wonder that if I use a HashMap to collect the conditions and loop each one in one if statement can I reach higher performance rather than to write one by one if - else if statement?

In my opinion, one-by-one if-else, if statements may be faster because in for loop runs one more condition in each loop like, does the counter reach the target number? So actually each if statement, it runs 2 if statements. Of course inside of the statements different but if we talk about just statement performance, I think one-by-one type would be better?

Edit: this is just a sample code, my question is about the performance differences between the usage of these statements.

Map<String, Integer> words = new HashMap<String, Integer>
String letter ="d";
int n = 4;
words.put("a",1);
words.put("b",2);
words.put("c",3);
words.put("d",4);
words.put("e",5);

words.forEach((word,number)->{
if(letter.equals(word){
System.out.println(number*n);
});

```

<pre class="lang-java prettyprint-override"><code>String letter ="d";
int n = 4;
if(letter.equals("a"){
System.out.println(number*1);
}else if(letter.equals("b"){
System.out.println(number*2);
}else if(letter.equals("c"){
System.out.println(number*3);
}else if(letter.equals("d"){
System.out.println(number*4);
}else if(letter.equals("e"){
System.out.println(number*5);
}

</code>```

答:
For your example, having a HashMap but then doing an iterative lookup seems to be a bad idea.  The point of using a HashMap is to be able to do a hash based lookup.  That is much faster than doing an iterative lookup.

Also, from your example, cascading if-then tests will definitely be faster, since they will avoid the overhead of the map iterator and extra function calls.  Also, they will avoid the overhead of the map iterator skipping empty storage locations in the hash map backing array.  A better question is whether the cascading if-thens are faster than iterating across a simple list.  That is hard to answer.  Cascading if-thens seem likely to be faster, except that if there are a lot of if-thens, then a cost of loading the code should be added.

For string lookups, a list data structure provides adequate behavior up to a limiting value, above which a more sophisticated data structure must be used.  What is the limiting value depends on the environment.  For string comparisons, I've found the transition between 20 and 100 elements.

For particular lookups, and whether low level optimizations are available, the transition value may be much larger.  For example, doing integer lookups using "C", which will can do direct memory lookups, the transition value is much higher.

Typical data structures are HashMaps, Tries, and sorted arrays.  Each fits particular patterns of access.  For example, sorted arrays are fastest and most compact, but are expensive to update.  HashMaps support dynamic updates, and for good hash functions, provide constant time lookups.  But, HashMaps are space inefficient, since they depend on having empty cells between hash values.

For cases which do not involve "very large" data sets, and which are not in critical "hot" code paths, HashMaps are the usual structure which is used.

Body:
I wonder that if I use a HashMap to collect the conditions and loop each one in one if statement can I reach higher performance rather than to write one by one if - else if statement?

In my opinion, one-by-one if-else, if statements may be faster because in for loop runs one more condition in each loop like, does the counter reach the target number? So actually each if statement, it runs 2 if statements. Of course inside of the statements different but if we talk about just statement performance, I think one-by-one type would be better?

Edit: this is just a sample code, my question is about the performance differences between the usage of these statements.

Map<String, Integer> words = new HashMap<String, Integer>
String letter ="d";
int n = 4;
words.put("a",1);
words.put("b",2);
words.put("c",3);
words.put("d",4);
words.put("e",5);

words.forEach((word,number)->{
if(letter.equals(word){
System.out.println(number*n);
});

String letter ="d";
int n = 4;
if(letter.equals("a"){
System.out.println(number*1);
}else if(letter.equals("b"){
System.out.println(number*2);
}else if(letter.equals("c"){
System.out.println(number*3);
}else if(letter.equals("d"){
System.out.println(number*4);
}else if(letter.equals("e"){
System.out.println(number*5);
}


问:
Composite score function fails on data frame but works on single set of values
I created a function to calculate a numeric score, based on three strings containing characters A thru F.  The intermediate scores are calculated by determining the most frequent character for each string.  The final score is calculated by majority voting.  If all three intermediate scores are different, then the final numeric score is the mean of all intermediate scores.  I know that the function is not optimized - there are several ways in which I could write it better.  Any suggestions are more than welcome!

I got part of the code from the following StackOverflow issue...
Character frequency in a string

```<code>fncLetterValue <- function(strLetter)
{
  intValue = 9
  if(strLetter=="A") intValue <- 1
  if(strLetter=="B") intValue <- 2
  if(strLetter=="C") intValue <- 3
  if(strLetter=="D") intValue <- 4
  if(strLetter=="E") intValue <- 5
  if(strLetter=="F") intValue <- 6
  return(intValue)
}

fncScore <- function(str1, str2, str3)
{
  # determine frequency of letters in str1
  A1 <- sum(charToRaw(str1)==charToRaw("A"))
  B1 <- sum(charToRaw(str1)==charToRaw("B"))
  C1 <- sum(charToRaw(str1)==charToRaw("C"))
  D1 <- sum(charToRaw(str1)==charToRaw("D"))
  E1 <- sum(charToRaw(str1)==charToRaw("E"))
  F1 <- sum(charToRaw(str1)==charToRaw("F"))
  Max1 <- max(A1,B1,C1,D1,E1,F1) # determine the maximum frequency
  Score1 <- 9
  if(A1==Max1) Score1 <- 1
  if(B1==Max1) Score1 <- 2
  if(C1==Max1) Score1 <- 3
  if(D1==Max1) Score1 <- 4
  if(E1==Max1) Score1 <- 5
  if(F1==Max1) Score1 <- 6

  # determine frequency of letters in str2
  A2 <- sum(charToRaw(str2)==charToRaw("A"))
  B2 <- sum(charToRaw(str2)==charToRaw("B"))
  C2 <- sum(charToRaw(str2)==charToRaw("C"))
  D2 <- sum(charToRaw(str2)==charToRaw("D"))
  E2 <- sum(charToRaw(str2)==charToRaw("E"))
  F2 <- sum(charToRaw(str2)==charToRaw("F"))
  Max2 <- max(A2,B2,C2,D2,E2,F2) # determine the maximum frequency
  Score2 <- 9
  if(A2==Max2) Score2 <- 1
  if(B2==Max2) Score2 <- 2
  if(C2==Max2) Score2 <- 3
  if(D2==Max2) Score2 <- 4
  if(E2==Max2) Score2 <- 5
  if(F2==Max2) Score2 <- 6

  # determine frequency of letters in str3
  A3 <- sum(charToRaw(str3)==charToRaw("A"))
  B3 <- sum(charToRaw(str3)==charToRaw("B"))
  C3 <- sum(charToRaw(str3)==charToRaw("C"))
  D3 <- sum(charToRaw(str3)==charToRaw("D"))
  E3 <- sum(charToRaw(str3)==charToRaw("E"))
  F3 <- sum(charToRaw(str3)==charToRaw("F"))
  Max3 <- max(A3,B3,C3,D3,E3,F3) # determine the maximum frequency
  Score3 <- 9
  if(A3==Max3) Score3 <- 1
  if(B3==Max3) Score3 <- 2
  if(C3==Max3) Score3 <- 3
  if(D3==Max3) Score3 <- 4
  if(E3==Max3) Score3 <- 5
  if(F3==Max3) Score3 <- 6

  # get final score by majority voting
  dblFinalScore <- 9
  if(Score1==Score2 | Score1==Score3) dblFinalScore <- Score1
  if(Score2==Score1 | Score2==Score3) dblFinalScore <- Score2
  if(Score3==Score1 | Score3==Score2) dblFinalScore <- Score3
  if(dblFinalScore==9) dblFinalScore <- mean(c(Score1,Score2,Score3))

  return(dblFinalScore)
}

# read csv
setwd("~/Downloads")
df <- read.csv("CompositeScore.csv", header = TRUE)

df$score <- fncScore(df$Vector1, df$Vector2, df$Vector3) #THIS LINE GIVES AN ERROR!
</code>```

The function does work in the console for one set of strings...
e.g. fncScore("AAAABBBBBBBBB","ABBCCCCCCCCCC","FFFFFFFFFFF")

[1] 3.666667

However, the same function does not work for a dataframe.
I get the following error:
"Error in charToRaw(str1) : argument must be a character vector of length 1"

I expected to get a new column in the dataframe with the final scores.

What am I doing wrong?

答:
If I've understood your scoring system correctly, I think this does what you are looking for using the tidyverse...

```<code>library(tidyverse)

df <- read_csv("CompositeScore.csv")

scores <- function(x){   #function to identify most common letter in each string
  map_int(x, ~which.max(str_count(., LETTERS[1:6])))
}

df <- df %>%
  gather(key = Vector, value = value, -Observation) %>%  #change to 'long' format
  mutate(score = scores(value)) %>%                      #calculate scores
  group_by(Observation) %>%                              #group by Observation for next line
  mutate(score = ifelse(sum(score == median(score)) > 1, #if two the same
                        median(score),                   #then median
                        mean(score))) %>%                #otherwise mean
  spread(key = Vector, value = value)                    #back to wide format

head(df)

  Observation score Vector1      Vector2      Vector3
1           1  3.33 CCEDDBEACBAD ADAABEEAEADD ACEFBAFDFDCB
2           2  3.33 ECBDEFACDAEA AFDEECDBEDFF EBEFCCEAEDFB
3           3  5    BDDDBBAFDFFF BBEEDEDBDCAE FFBADEEFCFFF
4           4  4    FDDFDEFBCBBA FECEEFDDCDAF FDFCDFEFBBCE
5           5  2    DBBEEDCBEECB CBFCAAFEBBCD FCFFBEBEEBDA
6           6  6    CBAEEEDBEBDF DCABCEAEDFFF CEFFFDBCADFC
</code>```

Body:
I created a function to calculate a numeric score, based on three strings containing characters A thru F.  The intermediate scores are calculated by determining the most frequent character for each string.  The final score is calculated by majority voting.  If all three intermediate scores are different, then the final numeric score is the mean of all intermediate scores.  I know that the function is not optimized - there are several ways in which I could write it better.  Any suggestions are more than welcome!

I got part of the code from the following StackOverflow issue...
Character frequency in a string

fncLetterValue <- function(strLetter)
{
  intValue = 9
  if(strLetter=="A") intValue <- 1
  if(strLetter=="B") intValue <- 2
  if(strLetter=="C") intValue <- 3
  if(strLetter=="D") intValue <- 4
  if(strLetter=="E") intValue <- 5
  if(strLetter=="F") intValue <- 6
  return(intValue)
}

fncScore <- function(str1, str2, str3)
{
  # determine frequency of letters in str1
  A1 <- sum(charToRaw(str1)==charToRaw("A"))
  B1 <- sum(charToRaw(str1)==charToRaw("B"))
  C1 <- sum(charToRaw(str1)==charToRaw("C"))
  D1 <- sum(charToRaw(str1)==charToRaw("D"))
  E1 <- sum(charToRaw(str1)==charToRaw("E"))
  F1 <- sum(charToRaw(str1)==charToRaw("F"))
  Max1 <- max(A1,B1,C1,D1,E1,F1) # determine the maximum frequency
  Score1 <- 9
  if(A1==Max1) Score1 <- 1
  if(B1==Max1) Score1 <- 2
  if(C1==Max1) Score1 <- 3
  if(D1==Max1) Score1 <- 4
  if(E1==Max1) Score1 <- 5
  if(F1==Max1) Score1 <- 6

  # determine frequency of letters in str2
  A2 <- sum(charToRaw(str2)==charToRaw("A"))
  B2 <- sum(charToRaw(str2)==charToRaw("B"))
  C2 <- sum(charToRaw(str2)==charToRaw("C"))
  D2 <- sum(charToRaw(str2)==charToRaw("D"))
  E2 <- sum(charToRaw(str2)==charToRaw("E"))
  F2 <- sum(charToRaw(str2)==charToRaw("F"))
  Max2 <- max(A2,B2,C2,D2,E2,F2) # determine the maximum frequency
  Score2 <- 9
  if(A2==Max2) Score2 <- 1
  if(B2==Max2) Score2 <- 2
  if(C2==Max2) Score2 <- 3
  if(D2==Max2) Score2 <- 4
  if(E2==Max2) Score2 <- 5
  if(F2==Max2) Score2 <- 6

  # determine frequency of letters in str3
  A3 <- sum(charToRaw(str3)==charToRaw("A"))
  B3 <- sum(charToRaw(str3)==charToRaw("B"))
  C3 <- sum(charToRaw(str3)==charToRaw("C"))
  D3 <- sum(charToRaw(str3)==charToRaw("D"))
  E3 <- sum(charToRaw(str3)==charToRaw("E"))
  F3 <- sum(charToRaw(str3)==charToRaw("F"))
  Max3 <- max(A3,B3,C3,D3,E3,F3) # determine the maximum frequency
  Score3 <- 9
  if(A3==Max3) Score3 <- 1
  if(B3==Max3) Score3 <- 2
  if(C3==Max3) Score3 <- 3
  if(D3==Max3) Score3 <- 4
  if(E3==Max3) Score3 <- 5
  if(F3==Max3) Score3 <- 6

  # get final score by majority voting
  dblFinalScore <- 9
  if(Score1==Score2 | Score1==Score3) dblFinalScore <- Score1
  if(Score2==Score1 | Score2==Score3) dblFinalScore <- Score2
  if(Score3==Score1 | Score3==Score2) dblFinalScore <- Score3
  if(dblFinalScore==9) dblFinalScore <- mean(c(Score1,Score2,Score3))

  return(dblFinalScore)
}

# read csv
setwd("~/Downloads")
df <- read.csv("CompositeScore.csv", header = TRUE)

df$score <- fncScore(df$Vector1, df$Vector2, df$Vector3) #THIS LINE GIVES AN ERROR!

The function does work in the console for one set of strings...
e.g. fncScore("AAAABBBBBBBBB","ABBCCCCCCCCCC","FFFFFFFFFFF")

[1] 3.666667

However, the same function does not work for a dataframe.
I get the following error:
"Error in charToRaw(str1) : argument must be a character vector of length 1"

I expected to get a new column in the dataframe with the final scores.

What am I doing wrong?

Body:
If I've understood your scoring system correctly, I think this does what you are looking for using the tidyverse...

library(tidyverse)

df <- read_csv("CompositeScore.csv")

scores <- function(x){   #function to identify most common letter in each string
  map_int(x, ~which.max(str_count(., LETTERS[1:6])))
}

df <- df %>%
  gather(key = Vector, value = value, -Observation) %>%  #change to 'long' format
  mutate(score = scores(value)) %>%                      #calculate scores
  group_by(Observation) %>%                              #group by Observation for next line
  mutate(score = ifelse(sum(score == median(score)) > 1, #if two the same
                        median(score),                   #then median
                        mean(score))) %>%                #otherwise mean
  spread(key = Vector, value = value)                    #back to wide format

head(df)

  Observation score Vector1      Vector2      Vector3
1           1  3.33 CCEDDBEACBAD ADAABEEAEADD ACEFBAFDFDCB
2           2  3.33 ECBDEFACDAEA AFDEECDBEDFF EBEFCCEAEDFB
3           3  5    BDDDBBAFDFFF BBEEDEDBDCAE FFBADEEFCFFF
4           4  4    FDDFDEFBCBBA FECEEFDDCDAF FDFCDFEFBBCE
5           5  2    DBBEEDCBEECB CBFCAAFEBBCD FCFFBEBEEBDA
6           6  6    CBAEEEDBEBDF DCABCEAEDFFF CEFFFDBCADFC


问:
Center different size images in the same block size
I have different images encapsulated in square style blocks that I would like to always center in but I'm having a heck of a time trying to get them to do so.

I made an example of what's happening to me in similar design. Notice the product (the grill) is not actually centered in the imgblock container.

This starts to become very apparent with other product images that are much wider than narrow.

.imgBlock {
  width:100px;
  height:100px;
  border:2px solid black;
  margin:1px;
  padding:4px;
}

.imgBlock img{
  max-height:100%;
  max-width:100%;
  margin:auto;
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/WG-logo-short-black.png?43066">
  </div>
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/M1-Grill-FAQ.jpg?43066">
  </div>
</div></code>```

答:
You can use the older positioning attributes as well as the Flex techniques.  Make the main block position relative.  Then set the img inside that block to position: absolute.  Place that block element to top: 50% left: 50% of the parent element. Since this goes by the top left corner it will be slightly of the center. We will then use transform: translate(-50%, -50%) to bring it back to the true center.

More on position here at the MDN.

.imgBlock {
  position: relative;
  width:100px;
  height:100px;
  border:2px solid black;
  margin:1px;
  padding:4px;
}

.imgBlock img{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height:100%;
  max-width:100%;
  display:block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/WG-logo-short-black.png?43066">
  </div>
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/M1-Grill-FAQ.jpg?43066">
  </div>
</div></code>```

Body:
You can use the older positioning attributes as well as the Flex techniques.  Make the main block position relative.  Then set the img inside that block to position: absolute.  Place that block element to top: 50% left: 50% of the parent element. Since this goes by the top left corner it will be slightly of the center. We will then use transform: translate(-50%, -50%) to bring it back to the true center.

More on position here at the MDN.

.imgBlock {
  position: relative;
  width:100px;
  height:100px;
  border:2px solid black;
  margin:1px;
  padding:4px;
}

.imgBlock img{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height:100%;
  max-width:100%;
  display:block;
}

<div class="container">
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/WG-logo-short-black.png?43066">
  </div>
  <div class="imgBlock">
    <img src="https://cdn.shopify.com/s/files/1/1150/2512/t/41/assets/M1-Grill-FAQ.jpg?43066">
  </div>
</div>


问:
In R, is it possible to write an empty data frame with no observations but with column names to an Excel Sheet?
I have 2 data frame: one with observations and one with no observations. I am using the "xlsx" package to write the data frame to an Excel Sheet. Because the second data frame has no observations, the write.xlsx function outputs the error:

Error in mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]],  :
  zero-length inputs cannot be mixed with those of non-zero length

I want to be able to write an Excel Sheet with the empty data frame and keep the column names, and output with no observations.

```<code>library(xlsx)
nonemptydf <- data.frame("SN" = 1:2,
                         "Age" = c(21, 15),
                         "Name" = c("John", "Jane"))
emptydf <- data.frame("SN" = numeric(),
                      "Age" = numeric(),
                      "Name" = character())
write.xlsx(nonemptydf,
           "Test.xlsx",
           sheetName = "Not empty")

#The code below won't work because emptydf has no observations
write.xlsx(emptydf,
           "Test.xlsx",
           sheetName = "Empty",
           append = TRUE)
</code>```

Error from xlsx function:
Error in mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]],  :
  zero-length inputs cannot be mixed with those of non-zero length

答:
Tibbles have more flexibility and functionality than 'data.frame' objects. In particular, you can use the tribble() function to specify column names directly in the call.</p>

```<code># load the packages
library(tidyverse)    # provides the tribble() function
library(zip)          # helps zip the dataset that will be exported to R
library(rio)          # better export package than xlsx

# create your tibble
d <- tribble(
       ~SN, ~Age, ~Name
)

# convert to data.frame (if you'd prefer this class); it's not necessary though...
d <- as.data.frame(d)

# export your data frame as an Excel-compatible file
export(d, "data.xlsx")
</code>```

Body:
I have 2 data frame: one with observations and one with no observations. I am using the "xlsx" package to write the data frame to an Excel Sheet. Because the second data frame has no observations, the write.xlsx function outputs the error:

Error in mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]],  :
  zero-length inputs cannot be mixed with those of non-zero length

I want to be able to write an Excel Sheet with the empty data frame and keep the column names, and output with no observations.

library(xlsx)
nonemptydf <- data.frame("SN" = 1:2,
                         "Age" = c(21, 15),
                         "Name" = c("John", "Jane"))
emptydf <- data.frame("SN" = numeric(),
                      "Age" = numeric(),
                      "Name" = character())
write.xlsx(nonemptydf,
           "Test.xlsx",
           sheetName = "Not empty")

#The code below won't work because emptydf has no observations
write.xlsx(emptydf,
           "Test.xlsx",
           sheetName = "Empty",
           append = TRUE)

Error from xlsx function:
Error in mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]],  :
  zero-length inputs cannot be mixed with those of non-zero length

Body:
Tibbles have more flexibility and functionality than 'data.frame' objects. In particular, you can use the tribble() function to specify column names directly in the call.

# load the packages
library(tidyverse)    # provides the tribble() function
library(zip)          # helps zip the dataset that will be exported to R
library(rio)          # better export package than xlsx

# create your tibble
d <- tribble(
       ~SN, ~Age, ~Name
)

# convert to data.frame (if you'd prefer this class); it's not necessary though...
d <- as.data.frame(d)

# export your data frame as an Excel-compatible file
export(d, "data.xlsx")


问:
R parallel abort all mclapply operations
Is it possible to request that parallel::mclapply() abandons all further processing asap if it encounters an error (e.g., a stop()) in any one of its processes?

答:
Terminating the evaluations in all processes of a cluster upon an error in one process is not possible with a standard mclapply() call. The reason for this is that the processes do not communicate among each other until they are done.

Using the R package future one can achieve such a behavior. The idea is to

create futures and evaluate them in parallel

check every 2 seconds if one feature is resolved into an error

if an error is detected, kill all process of the cluster

A sketch how this could work:

```<code>library(future)
library(parallel)
library(tools)

parallelLapply <- function(x, fun, checkInterval=2, nProcess=2){

    ## setup cluster and get process IDs of process in cluster
    cl <- makeCluster(spec=nProcess)
    pids <- unlist(parLapply(cl=cl, X=1:nProcess, function(x) Sys.getpid()))
    plan(cluster, workers=cl)

    ## create futures and start their evaluation
    fList <- lapply(1:2, function(x) futureCall(function(x) try(fun(x), silent=TRUE), list(x=x)))

    ## check every 2 second whether an error occurred or whether all are resolved
    while(TRUE){
        Sys.sleep(checkInterval)

        ## check for errors
        errorStatus <- unlist(lapply(fList, function(x)
            resolved(x) && class(value(x))=="try-error"))
        if(any(unlist(errorStatus))){
            lapply(pids, pskill)
            results <- NULL
            cat("an error occurred in one future: all process of the cluster were killed.\n")
            break
        }

        ## check if all resolved without error
        allResolved <- all(unlist(lapply(fList, resolved)))
        if(allResolved){
            results <- lapply(fList, value)
            cat("all futures are resolved sucessfully.\n")
            break
        }
    }
    results
}

## test 1: early termination because x=1 results in an error.
f1 <- function(x){
    if(x==1) stop()
    Sys.sleep(15)
    x
}
parallelLapply(x=1:5, fun=f1)
# an error occurred in one future: all process of the cluster were killed.
# NULL

## test 2: no error
f2 <- function(x){
    Sys.sleep(15)
    x
}
parallelLapply(x=1:5, fun=f2)
## all futures are resolved sucessfully.
## [[1]]
## [1] 1
##
## [[2]]
## [1] 2
</code>```

Note:

Additional adjustment are needed if the function passed to fun depends on additional arguments.

On Linux one can use makeForkCluster() instead of makeCluster() for convenience. Then the usage is closer to mclapply().

Body:
Terminating the evaluations in all processes of a cluster upon an error in one process is not possible with a standard mclapply() call. The reason for this is that the processes do not communicate among each other until they are done.

Using the R package future one can achieve such a behavior. The idea is to

create futures and evaluate them in parallel

check every 2 seconds if one feature is resolved into an error

if an error is detected, kill all process of the cluster

A sketch how this could work:

library(future)
library(parallel)
library(tools)

parallelLapply <- function(x, fun, checkInterval=2, nProcess=2){

    ## setup cluster and get process IDs of process in cluster
    cl <- makeCluster(spec=nProcess)
    pids <- unlist(parLapply(cl=cl, X=1:nProcess, function(x) Sys.getpid()))
    plan(cluster, workers=cl)

    ## create futures and start their evaluation
    fList <- lapply(1:2, function(x) futureCall(function(x) try(fun(x), silent=TRUE), list(x=x)))

    ## check every 2 second whether an error occurred or whether all are resolved
    while(TRUE){
        Sys.sleep(checkInterval)

        ## check for errors
        errorStatus <- unlist(lapply(fList, function(x)
            resolved(x) && class(value(x))=="try-error"))
        if(any(unlist(errorStatus))){
            lapply(pids, pskill)
            results <- NULL
            cat("an error occurred in one future: all process of the cluster were killed.\n")
            break
        }

        ## check if all resolved without error
        allResolved <- all(unlist(lapply(fList, resolved)))
        if(allResolved){
            results <- lapply(fList, value)
            cat("all futures are resolved sucessfully.\n")
            break
        }
    }
    results
}

## test 1: early termination because x=1 results in an error.
f1 <- function(x){
    if(x==1) stop()
    Sys.sleep(15)
    x
}
parallelLapply(x=1:5, fun=f1)
# an error occurred in one future: all process of the cluster were killed.
# NULL

## test 2: no error
f2 <- function(x){
    Sys.sleep(15)
    x
}
parallelLapply(x=1:5, fun=f2)
## all futures are resolved sucessfully.
## [[1]]
## [1] 1
##
## [[2]]
## [1] 2

Note:

Additional adjustment are needed if the function passed to fun depends on additional arguments.

On Linux one can use makeForkCluster() instead of makeCluster() for convenience. Then the usage is closer to mclapply().


问:
Getting patterns out of a binary string
I have a binary string of length N which is a power of 2 (N = 2^n).

I need to extract specific patterns of length L which is a power of 2 (L = 2^l).

In a full binary tree, these patterns should

start with a left leaf node (even index) and

end with a right leaf node (odd index).

These patterns should include leaves of an entire subtree.
Patterns I need to extract are,

```<code>(1). 0 0 --- 0  (All zero)
(2). 1 1 --- 1  (All one)
(3). 0 0 --- 1  (Only the last right leaf is one).
</code>```

For example, if I have a binary string of N=16, (n=4) such as
 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 ,  I need to extract

indices 0 to 7 as pattern (3),

indices 8 to 11 as pattern (2) and

last 4 indices as pattern (1).

I need this as a part of a channel decoding algorithm, to prune the binary tree. Is there an efficient method to do this in Matlab?

答:
I have implemented the solution recursively as below,

```<code>s = [0  0  0  1  0  0  0  1  0  0  0  1  0  1  1  1  0  0  0  1  0  1  1  1  0  1  1  1  0  1  1  1 ];
N=length(s);
n = log2(N);

mask = zeros(1,N);
pattern1_indices = [];
pattern2_indices = [];
pattern3_indices = [];

for l= n:-1:1
    L = 2^l;
    t  = 2^(n-l); % Number of strings of size L

    pattern1= zeros(1,L);
    pattern3= pattern1;
    pattern3(end) = 1;
    pattern2 = ones(1,L);

    for i = 1:t
        st = (i-1)*L+1 ;
        ed = i*L ;
        if(mask(st)==1)
            continue
        end
        chunk =  s(st:ed) ;

        if chunk == pattern3 % Only the last bit is one
            mask(st:ed) = 1;
            pattern3_indices = [pattern3_indices ; [st,ed]];
        elseif chunk == pattern1
            mask(st:ed) = 1; % All zero
            pattern1_indices = [pattern1_indices ; [st,ed]];
        elseif chunk == pattern2
            mask(st:ed) = 1; % All one
            pattern2_indices = [pattern2_indices ; [st,ed]];
        end
    end
end
</code>```

I get the start and end indices of each pattern as below,

```<code>pattern1_indices

pattern1_indices =

     []

>> pattern2_indices

pattern2_indices =

    15    16
    23    24
    27    28
    31    32

>> pattern3_indices

pattern3_indices =

     1     4
     5     8
     9    12
    17    20
    13    14
    21    22
    25    26
    29    30
</code>```

Title: Getting patterns out of a binary string

Body:
I have a binary string of length N which is a power of 2 (N = 2^n).

I need to extract specific patterns of length L which is a power of 2 (L = 2^l).

In a full binary tree, these patterns should

start with a left leaf node (even index) and

end with a right leaf node (odd index).

These patterns should include leaves of an entire subtree.
Patterns I need to extract are,

(1). 0 0 --- 0  (All zero)
(2). 1 1 --- 1  (All one)
(3). 0 0 --- 1  (Only the last right leaf is one).

For example, if I have a binary string of N=16, (n=4) such as
 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 ,  I need to extract

indices 0 to 7 as pattern (3),

indices 8 to 11 as pattern (2) and

last 4 indices as pattern (1).

I need this as a part of a channel decoding algorithm, to prune the binary tree. Is there an efficient method to do this in Matlab?

Body:
I have implemented the solution recursively as below,

s = [0  0  0  1  0  0  0  1  0  0  0  1  0  1  1  1  0  0  0  1  0  1  1  1  0  1  1  1  0  1  1  1 ];
N=length(s);
n = log2(N);

mask = zeros(1,N);
pattern1_indices = [];
pattern2_indices = [];
pattern3_indices = [];

for l= n:-1:1
    L = 2^l;
    t  = 2^(n-l); % Number of strings of size L

    pattern1= zeros(1,L);
    pattern3= pattern1;
    pattern3(end) = 1;
    pattern2 = ones(1,L);

    for i = 1:t
        st = (i-1)*L+1 ;
        ed = i*L ;
        if(mask(st)==1)
            continue
        end
        chunk =  s(st:ed) ;

        if chunk == pattern3 % Only the last bit is one
            mask(st:ed) = 1;
            pattern3_indices = [pattern3_indices ; [st,ed]];
        elseif chunk == pattern1
            mask(st:ed) = 1; % All zero
            pattern1_indices = [pattern1_indices ; [st,ed]];
        elseif chunk == pattern2
            mask(st:ed) = 1; % All one
            pattern2_indices = [pattern2_indices ; [st,ed]];
        end
    end
end

I get the start and end indices of each pattern as below,

pattern1_indices

pattern1_indices =

     []

>> pattern2_indices

pattern2_indices =

    15    16
    23    24
    27    28
    31    32

>> pattern3_indices

pattern3_indices =

     1     4
     5     8
     9    12
    17    20
    13    14
    21    22
    25    26
    29    30


问:
How to insert concatenated values from a data-frame into another data-frame in Pyspark?
I'm creating a time_interval column and adding it to an existing Data-frame in Pyspark. Ideally the time_interval will be in the "HHmm" format with the minutes being rounded down to the nearest 15 minute mark (815, 830, 845, 900, etc).

I have the spark sql code that does the logic for me but how do I take that value that's concatenated as string column and insert that into an existing Data-frame?

```<code>time_interval = sqlContext.sql("select extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15")

time_interval.show()

+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|concat(CAST(hour(current_timestamp()) AS STRING), CAST((FLOOR((CAST(minute(current_timestamp()) AS DOUBLE) / CAST(15 AS DOUBLE))) * CAST(15 AS BIGINT)) AS STRING))|
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|                                                                                1045|
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+

baseDF = sqlContext.sql("select * from test_table")
newBase = baseDF.withColumn("time_interval", lit(str(time_interval)))

newBase.select("time_interval").show()

+--------------------+
|       time_interval|
+--------------------+
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
+--------------------+
only showing top 20 rows
</code>```

So the actual expected results should be just showing the actual string value in the new column i'm creating rather than this concatenated value from a data-frame. Something like below:

```<code>newBase.select("time_interval").show(1)
+-------------+
|time_interval|
+-------------+
|    1045     |
+-------------+
</code>```

答:
As time_interval is a dataframe type, for this case need to collect and extract the required value out from dataframe.

Try this way:

```<code>newBase = baseDF.withColumn("time_interval", lit(str(time_interval.collect()[0][0])))
newBase.show()
</code>```

(or)

By using select(expr()) function:

```<code>newBase = baseDF.select("*",expr("string(extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15) AS time_interval"))
</code>```

As pault mentioned in comments, using selectExpr() function:

```<code>newBase = baseDF.selectExpr("*","string(extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15) AS time_interval")
</code>```

Example:

```<code>>>> from pyspark.sql.functions import *
>>> from pyspark.sql.types import IntegerType
>>> time_interval = spark.sql("select extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15")
>>> baseDF=spark.createDataFrame([1,2,3,4],IntegerType())
>>> newBase = baseDF.withColumn("time_interval", lit(str(time_interval.collect()[0][0])))
>>> newBase.show()
+-----+-------------+
|value|time_interval|
+-----+-------------+
|    1|         1245|
|    2|         1245|
|    3|         1245|
|    4|         1245|
+-----+-------------+
</code>```

Body:
I'm creating a time_interval column and adding it to an existing Data-frame in Pyspark. Ideally the time_interval will be in the "HHmm" format with the minutes being rounded down to the nearest 15 minute mark (815, 830, 845, 900, etc).

I have the spark sql code that does the logic for me but how do I take that value that's concatenated as string column and insert that into an existing Data-frame?

time_interval = sqlContext.sql("select extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15")

time_interval.show()

+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|concat(CAST(hour(current_timestamp()) AS STRING), CAST((FLOOR((CAST(minute(current_timestamp()) AS DOUBLE) / CAST(15 AS DOUBLE))) * CAST(15 AS BIGINT)) AS STRING))|
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|                                                                                1045|
+-------------------------------------------------------------------------------------------------------------------------------------------------------------------+

baseDF = sqlContext.sql("select * from test_table")
newBase = baseDF.withColumn("time_interval", lit(str(time_interval)))

newBase.select("time_interval").show()

+--------------------+
|       time_interval|
+--------------------+
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
|DataFrame[concat(...|
+--------------------+
only showing top 20 rows

So the actual expected results should be just showing the actual string value in the new column i'm creating rather than this concatenated value from a data-frame. Something like below:

newBase.select("time_interval").show(1)
+-------------+
|time_interval|
+-------------+
|    1045     |
+-------------+

Body:
As time_interval is a dataframe type, for this case need to collect and extract the required value out from dataframe.

Try this way:

newBase = baseDF.withColumn("time_interval", lit(str(time_interval.collect()[0][0])))
newBase.show()

(or)

By using select(expr()) function:

newBase = baseDF.select("*",expr("string(extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15) AS time_interval"))

As pault mentioned in comments, using selectExpr() function:

newBase = baseDF.selectExpr("*","string(extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15) AS time_interval")

Example:

>>> from pyspark.sql.functions import *
>>> from pyspark.sql.types import IntegerType
>>> time_interval = spark.sql("select extract(hour from current_timestamp())||floor(extract(minute from current_timestamp())/15)*15")
>>> baseDF=spark.createDataFrame([1,2,3,4],IntegerType())
>>> newBase = baseDF.withColumn("time_interval", lit(str(time_interval.collect()[0][0])))
>>> newBase.show()
+-----+-------------+
|value|time_interval|
+-----+-------------+
|    1|         1245|
|    2|         1245|
|    3|         1245|
|    4|         1245|
+-----+-------------+


问:
How to disable a filed using form builder in Angular
Hello I want to disable a filed/drop-down based on conditions angular form builder:

I have 3 drop downs, first drop down will be loading while page loading.. when I select the option in first drop-down second should be enabled, when I select the option in second third should be enabled.

here is what I tried:

```<code>       ngOnInit(): void {

            this.someMethodToFetchDataForSelectbox();
            this.method1.subscribe(data => {
                this.data= data;
              }
            );
            this.constructForm();
          }

    constructForm() {
    this.form =  this.fb.group({
     listOfFruits: [''],
     listOfAnimals: [''],
listOfLetters: ['']
    });
this.form.get('listOfAnimals').disable();
    this.form.get('listOfLetters').disable();
    this.form.controls.listOfFruits.valueChanges.subscribe(value=>{
   his.forms.controls.listOfAnimals.enable();
      this.form.get('listOfLetters').disable();
//method to fetch list of animals from DB
fetchAnimals(value) ;

    });
    }
fetchAnimals(value) {
 this.form.controls.listOfAnimals.valueChanges.subscribe(value=>{
   this.forms.controls.listOfLetters.enable();
      //method to fetch list of letters from DB
fetchLetters(value) ;
  });
}
</code>```

I tried the above but it is not working..

答:
in additions to @malbarmawi's answer make listOfAnimals disable initially </p>

```<code>this.form =  this.fb.group({
 listOfFruits: [''],
 listOfAnimals: [{value: '', disabled:true}]
});

this.form.controls.listOfFruits.valueChanges.subscribe(value => {
  (value) ? this.form.controls.listOfAnimals.enable() : this.form.controls.listOfAnimals.disable()
});
</code>```

Body:
Hello I want to disable a filed/drop-down based on conditions angular form builder:

I have 3 drop downs, first drop down will be loading while page loading.. when I select the option in first drop-down second should be enabled, when I select the option in second third should be enabled.

here is what I tried:

       ngOnInit(): void {

            this.someMethodToFetchDataForSelectbox();
            this.method1.subscribe(data => {
                this.data= data;
              }
            );
            this.constructForm();
          }

    constructForm() {
    this.form =  this.fb.group({
     listOfFruits: [''],
     listOfAnimals: [''],
listOfLetters: ['']
    });
this.form.get('listOfAnimals').disable();
    this.form.get('listOfLetters').disable();
    this.form.controls.listOfFruits.valueChanges.subscribe(value=>{
   his.forms.controls.listOfAnimals.enable();
      this.form.get('listOfLetters').disable();
//method to fetch list of animals from DB
fetchAnimals(value) ;

    });
    }
fetchAnimals(value) {
 this.form.controls.listOfAnimals.valueChanges.subscribe(value=>{
   this.forms.controls.listOfLetters.enable();
      //method to fetch list of letters from DB
fetchLetters(value) ;
  });
}

I tried the above but it is not working..

Body:
in additions to @malbarmawi's answer make listOfAnimals disable initially

this.form =  this.fb.group({
 listOfFruits: [''],
 listOfAnimals: [{value: '', disabled:true}]
});

this.form.controls.listOfFruits.valueChanges.subscribe(value => {
  (value) ? this.form.controls.listOfAnimals.enable() : this.form.controls.listOfAnimals.disable()
});


问:
Laravel orm not save relation key and child model
I would like to save data through Eloquent, in particular an Object and its respective Address. The Object has inside an id_address which should be updated following the creation of the Address. But this does not happen. Although it is following the guide code and the mapping of the relationships in the models is correct.

That's the code in my controller Object:

```<code>$obj= new Object(['alias' => $curr['alias']]);
$obj->save();
$address= new Address(['address'=>$curr['address']['city']]);
$obj->address()->associate($address);
$obj->save();
</code>```

relation in models Object:

```<code>public $belongsTo = [
        'address' => [
                '\XXXXXX\Models\Address',
                'key'=>'id_address',
                'otherKey'=>'id',
                'delete'=>true
        ],
</code>```

relation in address model:

```<code>public $hasOne = [
        'obj' => [
                '\XXXXXXX\Models\Object',
                'key'=>'id',
                'otherKey'=>'id_address',
                'delete'=>false
        ]
];
</code>```

Why is created only the object and not the address and the id_address in object table?

答:
```<code>$address= new Address(['address'=>$curr['address']['city']]);
</code>```

This will instantiate an Address object, but it will not save in db.
So that object doesn't have an id and that's why the id_address (btw I strongly suggest you to change the field name to address_id) is not updated.

You should do

```<code>$address= new Address(['address'=>$curr['address']['city']]);
$address->save();
$obj->address()->associate($address);
</code>```

Anyway it doesn't make sense to save your Object twice, just save it after the associate() call.

Body:
I would like to save data through Eloquent, in particular an Object and its respective Address. The Object has inside an id_address which should be updated following the creation of the Address. But this does not happen. Although it is following the guide code and the mapping of the relationships in the models is correct.

That's the code in my controller Object:

$obj= new Object(['alias' => $curr['alias']]);
$obj->save();
$address= new Address(['address'=>$curr['address']['city']]);
$obj->address()->associate($address);
$obj->save();

relation in models Object:

public $belongsTo = [
        'address' => [
                '\XXXXXX\Models\Address',
                'key'=>'id_address',
                'otherKey'=>'id',
                'delete'=>true
        ],

relation in address model:

public $hasOne = [
        'obj' => [
                '\XXXXXXX\Models\Object',
                'key'=>'id',
                'otherKey'=>'id_address',
                'delete'=>false
        ]
];

Why is created only the object and not the address and the id_address in object table?

Body:
$address= new Address(['address'=>$curr['address']['city']]);

This will instantiate an Address object, but it will not save in db.
So that object doesn't have an id and that's why the id_address (btw I strongly suggest you to change the field name to address_id) is not updated.

You should do

$address= new Address(['address'=>$curr['address']['city']]);
$address->save();
$obj->address()->associate($address);

Anyway it doesn't make sense to save your Object twice, just save it after the associate() call.


问:
Is there a way to overload an abstract method in a functional interface?
I would like to be able to provide a functional interface that accepts several different types of lambda functions.

I read this. The first answer to this question clarifies why overloading an abstract method in a functional interface could cause undefined behavior. However, is there a way to do the equivalent of overloading an abstract method in a functional interface if I supply all of the defaults?

I would like to be able to write something like the following code:

Ball b = () -> System.out.println("You hit it!");
Ball ba = (boolean miss) -> System.out.println(miss);

b.hit();
b.hit(false);
ba.hit();
ba.hit(false);
```

<p>The desired result would be:</p>

```You hit it!
default false
default hit
false
```

<p>Consider the following (non-compilable) code (mostly copied from the linked question):</p>

```@FunctionalInterface
public interface Ball
{
    void hit();
    void hit(boolean miss);
    default void hit(){
        System.out.println("default hit");
    }
    default void hit(boolean miss){
        System.out.println("default" + miss);
    }

}
```

I am looking for an alternative to this code that would compile.

答:
first thing about functional interface is , it can have only one abstract method.In that case you cant even think of the second method (let it be abstract method too). you can have any number of default methods.

So answer is 100% not possible and Your code above will get compilation error as you kept @FunctionalInterface annotation which strictly prohibits keeping more than one abstract method.
As per your code

```<code>@FunctionalInterface
public interface MyInter {
    public abstract void fly();

    public abstract void fly(int a);

    default void fly() {}          \\line1
    default void fly(int g) {   }   \\line2
}
</code>```

line 1 and 2 will throw compile time error as java sees them by method name are same and argument types are same , they will never bother of return type or default or etc..(primary rule of overloading).

more over if remove line 1 and 2 , then too code will throw error because @functionalinterface will give compilation error stating invalid '@FunctionalInterface' annotation; MyInter is not a functional interface .

Hope this answers your question...

Body:
I would like to be able to provide a functional interface that accepts several different types of lambda functions.

I read this. The first answer to this question clarifies why overloading an abstract method in a functional interface could cause undefined behavior. However, is there a way to do the equivalent of overloading an abstract method in a functional interface if I supply all of the defaults?

I would like to be able to write something like the following code:

Ball b = () -> System.out.println("You hit it!");
Ball ba = (boolean miss) -> System.out.println(miss);

b.hit();
b.hit(false);
ba.hit();
ba.hit(false);

The desired result would be:

You hit it!
default false
default hit
false

Consider the following (non-compilable) code (mostly copied from the linked question):

@FunctionalInterface
public interface Ball
{
    void hit();
    void hit(boolean miss);
    default void hit(){
        System.out.println("default hit");
    }
    default void hit(boolean miss){
        System.out.println("default" + miss);
    }

}

I am looking for an alternative to this code that would compile.

Body:
first thing about functional interface is , it can have only one abstract method.In that case you cant even think of the second method (let it be abstract method too). you can have any number of default methods.

So answer is 100% not possible and Your code above will get compilation error as you kept @FunctionalInterface annotation which strictly prohibits keeping more than one abstract method.
As per your code

@FunctionalInterface
public interface MyInter {
    public abstract void fly();

    public abstract void fly(int a);

    default void fly() {}          \\line1
    default void fly(int g) {   }   \\line2
}

line 1 and 2 will throw compile time error as java sees them by method name are same and argument types are same , they will never bother of return type or default or etc..(primary rule of overloading).

more over if remove line 1 and 2 , then too code will throw error because @functionalinterface will give compilation error stating invalid '@FunctionalInterface' annotation; MyInter is not a functional interface .

Hope this answers your question...


问:
Can JUNG library make edges based on predefined properties?
I have some data of let’s say type Person. This Person has a phone-number property but also a calling and a called phone-number properties.

```<code>class Person {
   String id;
   String displayName;
   String phoneNr;
   String callingNr; // or List<String> callingNrs;
   String calledNr;  // or List<String> calledNrs;
}
</code>```

What I want, is I put a bunch of those Person objects in a Graph instance and than render the relationships on a view. Ideally the components drawn on the view are interactive, meaning you can click on a node/vertex that highlight the edges (and maybe more).

I tried JUNG, but in the documentation, I see some examples that I have to, kind of, define the relationships between Person objects myself, like below:

```<code>Graph.addEdge("edge-name", personA.phoneNr, personB.phoneNr);
</code>```

I’m new to JUNG, but maybe there’s a way to tell JUNG about the properties of Person and that JUNG knows how to connect them?

Is this possible with JUNG? Or do I need another type of library, if yes, than can someone please provide me one I can use?

答:
Here is what I would do:

Make a java.util.Map of each person's phone number (key) to an instance of the Person (value). That is your reverse number lookup.
Populate your reverse number lookup map by iterating over your collection of people using the PhoneNr as the key and the Person instance as the value.

Next, I would create an edge class 'PhoneCall' that contains information like 'time of call' and 'duration of call' (more or less info, depending on what you have available).

To add edges to your graph, iterate over your collection of Person instances, and for each Person, iterate over the collection of calling numbers. For each calling number, use the reverse number lookup map to get the person calling and make a directed edge to connect the calling person to the current person.
Do something similar for the each Person's collection of called numbers.
Your graph nodes will be Person instances, and your edges will be PhoneCall instances that connect one Person to another. Be sure to add an equals and hashCode method to your Person class and to your PhoneCall class so that they will work properly (and duplicates will be detected and hopefully ignored).

Hope this helps!

Body:
I have some data of let’s say type Person. This Person has a phone-number property but also a calling and a called phone-number properties.

class Person {
   String id;
   String displayName;
   String phoneNr;
   String callingNr; // or List<String> callingNrs;
   String calledNr;  // or List<String> calledNrs;
}

What I want, is I put a bunch of those Person objects in a Graph instance and than render the relationships on a view. Ideally the components drawn on the view are interactive, meaning you can click on a node/vertex that highlight the edges (and maybe more).

I tried JUNG, but in the documentation, I see some examples that I have to, kind of, define the relationships between Person objects myself, like below:

Graph.addEdge("edge-name", personA.phoneNr, personB.phoneNr);

I’m new to JUNG, but maybe there’s a way to tell JUNG about the properties of Person and that JUNG knows how to connect them?

Is this possible with JUNG? Or do I need another type of library, if yes, than can someone please provide me one I can use?


问:
How to have powershell display the current directory
I recently ran "conda init powershell" on my powershell in order to be able to activate conda environments (previously, "activate env_name" would not work).
However, I do not like what this has done to my powershell. For one, it always displays the current virual environment even if it is simply the base environment. Also, it no longer displays the current directory I am in.

I tried running commands like conda deinit, but it does not exist.
I tried removing anaconda from the path and restart the computer, but it did not work and powershell still recognized conda as a cmdlet.
I tried changing defaults from powershell, but it only lets me change Options, Font, Layout, and Colors. None of which are helpful.

Minimal reproducible example. With "pathtoanaconda/Scripts" in path, open PS and run "conda init powershell", restart powershell.

Notice in my screenshot how my current directory is not displayed.. Instead, I get a "(base) PS" for any directory I am in1

答:
Oh.. I quickly realized https://superuser.com/questions/446827/configure-the-windows-powershell-to-display-only-the-current-folder-name-in-the has instructions that solve my problem. </p>

<p>I had to delete the information on that file in order to undo the conda init. </p>

Body:
Oh.. I quickly realized https://superuser.com/questions/446827/configure-the-windows-powershell-to-display-only-the-current-folder-name-in-the has instructions that solve my problem.

I had to delete the information on that file in order to undo the conda init.


问:
'TypeError: integer argument expected, got float'
I'm doing a game in python and I have one error

integer argument expected, got float

, and I'm not understanding why. The line that give me error is:

pygame.draw.circle(screen, (128, 128, 128),
    (self.location[0]-1, self.location[1]-1), self.size+1)
```

```class Player(object):
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
        self.level = 1
        self.feed = 0
        self.size = 2
        self.speed = 6
        self.location = (SCREEN_SIZE[0]/2, SCREEN_SIZE[1]/2)
        self.destination = self.location
        self.stopDis = 5    #Stopping distance

    def render(self, screen):
        pygame.draw.circle(screen, (128, 128, 128),
            (self.location[0]-1, self.location[1]-1), self.size+1)  #Error here
        pygame.draw.circle(screen, self.colour, self.location, self.size)   #Draw circle
```

答:
The 3rd parameter to pygame.draw.circle has to be a integral coordinate (tuple (x, y)), but the result of a division (/) is a floationg point value.

Use int or round to cast self.location from floating point values to integral values:

pygame.draw.circle(screen, (128, 128, 128),
    (int(self.location[0]-1), int(self.location[1]-1)), self.size+1)
```

<p>Or do a integral division (<code>//</code>) instead of the floating point division (<code>/</code>), when you calculate <code>self.location</code>:</p>

<pre class="lang-py prettyprint-override"><code>self.location = (SCREEN_SIZE[0] // 2, SCREEN_SIZE[1] // 2)
</code>```

See also Numeric Types.

Body:
I'm doing a game in python and I have one error

integer argument expected, got float

, and I'm not understanding why. The line that give me error is:

pygame.draw.circle(screen, (128, 128, 128),
    (self.location[0]-1, self.location[1]-1), self.size+1)

class Player(object):
    def __init__(self, name, colour):
        self.name = name
        self.colour = colour
        self.level = 1
        self.feed = 0
        self.size = 2
        self.speed = 6
        self.location = (SCREEN_SIZE[0]/2, SCREEN_SIZE[1]/2)
        self.destination = self.location
        self.stopDis = 5    #Stopping distance

    def render(self, screen):
        pygame.draw.circle(screen, (128, 128, 128),
            (self.location[0]-1, self.location[1]-1), self.size+1)  #Error here
        pygame.draw.circle(screen, self.colour, self.location, self.size)   #Draw circle

Body:
The 3rd parameter to pygame.draw.circle has to be a integral coordinate (tuple (x, y)), but the result of a division (/) is a floationg point value.

Use int or round to cast self.location from floating point values to integral values:

pygame.draw.circle(screen, (128, 128, 128),
    (int(self.location[0]-1), int(self.location[1]-1)), self.size+1)

Or do a integral division (//) instead of the floating point division (/), when you calculate self.location:

self.location = (SCREEN_SIZE[0] // 2, SCREEN_SIZE[1] // 2)

See also Numeric Types.


问:
Django: include paths with pk
I'm developping an app that uses context processors, the function within the context processors is executed only if it doesn't belong to any of the paths specified as follows:

```<code>if request.path != "/details/" and \
            request.path != "/live/":
     # EXECUTE FUNCTIONS
</code>```

However, I'm not managing to include a path that has pk included on it. I've tried the following: request.path != "/live/<int:pk> without results. Any ideas?

thanks!

答:
I just ended up doing the following :

```<code>+    if request.path != "/backtest/details/" and \
+            request.path != "/live/details/" and \
+            request.path[-7:] != "delete/" and \
+            request.user.is_authenticated:
</code>```

So just looking at the last characters of the path.

Title: Django: include paths with pk

Body:
I'm developping an app that uses context processors, the function within the context processors is executed only if it doesn't belong to any of the paths specified as follows:

if request.path != "/details/" and \
            request.path != "/live/":
     # EXECUTE FUNCTIONS

However, I'm not managing to include a path that has pk included on it. I've tried the following: request.path != "/live/<int:pk> without results. Any ideas?

thanks!

Body:
I just ended up doing the following :

+    if request.path != "/backtest/details/" and \
+            request.path != "/live/details/" and \
+            request.path[-7:] != "delete/" and \
+            request.user.is_authenticated:

So just looking at the last characters of the path.


问:
Fabric.js - how to save canvas on server with custom attributes
I'd like to be able to save the current canvas' state to a server-side database, probably as a JSON string, and then later restore it with loadFromJSON. Typically, this is easily accomplished using:

```<code>var canvas = new fabric.Canvas();
function saveCanvas() {
    // convert canvas to a json string
    var json = JSON.stringify( canvas.toJSON() );

    // save via xhr
    $.post('/save', { json : json }, function(resp){
        // do whatever ...
    }, 'json');
}
</code>```

And then

```<code>function loadCanvas(json) {

  // parse the data into the canvas
  canvas.loadFromJSON(json);

  // re-render the canvas
  canvas.renderAll();

  // optional
  canvas.calculateOffset();
}
</code>```

However, I've also been setting a few custom attributes on the fabric objects I'm adding to the canvas using the builtin Object#set method:

```<code>// get some item from the canvas
var item = canvas.item(0);

// add misc properties
item.set('wizard', 'gandalf');
item.set('hobbit', 'samwise');

// save current state
saveCanvas();
</code>```

The problem is that when I check the request on the server-side, I see that my custom attributes were not parsed from the canvas and sent along with everything else. This probably has to do with how toObject method removes anything that's not a default attribute in the object class. What would be a good way to tackle this issue, such that I'll be able to both save and restore the canvas from a JSON string sent by the server, and the restored canvas will also include my custom attributes? thanks.

答:
If you don't want to specify the custom attributes you are using every time you call canvas.toJSON(), and you don't want to use a complicated subclassing approach, here is a very simple way to extend Fabric's toObject method.

```<code>//EXTEND THE PROPS FABRIC WILL EXPORT TO JSON
fabric.Object.prototype.toObject = (function(toObject) {
    return function() {
        return fabric.util.object.extend(toObject.call(this), {
            id: this.id,
            wizard: this.wizard,
            hobbit: this.hobbit,
        });
    };
})(fabric.Object.prototype.toObject);
</code>```

Then you can set custom properties on Fabric objects.

```<code>item.set("wizard","gandalf");
item.set("hobbit","bilbo");
</code>```

And when you call canvas.toJSON() those properties will persist to the output. If you then use canvas.loadFromJSON() with your JSON output, the custom attributes will be imported and applied to the Fabric objects.

ContentLicense: CC BY-SA 3.0

Body:
I'd like to be able to save the current canvas' state to a server-side database, probably as a JSON string, and then later restore it with loadFromJSON. Typically, this is easily accomplished using:

var canvas = new fabric.Canvas();
function saveCanvas() {
    // convert canvas to a json string
    var json = JSON.stringify( canvas.toJSON() );

    // save via xhr
    $.post('/save', { json : json }, function(resp){
        // do whatever ...
    }, 'json');
}

And then

function loadCanvas(json) {

  // parse the data into the canvas
  canvas.loadFromJSON(json);

  // re-render the canvas
  canvas.renderAll();

  // optional
  canvas.calculateOffset();
}

However, I've also been setting a few custom attributes on the fabric objects I'm adding to the canvas using the builtin Object#set method:

// get some item from the canvas
var item = canvas.item(0);

// add misc properties
item.set('wizard', 'gandalf');
item.set('hobbit', 'samwise');

// save current state
saveCanvas();

The problem is that when I check the request on the server-side, I see that my custom attributes were not parsed from the canvas and sent along with everything else. This probably has to do with how toObject method removes anything that's not a default attribute in the object class. What would be a good way to tackle this issue, such that I'll be able to both save and restore the canvas from a JSON string sent by the server, and the restored canvas will also include my custom attributes? thanks.

Body:
If you don't want to specify the custom attributes you are using every time you call canvas.toJSON(), and you don't want to use a complicated subclassing approach, here is a very simple way to extend Fabric's toObject method.

//EXTEND THE PROPS FABRIC WILL EXPORT TO JSON
fabric.Object.prototype.toObject = (function(toObject) {
    return function() {
        return fabric.util.object.extend(toObject.call(this), {
            id: this.id,
            wizard: this.wizard,
            hobbit: this.hobbit,
        });
    };
})(fabric.Object.prototype.toObject);

Then you can set custom properties on Fabric objects.

item.set("wizard","gandalf");
item.set("hobbit","bilbo");

And when you call canvas.toJSON() those properties will persist to the output. If you then use canvas.loadFromJSON() with your JSON output, the custom attributes will be imported and applied to the Fabric objects.


问:
How to save a queryset?
I would like to know how I can save my queryset in the database:

```<code>def data_min(self):
        qs1 = Csr.objects.values_list('value_base')
        qs2 = Modelb.objects.filter(Q(limit_a__gte=qs1) & (Q(limit_b__lte=qs1))).distinct().values_list('limit_b')
        qs3 = qs2[0]
        return qs3
</code>```

This function returns me:

```<code><QuerySet [(Decimal('133.22'),)]>
</code>```

Now my question is how I keep it in my Model in the field "bdata_superior":

```<code>class Csr(models.Model):
tarifa_cobro = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, null=True, blank=True)
value_base = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
bdata_superior = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
data_inferior = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

class Modelb(models.Model):
    limit_a = models.DecimalField(max_digits=10, decimal_places=2)
    limit_b = models.DecimalField(max_digits=10, decimal_places=2)
</code>```

The problem is that when I save it, I get the following error:

```<code>conversion from method to Decimal is not supported

def save(self, *args, **kwargs):
        self.bdata_superior = self.data_min
        super (Crs, self).save(*args, **kwargs)
</code>```

答:
I update the response to this thread.

First update my qs2, the error showed it to me because I was trying to save the queryset, then a tuple, to access the value of my queryset, just add the flat = True parameter, within the values_list () method and access the first value of my tuple in the position [0]

Here is my updated function

```<code>def data_min(self):
    qs1 = Csr.objects.values_list('base_gravada')
    qs2 = Modelb.objects.filter
    (Q(limit_a__gte=qs1) &
     Q(limit_b__lte=qs1))
     .distinct().values_list('limit_b', flat=True)[0]
</code>```

and the save method

```<code>def save(self, *args, **kwargs):
    self.bdata_superior = self.data_min()
    super (Calculadora_isr, self).save(*args, **kwargs)
</code>```

Thank you so much for everything @harshil9968

Title: How to save a queryset?

Body:
I would like to know how I can save my queryset in the database:

def data_min(self):
        qs1 = Csr.objects.values_list('value_base')
        qs2 = Modelb.objects.filter(Q(limit_a__gte=qs1) & (Q(limit_b__lte=qs1))).distinct().values_list('limit_b')
        qs3 = qs2[0]
        return qs3

This function returns me:

<QuerySet [(Decimal('133.22'),)]>

Now my question is how I keep it in my Model in the field "bdata_superior":

class Csr(models.Model):
tarifa_cobro = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, null=True, blank=True)
value_base = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
bdata_superior = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
data_inferior = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)

class Modelb(models.Model):
    limit_a = models.DecimalField(max_digits=10, decimal_places=2)
    limit_b = models.DecimalField(max_digits=10, decimal_places=2)

The problem is that when I save it, I get the following error:

conversion from method to Decimal is not supported

def save(self, *args, **kwargs):
        self.bdata_superior = self.data_min
        super (Crs, self).save(*args, **kwargs)

Body:
I update the response to this thread.

First update my qs2, the error showed it to me because I was trying to save the queryset, then a tuple, to access the value of my queryset, just add the flat = True parameter, within the values_list () method and access the first value of my tuple in the position [0]

Here is my updated function

def data_min(self):
    qs1 = Csr.objects.values_list('base_gravada')
    qs2 = Modelb.objects.filter
    (Q(limit_a__gte=qs1) &
     Q(limit_b__lte=qs1))
     .distinct().values_list('limit_b', flat=True)[0]

and the save method

def save(self, *args, **kwargs):
    self.bdata_superior = self.data_min()
    super (Calculadora_isr, self).save(*args, **kwargs)

Thank you so much for everything @harshil9968


问:
Get data from future function to text widget
I am trying to implement a Column with a Text:

```<code>Column(
        children: <Widget>[
        Text('data from future function')
      ],
    ),
</code>```

I can't get the data from initState() cause initState() it's only void
If I get data directly from the function

```<code>Text(function)
</code>```

I get

instance of function

The function:

```<code>Future<double> calculate(int index) async {
    LocData _getUser = await getLoc();
    double uLat = _getUser.latitude;
    double uLng = _getUser.latitude;
    double pLat = parks[data].loc.lat;
    double pLng = parks[data].loc.lng;

    double dis = await Geolocator()
        .distanceBetween(uLat , uLng, uLng , pLat );
    return dis ;
  }
</code>```

Any idea what can i do to get this data from the function directly to the text wigdet?

答:
Here is the full working code. </p>

```<code>class _InfoPageState extends State<InfoPage> {
  String _text = "";

  @override
  void initState() {
    super.initState();

    calculate(10).then((value) {
      setState(() {
        _text = value.toString();
      });
    });
  }

  Future<double> calculate(int index) async {
    LocData _getUser = await getLoc();
    double uLat = _getUser.latitude;
    double uLng = _getUser.latitude;
    double pLat = parks[data].loc.lat;
    double pLng = parks[data].loc.lng;

    double dis = await Geolocator().distanceBetween(uLat, userLng, uLng, pLat);
    return dis;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(children: <Widget>[Text(_text)]),
    );
  }
}
</code>```

Body:
I am trying to implement a Column with a Text:

Column(
        children: <Widget>[
        Text('data from future function')
      ],
    ),

I can't get the data from initState() cause initState() it's only void
If I get data directly from the function

Text(function)

I get

instance of function

The function:

Future<double> calculate(int index) async {
    LocData _getUser = await getLoc();
    double uLat = _getUser.latitude;
    double uLng = _getUser.latitude;
    double pLat = parks[data].loc.lat;
    double pLng = parks[data].loc.lng;

    double dis = await Geolocator()
        .distanceBetween(uLat , uLng, uLng , pLat );
    return dis ;
  }

Any idea what can i do to get this data from the function directly to the text wigdet?

Body:
Here is the full working code.

class _InfoPageState extends State<InfoPage> {
  String _text = "";

  @override
  void initState() {
    super.initState();

    calculate(10).then((value) {
      setState(() {
        _text = value.toString();
      });
    });
  }

  Future<double> calculate(int index) async {
    LocData _getUser = await getLoc();
    double uLat = _getUser.latitude;
    double uLng = _getUser.latitude;
    double pLat = parks[data].loc.lat;
    double pLng = parks[data].loc.lng;

    double dis = await Geolocator().distanceBetween(uLat, userLng, uLng, pLat);
    return dis;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(children: <Widget>[Text(_text)]),
    );
  }
}


问:
Multiple scatter plots in a single figure from multiple data frame in R using ggplot?
I want to generate a figure that display all the scatter plots on this single figure using data from the two data frame (i.e., regressing column-A of Data1 against Column-A of Data2). Each plot in the figure should show R-square and p-value. I am more interested to know how I can use the fact_wrap function of ggplot while grabing data from multiple data frame.
I tried a couple of method but did not succeeded.

```<code>library(tidyverse)
Data1=data.frame(A=runif(20, min = 0, max = 100), B=runif(20, min = 0, max = 250), C=runif(20, min = 0, max = 300))
Data2=data.frame(A=runif(20, min = -10, max = 50), B=runif(20, min = -5, max = 150), C=runif(20, min = 5, max = 200))

#method-1: using plot functions
par(mfrow=c(3,1))
plot(Data1$A, Data2$A)
abline(lm(Data1$A ~ Data2$A))
plot(Data1$B, Data2$B)
abline(lm(Data1$B ~ Data2$B))
plot(Data1$C, Data2$C)
abline(lm(Data1$C ~ Data2$C))
dev.off()

#method-2: using ggplot
ggplot()+
  geom_point(aes(Data1$A,Data2$A))
</code>```

I want a Figure like the one below

答:
The hardest part is tidying up your data.  Once that's done, the plot is pretty straightforward.

```<code>    library(tidyverse)
Data1=data.frame(A=runif(20, min = 0, max = 100), B=runif(20, min = 0, max = 250), C=runif(20, min = 0, max = 300))
Data2=data.frame(A=runif(20, min = -10, max = 50), B=runif(20, min = -5, max = 150), C=runif(20, min = 5, max = 200))

data <- Data1 %>%
  #add columns to indicate the source and the observation number
  mutate(source = "Data1",
         obs = row_number()) %>%
  #bind to Data2 with the same new columns
  bind_rows(Data2 %>% mutate(source = "Data2", obs = row_number())) %>%
  #tidy the data so we've got a column for Data1 and Data2 and an indicator for the series (A, B, C)
  gather(A, B, C, key = series, value = value) %>%
  spread(key = source, value = value)

#create a separate data frame for annotations, finding the "top left" corner of each series
annotations <- data %>%
  group_by(series) %>%
  summarise(x = min(Data1),
            y = max(Data2)) %>%
  mutate(label = c("P = 0.6", "P = 0.5", "P = 0.9"))

#plot the data, faceting by series
data %>%
  ggplot(aes(Data1, Data2))+
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  facet_grid(series~., scales = "free") +
  #add the annotations with adjustments to the horiz & vert placement
  geom_text(data = annotations, aes(x = x, y = y, label = label, hjust = 0, vjust = 1),
           color = "red", fontface = "italic")
</code>```

Body:
I want to generate a figure that display all the scatter plots on this single figure using data from the two data frame (i.e., regressing column-A of Data1 against Column-A of Data2). Each plot in the figure should show R-square and p-value. I am more interested to know how I can use the fact_wrap function of ggplot while grabing data from multiple data frame.
I tried a couple of method but did not succeeded.

library(tidyverse)
Data1=data.frame(A=runif(20, min = 0, max = 100), B=runif(20, min = 0, max = 250), C=runif(20, min = 0, max = 300))
Data2=data.frame(A=runif(20, min = -10, max = 50), B=runif(20, min = -5, max = 150), C=runif(20, min = 5, max = 200))

#method-1: using plot functions
par(mfrow=c(3,1))
plot(Data1$A, Data2$A)
abline(lm(Data1$A ~ Data2$A))
plot(Data1$B, Data2$B)
abline(lm(Data1$B ~ Data2$B))
plot(Data1$C, Data2$C)
abline(lm(Data1$C ~ Data2$C))
dev.off()

#method-2: using ggplot
ggplot()+
  geom_point(aes(Data1$A,Data2$A))

I want a Figure like the one below

Body:
The hardest part is tidying up your data.  Once that's done, the plot is pretty straightforward.

    library(tidyverse)
Data1=data.frame(A=runif(20, min = 0, max = 100), B=runif(20, min = 0, max = 250), C=runif(20, min = 0, max = 300))
Data2=data.frame(A=runif(20, min = -10, max = 50), B=runif(20, min = -5, max = 150), C=runif(20, min = 5, max = 200))

data <- Data1 %>%
  #add columns to indicate the source and the observation number
  mutate(source = "Data1",
         obs = row_number()) %>%
  #bind to Data2 with the same new columns
  bind_rows(Data2 %>% mutate(source = "Data2", obs = row_number())) %>%
  #tidy the data so we've got a column for Data1 and Data2 and an indicator for the series (A, B, C)
  gather(A, B, C, key = series, value = value) %>%
  spread(key = source, value = value)

#create a separate data frame for annotations, finding the "top left" corner of each series
annotations <- data %>%
  group_by(series) %>%
  summarise(x = min(Data1),
            y = max(Data2)) %>%
  mutate(label = c("P = 0.6", "P = 0.5", "P = 0.9"))

#plot the data, faceting by series
data %>%
  ggplot(aes(Data1, Data2))+
  geom_point() +
  geom_smooth(method = "lm", se = FALSE) +
  facet_grid(series~., scales = "free") +
  #add the annotations with adjustments to the horiz & vert placement
  geom_text(data = annotations, aes(x = x, y = y, label = label, hjust = 0, vjust = 1),
           color = "red", fontface = "italic")


问:
How to print number with commas as lakhs separators?
How to print number with commas as lakhs separators?</p>

```<code>For Ex:
val = 1023456
output = 10,23,456

val = 12345676
output = 123,45,676
</code>```

答: thanx for your prompt reply but I'm expecting the output format(1023456)) is 10,23,456 as lakhs separators and then in thousand separators</p>

Body:
How to print number with commas as lakhs separators?

For Ex:
val = 1023456
output = 10,23,456

val = 12345676
output = 123,45,676


问:
Flatten JSON with array using AWS Glue crawler / classifier / ETL job
I'm crawling following JSON file (it's a valid JSON) from s3 data lake.
Inside there are 2 fields (device, timestamp) and an array of objects called "data". Each object in the data array differs from one another.

```<code>{
  "device": "0013374838793C8",
  "timestamp": "2019-03-04T14:44:39Z",
  "data": [
    { "eparke_status": "09" },
    { "eparke_x": "FFF588" },
    { "eparke_y": "000352" },
    { "eparke_z": "000ACC" },
    { "eparke_temp": "14.00" },
    { "eparke_voltage": "4.17" }
  ]
}
</code>```

Unfortunately, when I'm crawling with AWS Glue crawler schema cannot be inferred properly and what I got in Athena is not what I expect.

Following listing shows a row of data from AWS Athena.

```<code>1   0013374838793C8 2019-03-05T13:11:41Z    [{eparke_status=0B, eparke_x=null, eparke_y=null, eparke_z=null, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=FFF6D4, eparke_y=null, eparke_z=null, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=000133, eparke_z=null, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=null, eparke_z=000DA3, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=null, eparke_z=null, eparke_temp=14.00, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=null, eparke_z=null, eparke_temp=null, eparke_voltage=4.17}]
</code>```

As you can see for each object inside array schema is discovered "wrongly". Each column in DB contains ALL of the array objects fields, the majority of which are just set as nulls, which is understandable because they are not found. The discovered schema is not what I'm looking for.

Expectations

Following listing shows expected form of a table row after crawling with AWS Glue.

```<code>1   0013374838793C8 2019-03-05T13:11:41Z    eparke_status=0B eparke_x=FFF6D4 eparke_y=000133 eparke_z=000DA3 eparke_temp=14.00 eparke_voltage=4.17
</code>```

What I have tried so far?

AWS Glue Classifiers
To force schema I tried to use classifiers.

```<code>$.device $.timestamp $.eparke_status $.eparke_x $.eparke_y $.eparke_z $.eparke_temp $.eparke_voltage
</code>```

and

```<code>$.device $.timestamp $.data[0].eparke_status $.data[1].eparke_x $.data[2].eparke_y $.data[3].eparke_z $.data[4].eparke_temp $.data[5].eparke_voltage
</code>```

Still, final schema looks the same - all objects are packed inside each column.

Any ideas how to address this issue?
I'm also trying to configure ETL job with a custom script but failed so far.

答:
One thing I noticed is that once a crawler runs once, the initially inferred schema and selected crawlers tend to not change on a new run. I just think it is safer to duplicate crawlers and delete any previously created tables while playing around.

I am not sure you can concatenate multiple root expressions in the Json classifier expression. Documentation says that for JSON classifier you just need to provide THE path to the node of each line that will be considered as the actual json to infer the schema from

To use each element of the array to infer the schema, you would have to use $.data[*]. But that would mean you would miss the device and timestamp.

You cannot do this simply through a crawler. My recommendation is to parse with no custom classifier and then UNNEST the data from the array structure using an Athena query (https://docs.aws.amazon.com/athena/latest/ug/flattening-arrays.html). Load the result to some datastore if needed. For S3, look at CTAS as an option. You might also be able to configure this as a ETL job

Body:
I'm crawling following JSON file (it's a valid JSON) from s3 data lake.
Inside there are 2 fields (device, timestamp) and an array of objects called "data". Each object in the data array differs from one another.

{
  "device": "0013374838793C8",
  "timestamp": "2019-03-04T14:44:39Z",
  "data": [
    { "eparke_status": "09" },
    { "eparke_x": "FFF588" },
    { "eparke_y": "000352" },
    { "eparke_z": "000ACC" },
    { "eparke_temp": "14.00" },
    { "eparke_voltage": "4.17" }
  ]
}

Unfortunately, when I'm crawling with AWS Glue crawler schema cannot be inferred properly and what I got in Athena is not what I expect.

Following listing shows a row of data from AWS Athena.

1   0013374838793C8 2019-03-05T13:11:41Z    [{eparke_status=0B, eparke_x=null, eparke_y=null, eparke_z=null, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=FFF6D4, eparke_y=null, eparke_z=null, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=000133, eparke_z=null, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=null, eparke_z=000DA3, eparke_temp=null, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=null, eparke_z=null, eparke_temp=14.00, eparke_voltage=null}, {eparke_status=null, eparke_x=null, eparke_y=null, eparke_z=null, eparke_temp=null, eparke_voltage=4.17}]

As you can see for each object inside array schema is discovered "wrongly". Each column in DB contains ALL of the array objects fields, the majority of which are just set as nulls, which is understandable because they are not found. The discovered schema is not what I'm looking for.

Expectations

Following listing shows expected form of a table row after crawling with AWS Glue.

1   0013374838793C8 2019-03-05T13:11:41Z    eparke_status=0B eparke_x=FFF6D4 eparke_y=000133 eparke_z=000DA3 eparke_temp=14.00 eparke_voltage=4.17

What I have tried so far?

AWS Glue Classifiers
To force schema I tried to use classifiers.

$.device $.timestamp $.eparke_status $.eparke_x $.eparke_y $.eparke_z $.eparke_temp $.eparke_voltage

and

$.device $.timestamp $.data[0].eparke_status $.data[1].eparke_x $.data[2].eparke_y $.data[3].eparke_z $.data[4].eparke_temp $.data[5].eparke_voltage

Still, final schema looks the same - all objects are packed inside each column.

Any ideas how to address this issue?
I'm also trying to configure ETL job with a custom script but failed so far.


问:
HTTP Request in Jmeter: How can i combine 2 parameters into 1?
I am trying to preform API load test using Jmeter and i wonder...
Can i combine 2 parameters into 1?

For example: instead of the following request:
[ip]/[address]?$[ParamA]&$[ParamB]

I would like
[ip]/[address]?$[ParamA]+$[ParamB]

so that the passing parameter will be

ParamAParamB

答:
Remove the + sign in between like ${ParamA}${ParamB}.
Hope this helps.</p>


问:
Dynamic ORDER BY and ASC / DESC in a plpgsql function
Following the approach mentioned in this link, I want to pass ORDER BY and sorting order to a function dynamically.

ORDER BY is working fine but I am not able to pass sorting order (ASC / DESC).

What I have now:

```<code>CREATE OR REPLACE FUNCTION list(_limit integer,_offset integer,sort_by varchar(100), _order varchar(100),_category varchar(100))
  RETURNS TABLE(
     id INTEGER,
     name VARCHAR,
     clientname VARCHAR,
     totalcount BIGINT
  ) AS
$$
DECLARE
   empty text := '';
BEGIN
RETURN Query EXECUTE
'SELECT d.id,
d.name,
d.clientname,
 count(*) OVER() AS full_count FROM design_list as d
    where ($5 = $6 Or d.category Ilike $5)
        ORDER BY ' || quote_ident(sort_by) || ' LIMIT $1 offset $2'
USING _limit,_offset,sort_by, _order,_category, empty;
END;
$$  LANGUAGE plpgsql;
</code>```

答:
non dynamic sql solution.

```<code>CREATE OR REPLACE FUNCTION list(
...
in_use_asc boolean default false,
_order_by varchar(100)
..
)
..

CREATE TEMPORARY TABLE tempHolder ON COMMIT DROP AS
SELECT SELECT id, name, clientname, count(*) OVER() AS full_count
      FROM   design_list
      WHERE ($1 = $2 OR category ILIKE $1);

     IF in_use_asc = TRUE THEN
        RETURN QUERY SELECT * FROM tempHolder ORDER BY _order_by asc LIMIT {} OFFSET {};
    ELSE
        RETURN QUERY SELECT * FROM tempHolder ORDER BY _order_by desc LIMIT {} OFFSET {};
    END IF;
</code>```

Shouldnt be any slower because SQL needs to grab everything anyway because of the ORDER BY plus you avoid the dynamic SQL.

Body:
Following the approach mentioned in this link, I want to pass ORDER BY and sorting order to a function dynamically.

ORDER BY is working fine but I am not able to pass sorting order (ASC / DESC).

What I have now:

CREATE OR REPLACE FUNCTION list(_limit integer,_offset integer,sort_by varchar(100), _order varchar(100),_category varchar(100))
  RETURNS TABLE(
     id INTEGER,
     name VARCHAR,
     clientname VARCHAR,
     totalcount BIGINT
  ) AS
$$
DECLARE
   empty text := '';
BEGIN
RETURN Query EXECUTE
'SELECT d.id,
d.name,
d.clientname,
 count(*) OVER() AS full_count FROM design_list as d
    where ($5 = $6 Or d.category Ilike $5)
        ORDER BY ' || quote_ident(sort_by) || ' LIMIT $1 offset $2'
USING _limit,_offset,sort_by, _order,_category, empty;
END;
$$  LANGUAGE plpgsql;

Body:
non dynamic sql solution.

CREATE OR REPLACE FUNCTION list(
...
in_use_asc boolean default false,
_order_by varchar(100)
..
)
..

CREATE TEMPORARY TABLE tempHolder ON COMMIT DROP AS
SELECT SELECT id, name, clientname, count(*) OVER() AS full_count
      FROM   design_list
      WHERE ($1 = $2 OR category ILIKE $1);

     IF in_use_asc = TRUE THEN
        RETURN QUERY SELECT * FROM tempHolder ORDER BY _order_by asc LIMIT {} OFFSET {};
    ELSE
        RETURN QUERY SELECT * FROM tempHolder ORDER BY _order_by desc LIMIT {} OFFSET {};
    END IF;

Shouldnt be any slower because SQL needs to grab everything anyway because of the ORDER BY plus you avoid the dynamic SQL.


问:
How can I send JSON data to server
Well, here is the story:

I have some data need to send to server, but they should turned into JSON dataType first.

I made such ajax call:

```<code>    $.ajax({
       url: url, // the url I want to post to.
       type: 'POST',
       contenttype:'application/json; charset=utf-8',
       beforeSend: //some HTTP basic auth stuff
       data: {
          name:'test',
          key:'foo',
          key2:'bar'
       },
       dataType:'JSON'
});
</code>```

basically I'm expecting the data I send to server was:

```<code>[name:test,key:foo,key2:bar]
</code>```

but what I've got was:

```<code>name=test&key=foo&key2=bar
</code>```

What did I missing? How can I get those data into JSON?

答:
There are many ways to send JSON data to the server

1. Using Ajax

```<code>var data = <?php echo json_encode($data) ?>;
var url  = '<?php echo $url ?>';
jQuery.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        var jsonObj = jQuery.parseJSON(data);
        alert(jsonObj.encPassword);
    },
    failure: function(errorMsg) {
        alert(errorMsg);
    }
});
</code>```

2. Using Curl

```<code><?php
$content = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //curl error SSL certificate problem, verify that the CA cert is OK

$result     = curl_exec($curl);
$response   = json_decode($result);
var_dump($response);
curl_close($curl);
?>
</code>```

3. Using Streams

```<code><?php
$options = array(
    'http' => array(
        'method'  => 'POST',
        'content' => json_encode( $data ),
        'header'=>  "Content-Type: application/json\r\n" .
                    "Accept: application/json\r\n"
      )
);

$context     = stream_context_create($options);
$result      = file_get_contents($url, false, $context);
$response    = json_decode($result);
var_dump($response);
</code>```

4. Raw HTTP Post

Using Zend Framework’s HTTP client: http://framework.zend.com/manual/en/zend.http.client.advanced.html#zend.http.client.raw_post_data

```<code>$json = json_encode($data);
$client = new Zend_Http_Client($url);
$client->setRawData($json, 'application/json')->request('POST');
var_dump($client->request()->getBody());
</code>```

SOURCE:- https://blog.magepsycho.com/sending-json-data-remote-server/

ContentLicense: CC BY-SA 2.5

Title: How can I send JSON data to server

Body:
Well, here is the story:

I have some data need to send to server, but they should turned into JSON dataType first.

I made such ajax call:

    $.ajax({
       url: url, // the url I want to post to.
       type: 'POST',
       contenttype:'application/json; charset=utf-8',
       beforeSend: //some HTTP basic auth stuff
       data: {
          name:'test',
          key:'foo',
          key2:'bar'
       },
       dataType:'JSON'
});

basically I'm expecting the data I send to server was:

[name:test,key:foo,key2:bar]

but what I've got was:

name=test&key=foo&key2=bar

What did I missing? How can I get those data into JSON?

Body:
There are many ways to send JSON data to the server

1. Using Ajax

var data = <?php echo json_encode($data) ?>;
var url  = '<?php echo $url ?>';
jQuery.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(data),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
        var jsonObj = jQuery.parseJSON(data);
        alert(jsonObj.encPassword);
    },
    failure: function(errorMsg) {
        alert(errorMsg);
    }
});

2. Using Curl

<?php
$content = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //curl error SSL certificate problem, verify that the CA cert is OK

$result     = curl_exec($curl);
$response   = json_decode($result);
var_dump($response);
curl_close($curl);
?>

3. Using Streams

<?php
$options = array(
    'http' => array(
        'method'  => 'POST',
        'content' => json_encode( $data ),
        'header'=>  "Content-Type: application/json\r\n" .
                    "Accept: application/json\r\n"
      )
);

$context     = stream_context_create($options);
$result      = file_get_contents($url, false, $context);
$response    = json_decode($result);
var_dump($response);

4. Raw HTTP Post

Using Zend Framework’s HTTP client: http://framework.zend.com/manual/en/zend.http.client.advanced.html#zend.http.client.raw_post_data

$json = json_encode($data);
$client = new Zend_Http_Client($url);
$client->setRawData($json, 'application/json')->request('POST');
var_dump($client->request()->getBody());

SOURCE:- https://blog.magepsycho.com/sending-json-data-remote-server/