问:
How I can exclude NA from a density ggplot2 plot?
I have to create a density plot with Yes/No data of antiepileptic therapy by length of hospital stay..
I'm trying to remove NA from my ggplot2 density plot, but it doesn't work nd i don't understand why...

How can I fix it?

Thank you!

Here are my variables:

```<code>db$deg
  [1] NA  7 NA  0  0 NA  0 NA  0  0 NA  0  0  0  0  6 25 NA
 [19] NA  0  0 NA NA  0 NA  1  3 NA  0  5 NA  3 NA 15  0 NA
 [37]  0  0 NA  0  0  0 NA  0  0 12 NA 10  0  0 NA  0  0  0
 [55] 15  0  0  0  0  0  0 NA NA  3  0  8 NA  0  2  4  9 NA
 [73]  0  0  0  0  0  0  0  0 23  0  0  0  0  0  9  5 NA  0
 [91]  5  0  0  0  5 NA NA  0  0  0  0  0  0 NA  0 NA  0  0
[109]  0  0 NA 19  0  0  0  0 NA NA NA NA 11  0  0  3  0  7
[127] NA  0  0 NA NA  0  0  0  0  0 NA NA  2  2  0 NA  0  0
[145]  0  0 NA NA  9  5 NA  0  2 28 15  0  0 NA  0 20 NA 16
[163]  0 NA  3 NA  0  0  0  0 NA NA  0  0  0  1 NA  0  4 NA
[181] NA  0 NA NA  0  0  0  3  0  5  1  0  7  3  0  4  0  0
[199]  0  0  0  0  0  0  0  0  0  0  0  0  0 12  0  0  0 14
[217]  0  0  0  0  0  0  0  0  0  7  1  0  6  0 21  1  0  0
[235]  0  0  0  0  0  3  0  5  0  0  0  0  0 15 17  1  0  5
[253]  0  0  0 15  0  0  9  0  0  0  0  9  0  0  5  0  0  0

db$Antiepileptic
  [1] <NA> No   <NA> No   No   <NA> No   <NA> No   No
 [11] <NA> <NA> No   No   No   No   No   <NA> <NA> No
 [21] No   <NA> <NA> No   <NA> No   No   <NA> No   No
 [31] <NA> No   <NA> No   No   <NA> No   No   <NA> No
 [41] No   No   <NA> <NA> No   No   <NA> No   No   No
 [51] <NA> No   No   <NA> No   No   No   <NA> No   <NA>
 [61] No   <NA> <NA> No   No   No   <NA> No   No   No
 [71] No   <NA> No   No   No   No   No   No   No   No
 [81] No   No   No   No   No   No   No   No   <NA> No
 [91] No   No   No   No   No   <NA> <NA> No   No   No
[101] No   No   No   <NA> No   <NA> No   No   No   No
[111] <NA> No   No   No   No   No   <NA> <NA> <NA> <NA>
[121] No   No   No   No   No   No   <NA> No   Yes  <NA>
[131] <NA> No   No   No   No   Yes  <NA> <NA> No   No
[141] No   <NA> No   No   No   No   <NA> <NA> No   No
[151] <NA> No   No   No   No   No   No   <NA> No   No
[161] <NA> No   No   <NA> No   <NA> No   No   No   No
[171] <NA> <NA> No   No   No   No   <NA> No   No   <NA>
[181] <NA> No   <NA> <NA> No   No   No   No   No   No
[191] No   No   No   No   No   No   No   No   No   No
[201] No   No   No   No   No   No   No   No   No   No
[211] No   No   No   No   No   No   No   No   No   No
[221] No   No   No   No   No   No   No   No   No   Yes
[231] No   No   No   No   No   No   No   No   No   No
[241] No   No   No   No   No   No   No   No   No   No
[251] No   No   No   Yes  Yes  No   No   No   No   No
[261] No   No   No   No   Yes  No   No   No   No   No
</code>```

Here's my code:

```<code>p8 <- ggplot(db, aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  geom_density(position="identity", alpha=0.6, na.rm = TRUE) +
  scale_x_continuous(name = "Hospitalization",
                     breaks = seq(0, 31, 5),
                     limits=c(0, 31)) +
  scale_y_continuous(name = "Density") +
  ggtitle("Hospitalization by Antiepileptic therapy") +
  theme_bw() +
  theme(plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
        text = element_text(size = 12, family = "Tahoma")) +
  scale_fill_brewer(palette="Accent")
p8
</code>```

here's my plot:

答:
Drop NA before you go into ggplot.  You can either drop only Antiepileptic cases with

```<code>db %>%
  filter(!is.na(Antiepileptic)) %>%
  ggplot(aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  ...
</code>```

Or drop all rows with NA using complete.cases():

```<code>db %>%
  filter(complete.cases(.)) %>%
  ggplot(db, aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  ...
</code>```

Here's your code with NA dropped from Antiepileptic.  Data as dput provided at the end.

```<code>library(tidyverse)

df %>%
  filter(!is.na(Antiepileptic)) %>%
  ggplot(aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  geom_density(position="identity", alpha=0.6, na.rm = TRUE) +
  scale_x_continuous(name = "Hospitalization",
                     breaks = seq(0, 31, 5),
                     limits=c(0, 31)) +
  scale_y_continuous(name = "Density") +
  ggtitle("Hospitalization by Antiepileptic therapy") +
  theme_bw() +
  theme(plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
        text = element_text(size = 12, family = "Tahoma")) +
  scale_fill_brewer(palette="Accent")
</code>```

Data:

```<code>structure(list(deg = c(NA, 7, NA, 0, 0, NA, 0, NA, 0, 0, NA,
0, 0, 0, 0, 6, 25, NA, NA, 0, 0, NA, NA, 0, NA, 1, 3, NA, 0,
5, NA, 3, NA, 15, 0, NA, 0, 0, NA, 0, 0, 0, NA, 0, 0, 12, NA,
10, 0, 0, NA, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, NA, NA, 3, 0, 8,
NA, 0, 2, 4, 9, NA, 0, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0,
9, 5, NA, 0, 5, 0, 0, 0, 5, NA, NA, 0, 0, 0, 0, 0, 0, NA, 0,
NA, 0, 0, 0, 0, NA, 19, 0, 0, 0, 0, NA, NA, NA, NA, 11, 0, 0,
3, 0, 7, NA, 0, 0, NA, NA, 0, 0, 0, 0, 0, NA, NA, 2, 2, 0, NA,
0, 0, 0, 0, NA, NA, 9, 5, NA, 0, 2, 28, 15, 0, 0, NA, 0, 20,
NA, 16, 0, NA, 3, NA, 0, 0, 0, 0, NA, NA, 0, 0, 0, 1, NA, 0,
4, NA, NA, 0, NA, NA, 0, 0, 0, 3, 0, 5, 1, 0, 7, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 14, 0,
0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 0, 6, 0, 21, 1, 0, 0, 0, 0, 0,
0, 0, 3, 0, 5, 0, 0, 0, 0, 0, 15, 17, 1, 0, 5, 0, 0, 0, 15, 0,
0, 9, 0, 0, 0, 0, 9, 0, 0, 5, 0, 0, 0), Antiepileptic = c(NA,
"No", NA, "No", "No", NA, "No", NA, "No", "No", NA, NA, "No",
"No", "No", "No", "No", NA, NA, "No", "No", NA, NA, "No", NA,
"No", "No", NA, "No", "No", NA, "No", NA, "No", "No", NA, "No",
"No", NA, "No", "No", "No", NA, NA, "No", "No", NA, "No", "No",
"No", NA, "No", "No", NA, "No", "No", "No", NA, "No", NA, "No",
NA, NA, "No", "No", "No", NA, "No", "No", "No", "No", NA, "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", NA, "No", "No", "No", "No", "No", "No",
NA, NA, "No", "No", "No", "No", "No", "No", NA, "No", NA, "No",
"No", "No", "No", NA, "No", "No", "No", "No", "No", NA, NA, NA,
NA, "No", "No", "No", "No", "No", "No", NA, "No", "Yes", NA,
NA, "No", "No", "No", "No", "Yes", NA, NA, "No", "No", "No",
NA, "No", "No", "No", "No", NA, NA, "No", "No", NA, "No", "No",
"No", "No", "No", "No", NA, "No", "No", NA, "No", "No", NA, "No",
NA, "No", "No", "No", "No", NA, NA, "No", "No", "No", "No", NA,
"No", "No", NA, NA, "No", NA, NA, "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "Yes", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "Yes",
"Yes", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"Yes", "No", "No", "No", "No", "No")), row.names = c(NA, -270L
), class = c("tbl_df", "tbl", "data.frame"))
</code>```

Body:
I have to create a density plot with Yes/No data of antiepileptic therapy by length of hospital stay..
I'm trying to remove NA from my ggplot2 density plot, but it doesn't work nd i don't understand why...

How can I fix it?

Thank you!

Here are my variables:

db$deg
  [1] NA  7 NA  0  0 NA  0 NA  0  0 NA  0  0  0  0  6 25 NA
 [19] NA  0  0 NA NA  0 NA  1  3 NA  0  5 NA  3 NA 15  0 NA
 [37]  0  0 NA  0  0  0 NA  0  0 12 NA 10  0  0 NA  0  0  0
 [55] 15  0  0  0  0  0  0 NA NA  3  0  8 NA  0  2  4  9 NA
 [73]  0  0  0  0  0  0  0  0 23  0  0  0  0  0  9  5 NA  0
 [91]  5  0  0  0  5 NA NA  0  0  0  0  0  0 NA  0 NA  0  0
[109]  0  0 NA 19  0  0  0  0 NA NA NA NA 11  0  0  3  0  7
[127] NA  0  0 NA NA  0  0  0  0  0 NA NA  2  2  0 NA  0  0
[145]  0  0 NA NA  9  5 NA  0  2 28 15  0  0 NA  0 20 NA 16
[163]  0 NA  3 NA  0  0  0  0 NA NA  0  0  0  1 NA  0  4 NA
[181] NA  0 NA NA  0  0  0  3  0  5  1  0  7  3  0  4  0  0
[199]  0  0  0  0  0  0  0  0  0  0  0  0  0 12  0  0  0 14
[217]  0  0  0  0  0  0  0  0  0  7  1  0  6  0 21  1  0  0
[235]  0  0  0  0  0  3  0  5  0  0  0  0  0 15 17  1  0  5
[253]  0  0  0 15  0  0  9  0  0  0  0  9  0  0  5  0  0  0

db$Antiepileptic
  [1] <NA> No   <NA> No   No   <NA> No   <NA> No   No
 [11] <NA> <NA> No   No   No   No   No   <NA> <NA> No
 [21] No   <NA> <NA> No   <NA> No   No   <NA> No   No
 [31] <NA> No   <NA> No   No   <NA> No   No   <NA> No
 [41] No   No   <NA> <NA> No   No   <NA> No   No   No
 [51] <NA> No   No   <NA> No   No   No   <NA> No   <NA>
 [61] No   <NA> <NA> No   No   No   <NA> No   No   No
 [71] No   <NA> No   No   No   No   No   No   No   No
 [81] No   No   No   No   No   No   No   No   <NA> No
 [91] No   No   No   No   No   <NA> <NA> No   No   No
