问:
Minimum difference based on group-index on two data frame
I have two data frame

```<code>A
            X1     Year_month
1          19.3945   1999_1
2          19.379    1999_1
3          19.2073   1999_1
4          19.267    2000_1
5          18.760    2000_1
6          19.3505   2000_1
</code>```

and B

```<code> Longitude   Year_month      CHL
1   12.3125     1999_1    12.70245
2    12.375     1999_1    12.63853
3   12.4375     1999_1    12.58700
4      12.5     2000_1    12.61019
5   12.5625     2000_1    12.75727
6    12.625     2000_1    13.06914
</code>```

I would like to calculate the minimum difference between each value of A$X1 and all values of B$Longitude, based on group-index Year_month, and report in a new column of A the value of B$CHL

Let's say when A$X1, minus each value of B$longitude, values for values, for the same Year_month group is the minimum difference, I put in a column A$res the values of B$CHL
Example, for the first row of df A:

```<code>A[1,1]-B[1,1]
A[1,1]-B[2,1]
A[1,1]-B[3,1] ---> this is the minimum difference
</code>```

in the column A$res I put the result 12.58 (value of B[3,3]), and so on for each row of A$X1

```<code>I tried this code:
A$res<- as.data.frame(lapply(A, function(x){
  if(as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))){
    return(B$CHL[unlist(lapply(as.numeric(as.character(B$Longitude)), function(t) which.min(abs(A$X1-t))))])
  } else{
    return(NA)
  }
}))
</code>```

But I have the error:

```<code>Error in if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  missing values where is required TRUE/FALSE
Furthermore Warning messages:
1: In FUN(X[[i]], ...) :  NA for coercion
2: In FUN(X[[i]], ...) : NA for coercion
3: In if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  the condition of length > 1 only the first element is used
</code>```

Any idea???

P.S:

```<code>sapply(A,class)
        X1 Year_month
  "factor"   "factor"

sapply(B,class)
 Longitude Year_month        CHL
  "factor"   "factor"  "numeric"
</code>```

答:
Here's a data.table solution. It's similar to @Parfait except I add an ID up front so that I can condense it down without having to re-join to the original data.table.

```<code>library(data.table)
A_dt[, ID := seq_len(.N), by = Year_month]

A_dt[B_dt
     , on = 'Year_month'
     , .(Year_month, ID, Res = X1 - Longitude, X1, Longitude, CHL)
     , allow.cartesian = T
     ][, .SD[which.min(Res), ] , by = .(Year_month, ID)]

   Year_month ID    Res      X1 Longitude      CHL
1:     1999_1  1 6.9570 19.3945   12.4375 12.58700
2:     1999_1  2 6.9415 19.3790   12.4375 12.58700
3:     1999_1  3 6.7698 19.2073   12.4375 12.58700
4:     2000_1  1 6.6420 19.2670   12.6250 13.06914
5:     2000_1  2 6.1350 18.7600   12.6250 13.06914
6:     2000_1  3 6.7255 19.3505   12.6250 13.06914
</code>```

Here's a base R solution that is a similar approach.

```<code>A$ID <- ave(seq_len(nrow(A)), A$Year_month, FUN = seq_along)

A2 <- merge(A, B, by = 'Year_month')
A2$Difference <- A2$X1 - A2$Longitude

A2$Min_Diff <- ave(A2$Difference, A2$Year_month, A2$ID, FUN = min)
A2[A2$Min_Diff == A2$Difference, c('Year_month', 'ID', 'Difference', 'X1', 'Longitude', 'CHL')]
</code>```

Finally, since there were some issues with data types, here are some ways I got then converted:

```<code>A <- data.frame("X1"=c("19.3945","19.379", "19.2073", "19.267", "18.760", "19.3505"),
                "Year_month" = c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"))

B <- data.frame( "Longitude"=c("12.3125", "12.375", "12.4375","12.5", "12.5625", "12.625"  ),
                 "Year_month"=c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"),
                 "CHL"=c( 12.70245, 12.63853, 12.58700, 12.61019, 12.75727, 13.06914))

#If the whole data.frame is a factor, we can just remake the data.frame
A <- data.frame(lapply(A, as.character), stringsAsFactors = F)
A$X1 <- as.numeric(A$X1)

#For the B data.frame, I didn't want to use the lapply trick because 'CHL' was already good.
B$Longitude <- as.numeric(as.character(B$Longitude))
B$Year_Month <- as.character(B$Year_month)

# Alternatively, you address the data types on making your data.frames

# Note, you can add "stringsAsFactors = F" to the data.frame call and we could have skipped a step.
A_dt <- data.table(X1 = as.numeric(c("19.3945","19.379", "19.2073", "19.267", "18.760", "19.3505"))
                   , Year_month = c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"))

B_dt <- data.table(Longitude= as.numeric(c("12.3125", "12.375", "12.4375","12.5", "12.5625", "12.625"))
                   , Year_month=c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1")
                   , CHL=c( 12.70245, 12.63853, 12.58700, 12.61019, 12.75727, 13.06914))

</code>```

Body:
I have two data frame

A
            X1     Year_month
1          19.3945   1999_1
2          19.379    1999_1
3          19.2073   1999_1
4          19.267    2000_1
5          18.760    2000_1
6          19.3505   2000_1

and B

 Longitude   Year_month      CHL
1   12.3125     1999_1    12.70245
2    12.375     1999_1    12.63853
3   12.4375     1999_1    12.58700
4      12.5     2000_1    12.61019
5   12.5625     2000_1    12.75727
6    12.625     2000_1    13.06914

I would like to calculate the minimum difference between each value of A$X1 and all values of B$Longitude, based on group-index Year_month, and report in a new column of A the value of B$CHL

Let's say when A$X1, minus each value of B$longitude, values for values, for the same Year_month group is the minimum difference, I put in a column A$res the values of B$CHL
Example, for the first row of df A:

A[1,1]-B[1,1]
A[1,1]-B[2,1]
A[1,1]-B[3,1] ---> this is the minimum difference

in the column A$res I put the result 12.58 (value of B[3,3]), and so on for each row of A$X1

I tried this code:
A$res<- as.data.frame(lapply(A, function(x){
  if(as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))){
    return(B$CHL[unlist(lapply(as.numeric(as.character(B$Longitude)), function(t) which.min(abs(A$X1-t))))])
  } else{
    return(NA)
  }
}))

But I have the error:

Error in if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  missing values where is required TRUE/FALSE
Furthermore Warning messages:
1: In FUN(X[[i]], ...) :  NA for coercion
2: In FUN(X[[i]], ...) : NA for coercion
3: In if (as.numeric(as.character(A$Year_month)) == as.numeric(as.character(B$Year_month))) { :
  the condition of length > 1 only the first element is used

Any idea???

P.S:

sapply(A,class)
        X1 Year_month
  "factor"   "factor"

sapply(B,class)
 Longitude Year_month        CHL
  "factor"   "factor"  "numeric"

Body:
Here's a data.table solution. It's similar to @Parfait except I add an ID up front so that I can condense it down without having to re-join to the original data.table.

library(data.table)
A_dt[, ID := seq_len(.N), by = Year_month]

A_dt[B_dt
     , on = 'Year_month'
     , .(Year_month, ID, Res = X1 - Longitude, X1, Longitude, CHL)
     , allow.cartesian = T
     ][, .SD[which.min(Res), ] , by = .(Year_month, ID)]

   Year_month ID    Res      X1 Longitude      CHL
1:     1999_1  1 6.9570 19.3945   12.4375 12.58700
2:     1999_1  2 6.9415 19.3790   12.4375 12.58700
3:     1999_1  3 6.7698 19.2073   12.4375 12.58700
4:     2000_1  1 6.6420 19.2670   12.6250 13.06914
5:     2000_1  2 6.1350 18.7600   12.6250 13.06914
6:     2000_1  3 6.7255 19.3505   12.6250 13.06914

Here's a base R solution that is a similar approach.

A$ID <- ave(seq_len(nrow(A)), A$Year_month, FUN = seq_along)

A2 <- merge(A, B, by = 'Year_month')
A2$Difference <- A2$X1 - A2$Longitude

A2$Min_Diff <- ave(A2$Difference, A2$Year_month, A2$ID, FUN = min)
A2[A2$Min_Diff == A2$Difference, c('Year_month', 'ID', 'Difference', 'X1', 'Longitude', 'CHL')]

Finally, since there were some issues with data types, here are some ways I got then converted:

A <- data.frame("X1"=c("19.3945","19.379", "19.2073", "19.267", "18.760", "19.3505"),
                "Year_month" = c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"))

B <- data.frame( "Longitude"=c("12.3125", "12.375", "12.4375","12.5", "12.5625", "12.625"  ),
                 "Year_month"=c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"),
                 "CHL"=c( 12.70245, 12.63853, 12.58700, 12.61019, 12.75727, 13.06914))

#If the whole data.frame is a factor, we can just remake the data.frame
A <- data.frame(lapply(A, as.character), stringsAsFactors = F)
A$X1 <- as.numeric(A$X1)

#For the B data.frame, I didn't want to use the lapply trick because 'CHL' was already good.
B$Longitude <- as.numeric(as.character(B$Longitude))
B$Year_Month <- as.character(B$Year_month)

# Alternatively, you address the data types on making your data.frames

# Note, you can add "stringsAsFactors = F" to the data.frame call and we could have skipped a step.
A_dt <- data.table(X1 = as.numeric(c("19.3945","19.379", "19.2073", "19.267", "18.760", "19.3505"))
                   , Year_month = c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1"))

B_dt <- data.table(Longitude= as.numeric(c("12.3125", "12.375", "12.4375","12.5", "12.5625", "12.625"))
                   , Year_month=c("1999_1", "1999_1", "1999_1", "2000_1", "2000_1", "2000_1")
                   , CHL=c( 12.70245, 12.63853, 12.58700, 12.61019, 12.75727, 13.06914))


来源: stackexchange

问:
Fizbuzz in OCaml gets gets error "is not compatible with type unit"
I have the following fizbuzz program written in OCaml (using a bit of recursion):

```<code>let rec fizbuzz_r =
  let rec fizbuzz_rr i =
    if i == 0 then
      ()
    else if i mod 3 == 0 && i mod 5 != 0 then
      Printf.printf "Fizz: %d \n" i
      fizbuzz_rr (i - 1)
    else if i mod 3 != 0 && i mod 5 == 0 then
      Printf.printf "Buzz: %d \n" i
      fizbuzz_rr (i - 1)
    else if i mod 5 == 0 && i mod 3 == 0 then
      Printf.printf "Fizbuzz: %d \n" i
      fizbuzz_rr (i - 1)
    else
      Printf.printf "Current Number: %d \n" i
      fizbuzz_rr (i - 1)
    ()
  in
    fizbuzz_rr 100

let () = fizbuzz_r
</code>```

The problem is when I compile it, I get the following error message:

```<code>Error: This expression has type
         ('a -> 'b -> 'c -> 'd, out_channel, unit, unit, unit,
          'a -> 'b -> 'c -> 'd)
         CamlinternalFormatBasics.fmt
       but an expression was expected of type
         ('a -> 'b -> 'c -> 'd, out_channel, unit, unit, unit, unit)
         CamlinternalFormatBasics.fmt
       Type 'a -> 'b -> 'c -> 'd is not compatible with type unit
</code>```

However, it seems to me that the nested function fizbuzz_rr is correctly returning a unit type. What am I missing here?

答:
This expression:

```<code>  Printf.printf "Fizz: %d \n" i
  fizbuzz_rr (i - 1)
</code>```

Has the form of a call to Printf.printf with 4 arguments. You need a semicolon to separate the two expressions that you want to have.

However, after then you can only have one expression. So you need to parenthesize the two expressions. It will look like this:

```<code>  . . .
else if i mod 3 == 0 && i mod 5 != 0 then (
  Printf.printf "Fizz: %d \n" i;
  fizbuzz_rr (i - 1)
) else if i mod 3 != 0 && i mod 5 == 0 then (
  . . .
</code>```

You also have an extra () at the end that is not doing anything. You should remove it like this:

```<code>else (
  Printf.printf "Current Number: %d \n" i ;
  fizbuzz_rr (i - 1)
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have the following fizbuzz program written in OCaml (using a bit of recursion):

let rec fizbuzz_r =
  let rec fizbuzz_rr i =
    if i == 0 then
      ()
    else if i mod 3 == 0 && i mod 5 != 0 then
      Printf.printf "Fizz: %d \n" i
      fizbuzz_rr (i - 1)
    else if i mod 3 != 0 && i mod 5 == 0 then
      Printf.printf "Buzz: %d \n" i
      fizbuzz_rr (i - 1)
    else if i mod 5 == 0 && i mod 3 == 0 then
      Printf.printf "Fizbuzz: %d \n" i
      fizbuzz_rr (i - 1)
    else
      Printf.printf "Current Number: %d \n" i
      fizbuzz_rr (i - 1)
    ()
  in
    fizbuzz_rr 100

let () = fizbuzz_r

The problem is when I compile it, I get the following error message:

Error: This expression has type
         ('a -> 'b -> 'c -> 'd, out_channel, unit, unit, unit,
          'a -> 'b -> 'c -> 'd)
         CamlinternalFormatBasics.fmt
       but an expression was expected of type
         ('a -> 'b -> 'c -> 'd, out_channel, unit, unit, unit, unit)
         CamlinternalFormatBasics.fmt
       Type 'a -> 'b -> 'c -> 'd is not compatible with type unit

However, it seems to me that the nested function fizbuzz_rr is correctly returning a unit type. What am I missing here?

Body:
This expression:

  Printf.printf "Fizz: %d \n" i
  fizbuzz_rr (i - 1)

Has the form of a call to Printf.printf with 4 arguments. You need a semicolon to separate the two expressions that you want to have.

However, after then you can only have one expression. So you need to parenthesize the two expressions. It will look like this:

  . . .
else if i mod 3 == 0 && i mod 5 != 0 then (
  Printf.printf "Fizz: %d \n" i;
  fizbuzz_rr (i - 1)
) else if i mod 3 != 0 && i mod 5 == 0 then (
  . . .

You also have an extra () at the end that is not doing anything. You should remove it like this:

else (
  Printf.printf "Current Number: %d \n" i ;
  fizbuzz_rr (i - 1)
)


问:
How to plot times on the abscissa of a matplotlib specgram?
I am trying to plot the specgram of an array (my_array) sampled at 4,000Hz.
In this example, the data were collected on May 15, 2019 over 11 minutes, from 08:41 to 08:52.

I am extracting my data from a csv file using pandas, but for the sake of creating a reprex, I am creating a time array (my_times) of unix timestamps from scratch:

```<code>import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import datetime
import numpy as np

SR=4000 #sampling rate

my_times = np.arange(1557909700.221257,1557910338.095864,0.00025)
my_array = np.random.rand(my_times.shape[0])
</code>```

I would like to plot the specgram (matplotlib.pyplot.specgram) but instead of displaying the number of bins on the abscissa, I would like to represent actual times.

This is my current code, taking inspiration from this SO post:

```<code>Pxx, freqs, bins, im=plt.specgram(my_array,Fs=SR, NFFT=8192, scale_by_freq='True', detrend='mean', scale='dB')
ax=plt.gca()
def timeTicks(my_times, pos):
    return datetime.datetime.utcfromtimestamp(my_times).strftime("%H:%M:%S")
formatter = tick.FuncFormatter(timeTicks)
ax.xaxis.set_major_formatter(formatter)

plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (hh:mm:ss)')
</code>```

This code yields the following plot:

My problem is that the times given here start at 00:00. How can I plot the "absolute" time, i.e. have my plot start at 08:42?

I do not really understand how the FuncFormatter works. Any help would be appreciated!

答:
I ended up using xextent to specify the image extent along the x-axis parameter. I specified the first sample of my time array (my_times[0]) as xmin and the last sample (my_times[0]) as xmax:

Pxx, freqs, bins, im=plt.specgram(my_array,Fs=SR, NFFT=8192, scale_by_freq='True', detrend='mean', scale='dB', xextent=[my_times[0],my_times[-1]])

Modifying the code yielded the following image:

Body:
I am trying to plot the specgram of an array (my_array) sampled at 4,000Hz.
In this example, the data were collected on May 15, 2019 over 11 minutes, from 08:41 to 08:52.

I am extracting my data from a csv file using pandas, but for the sake of creating a reprex, I am creating a time array (my_times) of unix timestamps from scratch:

import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import datetime
import numpy as np

SR=4000 #sampling rate

my_times = np.arange(1557909700.221257,1557910338.095864,0.00025)
my_array = np.random.rand(my_times.shape[0])

I would like to plot the specgram (matplotlib.pyplot.specgram) but instead of displaying the number of bins on the abscissa, I would like to represent actual times.

This is my current code, taking inspiration from this SO post:

Pxx, freqs, bins, im=plt.specgram(my_array,Fs=SR, NFFT=8192, scale_by_freq='True', detrend='mean', scale='dB')
ax=plt.gca()
def timeTicks(my_times, pos):
    return datetime.datetime.utcfromtimestamp(my_times).strftime("%H:%M:%S")
formatter = tick.FuncFormatter(timeTicks)
ax.xaxis.set_major_formatter(formatter)

plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (hh:mm:ss)')

This code yields the following plot:

My problem is that the times given here start at 00:00. How can I plot the "absolute" time, i.e. have my plot start at 08:42?

I do not really understand how the FuncFormatter works. Any help would be appreciated!


问:
Do xhtml or xml allow comments to be started by user defined tags?
Reusing old php-code and html-files I wanted to comment out large sections, but that's not too easily achievable, because those sections contain comments themselves already.

Looking at the helpfile for php and the 5.3 html syntax at w3 I found out, that comments have a very limited amount of tags one could use.

As I remember I have read years ago about some coding language which allows userdefined comment-tags, albeit they had to follow some rules.

Especially I wonder

- if userdefined comment-tags are possible in xhtml?

- if userdefined comment-tags are possible in xml?

- if it's possible in xhtml or xml, shouldn't it be possible in html, too, to define new comment-tags?

答:
No.

HTML comments (all versions, including HTML4, XHTML, and HTML5) and XML comments have always had the following form:

```<code><!-- This is a comment -->
</code>```

There are no "user-defined comment-tags" in HTML or XML.

Body:
No.

HTML comments (all versions, including HTML4, XHTML, and HTML5) and XML comments have always had the following form:

<!-- This is a comment -->

There are no "user-defined comment-tags" in HTML or XML.


问:
How to prevent errors with large results when using eval()?
I'm making a calculator in Python and am currently trying to prevent the program crashing when dealing with large input.

The only way I know how to catch errors is using 'try' and 'except', so I wrote this:

```<code>def solve(self, equation):
    try:
        return eval(equation)
    except(OverflowError):
        messagebox.showinfo("Error","Result too large")
    return equation
</code>```

(I'm aware eval can be dangerous but the user is unable to type any input so I think it's fine)

When I input a massive number in scientific notation like '389e+10**(58)*9' the OverflowError is caught successfully, but if I put in something like '55555555**5555555' the window stops responding.

I was under the impression the latter also raises an OverflowError but I now I think this is could be happening because it doesn't create an error at all, and eval just can't handle working out a result this large.

If this is the case, I think I should put a limit on how large the answer should be, but I'm unsure of how I would decide on this limit. Any suggestions?

答:
In Python, float is usually a 64-bit floating point number, which can hold a finite range. Values above that cause an OverflowError to be raised. As 389e+10 returns a float, the entire expression 389e+10**(58)*9 also returns a float.

On the other hand, 55555555**5555555 returns an int. In Python, int can hold arbitrarily large values, limited only by memory. Therefore, what is happening is that Python attempts to calculate a really big number, taking a really, really long time to do so.

This is, in general, not that easy of a question to solve, because you're using eval, and therefore you have no information about the exact nature of the equation.

I would suggest instead parsing the equation, which will allow you to inspect it in detail. You could then, among other things, not perform exponentiation calculations where both the base and exponent are large.

(or you could just use floating point calculation for everything, which will affect precision, but I don't think that really matters for a simple calculator, right?)

Body:
I'm making a calculator in Python and am currently trying to prevent the program crashing when dealing with large input.

The only way I know how to catch errors is using 'try' and 'except', so I wrote this:

def solve(self, equation):
    try:
        return eval(equation)
    except(OverflowError):
        messagebox.showinfo("Error","Result too large")
    return equation

(I'm aware eval can be dangerous but the user is unable to type any input so I think it's fine)

When I input a massive number in scientific notation like '389e+10**(58)*9' the OverflowError is caught successfully, but if I put in something like '55555555**5555555' the window stops responding.

I was under the impression the latter also raises an OverflowError but I now I think this is could be happening because it doesn't create an error at all, and eval just can't handle working out a result this large.

If this is the case, I think I should put a limit on how large the answer should be, but I'm unsure of how I would decide on this limit. Any suggestions?


答: It stops responding because it is busy calculating 55555555**5555555.  It won't produce an OverflowError because integers in Python are arbitrary precision.  It will keep getting larger and larger, taking more and more memory, until it cripples your computer, which it has done.

Title: How to prevent errors with large results when using eval()?


问:
Conditional calculation dataframe
The calculation I would like to do on this dataframe is quit simple still I do not manage to think of any preliminary code. The data in columns '10' are sorted (ascending order).

I want to:
1. first row in column '10' * 1.05 (add 5%)
      ex: 871103 * 1.05 = 914658.15 (the closest value in the df is 914657)
2. count the number of rows to find the data closer to the result find
   in 1.
      ex: 16th rows in the df below.
3. sum up the same number of rows in column '2'.
     ex: 0.04242 in the df below

DATAFRAME SAMPLE:

```<code>             2              10
1
asks:   0.1546         871103
        0.011          871280
        0.004          871315
        0.01           871333
        0.004          871341
        0.0106         871347
        0.01           871347
        0.023          871363
        0.002          871365
        0.01           871401
        0.001          871462
        0.139          871477
        0.005          871483
        0.005          871499
        0.03           871502
        0.005          914657
        0.01119222     914800
        0.50000013     920000
</code>```

THE OUTPUT:

```<code>             2               10
 1
   asks:    0.4242         914657
</code>```

答:
Assuming that df is your dataframe:

```<code>idx = (df['10'] - (df['10'][0] * 1.05)).abs().idxmin()
csdf = df.cumsum()
csdf['10'] = df['10']
</code>```

idx is the index of the row you are looking for: obtained looking fo the minimum of the absolute value of the difference between each value of column '10' and the first value of column '10' multiplied by 1.05.

csdf is a new dataframe obtained doing the cumulative sum of the elements of df, and then I replaced column '10' of csdf with the original column '10' of df.

So

```<code>csdf.iloc[idx]
</code>```

is the row you are looking for.

Title: Conditional calculation dataframe

Body:
The calculation I would like to do on this dataframe is quit simple still I do not manage to think of any preliminary code. The data in columns '10' are sorted (ascending order).

I want to:
1. first row in column '10' * 1.05 (add 5%)
      ex: 871103 * 1.05 = 914658.15 (the closest value in the df is 914657)
2. count the number of rows to find the data closer to the result find
   in 1.
      ex: 16th rows in the df below.
3. sum up the same number of rows in column '2'.
     ex: 0.04242 in the df below

DATAFRAME SAMPLE:

             2              10
1
asks:   0.1546         871103
        0.011          871280
        0.004          871315
        0.01           871333
        0.004          871341
        0.0106         871347
        0.01           871347
        0.023          871363
        0.002          871365
        0.01           871401
        0.001          871462
        0.139          871477
        0.005          871483
        0.005          871499
        0.03           871502
        0.005          914657
        0.01119222     914800
        0.50000013     920000

THE OUTPUT:

             2               10
 1
   asks:    0.4242         914657

Body:
Assuming that df is your dataframe:

idx = (df['10'] - (df['10'][0] * 1.05)).abs().idxmin()
csdf = df.cumsum()
csdf['10'] = df['10']

idx is the index of the row you are looking for: obtained looking fo the minimum of the absolute value of the difference between each value of column '10' and the first value of column '10' multiplied by 1.05.

csdf is a new dataframe obtained doing the cumulative sum of the elements of df, and then I replaced column '10' of csdf with the original column '10' of df.

So

csdf.iloc[idx]

is the row you are looking for.


问:
.NET Core high memory usage base64 encoding messages from database
I have a large database of messages I need to send to other systems. The messages average 5-10mb in size but some are larger (50-70mb). I need to base64 encode each message to disk. My application is consuming a large amount of memory encoding the messages to disk and I cannot figure out why.

What I have tried: I have read multiple posts regarding dispose method. I have implemented the dispose function as much as I can (via using) to release resources but I am still observing high memory usage (700mb+) for my Console application.

To keep things simple, I selected the 10 largest files from my database that range from 55-75mb. Under normal circumstances, the application will be processing messages 24/7.

Here is what my memory usage looks like when executing the below code. The flat line indicates the end of processing the large files. Why are these resources not being released?

Here is a capture of my heap view:

Here's my code:

```<code>const string sql = "SELECT TOP 10 * FROM [dbo].[OutboundMessages] ORDER BY [Length] DESC";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand(sql, connection))
    using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    int ordinal = reader.GetOrdinal("FileData");
                    long bytesRead, offset = 0;
                    byte[] buffer = new byte[4096];
                    while ((bytesRead = reader.GetBytes(ordinal, offset, buffer, 0, buffer.Length)) > 0)
                    {
                        offset += bytesRead;
                        stream.Write(buffer, 0, (int)bytesRead);
                    }
                    string file = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    using (StreamWriter writer = new StreamWriter(file))
                    {
                        writer.Write(Convert.ToBase64String(stream.ToArray()));
                    }
                }
            }
        }
    }
}
</code>```

答:
I solved the issue by writing the bytes directly to file in multiples of 3 bytes (3*1024=3072). Now my process memory stays at a stable 20mb. Writing 3 bytes (or multiples of) at a time ensures base64 does not lose it's binary to text formatting.</p>

```<code>const string sql = "SELECT TOP 10 * FROM [dbo].[OutboundMessages] ORDER BY [Length] DESC";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand(sql, connection))
    using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                string file = Guid.NewGuid().ToString().Replace("-", string.Empty);
                using (StreamWriter writer = new StreamWriter(file))
                {
                    int ordinal = reader.GetOrdinal("FileData");
                    long bytesRead, offset = 0;
                    byte[] buffer = new byte[3072];
                    while ((bytesRead = reader.GetBytes(ordinal, offset, buffer, 0, buffer.Length)) > 0)
                    {
                        offset += bytesRead;
                        writer.Write(Convert.ToBase64String(buffer));
                    }
                }
            }
        }
    }
}
</code>```

Body:
I have a large database of messages I need to send to other systems. The messages average 5-10mb in size but some are larger (50-70mb). I need to base64 encode each message to disk. My application is consuming a large amount of memory encoding the messages to disk and I cannot figure out why.

What I have tried: I have read multiple posts regarding dispose method. I have implemented the dispose function as much as I can (via using) to release resources but I am still observing high memory usage (700mb+) for my Console application.

To keep things simple, I selected the 10 largest files from my database that range from 55-75mb. Under normal circumstances, the application will be processing messages 24/7.

Here is what my memory usage looks like when executing the below code. The flat line indicates the end of processing the large files. Why are these resources not being released?

Here is a capture of my heap view:

Here's my code:

const string sql = "SELECT TOP 10 * FROM [dbo].[OutboundMessages] ORDER BY [Length] DESC";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand(sql, connection))
    using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    int ordinal = reader.GetOrdinal("FileData");
                    long bytesRead, offset = 0;
                    byte[] buffer = new byte[4096];
                    while ((bytesRead = reader.GetBytes(ordinal, offset, buffer, 0, buffer.Length)) > 0)
                    {
                        offset += bytesRead;
                        stream.Write(buffer, 0, (int)bytesRead);
                    }
                    string file = Guid.NewGuid().ToString().Replace("-", string.Empty);
                    using (StreamWriter writer = new StreamWriter(file))
                    {
                        writer.Write(Convert.ToBase64String(stream.ToArray()));
                    }
                }
            }
        }
    }
}

Body:
I solved the issue by writing the bytes directly to file in multiples of 3 bytes (3*1024=3072). Now my process memory stays at a stable 20mb. Writing 3 bytes (or multiples of) at a time ensures base64 does not lose it's binary to text formatting.

const string sql = "SELECT TOP 10 * FROM [dbo].[OutboundMessages] ORDER BY [Length] DESC";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
    connection.Open();
    using (SqlCommand command = new SqlCommand(sql, connection))
    using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
    {
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                string file = Guid.NewGuid().ToString().Replace("-", string.Empty);
                using (StreamWriter writer = new StreamWriter(file))
                {
                    int ordinal = reader.GetOrdinal("FileData");
                    long bytesRead, offset = 0;
                    byte[] buffer = new byte[3072];
                    while ((bytesRead = reader.GetBytes(ordinal, offset, buffer, 0, buffer.Length)) > 0)
                    {
                        offset += bytesRead;
                        writer.Write(Convert.ToBase64String(buffer));
                    }
                }
            }
        }
    }
}


问:
Trying to create a comic book page
I am trying to create a comic book page for a project. I managed to create a cover that opens and I am now trying to add separate blocks to the first page, just like a comic book would look.

However, when I try to add these blocks, it seems to "push" my cover over. Ex: https://codepen.io/reallynotprogramming/pen/GadVZJ

I tried to nest individual divs inside my main div container, but it does not seem to work.

body {
     background-image: url('images/Avenger\ vs\ Justice\ League2-01.jpg');
     background-size: contain;
     background-position: center;

}

 .flex-container {
    /* display: flex;
    flex-direction: row; */
    background-color: white;
    height: 820px;
    width: 700px;
    margin-top:40px;
    margin-bottom: 40px;
    margin-left: 500px;
    box-shadow: 20px 20px;
  }

  .cover{
    background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Symbol_from_Marvel%27s_The_Avengers_logo.svg/877px-Symbol_from_Marvel%27s_The_Avengers_logo.svg.png);
    width: 700px;
    height: 820px;
    transform: rotateY(0deg);
    background-color: blue;
    transform-style: preserve-3d;
    transform-origin: left;
    transition: all .5s ease-in;
}

.flex-container:hover .cover{
    transform: rotateY(-180deg);
  }

.page1{
    width: 700px;
    height: 820px;
    margin-top: 75px;
    margin-left: 100px;
    background-color: green;
}

 .flex-container {
    /* display: flex;
    flex-direction: row; */
    background-color: white;
    height: 820px;
    width: 700px;
    margin-top:40px;
    margin-bottom: 40px;
    margin-left: 500px;
    box-shadow: 20px 20px;
  }

  .cover{
    background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Symbol_from_Marvel%27s_The_Avengers_logo.svg/877px-Symbol_from_Marvel%27s_The_Avengers_logo.svg.png);
    width: 700px;
    height: 820px;
    transform: rotateY(0deg);
    background-color: blue;
    transform-style: preserve-3d;
    transform-origin: left;
    transition: all .5s ease-in;
}

.flex-container:hover .cover{
    transform: rotateY(-180deg);
  }

.page1{
    width: 700px;
    height: 820px;
    margin-top: 75px;
    margin-left: 100px;
    background-color: green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Avengers vs JL</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- CSS Link -->
    <link rel="stylesheet" type="text/css" href="project.css">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>

    <!--Comic Book-->
    <div class="flex-container">
      <div class="cover"></div>
      <div class="page1">Test</div>
    </div>

    <!-- Optional JavaScript -->

    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  </body>
</html></code>```