[101] No   No   No   <NA> No   <NA> No   No   No   No
[111] <NA> No   No   No   No   No   <NA> <NA> <NA> <NA>
[121] No   No   No   No   No   No   <NA> No   Yes  <NA>
[131] <NA> No   No   No   No   Yes  <NA> <NA> No   No
[141] No   <NA> No   No   No   No   <NA> <NA> No   No
[151] <NA> No   No   No   No   No   No   <NA> No   No
[161] <NA> No   No   <NA> No   <NA> No   No   No   No
[171] <NA> <NA> No   No   No   No   <NA> No   No   <NA>
[181] <NA> No   <NA> <NA> No   No   No   No   No   No
[191] No   No   No   No   No   No   No   No   No   No
[201] No   No   No   No   No   No   No   No   No   No
[211] No   No   No   No   No   No   No   No   No   No
[221] No   No   No   No   No   No   No   No   No   Yes
[231] No   No   No   No   No   No   No   No   No   No
[241] No   No   No   No   No   No   No   No   No   No
[251] No   No   No   Yes  Yes  No   No   No   No   No
[261] No   No   No   No   Yes  No   No   No   No   No

Here's my code:

p8 <- ggplot(db, aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  geom_density(position="identity", alpha=0.6, na.rm = TRUE) +
  scale_x_continuous(name = "Hospitalization",
                     breaks = seq(0, 31, 5),
                     limits=c(0, 31)) +
  scale_y_continuous(name = "Density") +
  ggtitle("Hospitalization by Antiepileptic therapy") +
  theme_bw() +
  theme(plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
        text = element_text(size = 12, family = "Tahoma")) +
  scale_fill_brewer(palette="Accent")
p8

here's my plot:

Body:
Drop NA before you go into ggplot.  You can either drop only Antiepileptic cases with

db %>%
  filter(!is.na(Antiepileptic)) %>%
  ggplot(aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  ...

Or drop all rows with NA using complete.cases():

db %>%
  filter(complete.cases(.)) %>%
  ggplot(db, aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  ...

Here's your code with NA dropped from Antiepileptic.  Data as dput provided at the end.

library(tidyverse)

df %>%
  filter(!is.na(Antiepileptic)) %>%
  ggplot(aes(x = deg, fill = Antiepileptic, na.rm = TRUE)) +
  geom_density(position="identity", alpha=0.6, na.rm = TRUE) +
  scale_x_continuous(name = "Hospitalization",
                     breaks = seq(0, 31, 5),
                     limits=c(0, 31)) +
  scale_y_continuous(name = "Density") +
  ggtitle("Hospitalization by Antiepileptic therapy") +
  theme_bw() +
  theme(plot.title = element_text(size = 14, family = "Tahoma", face = "bold"),
        text = element_text(size = 12, family = "Tahoma")) +
  scale_fill_brewer(palette="Accent")

Data:

structure(list(deg = c(NA, 7, NA, 0, 0, NA, 0, NA, 0, 0, NA,
0, 0, 0, 0, 6, 25, NA, NA, 0, 0, NA, NA, 0, NA, 1, 3, NA, 0,
5, NA, 3, NA, 15, 0, NA, 0, 0, NA, 0, 0, 0, NA, 0, 0, 12, NA,
10, 0, 0, NA, 0, 0, 0, 15, 0, 0, 0, 0, 0, 0, NA, NA, 3, 0, 8,
NA, 0, 2, 4, 9, NA, 0, 0, 0, 0, 0, 0, 0, 0, 23, 0, 0, 0, 0, 0,
9, 5, NA, 0, 5, 0, 0, 0, 5, NA, NA, 0, 0, 0, 0, 0, 0, NA, 0,
NA, 0, 0, 0, 0, NA, 19, 0, 0, 0, 0, NA, NA, NA, NA, 11, 0, 0,
3, 0, 7, NA, 0, 0, NA, NA, 0, 0, 0, 0, 0, NA, NA, 2, 2, 0, NA,
0, 0, 0, 0, NA, NA, 9, 5, NA, 0, 2, 28, 15, 0, 0, NA, 0, 20,
NA, 16, 0, NA, 3, NA, 0, 0, 0, 0, NA, NA, 0, 0, 0, 1, NA, 0,
4, NA, NA, 0, NA, NA, 0, 0, 0, 3, 0, 5, 1, 0, 7, 3, 0, 4, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, 14, 0,
0, 0, 0, 0, 0, 0, 0, 0, 7, 1, 0, 6, 0, 21, 1, 0, 0, 0, 0, 0,
0, 0, 3, 0, 5, 0, 0, 0, 0, 0, 15, 17, 1, 0, 5, 0, 0, 0, 15, 0,
0, 9, 0, 0, 0, 0, 9, 0, 0, 5, 0, 0, 0), Antiepileptic = c(NA,
"No", NA, "No", "No", NA, "No", NA, "No", "No", NA, NA, "No",
"No", "No", "No", "No", NA, NA, "No", "No", NA, NA, "No", NA,
"No", "No", NA, "No", "No", NA, "No", NA, "No", "No", NA, "No",
"No", NA, "No", "No", "No", NA, NA, "No", "No", NA, "No", "No",
"No", NA, "No", "No", NA, "No", "No", "No", NA, "No", NA, "No",
NA, NA, "No", "No", "No", NA, "No", "No", "No", "No", NA, "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", NA, "No", "No", "No", "No", "No", "No",
NA, NA, "No", "No", "No", "No", "No", "No", NA, "No", NA, "No",
"No", "No", "No", NA, "No", "No", "No", "No", "No", NA, NA, NA,
NA, "No", "No", "No", "No", "No", "No", NA, "No", "Yes", NA,
NA, "No", "No", "No", "No", "Yes", NA, NA, "No", "No", "No",
NA, "No", "No", "No", "No", NA, NA, "No", "No", NA, "No", "No",
"No", "No", "No", "No", NA, "No", "No", NA, "No", "No", NA, "No",
NA, "No", "No", "No", "No", NA, NA, "No", "No", "No", "No", NA,
"No", "No", NA, NA, "No", NA, NA, "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "Yes", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"No", "No", "No", "No", "No", "No", "No", "No", "No", "No", "Yes",
"Yes", "No", "No", "No", "No", "No", "No", "No", "No", "No",
"Yes", "No", "No", "No", "No", "No")), row.names = c(NA, -270L
), class = c("tbl_df", "tbl", "data.frame"))


来源: stackexchange

问:
Entry not updating after button press in tkinter python 3
How can I improve this so that it works?

```<code>import os
import time
import random
import sys
import string
import tkinter as tk

root = tk.Tk()
root.geometry("400x400")
root.title("SecurePass v1.0.0")

welcome = tk.Label(root, text="Welcome to SecurePass v1.0.0")
welcome.pack()

res = ''.join(random.sample(string.ascii_lowercase + string.digits, k=7))

randPass = tk.Entry(root)
randPass.insert(0, "" + res)
randPass.pack()

def resetText():
    randPass.delete(0, tk.END)
    randPass.insert(0, "" + res)

resetButton = tk.Button(root, text="New Pass...", command=resetText)
resetButton.pack()

root.mainloop()
</code>```

No matter what I do, the button doesn't update the text field. All help is appreciated!

答:
You always insert the same text. You have to generate new one.</p>

```<code>def resetText():

    res = ''.join(random.sample(string.ascii_lowercase + string.digits, k=7))

    randPass.delete(0, tk.END)
    randPass.insert(0, res)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
How can I improve this so that it works?

import os
import time
import random
import sys
import string
import tkinter as tk

root = tk.Tk()
root.geometry("400x400")
root.title("SecurePass v1.0.0")

welcome = tk.Label(root, text="Welcome to SecurePass v1.0.0")
welcome.pack()

res = ''.join(random.sample(string.ascii_lowercase + string.digits, k=7))

randPass = tk.Entry(root)
randPass.insert(0, "" + res)
randPass.pack()

def resetText():
    randPass.delete(0, tk.END)
    randPass.insert(0, "" + res)

resetButton = tk.Button(root, text="New Pass...", command=resetText)
resetButton.pack()

root.mainloop()

No matter what I do, the button doesn't update the text field. All help is appreciated!

Body:
You always insert the same text. You have to generate new one.

def resetText():

    res = ''.join(random.sample(string.ascii_lowercase + string.digits, k=7))

    randPass.delete(0, tk.END)
    randPass.insert(0, res)


问:
Using correlation function with dynamic length parameter
My head is going to explode because of this question. Here is the case: I have an series float variable barCount which changes over time, and I want to use its value as the third length parameter for the built-in correlation function.

(I hope it works something like this: cc := correlation(close, barCount, int(barCount)))

But the problem is in Pine there seems to have no way to extract an integer from a series, which really stuck me at this seemingly elementary problem.

I tried several other methods, for example, I tried to write a series of if conditions to compare barCount with different integers and then set the third parameter manually according to the comparing results. However, I don't know why the correlation didn't work properly and gave na value. In some cases, I even see this function giving results that were greater than 1!

I am totally confused with this problem, since I am not very familiar with Pine language, I hope somebody could help me solve this annoying problem.

答:
See this set of functions lifted from Functions Allowing Series As Length - PineCoders FAQ:</p>

```<code>Sma(src,p) => a = cum(src), (a - a[max(p,0)])/max(p,0)
Stdev(src,p) => p == 1 ? 0 : sqrt(Sma(src*src,p) - pow(Sma(src,p),2))
Covariance(x,y,p) => Sma(x*y,p) - Sma(x,p)*Sma(y,p)
Correlation(x,y,p) => Covariance(x,y,p)/(Stdev(x,p)*Stdev(y,p))
</code>```

Body:
See this set of functions lifted from Functions Allowing Series As Length - PineCoders FAQ:

Sma(src,p) => a = cum(src), (a - a[max(p,0)])/max(p,0)
Stdev(src,p) => p == 1 ? 0 : sqrt(Sma(src*src,p) - pow(Sma(src,p),2))
Covariance(x,y,p) => Sma(x*y,p) - Sma(x,p)*Sma(y,p)
Correlation(x,y,p) => Covariance(x,y,p)/(Stdev(x,p)*Stdev(y,p))


问:
SQL - Show only records created 4 days ago - Nothing between
I want to contact people who were added to the database exactly 4 days ago - however my query brings up everyone who has been added within the last 4 days.</p>

```<code>WHERE DateAdded BETWEEN GetDate() - 4 AND GetDate() - 3
</code>```

答:
If you don't mind declaring variables then one way to do this is:

```<code>DECLARE @startdate date = DATEADD(DAY, -4, getdate())
DECLARE @enddate   date = DATEADD(DAY, 1, @startdate)

SELECT * FROM ...
WHERE DateAdded >= @startdate
  AND DateAdded < @enddate
</code>```

This avoids the inclusive properties of BETWEEN, meaning you don't include the next day at 00:00:00.000 time.  It's also sargable.

Body:
I want to contact people who were added to the database exactly 4 days ago - however my query brings up everyone who has been added within the last 4 days.

WHERE DateAdded BETWEEN GetDate() - 4 AND GetDate() - 3

Body:
If you don't mind declaring variables then one way to do this is:

DECLARE @startdate date = DATEADD(DAY, -4, getdate())
DECLARE @enddate   date = DATEADD(DAY, 1, @startdate)

SELECT * FROM ...
WHERE DateAdded >= @startdate
  AND DateAdded < @enddate

This avoids the inclusive properties of BETWEEN, meaning you don't include the next day at 00:00:00.000 time.  It's also sargable.


问:
Remove a row in a dataframe with empty series
I have a column in a data frame. That has an empty series in its row:

```<code>0                                          4.5
1                                          0.5
2                                            8
3                                            8
4                                            8
                        ...
704                                        3.5
705                                        0.5
706                                       11.5
707                                        0.5
708    Series([], Name: price, dtype: float64)
Name: pricediff, Length: 709, dtype: object",
0                                           4
1                                         0.5
2                                         2.5
3                                        19.5
4                                        19.5
                       ...
58                                          1
59                                          4
60                                        8.5
61    Series([], Name: price, dtype: float64)
62    Series([], Name: price, dtype: float64)
Name: pricediff, Length: 63, dtype: object",
</code>```

How can I remove the row or replace it with 0, without directly doing df.drop(df.index[61]), etc, because I have multiple data

答:
You can check if each element is an empty series and then replace all those entries.

First, we'll create a test DataFrame.

```<code>import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, 100, (3, 3)))
df[3] = [1, pd.Series([]), 5]
</code>```

So, we have:

```<code>    0   1   2                           3
0  31  29   1                           1
1  86  86  71  Series([], dtype: float64)
2  86  80  21                           5
</code>```

Now, we introduce a function to make empty Series to 0 and apply it to our DataFrame.

```<code>def make_empty_series_zero(element):
    if isinstance(element, pd.Series) and len(element) == 0:
        return 0
    else:
        return element

df.applymap(make_empty_series_nan)
</code>```

After applying it to our DataFrame, we have:

```<code>    0   1   2  3
0  57  58   2  1
1  96  27   8  0
2   0  43  91  5
</code>```

Body:
I have a column in a data frame. That has an empty series in its row:

0                                          4.5
1                                          0.5
2                                            8
3                                            8
4                                            8
                        ...
704                                        3.5
705                                        0.5
706                                       11.5
707                                        0.5
708    Series([], Name: price, dtype: float64)
Name: pricediff, Length: 709, dtype: object",
0                                           4
1                                         0.5
2                                         2.5
3                                        19.5
4                                        19.5
                       ...
58                                          1
59                                          4
60                                        8.5
61    Series([], Name: price, dtype: float64)
62    Series([], Name: price, dtype: float64)
Name: pricediff, Length: 63, dtype: object",

How can I remove the row or replace it with 0, without directly doing df.drop(df.index[61]), etc, because I have multiple data

Body:
You can check if each element is an empty series and then replace all those entries.

First, we'll create a test DataFrame.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(0, 100, (3, 3)))
df[3] = [1, pd.Series([]), 5]

So, we have:

    0   1   2                           3
0  31  29   1                           1
1  86  86  71  Series([], dtype: float64)
2  86  80  21                           5

Now, we introduce a function to make empty Series to 0 and apply it to our DataFrame.

def make_empty_series_zero(element):
    if isinstance(element, pd.Series) and len(element) == 0:
        return 0
    else:
        return element

df.applymap(make_empty_series_nan)

After applying it to our DataFrame, we have:

    0   1   2  3
0  57  58   2  1
1  96  27   8  0
2   0  43  91  5


问:
What is the meaning of the second output of Huggingface's Bert?
Using the vanilla configuration of base BERT model in the huggingface implementation, I get a tuple of length 2.

```<code>import torch

import transformers
from transformers import AutoModel,AutoTokenizer

bert_name="bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(bert_name)
BERT = AutoModel.from_pretrained(bert_name)

e=tokenizer.encode('I am hoping for the best', add_special_tokens=True)

q=BERT(torch.tensor([e]))

print (len(q)) #Output: 2
</code>```

The first element is what I expect to receive - the 768 dimension embedding of each input token.

```<code>print (e) #Output : [101, 1045, 2572, 5327, 2005, 1996, 2190, 102]
print (q[0].shape) #Output : torch.Size([1, 8, 768])
</code>```

But what is the second element in the tuple?

```<code>print (q[1].shape) # torch.Size([1, 768])
</code>```

It has the same size as the encoding of each token.
But what is it?

Maybe a copy of the [CLS] token, a representation for the classification of the entire encoded text?

Let's check.

```<code>a= q[0][:,0,:]
b=q[1]

print (torch.eq(a,b)) #Output : Tensor([[False, False, False, .... False]])
</code>```

Nope!

What about a copy the embedding of the last token (for whatever reason)?

```<code>c= q[0][:,-1,:]
b=q[1]

print (torch.eq(a,c)) #Output : Tensor([[False, False, False, .... False]])
</code>```

So, also not that.

The documentation talks about how changing the config can result in more tuple elements (like hidden states), but I did not find any description of this "mysterious" tuple element outputted by the default configuration.

Any ideas as to what is it and what is its usage?

答: The output in this case is a tuple of (last_hidden_state, pooler_output). You can find documentation about what the returns could be here.

Body:
Using the vanilla configuration of base BERT model in the huggingface implementation, I get a tuple of length 2.

import torch

import transformers
from transformers import AutoModel,AutoTokenizer

bert_name="bert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(bert_name)
BERT = AutoModel.from_pretrained(bert_name)

e=tokenizer.encode('I am hoping for the best', add_special_tokens=True)

q=BERT(torch.tensor([e]))

print (len(q)) #Output: 2

The first element is what I expect to receive - the 768 dimension embedding of each input token.

print (e) #Output : [101, 1045, 2572, 5327, 2005, 1996, 2190, 102]
print (q[0].shape) #Output : torch.Size([1, 8, 768])

But what is the second element in the tuple?

print (q[1].shape) # torch.Size([1, 768])

It has the same size as the encoding of each token.
But what is it?

Maybe a copy of the [CLS] token, a representation for the classification of the entire encoded text?

Let's check.

a= q[0][:,0,:]
b=q[1]

print (torch.eq(a,b)) #Output : Tensor([[False, False, False, .... False]])

Nope!

What about a copy the embedding of the last token (for whatever reason)?

c= q[0][:,-1,:]
b=q[1]

print (torch.eq(a,c)) #Output : Tensor([[False, False, False, .... False]])

So, also not that.

The documentation talks about how changing the config can result in more tuple elements (like hidden states), but I did not find any description of this "mysterious" tuple element outputted by the default configuration.

Any ideas as to what is it and what is its usage?


问:
How to get https on socket.io
currently I use

let connectTo = "http://myip:myport";
var socket = io.connect(connectTo, {secure: true});
```

<p>on client side, and</p>

<pre class="lang-js prettyprint-override"><code>const port = myport;
const io = require('socket.io')(port);
</code>```

on server side, I want to use https:// instead of http://, how do I do that? I also heard I need a certificate thing, how do I get that? and how to set it up? cause stupid anti viruses think the socket.io is "dangerous" when it isnt.. (the client side is on my electron application)

答:
You create your own https server (with appropriate certificates) and then bind socket.io to that server.   Every socket.io connection starts with an http(s) request so that's why you need that kind of server.

```<code>const https = require('https');

const options = {
  key: fs.readFileSync('somePath/agent2-key.pem'),
  cert: fs.readFileSync('somePath/agent2-cert.pem')
};
const server = https.createServer(options);
const io = require('socket.io')(server);
server.listen(443);
</code>```

I also heard I need a certification thing, how to I get that?

There are lots and lots of sources.  You can start here: https://letsencrypt.org/. You will have to bind a certificate to a particular domain as that's part of the security that it delivers.

Then, in the client, you would connect using an https URL such as:

```<code>const socket = io('https://example.com');
</code>```

Title: How to get https on socket.io

Body:
currently I use

let connectTo = "http://myip:myport";
var socket = io.connect(connectTo, {secure: true});

on client side, and

const port = myport;
const io = require('socket.io')(port);

on server side, I want to use https:// instead of http://, how do I do that? I also heard I need a certificate thing, how do I get that? and how to set it up? cause stupid anti viruses think the socket.io is "dangerous" when it isnt.. (the client side is on my electron application)

Body:
You create your own https server (with appropriate certificates) and then bind socket.io to that server.   Every socket.io connection starts with an http(s) request so that's why you need that kind of server.

const https = require('https');

const options = {
  key: fs.readFileSync('somePath/agent2-key.pem'),
  cert: fs.readFileSync('somePath/agent2-cert.pem')
};
const server = https.createServer(options);
const io = require('socket.io')(server);
server.listen(443);

I also heard I need a certification thing, how to I get that?

There are lots and lots of sources.  You can start here: https://letsencrypt.org/. You will have to bind a certificate to a particular domain as that's part of the security that it delivers.

Then, in the client, you would connect using an https URL such as:

const socket = io('https://example.com');


问:
Tinting the background pinstripes of a grouped UITableView
How do I apply a tint to the background of a UITableView using the grouped style? The standard "color" used ([UIColor groupTableViewBackgroundColor]) is tinted blue; I want a green tint instead.

This uses a pattern rather than a true color. I just want to tint that pattern to match the colors I'm using elsewhere, not replace it with a solid color.

答:
You could probably do this somehow with coregraphics by drawing the grouped tableview color to a context, tinting it, and then using a bitmap of the context as a repeated background for your tableview somehow. I couldn't tell you just how to do that, though.

Why not just do the tinting in Photoshop or GIMP or something and save it as a 32x480 (or whatever res you need) image, and use that image as your tableview's background image. To get the initial pinstripe image, just make a fullscreen view with that as the background color.

A third option would be to place a translucent green view above another view with the grouped tableview background color. Don't know how well that would work, though.

ContentLicense: CC BY-SA 3.0


问:
What happens to blocks if a block plugin is no longer maintained?
I have done a lot of research on the Internet, but I cannot find an answer to this question:

What happens to blocks if a block plugin is no longer maintained?

Let's say I use Atomic Blocks. What happens to Atomic Blocks' blocks if Atomic Blocks is no longer maintained?

Is there a danger that a future version of Wordpress will not recognize these blocks?

Thanks,

François

答:
The Atomic Block has over 40,000+ Active installations! I'm not sure if it's going to be shut off soon Alos for most page builders they all use either shortcodes of their own or use native Html for their block even if Atomic is not a full-page builder it still works like one.

So the answer to your question is: If the Atomic uses native HTML all the page you build using it will remain functional, but if it does use its own shortcodes, then as soon as you deactivate it or its updates stops and WP become un-compatible with it on the future all pages that are using it will not work as they should.

Plugins updates are so important so if a plugin is not maintained anymore then there is a chance it becomes open for threats by hackers.


问:
Check if two sets have a non-empty intersection
I wrote a function intersects that efficiently checks wether two sets have a non-empty intersection (at least, more efficient than checking the size of their intersection).

It works well, but now I would like to specialize this function for the type DataStructures.IntSet from the DataStructures library. I wrote the function below, which works, but is a bit messy.

As you can see, when the attribute inverse is true, I have to negate the current chunk. In an attempt to simplify the code, I wrote the function intersects2 which does the same work but without the need of multiples if/else.

But this code appears to be less efficient than the first one. I'm not sure, but I think the problem is that each call to op_u or op_v copy the parameter, as shown in the output below.

How can I rewrite this function such that it does not make any copy (ie. no allocation) and without several imbricated if/else? The full code, benchmarks and results can be found below.

```<code>using Random
using DataStructures
using BenchmarkTools

elems = [randstring(8) for i in 1:10000]
ii = rand(1:10000, 3000)
jj = rand(1:10000, 3000)

x1 = Set(elems[ii])
y1 = Set(elems[jj])

x2 = Set(ii)
y2 = Set(jj)

x3 = DataStructures.IntSet(ii)
y3 = DataStructures.IntSet(jj)

function intersects(u, v)
    for x in u
        if x in v
            return true
        end
    end
    false
end

function intersects(u::DataStructures.IntSet, v::DataStructures.IntSet)
    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if u.inverse
            if v.inverse
                if ~ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ~ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        else
            if v.inverse
                if ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        end
    end
    false
end

function intersects2(u::DataStructures.IntSet, v::DataStructures.IntSet)
    op_u = if u.inverse x->~x else x->x end
    op_v = if v.inverse x->~x else x->x end

    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
            return true
        end
    end
    false
end

println("Set{String}")
@btime intersects($x1, $y1)

println("Set{Int}")
@btime intersects($x2, $y2)

println("IntSet")
@btime intersects($x3, $y3)
@btime intersects2($x3, $y3)
</code>```

```<code>Set{String}
  190.163 ns (0 allocations: 0 bytes)
Set{Int}
  17.935 ns (0 allocations: 0 bytes)
IntSet
  7.099 ns (0 allocations: 0 bytes)
  90.000 ns (5 allocations: 80 bytes)
</code>```

答:
The overhead you are seeing is likely due to function call overhead: op_u is not being inlined.

This version inlines correctly and has the same performance as intersects:

```<code>julia> function intersects2(u::DataStructures.IntSet, v::DataStructures.IntSet)
           op_u(x) = u.inverse ? ~x : x
           op_v(x) = v.inverse ? ~x : x

           ch_u, ch_v = u.bits.chunks, v.bits.chunks
           for i in 1:length(ch_u)
               if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
                   return true
               end
           end
           false
       end
</code>```

Body:
I wrote a function intersects that efficiently checks wether two sets have a non-empty intersection (at least, more efficient than checking the size of their intersection).

It works well, but now I would like to specialize this function for the type DataStructures.IntSet from the DataStructures library. I wrote the function below, which works, but is a bit messy.

As you can see, when the attribute inverse is true, I have to negate the current chunk. In an attempt to simplify the code, I wrote the function intersects2 which does the same work but without the need of multiples if/else.

But this code appears to be less efficient than the first one. I'm not sure, but I think the problem is that each call to op_u or op_v copy the parameter, as shown in the output below.

How can I rewrite this function such that it does not make any copy (ie. no allocation) and without several imbricated if/else? The full code, benchmarks and results can be found below.

using Random
using DataStructures
using BenchmarkTools

elems = [randstring(8) for i in 1:10000]
ii = rand(1:10000, 3000)
jj = rand(1:10000, 3000)

x1 = Set(elems[ii])
y1 = Set(elems[jj])

x2 = Set(ii)
y2 = Set(jj)

x3 = DataStructures.IntSet(ii)
y3 = DataStructures.IntSet(jj)

function intersects(u, v)
    for x in u
        if x in v
            return true
        end
    end
    false
end

function intersects(u::DataStructures.IntSet, v::DataStructures.IntSet)
    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if u.inverse
            if v.inverse
                if ~ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ~ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        else
            if v.inverse
                if ch_u[i] & ~ch_v[i] > 0
                    return true
                end
            else
                if ch_u[i] & ch_v[i] > 0
                    return true
                end
            end
        end
    end
    false
end

function intersects2(u::DataStructures.IntSet, v::DataStructures.IntSet)
    op_u = if u.inverse x->~x else x->x end
    op_v = if v.inverse x->~x else x->x end

    ch_u, ch_v = u.bits.chunks, v.bits.chunks
    for i in 1:length(ch_u)
        if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
            return true
        end
    end
    false
end

println("Set{String}")
@btime intersects($x1, $y1)

println("Set{Int}")
@btime intersects($x2, $y2)

println("IntSet")
@btime intersects($x3, $y3)
@btime intersects2($x3, $y3)

Set{String}
  190.163 ns (0 allocations: 0 bytes)
Set{Int}
  17.935 ns (0 allocations: 0 bytes)
IntSet
  7.099 ns (0 allocations: 0 bytes)
  90.000 ns (5 allocations: 80 bytes)

Body:
The overhead you are seeing is likely due to function call overhead: op_u is not being inlined.

This version inlines correctly and has the same performance as intersects:

julia> function intersects2(u::DataStructures.IntSet, v::DataStructures.IntSet)
           op_u(x) = u.inverse ? ~x : x
           op_v(x) = v.inverse ? ~x : x

           ch_u, ch_v = u.bits.chunks, v.bits.chunks
           for i in 1:length(ch_u)
               if op_u(ch_u[i]) & op_v(ch_v[i]) > 0
                   return true
               end
           end
           false
       end


问:
Requirement of encapsulation
"Encapsulation is one of the most important features of OOP and is used for data protection" according to many books and websites. Wikipedia similarly states,

Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them.

But protection from what? Is it from our own ignorant selves, ensuring we dont mess up later on when programs are too long or some other factor?

答:
If you make something available, then someone's going to use it, and if someone uses it, then you can't change it. Or at least you can't change it without finding, thoroughly understanding, and testing all the stuff that uses it.

If something is privately encapsulated, you only need to worry about things in the encapsulating scope, which should be small enough to understand much more easily.

Title: Requirement of encapsulation


问:
Using Puppeteer, how can I open a page, get the data and navigate to the previous page with that data within a loop
Using Puppeteer, I would like to get all the elements on a page with a particular class name and then loop through and click each one and go back to the other page with that data from the page clicked.

I have tried this:

```<code>await page.goto('https://myschool.ng/classroom/christian-religious-knowledge-crk?exam_type=jamb&exam_year=2019', {waitUntil: 'load', timeout: 100000})
  let  questions=  await page.$$('div.media-body')
  let data = []
  await questions.forEach(async (element, i)=>{
         let question =  await  element.$eval(".question-desc.mt-0.mb-3 > p", el=>el.innerHTML)
         let options =   await element.$$eval("ul >li",el=>el.map(option=>option.innerHTML))
          await page.waitFor(2000)

          await element.$eval('a', el=>el.click())
          await page.waitForSelector("h5.text-success.mb-3")
          let correctOption = await page.$eval('h5.text-success.mb-3', el=>el.innerHTML)
          //data.push({question, options, correctOption})
          page.goBack()
          console.log({question, options, correctOption}, i)
    })

</code>```

but I always keep getting this in my console log:

```<code>   question: 'The core of Saul\'s disobedience was that_____________',
  options:
   [ '\n            <strong>A.</strong>\n            He freed the Kenites\n        ',
     '\n            <strong>B.</strong>\n            He refused to carry out God\'s assignment on eliminating the Amalekites\n        ',
     '\n            <strong>C.</strong>\n            He didn\'t perform the task of smiting Amalekites to the letter\n        ',
     '\n            <strong>D.</strong>\n            He preserved the booty for himself\n        ' ],
  correctOption: 'Correct Answer: Option D' } 0
{ question:
   'God instructed Saul to utterly destroy Amalek because___________',
  options:
   [ '\n            <strong>A.</strong>\n            He abhors Idolatory and all forms of Unrighteousness\n        ',
     '\n            <strong>B.</strong>\n            Its people opposed the Israelites on the way after departing Egypt\n        ',
     '\n            <strong>C.</strong>\n            Its people encouraged Israel to disobey God\n        ',
     '\n            <strong>D.</strong>\n            Samuel had prayed for it destruction\n        ' ],
  correctOption: 'Correct Answer: Option D' } 1
{ question:
   'One of the most significant lessons from the emergence of Deborah as a leader is that_________',
  options:
   [ '\n            <strong>A.</strong>\n            She not only prophesied but also advised Israel\n        ',
     '\n            <strong>B.</strong>\n            Gender difference isn\'t a limitation to leadership\n        ',
     '\n            <strong>C.</strong>\n            Honesty and Integrity are key to leadership\n        ',
     '\n            <strong>D.</strong>\n            One needs to summon courage as a leader to solve problems\n        ' ],
  correctOption: 'Correct Answer: Option D' } 2
{ question:
   'Jeremiah prophesied God\'s punishment of the Israelites because they had_______',
  options:
   [ '\n            <strong>A.</strong>\n            Compromised his worship\n        ',
     '\n            <strong>B.</strong>\n            Committed atrocities with their neighbors\' wives\n        ',
     '\n            <strong>C.</strong>\n            Trampled on the needy\n        ',
     '\n            <strong>D.</strong>\n            No belief in his message\n        ',
     '\n            <strong>D.</strong>\n            No belief in his message\n        ' ],
  correctOption: 'Correct Answer: Option D' } 3
{ question:
   'Jesus healed the lame man who had been sick for thirty-eight years at?',
  options:
   [ '\n            <strong>A.</strong>\n            Capernaum\n        ',
     '\n            <strong>B.</strong>\n            Samaria\n        ',
     '\n            <strong>C.</strong>\n            Galilee\n        ',
     '\n            <strong>D.</strong>\n            Betsheba\n        ' ],
  correctOption: 'Correct Answer: Option D' } 4

</code>```

I have tried everything  but the correctOption  is not the data that I web scraped and it give displaying the first option.

答:
The main reason was  because forEach is asynchronously and i need  the loop to run
in a  synchronously manner  , The finally solution is</p>

```<code>await page.goto('https://myschool.ng/classroom/christian-religious-knowledge-crk?exam_type=jamb&exam_year=2019', {waitUntil: 'load', timeout: 100000})
  let  questions=  await page.$$('div.media-body')
  let data = []
    for (let index = 0; index < questions.length; index++) {
        let question =  await questions[index].$eval(".question-desc.mt-0.mb-3 > p", el=>el.innerHTML)
        let options =   await questions[index].$$eval("ul >li",el=>el.map(option=>option.innerHTML))
        await questions[index].$eval('.btn', el=>el.click())
        await page.waitFor(2000)
        await page.waitForSelector("h5.text-success.mb-3")
         .then( async()=>{
            console.log(await  page.$eval(" .text-success.mb-3", el=>el.innerHTML))
            page.goBack()
            await page.waitFor(2000)
            questions=  await page.$$('div.media-body')
         })
         .catch(async ()=>{
            console.log("jsjjs")
             page.goBack()
             await page.waitFor(2000)
           questions=  await page.$$('div.media-body')
         })
    }

})