答:
Your issue is that block elements don't "stack" by default. For the web, things follow a linear flow. If you want things to kinda bunch up and stack, you're going to have to alter their layout. The simplest way to do this is going to be using position "absolute" directives. I forked your example and added something here:

https://codepen.io/anon/pen/yWELQM

You will note the page is now under. Specifically, it's the following CSS rule allowing for this:

```<code>.page1{
    width: 700px;
    height: 820px;
    margin-top: 39px;
    padding: 2em;
    color: white;
    background-color: green;
    position: absolute;
    top: 0;
    bottom: 0;
    z-index: -1;
}
</code>```

You can consider reading up about how HTML element layouts work as well to get a better understanding of how this works.

Title: Trying to create a comic book page

Body:
I am trying to create a comic book page for a project. I managed to create a cover that opens and I am now trying to add separate blocks to the first page, just like a comic book would look.

However, when I try to add these blocks, it seems to "push" my cover over. Ex: https://codepen.io/reallynotprogramming/pen/GadVZJ

I tried to nest individual divs inside my main div container, but it does not seem to work.

body {
     background-image: url('images/Avenger\ vs\ Justice\ League2-01.jpg');
     background-size: contain;
     background-position: center;

}

 .flex-container {
    /* display: flex;
    flex-direction: row; */
    background-color: white;
    height: 820px;
    width: 700px;
    margin-top:40px;
    margin-bottom: 40px;
    margin-left: 500px;
    box-shadow: 20px 20px;
  }

  .cover{
    background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Symbol_from_Marvel%27s_The_Avengers_logo.svg/877px-Symbol_from_Marvel%27s_The_Avengers_logo.svg.png);
    width: 700px;
    height: 820px;
    transform: rotateY(0deg);
    background-color: blue;
    transform-style: preserve-3d;
    transform-origin: left;
    transition: all .5s ease-in;
}