</code>```

Body:
Using Puppeteer, I would like to get all the elements on a page with a particular class name and then loop through and click each one and go back to the other page with that data from the page clicked.

I have tried this:

await page.goto('https://myschool.ng/classroom/christian-religious-knowledge-crk?exam_type=jamb&exam_year=2019', {waitUntil: 'load', timeout: 100000})
  let  questions=  await page.$$('div.media-body')
  let data = []
  await questions.forEach(async (element, i)=>{
         let question =  await  element.$eval(".question-desc.mt-0.mb-3 > p", el=>el.innerHTML)
         let options =   await element.$$eval("ul >li",el=>el.map(option=>option.innerHTML))
          await page.waitFor(2000)

          await element.$eval('a', el=>el.click())
          await page.waitForSelector("h5.text-success.mb-3")
          let correctOption = await page.$eval('h5.text-success.mb-3', el=>el.innerHTML)
          //data.push({question, options, correctOption})
          page.goBack()
          console.log({question, options, correctOption}, i)
    })

but I always keep getting this in my console log:

   question: 'The core of Saul\'s disobedience was that_____________',
  options:
   [ '\n            A.\n            He freed the Kenites\n        ',
     '\n            B.\n            He refused to carry out God\'s assignment on eliminating the Amalekites\n        ',
     '\n            C.\n            He didn\'t perform the task of smiting Amalekites to the letter\n        ',
     '\n            D.\n            He preserved the booty for himself\n        ' ],
  correctOption: 'Correct Answer: Option D' } 0
{ question:
   'God instructed Saul to utterly destroy Amalek because___________',
  options:
   [ '\n            A.\n            He abhors Idolatory and all forms of Unrighteousness\n        ',
     '\n            B.\n            Its people opposed the Israelites on the way after departing Egypt\n        ',
     '\n            C.\n            Its people encouraged Israel to disobey God\n        ',
     '\n            D.\n            Samuel had prayed for it destruction\n        ' ],
  correctOption: 'Correct Answer: Option D' } 1
{ question:
   'One of the most significant lessons from the emergence of Deborah as a leader is that_________',
  options:
   [ '\n            A.\n            She not only prophesied but also advised Israel\n        ',
     '\n            B.\n            Gender difference isn\'t a limitation to leadership\n        ',
     '\n            C.\n            Honesty and Integrity are key to leadership\n        ',
     '\n            D.\n            One needs to summon courage as a leader to solve problems\n        ' ],
  correctOption: 'Correct Answer: Option D' } 2
{ question:
   'Jeremiah prophesied God\'s punishment of the Israelites because they had_______',
  options:
   [ '\n            A.\n            Compromised his worship\n        ',
     '\n            B.\n            Committed atrocities with their neighbors\' wives\n        ',
     '\n            C.\n            Trampled on the needy\n        ',
     '\n            D.\n            No belief in his message\n        ',
     '\n            D.\n            No belief in his message\n        ' ],
  correctOption: 'Correct Answer: Option D' } 3
{ question:
   'Jesus healed the lame man who had been sick for thirty-eight years at?',
  options:
   [ '\n            A.\n            Capernaum\n        ',
     '\n            B.\n            Samaria\n        ',
     '\n            C.\n            Galilee\n        ',
     '\n            D.\n            Betsheba\n        ' ],
  correctOption: 'Correct Answer: Option D' } 4

I have tried everything  but the correctOption  is not the data that I web scraped and it give displaying the first option.

Body:
The main reason was  because forEach is asynchronously and i need  the loop to run
in a  synchronously manner  , The finally solution is

await page.goto('https://myschool.ng/classroom/christian-religious-knowledge-crk?exam_type=jamb&exam_year=2019', {waitUntil: 'load', timeout: 100000})
  let  questions=  await page.$$('div.media-body')
  let data = []
    for (let index = 0; index < questions.length; index++) {
        let question =  await questions[index].$eval(".question-desc.mt-0.mb-3 > p", el=>el.innerHTML)
        let options =   await questions[index].$$eval("ul >li",el=>el.map(option=>option.innerHTML))
        await questions[index].$eval('.btn', el=>el.click())
        await page.waitFor(2000)
        await page.waitForSelector("h5.text-success.mb-3")
         .then( async()=>{
            console.log(await  page.$eval(" .text-success.mb-3", el=>el.innerHTML))
            page.goBack()
            await page.waitFor(2000)
            questions=  await page.$$('div.media-body')
         })
         .catch(async ()=>{
            console.log("jsjjs")
             page.goBack()
             await page.waitFor(2000)
           questions=  await page.$$('div.media-body')
         })
    }

})


问:
Incrementing and comparing version in pl/sql
I want to do the following

1a.0.0.0 should come before 18.9.3.1 in a sort

1a.0.0.0 should come first

Increment by 1 in any numeric value

Increment by alphabet any alpha numeric value

Select the max version by correct sort

create table revision_table
(revision_nbr varchar2(30))

```<code>REVISION_NBR
1.0.0.0
1.2.0.1
18.9.3.1
1a.0.0.0
20.2.0.0
20a.2.0.0
</code>```

答:
Well this sounds like a "Fool's errand", if not just a bad design.

First lets give version a format definition.

Let Version, denoted by V, be composed of levels, denoted by L, separated by single dots, ( V -> L1.L2. ... Ln)

Let each level be composed of a mandatory string of digits, denoted by Lnd, and an option string of lower case English letters a though z, denoted by Lns.

With the definition is hand sort the version list on L1d, L1s,L2d, L2s ... Lnd, Lds. Where omitted Lns values sort to the end of list for a given Ln.

The following SQL performs the requested sort for N=4.

```<code>with versions as
   (select '1.2.3.4'  v  from dual union all
    select '1.0.0.0'     from dual union all
    select '1.2.0.1'     from dual union all
    select '1.10.0.1'    from dual union all
    select '18.9.3.1'    from dual union all
    select '1a.0.0.0'    from dual union all
    select '1b.0.0.0'    from dual union all
    select '20.2.0.0'    from dual union all
    select '20a.2.0.0'   from dual union all
    select '1az.0.0.0'   from dual union all
    select '1a.2b.3c.4d' from dual
   )
select v
  from versions
 order by
       to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,1 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,1 ) ,'.',null),'(\d+)([a-z]*)','\2')
     , to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,2 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,2 ) ,'.',null),'(\d+)([a-z]*)','\2')
     , to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,3 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,3 ) ,'.',null),'(\d+)([a-z]*)','\2')
     , to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,4 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,4 ) ,'.',null),'(\d+)([a-z]*)','\2')
;
</code>```

So that takes care of The easy Part correctly(?) sorting. To increment versions defines a function with the following parameters:
The version to increment  (V),
The Level to Increment   (Ln),
The Part of the Level to Increment  (Lnd) or (Lns)

In addition to just upping the indicated value for parameters what needs to be done for the currently undefined actions.

When incrementing Lns and the letter is already 'z'.

When incrementing Lnd and Lns exists is keep or drop Lns.

How to increment Lnd + Lns to just Lnd (ie 1a. to 1.)

You really don't want to do this but if you try well echoing @APC: Good luck with that.

Body:
I want to do the following

1a.0.0.0 should come before 18.9.3.1 in a sort

1a.0.0.0 should come first

Increment by 1 in any numeric value

Increment by alphabet any alpha numeric value

Select the max version by correct sort

create table revision_table
(revision_nbr varchar2(30))

REVISION_NBR
1.0.0.0
1.2.0.1
18.9.3.1
1a.0.0.0
20.2.0.0
20a.2.0.0

Body:
Well this sounds like a "Fool's errand", if not just a bad design.

First lets give version a format definition.

Let Version, denoted by V, be composed of levels, denoted by L, separated by single dots, ( V -> L1.L2. ... Ln)

Let each level be composed of a mandatory string of digits, denoted by Lnd, and an option string of lower case English letters a though z, denoted by Lns.

With the definition is hand sort the version list on L1d, L1s,L2d, L2s ... Lnd, Lds. Where omitted Lns values sort to the end of list for a given Ln.

The following SQL performs the requested sort for N=4.

with versions as
   (select '1.2.3.4'  v  from dual union all
    select '1.0.0.0'     from dual union all
    select '1.2.0.1'     from dual union all
    select '1.10.0.1'    from dual union all
    select '18.9.3.1'    from dual union all
    select '1a.0.0.0'    from dual union all
    select '1b.0.0.0'    from dual union all
    select '20.2.0.0'    from dual union all
    select '20a.2.0.0'   from dual union all
    select '1az.0.0.0'   from dual union all
    select '1a.2b.3c.4d' from dual
   )
select v
  from versions
 order by
       to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,1 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,1 ) ,'.',null),'(\d+)([a-z]*)','\2')
     , to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,2 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,2 ) ,'.',null),'(\d+)([a-z]*)','\2')
     , to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,3 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,3 ) ,'.',null),'(\d+)([a-z]*)','\2')
     , to_number(regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,4 ) ,'.',null),'(\d+)([a-z]*)','\1') )
     , regexp_replace(replace(regexp_substr(v,'(\d+)([a-z]*)(\.|$)',1,4 ) ,'.',null),'(\d+)([a-z]*)','\2')
;

So that takes care of The easy Part correctly(?) sorting. To increment versions defines a function with the following parameters:
The version to increment  (V),
The Level to Increment   (Ln),
The Part of the Level to Increment  (Lnd) or (Lns)

In addition to just upping the indicated value for parameters what needs to be done for the currently undefined actions.

When incrementing Lns and the letter is already 'z'.

When incrementing Lnd and Lns exists is keep or drop Lns.

How to increment Lnd + Lns to just Lnd (ie 1a. to 1.)

You really don't want to do this but if you try well echoing @APC: Good luck with that.


问:
How to: Save order of tabs when customizing tabs in UITabBarController
I am having problems finding any other information than the docs for how to save the tab order for my UITabBarController, so that the user's customization is saved for next app launch. I have searched online, but have been unable to find any blog posts or articles that goes through the proper code for doing this.

I realize I have to use the delegate methods for the UITabBarController (didEndCustomizingViewControllers:) but I am not sure how I best approach persistance in terms of saving the state of the order the user wants the tabs in.

Can someone post some code, point me in the right direction or perhaps you have a link for something saved? :)

Thanks

答:
I'd like to share the code I have been working on for nearly 3 days now trying all sorts of combinations with many errors and failure - the general life of coding! ha ha.  Anyway the code below works with Swift 5.
 It's the extraction of How to: Save order of tabs when customizing tabs in UITabBarController  ,  Sam's Code, but with the for loop update for Swift 5.
I have got this working great, all in the TabBarViewController.swift file.

So if you just paste this into your Swift file, make sure your Tab Bar Items have a tag number from the Attributes Inspector and your good to go!

Thanks again to Sam for the Code in the first place.

```<code>import UIKit