.flex-container:hover .cover{
    transform: rotateY(-180deg);
  }

.page1{
    width: 700px;
    height: 820px;
    margin-top: 75px;
    margin-left: 100px;
    background-color: green;
}

 .flex-container {
    /* display: flex;
    flex-direction: row; */
    background-color: white;
    height: 820px;
    width: 700px;
    margin-top:40px;
    margin-bottom: 40px;
    margin-left: 500px;
    box-shadow: 20px 20px;
  }

  .cover{
    background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/0/0b/Symbol_from_Marvel%27s_The_Avengers_logo.svg/877px-Symbol_from_Marvel%27s_The_Avengers_logo.svg.png);
    width: 700px;
    height: 820px;
    transform: rotateY(0deg);
    background-color: blue;
    transform-style: preserve-3d;
    transform-origin: left;
    transition: all .5s ease-in;
}

.flex-container:hover .cover{
    transform: rotateY(-180deg);
  }

.page1{
    width: 700px;
    height: 820px;
    margin-top: 75px;
    margin-left: 100px;
    background-color: green;
}

<!DOCTYPE html>

    <title>Avengers vs JL</title>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" type="text/css" href="project.css">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Test

Body:
Your issue is that block elements don't "stack" by default. For the web, things follow a linear flow. If you want things to kinda bunch up and stack, you're going to have to alter their layout. The simplest way to do this is going to be using position "absolute" directives. I forked your example and added something here:

https://codepen.io/anon/pen/yWELQM

You will note the page is now under. Specifically, it's the following CSS rule allowing for this:

.page1{
    width: 700px;
    height: 820px;
    margin-top: 39px;
    padding: 2em;
    color: white;
    background-color: green;
    position: absolute;
    top: 0;
    bottom: 0;
    z-index: -1;
}

You can consider reading up about how HTML element layouts work as well to get a better understanding of how this works.


问:
is there a way to change elements of a page before opening it
I have designed a page to be used as a tool. I am getting some challenges here since my experience is very little in the field and im only new.
- my goal is to change values of an element on a page that is not open yet.
- is there a function i can make on current page to change the values of the element on the next page to preset it to some static numbers or some of them are dynamic

I dont know how to manipulate something that is not open yet, i dont even know if that's something possible. I was able to change elements on my open current page, but dont know how to change something on the next page if i click on one of the links

```<code>        <a href="https://rex.reportexecdirect.com/intelligarde/CESIReportExec/Reporting/ParkingPermit.aspx?groupid=174" class="btn btn-info mx-1" role="button">Park Property Management</a>
        <a href="https://rex.reportexecdirect.com/intelligarde/CESIReportExec/Reporting/ParkingPermit.aspx?groupid=121" class="btn btn-info mx-1" role="button">Millgate Manor</a>
        <a href="https://rex.reportexecdirect.com/intelligarde/CESIReportExec/Reporting/ParkingPermit.aspx?groupid=166" class="btn btn-info mx-1" role="button">Weston Towers</a>
        <a href="https://rex.reportexecdirect.com/intelligarde/CESIReportExec/Reporting/ParkingPermit.aspx?groupid=290" class="btn btn-info mx-1" role="button">Kingston</a>
        <a href="https://rex.reportexecdirect.com/intelligarde/CESIReportExec/Reporting/ParkingPermit.aspx?groupid=190" class="btn btn-info mx-1" role="button">Region Of Peel</a>
</code>```

so i expect to click on one of the links and when the link opens some elements in the links i need them to be filled with some values that are static always

答:
You can't directly influence the content of another page with JavaScript in the current page. That would have very big security concerns.

However, you could indirectly influence the content if you have access to the source for both pages, and can add JavaScript to both of them. Then, as some comments suggested, you can for example use search paramaters in the link url to pass along information.
(Search parameters are the stuff that comes at the end of a url sometimes and looks something like ?name=john&id=555)

You can read more about about working with search parameters in JavaScript here:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

Don't get discouraged! You're capabilities will grow as you try to make things work. (That's almost the only time they will grow.)

A word of caution!

Please be very careful when using search parameters to modify or display content on a page as there are some real security concerns involved. Never display anything from the search parameters directly on the page without validating the input first. A good way to handle dynamic content based on search parameters, at least if you know the possible options available, is to have some if .. else statements or maybe a switch block that you try to match the search parameters against, and simply not display anything at all if the content of the parameter does not match any input that you're expecting.

Body:
I have designed a page to be used as a tool. I am getting some challenges here since my experience is very little in the field and im only new.
- my goal is to change values of an element on a page that is not open yet.
- is there a function i can make on current page to change the values of the element on the next page to preset it to some static numbers or some of them are dynamic

I dont know how to manipulate something that is not open yet, i dont even know if that's something possible. I was able to change elements on my open current page, but dont know how to change something on the next page if i click on one of the links

        Park Property Management
        Millgate Manor
        Weston Towers
        Kingston
        Region Of Peel

so i expect to click on one of the links and when the link opens some elements in the links i need them to be filled with some values that are static always


问:
Integrity error in django foreign key field in django-rest-framework
I'm fairly new in django. I've had a foreignkey field as supervisor as shown below

```<code>class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)
</code>```

The serializer for this is:

```<code>class SiteSerializer(serializers.ModelSerializer):

supervisor = serializers.ReadOnlyField(source='supervisor.username')

class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')
</code>```

and the view for this is:

```<code>@csrf_exempt
def site_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        sites = Site.objects.all()
        serializer = SiteSerializer(sites, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':

    data = JSONParser().parse(request)

    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)
</code>```

Whenever I post data from postman, it says IntegrityError at /sites/
(1048, "Column 'supervisor_id' cannot be null")

I named the model field as supervisor and the db field becomes supervisor_id as django does it. But,how do I sort this error out.
This might be a really little thing but I couldnt figure out where to make the nexessary adjustments.
Please help.

My post request is {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor" : "1"
} OR

```<code>{
"sitename" : "Putalisadak",
"start_date" :"2019-5-5",
"supervisor_id" : "1"
}
</code>```

both yielding the same output

答:
try with:</p>

```<code>   {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor__id" : "1"
}
</code>```

Body:
I'm fairly new in django. I've had a foreignkey field as supervisor as shown below

class Site(models.Model):
sitename=models.CharField(max_length=255)
start_date=models.DateTimeField
supervisor=models.ForeignKey(User,on_delete=models.PROTECT)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

def __str__(self):
    return "{}".format(self.sitename)

The serializer for this is:

class SiteSerializer(serializers.ModelSerializer):

supervisor = serializers.ReadOnlyField(source='supervisor.username')

class Meta:
    model = Site
    fields = ('sitename', 'start_date', 'supervisor')

and the view for this is:

@csrf_exempt
def site_list(request):
    """
    List all code snippets, or create a new snippet.
    """
    if request.method == 'GET':
        sites = Site.objects.all()
        serializer = SiteSerializer(sites, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':

    data = JSONParser().parse(request)

    serializer = SiteSerializer(data=data)

    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)

Whenever I post data from postman, it says IntegrityError at /sites/
(1048, "Column 'supervisor_id' cannot be null")

I named the model field as supervisor and the db field becomes supervisor_id as django does it. But,how do I sort this error out.
This might be a really little thing but I couldnt figure out where to make the nexessary adjustments.
Please help.

My post request is {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor" : "1"
} OR

{
"sitename" : "Putalisadak",
"start_date" :"2019-5-5",
"supervisor_id" : "1"
}

both yielding the same output

Body:
try with:

   {
    "sitename" : "Tony Tower",
    "start_date" :"2019-5-5",
    "supervisor__id" : "1"
}


问:
RegEx for accessing a nested object
I have some JS objects and they each have a grandchild property called 'products'.

E.g. ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.products

I would like to access the products array regardless of what the specific object out of the above it is.

Tried using regex:

```<code>var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];
</code>```

TypeError: ecom[(((("detail" | "add") | "remove") | "checkout") | "purchase")] is undefined

```<code>var ecomProducts = ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/]['products'];
</code>```

TypeError: ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/] is undefined

How can I access the nested grandchild 'products' object regardless of the parents name?

答:
Let's say you have an object like that::

ecommerce = {
   add: { products: ['add products'] },
   remove: { products: ['remove'] },
   detail: { products: ['prod details'] },
   checkout: { products: ['checkout'] },
   purchase: { products: ['purchase'] }
};

    for( var x in ecommerce )"products" in ecommerce[ x ] ?
    console.log( ecommerce[ x ].products ) : 0;```
</div>
</div>
</p>

<p>You cannot pick up apples from whichever tree you happen upon - you will need to visit the trees and the branches that contain them...</p>

<p>The easiest and the most portable way would be to have a function that utilizes the following expression ::</p>

```for( var x in ecommerce )"products" in ecommerce[ x ] ?
console.log( ecommerce[ x ].products ) : 0;
```

and run error free.

Title: RegEx for accessing a nested object

Body:
I have some JS objects and they each have a grandchild property called 'products'.

E.g. ecommerce.add.products, ecommerce.remove.products, ecommerce.detail.products, ecommerce.checkout.products, ecommerce.purchase.products

I would like to access the products array regardless of what the specific object out of the above it is.

Tried using regex:

var ecomProducts = ecom[('detail'|'add'|'remove'|'checkout'|'purchase')]['products'];

TypeError: ecom[(((("detail" | "add") | "remove") | "checkout") | "purchase")] is undefined

var ecomProducts = ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/]['products'];

TypeError: ecom[/'detail'|'add'|'remove'|'checkout'|'purchase'/] is undefined

How can I access the nested grandchild 'products' object regardless of the parents name?

Body:
Let's say you have an object like that::

ecommerce = {
   add: { products: ['add products'] },
   remove: { products: ['remove'] },
   detail: { products: ['prod details'] },
   checkout: { products: ['checkout'] },
   purchase: { products: ['purchase'] }
};

    for( var x in ecommerce )"products" in ecommerce[ x ] ?
    console.log( ecommerce[ x ].products ) : 0;

You cannot pick up apples from whichever tree you happen upon - you will need to visit the trees and the branches that contain them...

The easiest and the most portable way would be to have a function that utilizes the following expression ::

for( var x in ecommerce )"products" in ecommerce[ x ] ?
console.log( ecommerce[ x ].products ) : 0;

and run error free.


问:
Match values on multiple rows then match differing values
I have a table with four columns; firstly I need to match rows across the first three columns. Then, I need to only trigger a match, if the variables are different in column D. Column D inputs are binary C or D. So each matching 'group' must contain at least one C and one D.

Preferably, I would like to add conditional formatting to highlight those rows that trigger a match.

I have been using the formula below to match the first three columns, but I am unable to isolate the results it returns to then perform something along the lines of D1<>D2 (if that is even the most efficient way to go about this).

```<code>=COUNTIFS($A:A,$A1,$B:B,$B1,$C:C,$C1)>1
</code>```

Example image - yellow highlight should trigger a match, red should not

答:
I propose :

=COUNTIFS($A:A,$A1,$B:B,$B1,$C:C,$C1,$D:D,IF(D1="D","C","D"))

key info :

Column D inputs are binary C or D

Implementation :

Use an if() in the criteria for count.

Glad it helps. (:

Body:
I have a table with four columns; firstly I need to match rows across the first three columns. Then, I need to only trigger a match, if the variables are different in column D. Column D inputs are binary C or D. So each matching 'group' must contain at least one C and one D.

Preferably, I would like to add conditional formatting to highlight those rows that trigger a match.

I have been using the formula below to match the first three columns, but I am unable to isolate the results it returns to then perform something along the lines of D1<>D2 (if that is even the most efficient way to go about this).

=COUNTIFS($A:A,$A1,$B:B,$B1,$C:C,$C1)>1

Example image - yellow highlight should trigger a match, red should not


问:
Installing Mongodb PHP Drivers on Ubuntu 18.04
I have installed mongodb on a new Ubuntu 18.04 server. I can access and work with the database through the command line, but cannot access it via PHP, and was wondering how other people have gotten it to work.

Following a new build of Ubuntu 18.04, and installation of LAMP, I ran:

sudo apt install mongodb-server php-pear php7.2-dev
sudo pecl install mongodb

I then added the mongodb.so extension to the php.ini file, and a phpinfo(); page shows mongodb as installed. So far so good.

If I browse to a test php page ($mongo=new Mongo();), the page fails to load though.

Through web searches, I find the https://github.com/alcaeus/mongo-php-adapter page come up a lot, and I have run the composer installation command there, but to no avail.

Installed versions are: Ubuntu 18.04.2 LTS; mongoDBv3.6.3; php 7.2.17; Apache 2.4.29

I was wondering what steps other people who have gotten PHP to work successfully with Mongodb have followed? I plan to scrap this server and start from a fresh VM install again.

答:
It appears that you're attempting to use the Mongo class from the legacy driver, but you're using the non-legacy driver so that class doesn't exist. Please look at the documentation for the updated version of the driver here. You might also consider using the MongoDB PHP Library to abstract away many of the driver calls.

Please note that there are also compatibility considerations between your versions of the PHP library, MongoDB, and the MongoDB PHP driver. You can find the compatibility information for them here.


问:
Socket IO works fine on local machine but doesn't work on Heroku
Situation:

I'm building an web app (a SPA) with ReactJS and ExpressJS. I'm using Socket.IO for real-time chatting. When I build my app and run it on localhost, everything works fine so I decide to deploy it on Heroku. My app is built successfully on Heroku and ready to use.

Problem:

So I enter my app to see if it works fine on Heroku. The app seems to be ok when I enter login page and register page (these pages are not going with Socket.IO). But when I go to chat page (this page is using Socket.IO for real-time chatting), the client is crashed, it's not loaded and throw the below error.

Error:

I get this following error:

```<code>> Uncaught TypeError: Cannot read property 'DEBUG' of undefined
    at load (browser.js:168)
    at Object.eval (browser.js:178)
    at eval (browser.js:197)
    at Object../node_modules/socket.io-client/node_modules/debug/src/browser.js (vendor.js:2639)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)
    at eval (url.js:7)
    at Object../node_modules/socket.io-client/lib/url.js (vendor.js:2628)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)
</code>```

When I look at the module online, it has the following check:

```<code>// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = undefined.DEBUG; //the error is showed here
  }
</code>```

So I start my app on localhost and search for above code, I get this:

```<code>// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = { /*A JSON object contains .env variables*/ }.DEBUG;
  }
</code>```

Code:

This is my server:

```<code>//requirements...
const socket = require("./server/socket");

const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 3000;

//middlewares...
//routes...
//database connection...

socket(server);

server.listen(port);
console.log("Server started on: " + port);

</code>```

My socket setup:

```<code>const socketIO = require("socket.io");

const socket = server => {
    const io = socketIO(server);
    const chat = io.of("/chat");

    chat.on("connection", client => {
        console.log("User started chat!");

        client.on("disconnect", () => {
            console.log("User left chat!");
        });

        client.on("sendMessage", msg => {
            const data = msg;
            client.broadcast.emit("incomingMessage", { data });
        });
    });
};

module.exports = socket;
</code>```

React component that using Socket.IO:

```<code>const _ChatBox = ({ props }) => {
    const [connection] = useState(io("/chat"));

    useEffect(() => {
        connection.on("incomingMessage", message => {
            //receive message...
        });
    }, []);

    const sendMessageToSocket = data => {
        connection.emit("sendMessage", data);
    };

    return (
        /* JSX here */
    );
};
</code>```

What I want:

I want to know if there is any problem with my code. When I deploy my app to Heroku, is there any extra setup I have to do on Heroku to make my app working with Socket.IO?

答:
The problem is not in the code you have pasted, or at least I doubt it. If you look at the module online, you see it has the following check:

```<code>    // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
    if (!r && typeof process !== 'undefined' && 'env' in process) {
        r = process.env.DEBUG;
    }
</code>```

You will notice it's reading it off process.env, this is a Node thing / Electron thing. Inside of the console of your client, type window.process, if you get something, that's probably it. It's inspecting process... probably webpack

Body:
Situation:

I'm building an web app (a SPA) with ReactJS and ExpressJS. I'm using Socket.IO for real-time chatting. When I build my app and run it on localhost, everything works fine so I decide to deploy it on Heroku. My app is built successfully on Heroku and ready to use.

Problem:

So I enter my app to see if it works fine on Heroku. The app seems to be ok when I enter login page and register page (these pages are not going with Socket.IO). But when I go to chat page (this page is using Socket.IO for real-time chatting), the client is crashed, it's not loaded and throw the below error.

Error:

I get this following error:

> Uncaught TypeError: Cannot read property 'DEBUG' of undefined
    at load (browser.js:168)
    at Object.eval (browser.js:178)
    at eval (browser.js:197)
    at Object../node_modules/socket.io-client/node_modules/debug/src/browser.js (vendor.js:2639)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)
    at eval (url.js:7)
    at Object../node_modules/socket.io-client/lib/url.js (vendor.js:2628)
    at __webpack_require__ (main.js:788)
    at fn (main.js:151)

When I look at the module online, it has the following check:

// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = undefined.DEBUG; //the error is showed here
  }

So I start my app on localhost and search for above code, I get this:

// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = { /*A JSON object contains .env variables*/ }.DEBUG;
  }

Code:

This is my server:

//requirements...
const socket = require("./server/socket");

const app = express();
const server = http.createServer(app);
const port = process.env.PORT || 3000;

//middlewares...
//routes...
//database connection...

socket(server);

server.listen(port);
console.log("Server started on: " + port);

My socket setup:

const socketIO = require("socket.io");

const socket = server => {
    const io = socketIO(server);
    const chat = io.of("/chat");

    chat.on("connection", client => {
        console.log("User started chat!");

        client.on("disconnect", () => {
            console.log("User left chat!");
        });

        client.on("sendMessage", msg => {
            const data = msg;
            client.broadcast.emit("incomingMessage", { data });
        });
    });
};

module.exports = socket;

React component that using Socket.IO:

const _ChatBox = ({ props }) => {
    const [connection] = useState(io("/chat"));

    useEffect(() => {
        connection.on("incomingMessage", message => {
            //receive message...
        });
    }, []);

    const sendMessageToSocket = data => {
        connection.emit("sendMessage", data);
    };

    return (
        /* JSX here */
    );
};

What I want:

I want to know if there is any problem with my code. When I deploy my app to Heroku, is there any extra setup I have to do on Heroku to make my app working with Socket.IO?

Body:
The problem is not in the code you have pasted, or at least I doubt it. If you look at the module online, you see it has the following check:

    // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
    if (!r && typeof process !== 'undefined' && 'env' in process) {
        r = process.env.DEBUG;
    }

You will notice it's reading it off process.env, this is a Node thing / Electron thing. Inside of the console of your client, type window.process, if you get something, that's probably it. It's inspecting process... probably webpack


问:
QueuePool limit reached for Flask application
I am running an application with Flask and Flask-SQLAlchemy.

```<code>from config import FlaskDatabaseConfig
from flask import Flask
from flask import request
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