class TabBarController: UITabBarController, UITabBarControllerDelegate {

let tabOrderKey = "customTabBarOrder"

override func viewDidLoad() {
super.viewDidLoad()

self.delegate = self
loadCustomTabOrder()
}

func loadCustomTabOrder() {

let defaults = UserDefaults.standard
let standardOrderChanged = defaults.bool(forKey: tabOrderKey)

if standardOrderChanged {
    print("Standard Order has changed")

    var VCArray = [UIViewController]()
    var tagNumber = 0

    let tabBar = self as UITabBarController

    if let countVC = tabBar.viewControllers?.count {
        print("\(countVC) VCs in total")
        for x in 0..<countVC {
            tagNumber = defaults.integer(forKey: "tabPosition\(x)")

            for VC in tabBar.viewControllers! {
                if tagNumber == VC.tabBarItem.tag {
                    VCArray.append(VC)
                    print("Position \(x): \(VCArray[x].tabBarItem.title!) VC (tag \(tagNumber))")
                }
            }
        }
    }
    tabBar.viewControllers = VCArray
 }

 }

func tabBarController(_ tabBarController: UITabBarController, didEndCustomizing viewControllers: [UIViewController], changed: Bool) {

print("Change func called")

if changed {
    print("Order has changed")
    let defaults = UserDefaults.standard

    for x in 0..<(viewControllers.count)  {
        defaults.set(viewControllers[x].tabBarItem.tag, forKey: "tabPosition\(x)")
        print("\(viewControllers[x].tabBarItem.title!) VC (with tag: \(viewControllers[x].tabBarItem.tag)) is now in position \(x)")
   }
    defaults.set(true, forKey: tabOrderKey)
    } else {
    print("Nothing has changed")
    }
  }

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'd like to share the code I have been working on for nearly 3 days now trying all sorts of combinations with many errors and failure - the general life of coding! ha ha.  Anyway the code below works with Swift 5.
 It's the extraction of How to: Save order of tabs when customizing tabs in UITabBarController  ,  Sam's Code, but with the for loop update for Swift 5.
I have got this working great, all in the TabBarViewController.swift file.

So if you just paste this into your Swift file, make sure your Tab Bar Items have a tag number from the Attributes Inspector and your good to go!

Thanks again to Sam for the Code in the first place.

import UIKit

class TabBarController: UITabBarController, UITabBarControllerDelegate {

let tabOrderKey = "customTabBarOrder"

override func viewDidLoad() {
super.viewDidLoad()

self.delegate = self
loadCustomTabOrder()
}

func loadCustomTabOrder() {

let defaults = UserDefaults.standard
let standardOrderChanged = defaults.bool(forKey: tabOrderKey)

if standardOrderChanged {
    print("Standard Order has changed")

    var VCArray = [UIViewController]()
    var tagNumber = 0

    let tabBar = self as UITabBarController

    if let countVC = tabBar.viewControllers?.count {
        print("\(countVC) VCs in total")
        for x in 0..<countVC {
            tagNumber = defaults.integer(forKey: "tabPosition\(x)")

            for VC in tabBar.viewControllers! {
                if tagNumber == VC.tabBarItem.tag {
                    VCArray.append(VC)
                    print("Position \(x): \(VCArray[x].tabBarItem.title!) VC (tag \(tagNumber))")
                }
            }
        }
    }
    tabBar.viewControllers = VCArray
 }

 }

func tabBarController(_ tabBarController: UITabBarController, didEndCustomizing viewControllers: [UIViewController], changed: Bool) {

print("Change func called")

if changed {
    print("Order has changed")
    let defaults = UserDefaults.standard

    for x in 0..<(viewControllers.count)  {
        defaults.set(viewControllers[x].tabBarItem.tag, forKey: "tabPosition\(x)")
        print("\(viewControllers[x].tabBarItem.title!) VC (with tag: \(viewControllers[x].tabBarItem.tag)) is now in position \(x)")
   }
    defaults.set(true, forKey: tabOrderKey)
    } else {
    print("Nothing has changed")
    }
  }

}


问:
Swift: DispatchGroup notify called before task finish
Why is dispatchGroup.notify being called before my stocks loop? Shouldn't it be called only after the task is done? Below is an image of my console to show you what I mean.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

     fetch { (stocks) in
        self.hud.dismiss()

          APIManager.shareInstance.getStockList(for: self.fetchedStocks) { (result) in

            switch result {
            case .success(let stocks):
                DispatchQueue.main.async {
                    self.fetchedStocks = stocks
                    print(self.fetchedStocks)
                }

            case .failure(let error):
                print("Couldn't find Symbol")
                print(error.localizedDescription)

            }
        }
        DispatchQueue.main.async {
            print("Reload data")
            self.tableView.reloadData()
        }
    }
</code>```

答:
You need to call dispatchGroup.enter() before getStockList, not inside the closure.

You also need to move the dispatchGroup.leave outside the stocks.forEach:

```<code>fetch { stocks in
    self.hud.dismiss()

    dispatchGroup.enter()

    APIManager.shareInstance.getStockList(for: self.fetchedStocks) { result in
        switch result {
        case .success(let stocks):
            stocks.forEach { stock in
                for index in 0..<stocks.count {
                    self.fetchedStocks[index] = stock
                    print("Stock Model:", self.fetchedStocks[index])
                }
            }

        case .failure(let error):
            print(error.localizedDescription)
        }

        dispatchGroup.leave()
    }

    dispatchGroup.notify(queue: .main) {
        print("Sucessfully retrieve necessary data, now reloading tableview")
        self.tableView.reloadData()
    }
}
</code>```

Alternatively, since it appears that getStockList is called only once, you can eliminate the dispatch group entirely:

```<code>fetch { stocks in
    self.hud.dismiss()

    APIManager.shareInstance.getStockList(for: self.fetchedStocks) { (result) in
        switch result {
        case .success(let stocks):
            stocks.forEach { (stock) in
                for index in 0..<stocks.count {
                    self.fetchedStocks[index] = stock
                    print("Stock Model:", self.fetchedStocks[index])
                }
            }

        case .failure(let error):
            print(error.localizedDescription)
        }

        DispatchQueue.main.async {
            print("Now reloading tableview")
            self.tableView.reloadData()
        }
    }
}
</code>```

Note, the DispatchQueue.main.async isn’t needed if fetch calls this closure on the main queue already. And if it’s not calling it on the main queue, then you probably want to dispatch the updating of self.fetchedStocks to the main queue, as well, to ensure thread safety of this model object.

I’m not sure why you’re iterating through stocks. I would have thought that this would be sufficient:

```<code>fetch { stocks in
    self.hud.dismiss()

    APIManager.shareInstance.getStockList(for: self.fetchedStocks) { (result) in
        switch result {
        case .success(let stocks):
            DispatchQueue.main.async {
                self.fetchedStocks = stocks
                self.tableView.reloadData()
            }

        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}
</code>```

Again, that DispatchQueue.main.async isn’t needed if the fetch completion handler already runs on the main queue.

Body:
Why is dispatchGroup.notify being called before my stocks loop? Shouldn't it be called only after the task is done? Below is an image of my console to show you what I mean.

override func viewDidLoad() {
    super.viewDidLoad()

     fetch { (stocks) in
        self.hud.dismiss()

          APIManager.shareInstance.getStockList(for: self.fetchedStocks) { (result) in

            switch result {
            case .success(let stocks):
                DispatchQueue.main.async {
                    self.fetchedStocks = stocks
                    print(self.fetchedStocks)
                }

            case .failure(let error):
                print("Couldn't find Symbol")
                print(error.localizedDescription)

            }
        }
        DispatchQueue.main.async {
            print("Reload data")
            self.tableView.reloadData()
        }
    }

Body:
You need to call dispatchGroup.enter() before getStockList, not inside the closure.

You also need to move the dispatchGroup.leave outside the stocks.forEach:

fetch { stocks in
    self.hud.dismiss()

    dispatchGroup.enter()

    APIManager.shareInstance.getStockList(for: self.fetchedStocks) { result in
        switch result {
        case .success(let stocks):
            stocks.forEach { stock in
                for index in 0..<stocks.count {
                    self.fetchedStocks[index] = stock
                    print("Stock Model:", self.fetchedStocks[index])
                }
            }

        case .failure(let error):
            print(error.localizedDescription)
        }

        dispatchGroup.leave()
    }

    dispatchGroup.notify(queue: .main) {
        print("Sucessfully retrieve necessary data, now reloading tableview")
        self.tableView.reloadData()
    }
}

Alternatively, since it appears that getStockList is called only once, you can eliminate the dispatch group entirely:

fetch { stocks in
    self.hud.dismiss()

    APIManager.shareInstance.getStockList(for: self.fetchedStocks) { (result) in
        switch result {
        case .success(let stocks):
            stocks.forEach { (stock) in
                for index in 0..<stocks.count {
                    self.fetchedStocks[index] = stock
                    print("Stock Model:", self.fetchedStocks[index])
                }
            }

        case .failure(let error):
            print(error.localizedDescription)
        }

        DispatchQueue.main.async {
            print("Now reloading tableview")
            self.tableView.reloadData()
        }
    }
}

Note, the DispatchQueue.main.async isn’t needed if fetch calls this closure on the main queue already. And if it’s not calling it on the main queue, then you probably want to dispatch the updating of self.fetchedStocks to the main queue, as well, to ensure thread safety of this model object.

I’m not sure why you’re iterating through stocks. I would have thought that this would be sufficient:

fetch { stocks in
    self.hud.dismiss()

    APIManager.shareInstance.getStockList(for: self.fetchedStocks) { (result) in
        switch result {
        case .success(let stocks):
            DispatchQueue.main.async {
                self.fetchedStocks = stocks
                self.tableView.reloadData()
            }

        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}

Again, that DispatchQueue.main.async isn’t needed if the fetch completion handler already runs on the main queue.


问:
Sending automatic email on specific day of the month based on day entered in a cell
I am trying to send an email from Google Apps Script on a specific day of the month based on the day that a user enters into a cell on the Sheet.

Currently I use a formula as below to send emails which sends to users based on cell values:

```<code>function sendChangeDetailsEmail() {
  var sh = SpreadsheetApp.getActive().getSheetByName("BALANCE SHEET");
  var data1 = sh.getRange("G2").getValues(); //USED AS DATA IN THE EMAIL BODY from values in the sheet
  var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G2");
  var emailRange1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G1");
  var emailAddress = emailRange.getValues();
  var recipient = emailRange1.getValues();
  var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
  var subject = 'REMINDER - Amount Due';
    MailApp.sendEmail(emailAddress, subject, message);
}
</code>```

As the sheet will be used as a separate doc for each user, the user would enter the date in cell M3 on configuration for when they want the reminder to be sent, and they would only enter the date number of the month e.g. 25

Does anyone know of a way that I could do this please?

答:
Send email once a month

```<code>function sendChangeDetailsEmail() {
  var ss=SpreadsheetApp.getActive();
  var sh = ss.getSheetByName("BALANCE SHEET");
  var dt=new Date();
  var today=dt.getDate();
  var days=new Date(dt.getFullYear(),dt.getMonth()+1,0).getDate();//number of days in this month
  var emailDay=sh.getRange('M3').getValue();
  if(emailDay>0 && emailDay<=Days && emailDay==today) {
    var data1 = sh.getRange("G2").getValue();
    var emailRange = ss.getSheetByName("BALANCE SHEET").getRange("G2");
    var emailRange1 = ss.getSheetByName("BALANCE SHEET").getRange("G1");
    var emailAddress = emailRange.getValue();
    var recipient = emailRange1.getValue();
    var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
    var subject = 'REMINDER - Amount Due';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}
</code>```

Run the next function just once and check Edit/Current Project Trigger to make sure that there is one and only one trigger created.

```<code>function createSendChangeDetailsEmail() {
  ScriptApp.newTrigger('sendChangeDetailsEmail').timeBased().everyDays(1).atHour(6).create();
}
</code>```

Body:
I am trying to send an email from Google Apps Script on a specific day of the month based on the day that a user enters into a cell on the Sheet.

Currently I use a formula as below to send emails which sends to users based on cell values:

function sendChangeDetailsEmail() {
  var sh = SpreadsheetApp.getActive().getSheetByName("BALANCE SHEET");
  var data1 = sh.getRange("G2").getValues(); //USED AS DATA IN THE EMAIL BODY from values in the sheet
  var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G2");
  var emailRange1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("BALANCE SHEET").getRange("G1");
  var emailAddress = emailRange.getValues();
  var recipient = emailRange1.getValues();
  var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
  var subject = 'REMINDER - Amount Due';
    MailApp.sendEmail(emailAddress, subject, message);
}

As the sheet will be used as a separate doc for each user, the user would enter the date in cell M3 on configuration for when they want the reminder to be sent, and they would only enter the date number of the month e.g. 25

Does anyone know of a way that I could do this please?

Body:
Send email once a month

function sendChangeDetailsEmail() {
  var ss=SpreadsheetApp.getActive();
  var sh = ss.getSheetByName("BALANCE SHEET");
  var dt=new Date();
  var today=dt.getDate();
  var days=new Date(dt.getFullYear(),dt.getMonth()+1,0).getDate();//number of days in this month
  var emailDay=sh.getRange('M3').getValue();
  if(emailDay>0 && emailDay<=Days && emailDay==today) {
    var data1 = sh.getRange("G2").getValue();
    var emailRange = ss.getSheetByName("BALANCE SHEET").getRange("G2");
    var emailRange1 = ss.getSheetByName("BALANCE SHEET").getRange("G1");
    var emailAddress = emailRange.getValue();
    var recipient = emailRange1.getValue();
    var message = 'Hello ' + recipient + "\r\r" + 'Please see the current amount that needs paying off: ' + data1 + "\r\r" + 'Many Thanks';
    var subject = 'REMINDER - Amount Due';
    MailApp.sendEmail(emailAddress, subject, message);
  }
}

Run the next function just once and check Edit/Current Project Trigger to make sure that there is one and only one trigger created.

function createSendChangeDetailsEmail() {
  ScriptApp.newTrigger('sendChangeDetailsEmail').timeBased().everyDays(1).atHour(6).create();
}


问:
Subscribe to observable is returning undefined
So I am trying to subscribe to a simple service that return data from a local JSON file.

I have managed to get the service working, I can log it out in the function, but when I subscribe to the service in the angular 2 component, it is always undefined. I'm not sure why? Any help would be much appreciated.

API service

```<code>export class ApiService {
   public data: any;

   constructor(private _http: Http) {
   }

   getData(): any {
       return this._http.get('api.json').map((response: Response) => {
       console.log('in response', response.json()); //This logs the Object
       this.data = response.json();
       return this.data;
   })
   .catch(this.handleError);
   }
}
</code>```

Component

```<code>export class AppComponent {
   public data: any
   public informationData;

   constructor(private _api: ApiService) {}

   public ngOnInit(): void {
      console.log(this.getDataFromService()); // This return undefined
   }

   public getDataFromService() {
      this._api.getData().subscribe(response => {
          this.informationData = response;
          return this.informationData;
      });
   }
}
</code>```

答:
you can do it like this:

In your app-component:

```<code>public getDataFromService() {
  this._api.getData(this);
}

public setData(data: any){
 this.data=data;
}
</code>```

In your service/api.ts:

```<code>public getData(obj: appComponentModel){
    this.http.get(url).subscribe(res => obj.setData(res));
}
</code>```

Body:
So I am trying to subscribe to a simple service that return data from a local JSON file.

I have managed to get the service working, I can log it out in the function, but when I subscribe to the service in the angular 2 component, it is always undefined. I'm not sure why? Any help would be much appreciated.

API service

export class ApiService {
   public data: any;

   constructor(private _http: Http) {
   }

   getData(): any {
       return this._http.get('api.json').map((response: Response) => {
       console.log('in response', response.json()); //This logs the Object
       this.data = response.json();
       return this.data;
   })
   .catch(this.handleError);
   }
}

Component

export class AppComponent {
   public data: any
   public informationData;

   constructor(private _api: ApiService) {}

   public ngOnInit(): void {
      console.log(this.getDataFromService()); // This return undefined
   }

   public getDataFromService() {
      this._api.getData().subscribe(response => {
          this.informationData = response;
          return this.informationData;
      });
   }
}

Body:
you can do it like this:

In your app-component:

public getDataFromService() {
  this._api.getData(this);
}

public setData(data: any){
 this.data=data;
}

In your service/api.ts:

public getData(obj: appComponentModel){
    this.http.get(url).subscribe(res => obj.setData(res));
}


问:
Enzyme Shallow not working but mount works
I have the following a.jsx file which I am trying to test:

```<code>import React, { Component } from "react";
import { SideNavigation } from "@xxx/react-components-xxx";
import { withTranslation } from "react-i18next";

class Navigation extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        const { t } = this.props;

        const ITEMS = [
            {
                type: "section",
                text: t("navigation.abc"),
                items: [
                    {
                        type: "link",
                        text: t("navigation.abc"),
                        href: "#/abc"
                    },
                    { type: "link", text: t("navigation.def"), href: "#/def" }
                ]
            }
        ];

        const HEADER = {
            href: "#/",
            text: t("navigation.title")
        };

        return (
            <SideNavigation
                header={HEADER}
                items={ITEMS}
            />
        );
    }
}

export default withTranslation()(Navigation);
</code>```

And following is the test case I have written:

```<code>import React from "react";
import { shallow } from 'enzyme';
import Navigation from '../src/a';
import { SideNavigation } from '@xxx/react-components-xxx';

describe('Navigation component', () => {
    it('should render consistently', () => {
        const wrapper = shallow(
            <Navigation />
        );

        console.log(wrapper.render());
        expect(wrapper).not.toBeNull();

        const sideNav = wrapper.find(SideNavigation);
        console.log(sideNav.render());
        const sideNavProps = sideNav.props();
        console.log(sideNavProps);
    });
});
</code>```

And with this, I get following eror:

Method “type” is meant to be run on 1 node. 0 found instead.

```<code>  14 |
  15 |         const sideNav = wrapper.find(SideNavigation);
> 16 |         console.log(sideNav.render());
     |                             ^
  17 |         const sideNavProps = sideNav.props();
  18 |         console.log(sideNavProps);
  19 |     });

  at ShallowWrapper.single (node_modules/enzyme/src/ShallowWrapper.js:1636:13)
  at ShallowWrapper.type (node_modules/enzyme/src/ShallowWrapper.js:1372:17)
  at ShallowWrapper.render (node_modules/enzyme/src/ShallowWrapper.js:1106:17)
  at Object.<anonymous> (tst/components/Navigation.test.js:16:29)
</code>```

But if I use mount instead of shallow, everything works fine here. Can someone tell what is the issue here?

答:
It's because of the WithTranslation.

They mention it in their doc

For testing purpose of your component you should export the pure component without extending with the withTranslation hoc and test that:

```<code>export MyComponent;
export default withTranslation('ns')(MyComponent);
</code>```

In the test, test the myComponent export passing a t function mock:

```<code>import { MyComponent } from './myComponent';
<MyComponent t={key => key} />
</code>```

Body:
I have the following a.jsx file which I am trying to test:

import React, { Component } from "react";
import { SideNavigation } from "@xxx/react-components-xxx";
import { withTranslation } from "react-i18next";

class Navigation extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        const { t } = this.props;

        const ITEMS = [
            {
                type: "section",
                text: t("navigation.abc"),
                items: [
                    {
                        type: "link",
                        text: t("navigation.abc"),
                        href: "#/abc"
                    },
                    { type: "link", text: t("navigation.def"), href: "#/def" }
                ]
            }
        ];

        const HEADER = {
            href: "#/",
            text: t("navigation.title")
        };

        return (
            <SideNavigation
                header={HEADER}
                items={ITEMS}
            />
        );
    }
}

export default withTranslation()(Navigation);

And following is the test case I have written:

import React from "react";
import { shallow } from 'enzyme';
import Navigation from '../src/a';
import { SideNavigation } from '@xxx/react-components-xxx';

describe('Navigation component', () => {
    it('should render consistently', () => {
        const wrapper = shallow(
            <Navigation />
        );

        console.log(wrapper.render());
        expect(wrapper).not.toBeNull();

        const sideNav = wrapper.find(SideNavigation);
        console.log(sideNav.render());
        const sideNavProps = sideNav.props();
        console.log(sideNavProps);
    });
});

And with this, I get following eror:

Method “type” is meant to be run on 1 node. 0 found instead.

  14 |
  15 |         const sideNav = wrapper.find(SideNavigation);
> 16 |         console.log(sideNav.render());
     |                             ^
  17 |         const sideNavProps = sideNav.props();
  18 |         console.log(sideNavProps);
  19 |     });

  at ShallowWrapper.single (node_modules/enzyme/src/ShallowWrapper.js:1636:13)
  at ShallowWrapper.type (node_modules/enzyme/src/ShallowWrapper.js:1372:17)
  at ShallowWrapper.render (node_modules/enzyme/src/ShallowWrapper.js:1106:17)
  at Object.<anonymous> (tst/components/Navigation.test.js:16:29)

But if I use mount instead of shallow, everything works fine here. Can someone tell what is the issue here?

Body:
It's because of the WithTranslation.

They mention it in their doc

For testing purpose of your component you should export the pure component without extending with the withTranslation hoc and test that:

export MyComponent;
export default withTranslation('ns')(MyComponent);

In the test, test the myComponent export passing a t function mock:

import { MyComponent } from './myComponent';
<MyComponent t={key => key} />


问:
Veracrypt with batchfile: how can execution be stopped if drive is not mounted?
I have a simple batch-file which starts first veracrypt and after mounting another batch-file:

```<code>C:
cd C:\Program2\VeraCrypt
veracrypt /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q

cd /D D:\backup
start_backup.bat
</code>```

start_backup.bat starts a backup using robocopy (Windows 10) which updates/copies files from one drive C to an external encrypted harddrive D respectively L (mount name).

If veracrypt can't mount the drive for any reason (e.g. there is no drive) the batch start_backup.bat will be started without backup since encrypted drive is not accessible. How can I avoid the start of start_backup.bat in case the drive couldn't be mounted?

The batch-file is written with commands of cmd.exe.

答:
Simple way to do this is using operator: && and || ...

@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"
(
.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q
) && (
cd /D "D:\backup" & call start_backup.bat
) || (
echo/ something really wrong is going on here....
%__APPDIR__%timeout.exe -1
goto :EOF
)

rem ::  continue with more task here.... or goto :EOF
```

<hr>

<ul>
<li>Or...

<hr></li>
</ul>

<pre class="lang-bat prettyprint-override"><code>@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"

.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q  && (
cd /D "D:\backup" & call start_backup.bat ) || (
echo/ Something really wrong is going on here....
%__APPDIR__%timeout.exe -1 & goto :EOF )

rem ::  continue with more task here.... or goto :EOF
</code>```

Option to go through three attempts and with a timeout of 30 seconds

@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"
:loop
set /a "_cnt+=1+0"
(
.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q
) && (
cd /D "D:\backup" & call start_backup.bat
) || (
echo/ something really wrong is going on here....
if "!_cnt!"=="3" (
     echo/ Some is really wrong here....
     %__APPDIR__%timeout.exe -1 & goto :EOF
    ) else (
     echo/ Let's try +1 times until 3 [!_cnt!/10]
     %__APPDIR__%timeout.exe 30
     goto :loop
   )
)
```

<hr>

<ul>
<li>Option to go through three attempts and with a timeout of 30 seconds by using <strong><code>if !errorlevel! 0/1 else</code></strong> as suggested by <strong>@Stephan</strong>...

<hr></li>
</ul>

<pre class="lang-bat prettyprint-override"><code>@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"

:loop
set /a "_cnt+=1+0" && type nul>nul

.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q

if !errorlevel! == 0 (
       cd /D "D:\backup" & call start_backup.bat
     ) else (
       echo/ Something really wrong is going on here....
       if "!_cnt!"=="4" (
            echo/ Some is really wrong here....
            %__APPDIR__%timeout.exe -1 & goto :EOF
           ) else (
             echo/ Let's try +1 times until 03 [0!_cnt!/03]
             %__APPDIR__%timeout.exe 30
             goto :loop
          )
     )