application = Flask(__name__)
application.config.from_object(FlaskDatabaseConfig())
db = SQLAlchemy(application)

@application.route("/queue/request", methods=["POST"])
    def handle_queued_request():
        stuff()
        return ""

def stuff():
    # Includes database queries and updates and a call to db.session.commit()
    # db.session.begin() and db.session.close() are not called
    pass

if __name__ == "__main__":
    application.run(debug=False, port=5001)
</code>```

Now, from my understanding, by using Flask-SQLAlchemy I do not need to manage sessions on my own. So why am I getting the following error if I run several requests turn by turn to my endpoint?

```<code>sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30 (Background on this error at: http://sqlalche.me/e/3o7r)
</code>```

I've tried using db.session.close() but then, instead of this error, my database updates are not committed properly. What am I doing incorrectly? Do I need to manually close connections with the database once a request has been handled?

答:
Just remove connection every time you make a query session to db.</p>

```<code>products = db.session.query(Product).limit(20).all()
db.session.remove()
</code>```

Body:
I am running an application with Flask and Flask-SQLAlchemy.

from config import FlaskDatabaseConfig
from flask import Flask
from flask import request
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

application = Flask(__name__)
application.config.from_object(FlaskDatabaseConfig())
db = SQLAlchemy(application)

@application.route("/queue/request", methods=["POST"])
    def handle_queued_request():
        stuff()
        return ""

def stuff():
    # Includes database queries and updates and a call to db.session.commit()
    # db.session.begin() and db.session.close() are not called
    pass

if __name__ == "__main__":
    application.run(debug=False, port=5001)

Now, from my understanding, by using Flask-SQLAlchemy I do not need to manage sessions on my own. So why am I getting the following error if I run several requests turn by turn to my endpoint?

sqlalchemy.exc.TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed out, timeout 30 (Background on this error at: http://sqlalche.me/e/3o7r)

I've tried using db.session.close() but then, instead of this error, my database updates are not committed properly. What am I doing incorrectly? Do I need to manually close connections with the database once a request has been handled?

Body:
Just remove connection every time you make a query session to db.

products = db.session.query(Product).limit(20).all()
db.session.remove()


问:
Use AspectJ aspects in Spring project
I am working on a large Spring Boot application and want to introduce an apsect. As I need "if()" pointcut designators, I need more than Spring AOP. But:
- I don't explicitly define my Aspect as a Spring Aspect, yet it seems to be handled by Spring
-If I define an aspect in a ".js" file, it is not found by the weaver.

I followed the instruction in https://www.baeldung.com/aspectj very closely. Basically I use a runtime weaver plugin for my maven project and register the aspect in an "aop.xml" file.

How can I separate the life cylce of my aspect from Spring?

package myApp;

public aspect MyAspect {

    pointcut prepInFile() :
            execution(public void MySpringBootApp.execute());

    after(): MyMethod() {
        System.out.println("*** I am here ***");
    }

}
```

<pre class="lang-xml prettyprint-override"><code><aspectj>
    <aspects>
        <aspect name="myApp.MyAspect"/>
        <weaver options="-verbose -showWeaveInfo">
            <include within="myApp"/>
        </weaver>
    </aspects>
 </aspectj>
</code>```

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.10</version>
            <configuration>
                <argLine>
                    -javaagent:"${settings.localRepository}"/org/aspectj/
                    aspectjweaver/${aspectj.version}/
                    aspectjweaver-${aspectj.version}.jar
                </argLine>
                <useSystemClassLoader>true</useSystemClassLoader>
                <forkMode>always</forkMode>
            </configuration>
        </plugin>
    </plugins>
</build>
```

答:
First of all, AspectJ source files are not JavaScript, i.e. they don't have a *.js file extension, rather *.aj.

Then, instead of @EnableAspectJAutoProxy (which activates proxy-based Spring AOP) you need to to what is describes in the Spring manual section of AspectJ, e.g. use @EnableLoadTimeWeaving as described in the section about load-time weaving.

Please also note that native syntax AspectJ files need to be compiled by the AspectJ compiler. For that you want to use the AspectJ Maven plugin.

Title: Use AspectJ aspects in Spring project

Body:
I am working on a large Spring Boot application and want to introduce an apsect. As I need "if()" pointcut designators, I need more than Spring AOP. But:
- I don't explicitly define my Aspect as a Spring Aspect, yet it seems to be handled by Spring
-If I define an aspect in a ".js" file, it is not found by the weaver.

I followed the instruction in https://www.baeldung.com/aspectj very closely. Basically I use a runtime weaver plugin for my maven project and register the aspect in an "aop.xml" file.

How can I separate the life cylce of my aspect from Spring?

package myApp;

public aspect MyAspect {

    pointcut prepInFile() :
            execution(public void MySpringBootApp.execute());

    after(): MyMethod() {
        System.out.println("*** I am here ***");
    }

}

<aspectj>
    <aspects>
        <aspect name="myApp.MyAspect"/>
        <weaver options="-verbose -showWeaveInfo">
            <include within="myApp"/>
        </weaver>
    </aspects>
 </aspectj>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.10</version>
            <configuration>
                <argLine>
                    -javaagent:"${settings.localRepository}"/org/aspectj/
                    aspectjweaver/${aspectj.version}/
                    aspectjweaver-${aspectj.version}.jar
                </argLine>
                <useSystemClassLoader>true</useSystemClassLoader>
                <forkMode>always</forkMode>
            </configuration>
        </plugin>
    </plugins>
</build>


问:
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV) when calling cv.saliency_MotionSaliencyBinWangApr2014.computeSaliency( )
I want to use the cv::saliency::MotionSaliencyBinWangApr2014 module. My code is like this:

import cv2

salCV = cv2.saliency.MotionSaliencyBinWangApr2014_create()

frame = cv2.imread(imgfile)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
retval, saliencyMap =   salCV.computeSaliency(grayFrame)
```

<p>But I get error in pycharm like this:</p>

```Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
```

<p>and like this in terminal:</p>

```Segmentation fault (core dumped)
```

What's wrong? How should I use the module cv::saliency::MotionSaliency?
Thanks!

答:
This is due to wrong use of that class（I did not intialize it）.How to use the saliency module can refer to https://www.pyimagesearch.com/2018/07/16/opencv-saliency-detection/.

import cv2

# initialize the detector
saliency = cv2.saliency.MotionSaliencyBinWangApr2014_create()
saliency.setImagesize(frame.shape[1], frame.shape[0])
saliency.init()

# call the detector
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
(success, saliencyMap) = saliency.computeSaliency(gray)
saliencyMap = (saliencyMap * 255).astype("uint8")
```

Body:
I want to use the cv::saliency::MotionSaliencyBinWangApr2014 module. My code is like this:

import cv2

salCV = cv2.saliency.MotionSaliencyBinWangApr2014_create()

frame = cv2.imread(imgfile)
grayFrame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
retval, saliencyMap =   salCV.computeSaliency(grayFrame)

But I get error in pycharm like this:

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

and like this in terminal:

Segmentation fault (core dumped)

What's wrong? How should I use the module cv::saliency::MotionSaliency?
Thanks!


问:
Is it necessary to create a Java class everytime?
I am starting to learn the Java programming language and I am a little confused.

I would like to create a simple program like adding two numbers or calculate the sum of n numbers. I can do this in C or Python easily, but in Java, I have to create a class for my program and then create a main class and call my program from it.

I use both Netbeans and IntelliJ.

Can I just create the program directly the way I do it in other languages? I mean is the concept of a class necessary in Java?

答:
I know this is an old question but I think the question is important to clarify something. Let's see this definitions:

Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible.

C is a general-purpose, imperative computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations.

Python is an interpreted, high-level, general-purpose programming language. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.

Teo. what is a programming paradigm?

Well my young Padawan, a programming paradigm it is a style of programming, or just a way of thinking about software construction. This concept does not refer to a specific language, but rather to a way to program, a methodology.

Now let’s dive into the programming paradigms that we found on this definitions:

C supports Structured programming (SP). SP sometimes known as modular programming, this is a technique devised to improve the reliability and clarity of programs. In SP, the program flow control is restricted to three structures (i.e., sequences, selection [IF/THEN/ELSE], and repetitions [FOR/WHILE]), or to a structure derivable from a combination of those. The result is a program built of modules that are highly independent of each other. This enforces a logical structure on the program being written to make it more efficient and easier to understand and modify.

Python supports Procedural Programming (PP). PP is a programming paradigm, derived from SP, based upon the concept of the procedure call. A procedure call is a simple statement made by stating the procedure name, and listing actual parameter names or values within parentheses. So this paradigm is about writing a list of instructions to tell the computer what to do step by step. It relies on procedures, witch simply contain a series of computational steps to be carried out.

Java only supports object-oriented programming (OOP). This main focus is about encapsulating data and behavior into objects. An OOP application will use a collection of objects which knows how to perform certain actions and how to interact with other elements of the application. For instance, an object could be a person. That person would have a name (that would be a property of the object), and would know how to walk (that would be a method). A method in OOP can be considered as a procedure in PP, but here it belongs to a specific object. Another important aspect of OOP are classes. A class can be considered as a blueprint for an object.

What this means?

As this simple definition says, Java is a class-based and object-oriented programming language. So when the user asked: "Can I just create the program directly the way I do it in other languages?", the answer is NO, because it is not part of the definition of the language.

Why can C and Python do that?

Well, it is because *C and Python support non-member functions, while Java supports only member functions.

What is the difference between a member function and a non-member function?

Basically, a non-member function always is defined out of a class. While a member function must defined as part of a class. This is to identify that that function is a member of a particular class. Another difference between member functions and non-member functions is how they are called (or invoked).
To call a member function you need a class object to get access to the function, but non-member functions can be invoked directly.

TL;DR

Java needs a class to define a member function like main() because it only supports OOP. So, if you want a very minimal program, you can create a class with a main() method. Consider the following segment of code:

public class MainClass {
    public static void main(String[] args)  {
        System.out.print("Hello World!");
    }
}
```
<p>This is the equivalent in C:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int main()
{
   printf("Hello, World!");
   return 0;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I know this is an old question but I think the question is important to clarify something. Let's see this definitions:

Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible.

C is a general-purpose, imperative computer programming language supporting structured programming, lexical variable scope, and recursion, while a static type system prevents unintended operations.

Python is an interpreted, high-level, general-purpose programming language. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming.

Teo. what is a programming paradigm?

Well my young Padawan, a programming paradigm it is a style of programming, or just a way of thinking about software construction. This concept does not refer to a specific language, but rather to a way to program, a methodology.

Now let’s dive into the programming paradigms that we found on this definitions:

C supports Structured programming (SP). SP sometimes known as modular programming, this is a technique devised to improve the reliability and clarity of programs. In SP, the program flow control is restricted to three structures (i.e., sequences, selection [IF/THEN/ELSE], and repetitions [FOR/WHILE]), or to a structure derivable from a combination of those. The result is a program built of modules that are highly independent of each other. This enforces a logical structure on the program being written to make it more efficient and easier to understand and modify.

Python supports Procedural Programming (PP). PP is a programming paradigm, derived from SP, based upon the concept of the procedure call. A procedure call is a simple statement made by stating the procedure name, and listing actual parameter names or values within parentheses. So this paradigm is about writing a list of instructions to tell the computer what to do step by step. It relies on procedures, witch simply contain a series of computational steps to be carried out.

Java only supports object-oriented programming (OOP). This main focus is about encapsulating data and behavior into objects. An OOP application will use a collection of objects which knows how to perform certain actions and how to interact with other elements of the application. For instance, an object could be a person. That person would have a name (that would be a property of the object), and would know how to walk (that would be a method). A method in OOP can be considered as a procedure in PP, but here it belongs to a specific object. Another important aspect of OOP are classes. A class can be considered as a blueprint for an object.

What this means?

As this simple definition says, Java is a class-based and object-oriented programming language. So when the user asked: "Can I just create the program directly the way I do it in other languages?", the answer is NO, because it is not part of the definition of the language.

Why can C and Python do that?

Well, it is because *C and Python support non-member functions, while Java supports only member functions.

What is the difference between a member function and a non-member function?

Basically, a non-member function always is defined out of a class. While a member function must defined as part of a class. This is to identify that that function is a member of a particular class. Another difference between member functions and non-member functions is how they are called (or invoked).
To call a member function you need a class object to get access to the function, but non-member functions can be invoked directly.

TL;DR

Java needs a class to define a member function like main() because it only supports OOP. So, if you want a very minimal program, you can create a class with a main() method. Consider the following segment of code:

public class MainClass {
    public static void main(String[] args)  {
        System.out.print("Hello World!");
    }
}

This is the equivalent in C:

#include <stdio.h>
int main()
{
   printf("Hello, World!");
   return 0;
}


问:
Access azure file storage from web app without a backend
Is there a way to access azure storage via Rest Api, using only frontend javascript?

e.g:

User tries to load an image stored in azure storage .

Redirected to portal.azure.com for logging in.

Sent back to my webapp, with the cookies or whatever is needed to generate an authenticated url.

答:
You can authenticate access to Azure blobs using Azure Active Directory.

Then you will be able to get an access token to access azure storage via Rest Api. Here is an example walks you through how to login a user and acquire a token to be used for Microsoft's Graph Api. You can change the Graph Api to storage api.

Updates:

The way to get access token. The scope can be https://storage.azure.com/.default

Access private blob with access token. You also need to add the x-ms-version header.


问:
Create new columns based on other's columns value
I'm trying to do some feature engineering for a pandas data frame.

Say I have this:

```<code>Data frame 1:
X |  date     | is_holiday
a |  1/4/2018 | 0
a |  1/5/2018 | 0
a |  1/6/2018 | 1
a |  1/7/2018 | 0
a |  1/8/2018 | 0
...
b |  1/1/2018 | 1
</code>```

I'd like to have an additional indicator for some dates, to indicate if the date is before 1 and 2 days from a holiday, and also 1 and 2 days after.

```<code>Data frame 1:
X |  date     | is_holiday | one_day_before_hol | ... | one_day_after_hol
a |  1/4/2018 | 0          | 0                  | ... | 0
a |  1/5/2018 | 0          | 1                  | ... | 0
a |  1/6/2018 | 1          | 0                  | ... | 0
a |  1/7/2018 | 0          | 0                  | ... | 1
a |  1/8/2018 | 0          | 0                  | ... | 0
...
b |  1/1/2018 | 1          | 0                  | ... | 0
</code>```

Is there any efficient way to do it? I believe I can do it using for statements, but since I'm new to python, I'd like to see if there is an elegant way to do it. Dates might not be adjacent or continuos (i.e. for some of the X columns, a specific date might not be present)

Thank you so much!

答:
Use pandas.DataFrame.groupby.shift:

```<code>import pandas as pd

g = df.groupby('X')['is_holiday']
df['one_day_before'] = g.shift(-1).fillna(0)
df['two_day_before'] = g.shift(-2).fillna(0)
df['one_day_after'] = g.shift(1).fillna(0)
</code>```

Output:

```<code>   X      date  is_holiday  one_day_before  two_day_before  one_day_after
0  a  1/4/2018           0             0.0             1.0            0.0
1  a  1/5/2018           0             1.0             0.0            0.0
2  a  1/6/2018           1             0.0             0.0            0.0
3  a  1/7/2018           0             0.0             0.0            1.0
4  a  1/8/2018           0             0.0             0.0            0.0
5  b  1/1/2018           1             0.0             0.0            0.0
</code>```

Body:
I'm trying to do some feature engineering for a pandas data frame.

Say I have this:

Data frame 1:
X |  date     | is_holiday
a |  1/4/2018 | 0
a |  1/5/2018 | 0
a |  1/6/2018 | 1
a |  1/7/2018 | 0
a |  1/8/2018 | 0
...
b |  1/1/2018 | 1

I'd like to have an additional indicator for some dates, to indicate if the date is before 1 and 2 days from a holiday, and also 1 and 2 days after.

Data frame 1:
X |  date     | is_holiday | one_day_before_hol | ... | one_day_after_hol
a |  1/4/2018 | 0          | 0                  | ... | 0
a |  1/5/2018 | 0          | 1                  | ... | 0
a |  1/6/2018 | 1          | 0                  | ... | 0
a |  1/7/2018 | 0          | 0                  | ... | 1
a |  1/8/2018 | 0          | 0                  | ... | 0
...
b |  1/1/2018 | 1          | 0                  | ... | 0

Is there any efficient way to do it? I believe I can do it using for statements, but since I'm new to python, I'd like to see if there is an elegant way to do it. Dates might not be adjacent or continuos (i.e. for some of the X columns, a specific date might not be present)

Thank you so much!

Body:
Use pandas.DataFrame.groupby.shift:

import pandas as pd

g = df.groupby('X')['is_holiday']
df['one_day_before'] = g.shift(-1).fillna(0)
df['two_day_before'] = g.shift(-2).fillna(0)
df['one_day_after'] = g.shift(1).fillna(0)

Output:

   X      date  is_holiday  one_day_before  two_day_before  one_day_after
0  a  1/4/2018           0             0.0             1.0            0.0
1  a  1/5/2018           0             1.0             0.0            0.0
2  a  1/6/2018           1             0.0             0.0            0.0
3  a  1/7/2018           0             0.0             0.0            1.0
4  a  1/8/2018           0             0.0             0.0            0.0
5  b  1/1/2018           1             0.0             0.0            0.0


问:
Is there a way to not create a new user and only allow existing users to login with firebase_auth, google sign in?
I would like my app to only authenticate previously logged in users and not create new users. I'm using flutter and Firebase Authentication. I'm using google as a sign in method.

Ive searched the internet for a solution with no such luck. All of the examples i see create new users in the process

```<code>void _signInWithGoogle() async {
  final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
  final GoogleSignInAuthentication googleAuth =
      await googleUser.authentication;
  final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );
  final FirebaseUser user = await _auth.signInWithCredential(credential);

  assert(user.email != null);
  assert(user.displayName != null);
  assert(!user.isAnonymous);
  assert(await user.getIdToken() != null);

  final FirebaseUser currentUser = await _auth.currentUser();
  assert(user.uid == currentUser.uid);
  setState(() {
    if (user != null) {
      _success = true;
      _userID = user.uid;
      print(user.displayName);
      print(user.phoneNumber);
      print(user.email);
    } else {
      _success = false;
    }
  });
}
</code>```

I expected this to fail when there was a new user trying to login. but this seems to create a user and then log him in.

答:
There is no way to prevent a user from signing in with Firebase Authentication. If the provider is enabled, users can sign in with that provider.

But them signing in does nothing more than prove their credentials. If I sign in to your app with a Google account, all it does is proving that I know the credentials of that Google account.

Whether you grant a user access to certain resources (known as authorization) is a completely separate process, and is up to your application. For example, if you're using the Firebase Realtime Database, or Cloud Firestore to store data, then you can control who can access this data with their server-side security rules. And in those security rules, you can ensure that only users you know have access to the data.

For example, see my answer here for how to limit access to the realtime database to users signing in with a verified email address from a specific domain: How do I lock down Firebase Database to any user from a specific (email) domain?

This question might also be handy, as it shows how to maintain a list of allowed email addresses that can access data in Cloud Firestore: Prevent user account creation with sign in by email in firestore.

Body:
I would like my app to only authenticate previously logged in users and not create new users. I'm using flutter and Firebase Authentication. I'm using google as a sign in method.

Ive searched the internet for a solution with no such luck. All of the examples i see create new users in the process

void _signInWithGoogle() async {
  final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
  final GoogleSignInAuthentication googleAuth =
      await googleUser.authentication;
  final AuthCredential credential = GoogleAuthProvider.getCredential(
    accessToken: googleAuth.accessToken,
    idToken: googleAuth.idToken,
  );
  final FirebaseUser user = await _auth.signInWithCredential(credential);

  assert(user.email != null);
  assert(user.displayName != null);
  assert(!user.isAnonymous);
  assert(await user.getIdToken() != null);

  final FirebaseUser currentUser = await _auth.currentUser();
  assert(user.uid == currentUser.uid);
  setState(() {
    if (user != null) {
      _success = true;
      _userID = user.uid;
      print(user.displayName);
      print(user.phoneNumber);
      print(user.email);
    } else {
      _success = false;
    }
  });
}

I expected this to fail when there was a new user trying to login. but this seems to create a user and then log him in.


问:
Data manipulation in D3.js
I have the following data:

```<code>var data = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"B", Var:"45", Temp:"40",Lo:"F"},
  {Name:"B", Var:"63", Temp:"340",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"B", Var:"405", Temp:"940",Lo:"F"},
  {Name:"B", Var:"415", Temp:"410",Lo:"T"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"C", Var:"43", Temp:"40",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]