</code>```

Where does goto eof return to

Operator/Syntax Redirection in bat/cmd

Body:
I have a simple batch-file which starts first veracrypt and after mounting another batch-file:

C:
cd C:\Program2\VeraCrypt
veracrypt /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q

cd /D D:\backup
start_backup.bat

start_backup.bat starts a backup using robocopy (Windows 10) which updates/copies files from one drive C to an external encrypted harddrive D respectively L (mount name).

If veracrypt can't mount the drive for any reason (e.g. there is no drive) the batch start_backup.bat will be started without backup since encrypted drive is not accessible. How can I avoid the start of start_backup.bat in case the drive couldn't be mounted?

The batch-file is written with commands of cmd.exe.

Body:
Simple way to do this is using operator: && and || ...

@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"
(
.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q
) && (
cd /D "D:\backup" & call start_backup.bat
) || (
echo/ something really wrong is going on here....
%__APPDIR__%timeout.exe -1
goto :EOF
)

rem ::  continue with more task here.... or goto :EOF

Or...

@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"

.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q  && (
cd /D "D:\backup" & call start_backup.bat ) || (
echo/ Something really wrong is going on here....
%__APPDIR__%timeout.exe -1 & goto :EOF )

rem ::  continue with more task here.... or goto :EOF

Option to go through three attempts and with a timeout of 30 seconds

@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"
:loop
set /a "_cnt+=1+0"
(
.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q
) && (
cd /D "D:\backup" & call start_backup.bat
) || (
echo/ something really wrong is going on here....
if "!_cnt!"=="3" (
     echo/ Some is really wrong here....
     %__APPDIR__%timeout.exe -1 & goto :EOF
    ) else (
     echo/ Let's try +1 times until 3 [!_cnt!/10]
     %__APPDIR__%timeout.exe 30
     goto :loop
   )
)

Option to go through three attempts and with a timeout of 30 seconds by using if !errorlevel! 0/1 else as suggested by @Stephan...

@echo off && setlocal EnableDelayedExpansion

cd /d "C:\Program2\VeraCrypt"

:loop
set /a "_cnt+=1+0" && type nul>nul

.\veracrypt.exe /v \Device\Harddisk2\Partition1 /l L /a /p 123xyz /q

if !errorlevel! == 0 (
       cd /D "D:\backup" & call start_backup.bat
     ) else (
       echo/ Something really wrong is going on here....
       if "!_cnt!"=="4" (
            echo/ Some is really wrong here....
            %__APPDIR__%timeout.exe -1 & goto :EOF
           ) else (
             echo/ Let's try +1 times until 03 [0!_cnt!/03]
             %__APPDIR__%timeout.exe 30
             goto :loop
          )
     )

Where does goto eof return to

Operator/Syntax Redirection in bat/cmd


问:
How to use string tokenizer when reading in from a file?
I am implementing a RPN calculator in Java and need help creating a class to parse the equations into separate tokens.

My input file will have an unknown number of equations similar to the ones shown below:

```
49+62*61-36
4/64
(53+26)
0*72
21-85+75-85
90*76-50+67
46*89-15
34/83-38
20/76/14+92-15
```

I have already implemented my own generic stack class to be used in the program, but I am now trying to figure out how to read data from the input file. Any help appreciated.

I've posted the source code for my stack class at PasteBin, in case it may help.

I have also uploaded the Calculator with no filereading to PasteBin to show what I have done already.

I have now managed to get the file read in and the tokens broken up thanks for the help. I am getting an error when it reaches the end of the file and was wondering how to solve that?

Here is the code:

```<code>import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

 public class TestClass {
  static public void main(String[] args) throws IOException {
 File file = new File("testEquations.txt");
  String[] lines = new String[10];
  try {
    FileReader reader = new FileReader(file);
    BufferedReader buffReader = new BufferedReader(reader);
    int x = 0;
    String s;
    while((s = buffReader.readLine()) != null){
        lines[x] = s;
        x++;
    }
 }
  catch(IOException e){
    System.exit(0);
}
String OPERATORS = "+-*/()";

for (String st : lines) {
    StringTokenizer tokens = new StringTokenizer(st, OPERATORS, true);
    while (tokens.hasMoreTokens()) {
        String token = tokens.nextToken();
        if (OPERATORS.contains(token))
            handleOperator(token);
        else
            handleNumber(token);
    }
     }
   }

private static void handleNumber(String token) {
System.out.println(""+token);

   }

 private static void handleOperator(String token) {
System.out.println(""+token);

  }
  }
</code>```

Also How would I make sure the RPN works line by line? I am getting quite confused by the algorithms I am trying to follow.

答:
```<code>public void actionPerformed(ActionEvent e) {
    double sum=0;
    int count = 0 ;
    try {
        String nomFichier = "Fichier.txt";
        FileReader fr = new FileReader(nomFichier);
        BufferedReader br = new BufferedReader(fr);
        String ligneLue;

        do {
            ligneLue = br.readLine();
            if(ligneLue != null) {
                StringTokenizer st = new StringTokenizer(ligneLue, ";");
                String nom = st.nextToken();
                String prenom = st.nextToken();
                String age = st.nextToken();
                String tele = st.nextToken();
                String adress = st.nextToken();
                String codePostal = st.nextToken();
                String ville = st.nextToken();
                String paye = st.nextToken();
                double note = Double.parseDouble(st.nextToken());
                count++;
            }
        }
        while(ligneLue != null);
        br.close();
        double mediane = count / 2;
        if(mediane % 2 == 0) {
            JOptionPane.showMessageDialog(null, "Le mediane dans le fichier est " + mediane);
        }
        else {
            mediane +=1;
            JOptionPane.showMessageDialog(null, "Le mediane dans le fichier est " + mediane);
        }
    }//fin try
    catch(FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
    catch(IOException ex) {
       System.out.println(ex.getMessage());
    }
}
</code>```

Body:
I am implementing a RPN calculator in Java and need help creating a class to parse the equations into separate tokens.

My input file will have an unknown number of equations similar to the ones shown below:

49+62*61-36
4/64
(53+26)
0*72
21-85+75-85
90*76-50+67
46*89-15
34/83-38
20/76/14+92-15

I have already implemented my own generic stack class to be used in the program, but I am now trying to figure out how to read data from the input file. Any help appreciated.

I've posted the source code for my stack class at PasteBin, in case it may help.

I have also uploaded the Calculator with no filereading to PasteBin to show what I have done already.

I have now managed to get the file read in and the tokens broken up thanks for the help. I am getting an error when it reaches the end of the file and was wondering how to solve that?

Here is the code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;

 public class TestClass {
  static public void main(String[] args) throws IOException {
 File file = new File("testEquations.txt");
  String[] lines = new String[10];
  try {
    FileReader reader = new FileReader(file);
    BufferedReader buffReader = new BufferedReader(reader);
    int x = 0;
    String s;
    while((s = buffReader.readLine()) != null){
        lines[x] = s;
        x++;
    }
 }
  catch(IOException e){
    System.exit(0);
}
String OPERATORS = "+-*/()";

for (String st : lines) {
    StringTokenizer tokens = new StringTokenizer(st, OPERATORS, true);
    while (tokens.hasMoreTokens()) {
        String token = tokens.nextToken();
        if (OPERATORS.contains(token))
            handleOperator(token);
        else
            handleNumber(token);
    }
     }
   }

private static void handleNumber(String token) {
System.out.println(""+token);

   }

 private static void handleOperator(String token) {
System.out.println(""+token);

  }
  }

Also How would I make sure the RPN works line by line? I am getting quite confused by the algorithms I am trying to follow.


问:
Flutter: What are the ways of making "lists" without having its own scroll?
In my Flutter app, I have a ListView inside a ListView. Please check below

```<code> ListView(
   children: < Widget > [
    //Stack Widget
    //More Widgets
    Container(
     height: MediaQuery.of(context).size.height,
     child: ListView.builder(
      physics: NeverScrollableScrollPhysics(), //Disable Scrolling
      itemCount: 100,
      itemBuilder: (BuildContext context, int index) {
       return Container(
        margin: EdgeInsets.only(bottom: 10, left: 10, right: 10),
        child: _createAdvertisement(),
       );
      },
     ),
    ),
   ],
  );
</code>```

There are 100 items in the second ListView and I used physics: NeverScrollableScrollPhysics() to stop it from scrolling. I do not want this to scroll because the top ListView can scroll the entire page, so I want the content in the second ListView to be added to the bottom of the page. User can scroll the entire page up, to see the content below.

However my trick of using physics: NeverScrollableScrollPhysics() didnt work, instead it limited the number of elements the ListView is going to generate. As a result, now I have less than 10 items in that listview, instead of 100.

How can I fix this issue?

答:
You can add "shrinkWrap: true," and remove "height: MediaQuery.of(context).size.height,".

```<code>ListView(
  children: <Widget>[
    Text("1"),
    Text("2"),
    Container(
      child: ListView.builder(
        shrinkWrap: true,  // add this line.
        physics: NeverScrollableScrollPhysics(), //Disable Scrolling
        itemCount: 100,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            margin: EdgeInsets.only(bottom: 10, left: 10, right: 10),
            child: Text("test"),
          );
        },
      ),
    ),
    Text("3"),
  ],
),
</code>```

Body:
In my Flutter app, I have a ListView inside a ListView. Please check below

 ListView(
   children: < Widget > [
    //Stack Widget
    //More Widgets
    Container(
     height: MediaQuery.of(context).size.height,
     child: ListView.builder(
      physics: NeverScrollableScrollPhysics(), //Disable Scrolling
      itemCount: 100,
      itemBuilder: (BuildContext context, int index) {
       return Container(
        margin: EdgeInsets.only(bottom: 10, left: 10, right: 10),
        child: _createAdvertisement(),
       );
      },
     ),
    ),
   ],
  );

There are 100 items in the second ListView and I used physics: NeverScrollableScrollPhysics() to stop it from scrolling. I do not want this to scroll because the top ListView can scroll the entire page, so I want the content in the second ListView to be added to the bottom of the page. User can scroll the entire page up, to see the content below.

However my trick of using physics: NeverScrollableScrollPhysics() didnt work, instead it limited the number of elements the ListView is going to generate. As a result, now I have less than 10 items in that listview, instead of 100.

How can I fix this issue?

Body:
You can add "shrinkWrap: true," and remove "height: MediaQuery.of(context).size.height,".

ListView(
  children: <Widget>[
    Text("1"),
    Text("2"),
    Container(
      child: ListView.builder(
        shrinkWrap: true,  // add this line.
        physics: NeverScrollableScrollPhysics(), //Disable Scrolling
        itemCount: 100,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            margin: EdgeInsets.only(bottom: 10, left: 10, right: 10),
            child: Text("test"),
          );
        },
      ),
    ),
    Text("3"),
  ],
),


问:
Declare optional last element in array?
I want to declare a Typescript array type in which the last element is optional. Is there any elegant way to achieve this?

```<code>const test = (a: [string, string, any | undefined]) => console.log(a)
test(['foo', 'bar'])
</code>```

In the test(...) function call, ts verbose this error

```<code>Argument of type '[string, string]' is not assignable to parameter of type '[string, string, any]'.
  Property '2' is missing in type '[string, string]' but required in type '[string, string, any]'.(2345)
</code>```

答:
```<code>const test = (a: [string, string, any?]) => console.log(a)
test(['foo', 'bar'])
</code>```

Hope this helps.

Title: Declare optional last element in array?

Body:
I want to declare a Typescript array type in which the last element is optional. Is there any elegant way to achieve this?

const test = (a: [string, string, any | undefined]) => console.log(a)
test(['foo', 'bar'])

In the test(...) function call, ts verbose this error

Argument of type '[string, string]' is not assignable to parameter of type '[string, string, any]'.
  Property '2' is missing in type '[string, string]' but required in type '[string, string, any]'.(2345)

Body:
const test = (a: [string, string, any?]) => console.log(a)
test(['foo', 'bar'])

Hope this helps.