</code>```

I filter the data to get

```<code>dataFiltered = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]
</code>```

But I want to have a new array of objects like:

```<code>dataNew = [
  {Vt:"35", Tv:"5"},
  {Vt:"865", Tv:"35"},
  {Vt:"75", Tv:"27"},
  {Vt:"80", Tv:"-1"}
]
</code>```

Finally I want to use dataNew to present the aggregated data for Vt (35+865+75+80) and Tv (5+35+27-1) on a pie chart.

Note Vt = Var + Temp and Tv = Temp - Var from dataFiltered.

I really do not know what to do after filtering the data and in particular how to get dataNew.

I leave the code for the filtering part here as well.

```<code>var filteredData = data.filter(function(d) {
    return d.Name == "A";
});
</code>```

答:
You can get all the output you need in one iteration over the original data using Array.reduce() to generate an object with the new array of data and the accumulated values for Vt and Tv, example:

var data = [
  {Name:"A", Var:"15", Temp:"20", Lo:"T"},
  {Name:"B", Var:"45", Temp:"40", Lo:"F"},
  {Name:"B", Var:"63", Temp:"340", Lo:"T"},
  {Name:"A", Var:"415", Temp:"450", Lo:"F"},
  {Name:"B", Var:"405", Temp:"940", Lo:"F"},
  {Name:"B", Var:"415", Temp:"410", Lo:"T"},
  {Name:"A", Var:"24", Temp:"51", Lo:"T"},
  {Name:"C", Var:"43", Temp:"40", Lo:"T"},
  {Name:"A", Var:"41", Temp:"40", Lo:"F"}
];

function reduceData(data, type)
{
    return data.reduce((acc, {Name, Var, Temp}) =>
    {
        if (Name !== type)
            return acc;

        let Vt = (+Var) + (+Temp), Tv = Temp - Var;
        let len = acc.newData.push({Vt, Tv});
        acc.acc_vt += Vt;
        acc.acc_tv += Tv;
        acc.avg_tv = (acc.avg_tv * (len-1) + Tv) / len;
        acc.avg_vt = (acc.avg_vt * (len-1) + Vt) / len;
        return acc;

    }, {newData: [], acc_vt: 0, acc_tv: 0, avg_vt: 0, avg_tv: 0})
}

console.log(reduceData(data, "A"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Title: Data manipulation in D3.js

Body:
I have the following data:

var data = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"B", Var:"45", Temp:"40",Lo:"F"},
  {Name:"B", Var:"63", Temp:"340",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"B", Var:"405", Temp:"940",Lo:"F"},
  {Name:"B", Var:"415", Temp:"410",Lo:"T"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"C", Var:"43", Temp:"40",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]

I filter the data to get

dataFiltered = [
  {Name:"A", Var:"15", Temp:"20",Lo:"T"},
  {Name:"A", Var:"415", Temp:"450",Lo:"F"},
  {Name:"A", Var:"24", Temp:"51",Lo:"T"},
  {Name:"A", Var:"41", Temp:"40",Lo:"F"}
]

But I want to have a new array of objects like:

dataNew = [
  {Vt:"35", Tv:"5"},
  {Vt:"865", Tv:"35"},
  {Vt:"75", Tv:"27"},
  {Vt:"80", Tv:"-1"}
]

Finally I want to use dataNew to present the aggregated data for Vt (35+865+75+80) and Tv (5+35+27-1) on a pie chart.

Note Vt = Var + Temp and Tv = Temp - Var from dataFiltered.

I really do not know what to do after filtering the data and in particular how to get dataNew.

I leave the code for the filtering part here as well.

var filteredData = data.filter(function(d) {
    return d.Name == "A";
});

Body:
You can get all the output you need in one iteration over the original data using Array.reduce() to generate an object with the new array of data and the accumulated values for Vt and Tv, example:

var data = [
  {Name:"A", Var:"15", Temp:"20", Lo:"T"},
  {Name:"B", Var:"45", Temp:"40", Lo:"F"},
  {Name:"B", Var:"63", Temp:"340", Lo:"T"},
  {Name:"A", Var:"415", Temp:"450", Lo:"F"},
  {Name:"B", Var:"405", Temp:"940", Lo:"F"},
  {Name:"B", Var:"415", Temp:"410", Lo:"T"},
  {Name:"A", Var:"24", Temp:"51", Lo:"T"},
  {Name:"C", Var:"43", Temp:"40", Lo:"T"},
  {Name:"A", Var:"41", Temp:"40", Lo:"F"}
];

function reduceData(data, type)
{
    return data.reduce((acc, {Name, Var, Temp}) =>
    {
        if (Name !== type)
            return acc;

        let Vt = (+Var) + (+Temp), Tv = Temp - Var;
        let len = acc.newData.push({Vt, Tv});
        acc.acc_vt += Vt;
        acc.acc_tv += Tv;
        acc.avg_tv = (acc.avg_tv * (len-1) + Tv) / len;
        acc.avg_vt = (acc.avg_vt * (len-1) + Vt) / len;
        return acc;

    }, {newData: [], acc_vt: 0, acc_tv: 0, avg_vt: 0, avg_tv: 0})
}

console.log(reduceData(data, "A"));

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


问:
Any way to get the user's UPN from an email sent to a Shared mailbox?
I have a Logic App that monitors a shared mailbox for emails subscribing to a service.

However, in our tenant the email addresses don't always match the User Principal Name.

Is there a way to get the UPN for somebody from their email address in a Logic App?

Thanks.

答: The Office 365 Users connector has an action:Get user profile (V2), you could use email id to get a GraphUser_V1 body, in the body it includes the User Principal Name(UPN).


问:
How do you enable newline seperation when writing multiple strings at once in Python 3?
I have an incredibly basic Python 3 program that works fine. All it does is take from user input a string and a number. It then prints the string that number of times.

```<code>program1 = 25
print("[Type anything!]")
while program1 == 25:
        pcmd = input()
        amount = input("How many lines?: ")
        if amount.isnumeric():
            print(pcmd * int(amount))
        elif pcmd or amount == "exit":
            exit()
        else:
            print("Invalid amount")
</code>```

The thing is, whenever I run it and put in a string and amount, it prints all those strings next to each other.

Before, when I had statically defined strings, I could just use '\n' to make a newline. How can I do the same thing in this case?

答:
There are a few ways to do this.

The simplest is to add a newline to the end of each string, like so:

```<code>print((pcmd + '\n') * int(amount))
</code>```

You could use f-strings (Python >= 3.6 only) to achieve the same result:

```<code>print(f'{pcmd}\n' * int(amount))
</code>```

You could use a for loop, since Python, by default, inserts a newline after every print call:

```<code>for i in range(int(amount)):
    print(pcmd)
</code>```

You could collect the pcmd copies in a list and use unpacking, along with specifying a newline separator (though I don't recommend this - wasteful):

```<code>pcmd_copies = [pcmd for i in range(int(amount))]

print(*pcmd_copies, sep='\n')
</code>```

Body:
I have an incredibly basic Python 3 program that works fine. All it does is take from user input a string and a number. It then prints the string that number of times.

program1 = 25
print("[Type anything!]")
while program1 == 25:
        pcmd = input()
        amount = input("How many lines?: ")
        if amount.isnumeric():
            print(pcmd * int(amount))
        elif pcmd or amount == "exit":
            exit()
        else:
            print("Invalid amount")

The thing is, whenever I run it and put in a string and amount, it prints all those strings next to each other.

Before, when I had statically defined strings, I could just use '\n' to make a newline. How can I do the same thing in this case?

Body:
There are a few ways to do this.

The simplest is to add a newline to the end of each string, like so:

print((pcmd + '\n') * int(amount))

You could use f-strings (Python >= 3.6 only) to achieve the same result:

print(f'{pcmd}\n' * int(amount))

You could use a for loop, since Python, by default, inserts a newline after every print call:

for i in range(int(amount)):
    print(pcmd)

You could collect the pcmd copies in a list and use unpacking, along with specifying a newline separator (though I don't recommend this - wasteful):

pcmd_copies = [pcmd for i in range(int(amount))]

print(*pcmd_copies, sep='\n')


问:
Run tasks in background in NativeScript
I am using NativeScript 2.0 and I am developing an Android module that is NOT allowed to be run in the main thread!

Is there a module that I can use to run a function in a background thread?

Or is it possible to use something like AsyncTask class in "native" JavaScript code (NOT TypeScript!)?

答:
As evidenced by Nativescript demo App single-threaded model is just fine as running everything on the UI thread is super fast. But still if you need background task in case of time taking operation, Nativescript introduced Workers API.

We know that as Web Workers in Web world. It's important to keep in mind that every time you spin up a new worker thread, you are adding to the resource and memory footprint of your app.

For further reading you can refer to this blog.

Title: Run tasks in background in NativeScript