问:
How do I plot two regression lines on the same plot with different x and y?
I am required to fit two simple linear regression lines, one with "y = father" and "x = son", the other with "y = son" and "x = father". I was able to do this with no issues and have gathered the correct equations. However, I am also required to plot them on the same scatterplot which is where I am running into some trouble. I am curious if there is a way I can plot the "y = father" and "x = son" regression line onto the scatterplot where y = son and x = father. Or is there a way I can combine the following two plots?

```<code>ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(slope = 0.46139, intercept = 37.28761, col = "blue") +
   theme_bw()
</code>```
```<code>ggplot(galton_heights, aes(x = son, y = father)) +
   geom_point() +
   geom_abline(slope = 0.40713, intercept = 40.93831, col = "red") +
   coord_flip() +
   theme_bw()
</code>```

I was told my plot should look similar to this which is the two separate graphs I have above combined together.

答:
I think I may have a different set of data than you, but the principle is the same. Let's run a linear regression of son's heights on father's heights, then repeat it vice-versa

father_x <- lm(son ~ father, data = galton_heights)
son_x    <- lm(father ~ son, data = galton_heights)

coef(father_x)
#> (Intercept)      father
#>   33.886604    0.514093

coef(son_x)
#> (Intercept)         son
#>    34.10745     0.48890
```
<p>Now, obviously the coefficients are different. The formula for son's heights based on father's heights is:</p>
<pre class="lang-r prettyprint-override"><code>son = 0.514093 * father + 33.886604
</code>```

But if we take the other regression, we can rearrange it to solve for son's heights based on fathers' heights too:

```<code>father = 0.48890 * son + 34.10745

son = (father - 34.10745)/0.48890

son = 2.045408 * father - 69.76365
</code>```

This gives us plotting coefficients for our two lines:

ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(aes(slope = 0.514093, intercept = 33.886604,
               colour = "son height regressed\non father height"),
               size = 2) +
   geom_abline(aes(slope = 2.045408, intercept = -69.76365,
               color = "father height regressed\non son height"),
               size = 2) +
   theme_bw()
```
<p><img src="https://i.stack.imgur.com/XCvTW.png" alt="enter image description here" /></p>
<p>Notice the symmetry when we flip co-ordinates:</p>
<pre class="lang-r prettyprint-override"><code>ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(aes(slope = 0.514093, intercept = 33.886604,
               colour = "son height regressed\non father height"),
               size = 2) +
   geom_abline(aes(slope = 2.045408, intercept = -69.76365,
               color = "father height regressed\non son height"),
               size = 2) +
   theme_bw() +
   coord_flip()
</code>```

Created on 2022-02-12 by the reprex package (v2.0.1)

Body:
I am required to fit two simple linear regression lines, one with "y = father" and "x = son", the other with "y = son" and "x = father". I was able to do this with no issues and have gathered the correct equations. However, I am also required to plot them on the same scatterplot which is where I am running into some trouble. I am curious if there is a way I can plot the "y = father" and "x = son" regression line onto the scatterplot where y = son and x = father. Or is there a way I can combine the following two plots?

ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(slope = 0.46139, intercept = 37.28761, col = "blue") +
   theme_bw()

ggplot(galton_heights, aes(x = son, y = father)) +
   geom_point() +
   geom_abline(slope = 0.40713, intercept = 40.93831, col = "red") +
   coord_flip() +
   theme_bw()

I was told my plot should look similar to this which is the two separate graphs I have above combined together.

Body:
I think I may have a different set of data than you, but the principle is the same. Let's run a linear regression of son's heights on father's heights, then repeat it vice-versa

father_x <- lm(son ~ father, data = galton_heights)
son_x    <- lm(father ~ son, data = galton_heights)

coef(father_x)
#> (Intercept)      father
#>   33.886604    0.514093

coef(son_x)
#> (Intercept)         son
#>    34.10745     0.48890

Now, obviously the coefficients are different. The formula for son's heights based on father's heights is:

son = 0.514093 * father + 33.886604

But if we take the other regression, we can rearrange it to solve for son's heights based on fathers' heights too:

father = 0.48890 * son + 34.10745

son = (father - 34.10745)/0.48890

son = 2.045408 * father - 69.76365

This gives us plotting coefficients for our two lines:

ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(aes(slope = 0.514093, intercept = 33.886604,
               colour = "son height regressed\non father height"),
               size = 2) +
   geom_abline(aes(slope = 2.045408, intercept = -69.76365,
               color = "father height regressed\non son height"),
               size = 2) +
   theme_bw()

Notice the symmetry when we flip co-ordinates:

ggplot(galton_heights, aes(x = father, y = son)) +
   geom_point() +
   geom_abline(aes(slope = 0.514093, intercept = 33.886604,
               colour = "son height regressed\non father height"),
               size = 2) +
   geom_abline(aes(slope = 2.045408, intercept = -69.76365,
               color = "father height regressed\non son height"),
               size = 2) +
   theme_bw() +
   coord_flip()

Created on 2022-02-12 by the reprex package (v2.0.1)


来源: stackexchange

问:
rJava on macOS with M1X processor
Does anybody know if there is a possibility to install and use the rJava package in R when having the following configuration:

MacBookPro with M1X processor,

macOs 12.1 Monterrey,

Java11, build Azul Zulu 11.0.13+8

R 4.1.2?

After installation from CRAN, an attempt to load rJava results in the following error:

```<code>Error: package or namespace load failed for 'rJava':
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(jli, FALSE)
  error: unable to load shared object '/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/lib/jli/libjli.dylib':
  dlopen(/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/lib/jli/libjli.dylib, 0x000A): tried: '/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/lib/jli/libjli.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/usr/lib/libjli.dylib' (no such file)
</code>```

Thank you very much for your help!
Tomek

答:
You are running Intel R on M1 machine in emulation.

Install native arm64 R instead (the R-4.1.2-arm64.pkg download from CRAN).

ContentLicense: CC BY-SA 4.0

Title: rJava on macOS with M1X processor

Body:
Does anybody know if there is a possibility to install and use the rJava package in R when having the following configuration:

MacBookPro with M1X processor,

macOs 12.1 Monterrey,

Java11, build Azul Zulu 11.0.13+8

R 4.1.2?

After installation from CRAN, an attempt to load rJava results in the following error:

Error: package or namespace load failed for 'rJava':
 .onLoad failed in loadNamespace() for 'rJava', details:
  call: dyn.load(jli, FALSE)
  error: unable to load shared object '/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/lib/jli/libjli.dylib':
  dlopen(/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/lib/jli/libjli.dylib, 0x000A): tried: '/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home/lib/jli/libjli.dylib' (mach-o file, but is an incompatible architecture (have 'arm64', need 'x86_64')), '/usr/lib/libjli.dylib' (no such file)

Thank you very much for your help!
Tomek


问:
Appeasing MyPy trying to use an instance variable
If I have the file mypytest/models.py that looks like this:

from typing import Type

class FakeBaseModel:
    pass

class FakeDatabase:
    Base: Type[FakeBaseModel]

    def __init__(self) -> None:
        self.Base = FakeBaseModel

db = FakeDatabase()

class FakeModel(db.Base):
    pass
```
<p>And I run <code>mypy .</code>, I get the following output:</p>
```[mypytest {mypytest}]$ mypy .
mypytest/models.py:18: error: Name "db.Base" is not defined
Found 1 error in 1 file (checked 2 source files)
```

Clearly, though, db.Base is defined. How do I get mypy to recognize it?

答:
I believe the problem here is that db.Base is a variable, not a type alias.

It's unclear from your example exactly why you need a dynamic base class. Inlining FakeBaseModel would obviously work; you could also just use a type alias while running the type checking:

from typing import Type, TYPE_CHECKING

# *snip*

db = FakeDatabase()

if TYPE_CHECKING:
    FakeBase = FakeBaseModel
else:
    FakeBase = db.Base

class FakeModel(FakeBase):
    pass
```

This will produce valid type checking based on what you've provided (basically, as long as FakeModel only uses what's in FakeBaseModel so it's safe to treat it as one).

Body:
If I have the file mypytest/models.py that looks like this:

from typing import Type

class FakeBaseModel:
    pass

class FakeDatabase:
    Base: Type[FakeBaseModel]

    def __init__(self) -> None:
        self.Base = FakeBaseModel

db = FakeDatabase()

class FakeModel(db.Base):
    pass

And I run mypy ., I get the following output:

[mypytest {mypytest}]$ mypy .
mypytest/models.py:18: error: Name "db.Base" is not defined
Found 1 error in 1 file (checked 2 source files)

Clearly, though, db.Base is defined. How do I get mypy to recognize it?

Body:
I believe the problem here is that db.Base is a variable, not a type alias.

It's unclear from your example exactly why you need a dynamic base class. Inlining FakeBaseModel would obviously work; you could also just use a type alias while running the type checking:

from typing import Type, TYPE_CHECKING

# *snip*

db = FakeDatabase()

if TYPE_CHECKING:
    FakeBase = FakeBaseModel
else:
    FakeBase = db.Base

class FakeModel(FakeBase):
    pass

This will produce valid type checking based on what you've provided (basically, as long as FakeModel only uses what's in FakeBaseModel so it's safe to treat it as one).


问:
finding and matching next address, but want to drop if string is too close
I have a somewhat messy address database that track moves by a given order in long format. I want to add columns to match it to the next address, but I want to skip it / drop the entry if the next address is too close.

The process I have so far mirrors this one:

```<code>ID = c("A", "A", "A", "A", "B", "B", "B")
Set = c(1, 2, 3, 4, 1, 2, 3)
Street = c("123 Mulburry St", "234 Willow St", "235 Willow St", "492 Basin st", "231 Farrow st", "492 Little st", "231 Big st")

df = data.frame(ID, Set, Street)

df <- df %>% mutate(set_id = paste0(ID,  "_", Set))
df <- df %>% mutate(next_id = paste0(ID,  "_", (Set + 1)))

match <- subset(df, select = c(set_id, Street))
match <- match %>% rename(next_street = Street)

df <- left_join(df, match, by = c("next_id" = "set_id"))
df$problem <- stringdist(df$Street, df$next_street) < 2
</code>```

However, I would want to drop A3, where the set goes from 234 Willow St to 235 Willow St, assuming that this is an error / typo (basically, drop what is flagged in df$problem). But I can't really figure how I would drop that and replace it with the correct line (which, would be from A_2 to A_4).

答:
This looks at the next address and drops it if it is close. It uses agrepl which can also be fine tuned with cost and max.distance

```<code>library(dplyr)

df %>%
  group_by(ID) %>%
  mutate(Street2=lag(Street)) %>%
  rowwise() %>%
  mutate(Street=ifelse(agrepl(Street, Street2)==T,NA,Street), Street2=NULL) %>%
  ungroup()
# A tibble: 7 × 3
  ID      Set Street
  <chr> <dbl> <chr>
1 A         1 123 Mulburry St
2 A         2 234 Willow St
3 A         3 NA
4 A         4 492 Basin st
5 B         1 231 Farrow st
6 B         2 492 Little st
7 B         3 231 Big st
</code>```

Body:
I have a somewhat messy address database that track moves by a given order in long format. I want to add columns to match it to the next address, but I want to skip it / drop the entry if the next address is too close.

The process I have so far mirrors this one:

ID = c("A", "A", "A", "A", "B", "B", "B")
Set = c(1, 2, 3, 4, 1, 2, 3)
Street = c("123 Mulburry St", "234 Willow St", "235 Willow St", "492 Basin st", "231 Farrow st", "492 Little st", "231 Big st")

df = data.frame(ID, Set, Street)

df <- df %>% mutate(set_id = paste0(ID,  "_", Set))
df <- df %>% mutate(next_id = paste0(ID,  "_", (Set + 1)))

match <- subset(df, select = c(set_id, Street))
match <- match %>% rename(next_street = Street)

df <- left_join(df, match, by = c("next_id" = "set_id"))
df$problem <- stringdist(df$Street, df$next_street) < 2

However, I would want to drop A3, where the set goes from 234 Willow St to 235 Willow St, assuming that this is an error / typo (basically, drop what is flagged in df$problem). But I can't really figure how I would drop that and replace it with the correct line (which, would be from A_2 to A_4).

Body:
This looks at the next address and drops it if it is close. It uses agrepl which can also be fine tuned with cost and max.distance

library(dplyr)

df %>%
  group_by(ID) %>%
  mutate(Street2=lag(Street)) %>%
  rowwise() %>%
  mutate(Street=ifelse(agrepl(Street, Street2)==T,NA,Street), Street2=NULL) %>%
  ungroup()
# A tibble: 7 × 3
  ID      Set Street
  <chr> <dbl> <chr>
1 A         1 123 Mulburry St
2 A         2 234 Willow St
3 A         3 NA
4 A         4 492 Basin st
5 B         1 231 Farrow st
6 B         2 492 Little st
7 B         3 231 Big st


问:
calculating running speed
My problem is a wrong result.
I have a function this function has a distance and a time.
The result I want to achieve is calculating running speed.

function runningPace(distance, time) {
  let result = time.replace(":", ".")
  let fl = parseFloat(result)
  let calc = fl / distance
  let num = calc.toFixed(2) + ''
  if(num.length === 1) {
    num = num + '.00'
  }
  let rep = num.replace('.', ':')
  console.log(distance, time, result, fl, calc, rep, num)

  return rep;
}

console.log(runningPace(5, '25:00')) // '5:00'
console.log(runningPace(4.99, '22:32')) // '4:30'```

I wrote such a function. Sorry for the naming, I'll fix it when I get it fixed.

When I test this code, the output is:

expected '4:47' to equal '4:30'

'4:30' => four minute thirty second

How can I find a solution? Thanks everyone in advance.

答:
convert anything in seconds:

function runningPace(dist, time)
  {
  let
    [ mn, sc ] = time.split(':').map(Number)
  , fl         = Math.floor(((mn *60) + sc) / dist)
    ;
  sc = fl % 60
  mn = (fl - sc) / 60

  return `${mn}:${(sc<9)?'0'+sc:sc}`
}

console.log(runningPace( 5,    '25:00'))  // 5:00
console.log(runningPace( 4.99, '22:32'))  // 4:30```

Title: calculating running speed

Body:
My problem is a wrong result.
I have a function this function has a distance and a time.
The result I want to achieve is calculating running speed.

function runningPace(distance, time) {
  let result = time.replace(":", ".")
  let fl = parseFloat(result)
  let calc = fl / distance
  let num = calc.toFixed(2) + ''
  if(num.length === 1) {
    num = num + '.00'
  }
  let rep = num.replace('.', ':')
  console.log(distance, time, result, fl, calc, rep, num)

  return rep;
}

console.log(runningPace(5, '25:00')) // '5:00'
console.log(runningPace(4.99, '22:32')) // '4:30'

I wrote such a function. Sorry for the naming, I'll fix it when I get it fixed.

When I test this code, the output is:

expected '4:47' to equal '4:30'

'4:30' => four minute thirty second

How can I find a solution? Thanks everyone in advance.


问:
How to limit the columns returned with a nested relationship - Laravel Eloquent
I'm trying to limit the columns returned on an eloquent relationship with no luck.

The following works:

```<code>$books = Book::with('author:id,name')->get();
</code>```

but what I need does not work:

```<code>$books = Book::with('author.company:id,name,phone')->get();
</code>```

答:
You are eager loading specific columns.

When using this feature, you should always include the id column and
any relevant foreign key columns in the list of columns you wish to
retrieve.

So check you company table and make sure you add all foreign key columns,

For example: If this is my company table has a column called owner_id, address_id, you have to add it to the with() method like this.

```<code>$books = Book::with('author:id,name, owner_id, address_id')->get();
</code>```

Body:
I'm trying to limit the columns returned on an eloquent relationship with no luck.

The following works:

$books = Book::with('author:id,name')->get();

but what I need does not work:

$books = Book::with('author.company:id,name,phone')->get();

Body:
You are eager loading specific columns.

When using this feature, you should always include the id column and
any relevant foreign key columns in the list of columns you wish to
retrieve.

So check you company table and make sure you add all foreign key columns,

For example: If this is my company table has a column called owner_id, address_id, you have to add it to the with() method like this.

$books = Book::with('author:id,name, owner_id, address_id')->get();


问:
How to keep grouped variables together in training and test data
I'm making and testing the accuracy of age extrapolations from growth measurements and to do this I have to split my data into my training and test data.

The issue is that individuals in my data set were measured multiple times and sometimes they were measured twice, sometimes 3 times. In the dataset Birds is the individual chick, age is the age at measurement, and wing is that measurement value.

I've tried using the group_by function to keep their measurements together, but this doesn't seem to work. I also tried nesting the data but that puts the data in a new table and my code doesn't like that. Is there another way I could keep the groups together while still randomly assigning them to training and test data?

```<code>library('tidyverse')
library("ggplot2")
library("readxl")
library("writexl")
library('dplyr')
library('Rmisc')
library('cowplot')
library('purrr')
library('caTools')
library('MLmetrics')

Bird<-c(1,1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,)
Age<-c(10,17,27,17,28,10,17,27,10,17,10,17,28,10,17,28,10,17,28,10,17,28,10,17,28,11,18,)
Wing<-c(39,63,98,61,99,34,48,80,30,37,35,51,71,40,55,79,34,47,77,36,55,84,35,55,88,36,59,)
Set14<-data.frame(Bird, Age, Wing) %>%
  group_by(Bird)
Set14$Bird<-as.factor((Set14$Bird))
Set14

sample_size = floor(0.7*nrow(Set14))

picked = sample(seq_len(nrow(Set14)),size = sample_size)
Training =Set14[picked,]
Training
Test =Set14[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

MAPE(error$actual, error$calculated)
</code>```

Body:
I'm making and testing the accuracy of age extrapolations from growth measurements and to do this I have to split my data into my training and test data.

The issue is that individuals in my data set were measured multiple times and sometimes they were measured twice, sometimes 3 times. In the dataset Birds is the individual chick, age is the age at measurement, and wing is that measurement value.

I've tried using the group_by function to keep their measurements together, but this doesn't seem to work. I also tried nesting the data but that puts the data in a new table and my code doesn't like that. Is there another way I could keep the groups together while still randomly assigning them to training and test data?

library('tidyverse')
library("ggplot2")
library("readxl")
library("writexl")
library('dplyr')
library('Rmisc')
library('cowplot')
library('purrr')
library('caTools')
library('MLmetrics')

Bird<-c(1,1,1,2,2,3,3,3,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9,10,10,)
Age<-c(10,17,27,17,28,10,17,27,10,17,10,17,28,10,17,28,10,17,28,10,17,28,10,17,28,11,18,)
Wing<-c(39,63,98,61,99,34,48,80,30,37,35,51,71,40,55,79,34,47,77,36,55,84,35,55,88,36,59,)
Set14<-data.frame(Bird, Age, Wing) %>%
  group_by(Bird)
Set14$Bird<-as.factor((Set14$Bird))
Set14

sample_size = floor(0.7*nrow(Set14))

picked = sample(seq_len(nrow(Set14)),size = sample_size)
Training =Set14[picked,]
Training
Test =Set14[-picked,]
Test

trm<-lm(Age~Wing, data=Training)

predval<-predict(object=trm,
                 newdata=Test)
predval

error<-data.frame(actual=Test$Age, calculated=predval)
error

MAPE(error$actual, error$calculated)

Body:
In Base R you could do:

a <- as.integer(Set14$Bird)
train_index <- a %in% sample(n<-length(unique(a)), 0.7*n)
train <- set14[train, ]
test <- set14[!train, ]

in Tidyverse:

ungroup(Set14) %>%
  nest_by(Bird) %>%
  ungroup() %>%
  mutate(tt = floor(.7*n()),
     tt = sample(rep(c('train', 'test'), c(tt[1], n()-tt[1])))) %>%
  unnest(data) %>%
  group_split(tt, .keep = FALSE)

[[1]]
# A tibble: 9 x 3
  Bird    Age  Wing
  <fct> <dbl> <dbl>
1 1        10    39
2 1        17    63
3 1        27    98
4 3        10    34
5 3        17    48
6 3        27    80
7 7        10    34
8 7        17    47
9 7        28    77

[[2]]
# A tibble: 18 x 3
   Bird    Age  Wing
   <fct> <dbl> <dbl>
 1 2        17    61
 2 2        28    99
 3 4        10    30
 4 4        17    37
 5 5        10    35
 6 5        17    51
 7 5        28    71
 8 6        10    40
 9 6        17    55
10 6        28    79
11 8        10    36
12 8        17    55
13 8        28    84
14 9        10    35
15 9        17    55
16 9        28    88
17 10       11    36
18 10       18    59


问:
How to save commit changes without editing when doing a merge in a script?
I wonder how to add in my basic script some commands with nano, Ctrl-O, Enter, Ctrl-X, Enter. You can see what I want at the end of the script. It is after git merge, I just need to save commit changes (formality)</p>
```<code>#!/bin/bash

## Set Local Rebase ##
git config pull.rebase true

## Update OpenWRT Scripts
./scripts/feeds update -a
./scripts/feeds install -a

## 5.4 kernel
git remote add wrt https://github.com/james/openwrt.git
git fetch james
git checkout -b wrt james/kernel5.4-qsdk10.0
git checkout master
git merge wrt
*ctrl o*
*enter*
*ctrl x*
*enter*
</code>```

答:
Instead of having to interact with your editor to set the merge commit message, you can use the -m flag to specify a commit message without opening an editor, or the --no-edit to accept the default message. You can also use git fmt-merge-msg to help generate a message to pass to -m, but that's a bit harder.

Using --no-edit:

```<code>git merge --no-edit
</code>```

Using -m:

```<code>git merge -m "automated merge by my script"
</code>```

Body:
I wonder how to add in my basic script some commands with nano, Ctrl-O, Enter, Ctrl-X, Enter. You can see what I want at the end of the script. It is after git merge, I just need to save commit changes (formality)

#!/bin/bash

## Set Local Rebase ##
git config pull.rebase true

## Update OpenWRT Scripts
./scripts/feeds update -a
./scripts/feeds install -a

## 5.4 kernel
git remote add wrt https://github.com/james/openwrt.git
git fetch james
git checkout -b wrt james/kernel5.4-qsdk10.0
git checkout master
git merge wrt
*ctrl o*
*enter*
*ctrl x*
*enter*

Body:
Instead of having to interact with your editor to set the merge commit message, you can use the -m flag to specify a commit message without opening an editor, or the --no-edit to accept the default message. You can also use git fmt-merge-msg to help generate a message to pass to -m, but that's a bit harder.

Using --no-edit:

git merge --no-edit

Using -m:

git merge -m "automated merge by my script"


问:
Why simple mysql++ code compiles standalone, but not in project?
At first, small program:

```<code>#include <mysql++.h>
using namespace mysqlpp;

void mainuu ()
{ Connection conn("mysql", "localhost", "root", "pwd");}
</code>```

If I compile it as one file in CodeLite or in such way:

```<code>g++ -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -o Test mysql_api.cpp
</code>```

it's ok
but, when I try to build whole project with this file I get this:

```<code>g++ -o ./Debug/server ./Debug/main.o ./Debug/log.o ./Debug/packet.o ./Debug/mysql_api.o  -L.
./Debug/mysql_api.o: In function `mainuu()':
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::Connection(char const*, char const*, char const*, char const*, unsigned int)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:12: undefined reference to `mysqlpp::Connection::query(char const*)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(char const*, bool)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::operator<<(mysqlpp::quote_type1, mysqlpp::SQLTypeAdapter const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:19: undefined reference to `mysqlpp::operator<<(std::basic_ostream<char, std::char_traits<char> >&, mysqlpp::String const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
./Debug/mysql_api.o: In function `mysqlpp::Row::operator[](int) const':
/usr/include/mysql++/row.h:328: undefined reference to `mysqlpp::Row::at(unsigned int) const'
./Debug/mysql_api.o: In function `mysqlpp::Query::store()':
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::str(mysqlpp::SQLQueryParms&)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::store(mysqlpp::SQLTypeAdapter const&)'
collect2: ld returned 1 exit status
make[1]: *** [Debug/server] Error 1
make[1]: Leaving directory `/home/asyler/.codelite/workspace/test/server'
make: *** [All] Error 2
</code>```

Here is CodeLite g++ compiler settings:

```<code>-g -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -L/usr/lib/mysql -L/usr/lib/mysql++ -lmysql++
</code>```

答: Looks like you need to edit CodeLite project settings and add these settings -lmysqlclient -lmysqlpp that you pass in command line. Fill Library Path and Libraries fields on Linker tab.

ContentLicense: CC BY-SA 3.0

Body:
At first, small program:

#include <mysql++.h>
using namespace mysqlpp;

void mainuu ()
{ Connection conn("mysql", "localhost", "root", "pwd");}

If I compile it as one file in CodeLite or in such way:

g++ -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -o Test mysql_api.cpp

it's ok
but, when I try to build whole project with this file I get this:

g++ -o ./Debug/server ./Debug/main.o ./Debug/log.o ./Debug/packet.o ./Debug/mysql_api.o  -L.
./Debug/mysql_api.o: In function `mainuu()':
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::Connection(char const*, char const*, char const*, char const*, unsigned int)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:12: undefined reference to `mysqlpp::Connection::query(char const*)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(char const*, bool)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:13: undefined reference to `mysqlpp::operator<<(mysqlpp::quote_type1, mysqlpp::SQLTypeAdapter const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:19: undefined reference to `mysqlpp::operator<<(std::basic_ostream<char, std::char_traits<char> >&, mysqlpp::String const&)'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
/home/asyler/.codelite/workspace/test/server/mysql_api.cpp:10: undefined reference to `mysqlpp::Connection::~Connection()'
./Debug/mysql_api.o: In function `mysqlpp::Row::operator[](int) const':
/usr/include/mysql++/row.h:328: undefined reference to `mysqlpp::Row::at(unsigned int) const'
./Debug/mysql_api.o: In function `mysqlpp::Query::store()':
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::str(mysqlpp::SQLQueryParms&)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::SQLTypeAdapter::SQLTypeAdapter(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool)'
/usr/include/mysql++/query.h:467: undefined reference to `mysqlpp::Query::store(mysqlpp::SQLTypeAdapter const&)'
collect2: ld returned 1 exit status
make[1]: *** [Debug/server] Error 1
make[1]: Leaving directory `/home/asyler/.codelite/workspace/test/server'
make: *** [All] Error 2

Here is CodeLite g++ compiler settings:

-g -I/usr/include/mysql -I/usr/include/mysql++ -lmysqlclient -lmysqlpp -L/usr/lib/mysql -L/usr/lib/mysql++ -lmysql++


问:
How test the accuracy for tensorflow lite model
I train a CNN tensorflow model, and convert for a tensorflow lite model. And now i want to know  how can i make the evaluate for the TFLITE model.

I make this code :

```<code>interpreter = tf.lite.Interpreter(model_save)
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

interpreter.resize_tensor_input(input_details[0]['index'], ((len(X_test)), 180,180, 3))
interpreter.resize_tensor_input(output_details[0]['index'], (len(X_test), 4))
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

interpreter.set_tensor(input_details[0]['index'], X_test)
interpreter.invoke()

loss, accuracy = interpreter.evaluate(X_test)
</code>```

But, show me the error:

```<code>'Interpreter' object has no attribute 'evaluate'
</code>```

After this I tried:

```<code>loss, accuracy = interpreter.evaluate_tflite(X_test)
</code>```

But apparently this just it works for Model Makers model.
So now i just don't know how to preceed.

答:
If your tflite model has a signature, then you can leverage the signature, see the guide.

If the model doesn't have signatures, then you can see what are the outputs like this

```<code>output_details = interpreter.get_output_details()
# Assuming you have 2 outputs
output_1 = interpreter.get_tensor(output_details[0]['index'])
output_2 = interpreter.get_tensor(output_details[1]['index'])
</code>```

The signature is the suggested way, and is safer for output reordering issues.

Body:
I train a CNN tensorflow model, and convert for a tensorflow lite model. And now i want to know  how can i make the evaluate for the TFLITE model.

I make this code :

interpreter = tf.lite.Interpreter(model_save)
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

interpreter.resize_tensor_input(input_details[0]['index'], ((len(X_test)), 180,180, 3))
interpreter.resize_tensor_input(output_details[0]['index'], (len(X_test), 4))
interpreter.allocate_tensors()

input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

interpreter.set_tensor(input_details[0]['index'], X_test)
interpreter.invoke()

loss, accuracy = interpreter.evaluate(X_test)

But, show me the error:

'Interpreter' object has no attribute 'evaluate'

After this I tried:

loss, accuracy = interpreter.evaluate_tflite(X_test)

But apparently this just it works for Model Makers model.
So now i just don't know how to preceed.

Body:
If your tflite model has a signature, then you can leverage the signature, see the guide.

If the model doesn't have signatures, then you can see what are the outputs like this

output_details = interpreter.get_output_details()
# Assuming you have 2 outputs
output_1 = interpreter.get_tensor(output_details[0]['index'])
output_2 = interpreter.get_tensor(output_details[1]['index'])

The signature is the suggested way, and is safer for output reordering issues.


问:
Is It Possible to Return the Sum from addmargins()
I am working with a motor vehicle thefts dataset.

I created a Month column, then a two-way table based on Month and Arrest.

```<code>addmargins(table(vehicle_thefts$Month, vehicle_thefts$Arrest))
</code>```

Is it possible to return just the total number of thefts (191,641)?

答:
It will be simpler to use

```<code>tbl <- table(vehicle_thefts$Month, vehicle_thefts$Arrest)
sum(tbl)
</code>```

But if you really need to get it from addmargins:

```<code>addmargins(tbl)[nrow(tbl)+1, ncol(tbl)+1]
</code>```

Body:
I am working with a motor vehicle thefts dataset.

I created a Month column, then a two-way table based on Month and Arrest.

addmargins(table(vehicle_thefts$Month, vehicle_thefts$Arrest))

Is it possible to return just the total number of thefts (191,641)?

Body:
It will be simpler to use

tbl <- table(vehicle_thefts$Month, vehicle_thefts$Arrest)
sum(tbl)

But if you really need to get it from addmargins:

addmargins(tbl)[nrow(tbl)+1, ncol(tbl)+1]


问:
R Shiny and Datatables ObserveEvent Reset Value
I have a table where the first column contains a radio button. If a user clicks any cell in a row, it updates the table so that its radio button is selected. This then updates a second table with the values from the selected row. In my actual app, I get this to work, however as the first table is dynamically changed the cell_clicked value in an observeEvent still changes the value and the wrong radio button is showed. This only affects the display as the second table correctly updates.

For a reproducible example I made just the first table. If you change the pet choice to 'dog' the table only has 5 rows, while if 'cat' it will have 10 rows. Select any cell in the third row. Change the select to dog and the radio for the third row will automatically be selected. Now change the choice to cat, choose a row > 5 (7 for instance). Now change the input to dog and no radio button will be selected. This is because the observeEvent changes the selected row to 7, but there is no seventh row now.

I want the radio button to go back to the first row any time the reactive dataframe is changed. How do I go about doing this?

See reproducible example here:

```<code>library(shiny)
library(shinydashboard)
library(tidyverse)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Testing Observe Event on Cell Clicked"),
  #dashboard sidebar-----
  dashboardSidebar(
    sidebarMenu(id = "tabs",
                menuItem("Home", tabName = "home_tab")
    )
  ),
  #dashboard Body ----
  dashboardBody(
    tabItems(
      #Home page-----
      tabItem(tabName = "home_tab",
              fluidPage(
                fluidRow(h2("Home Page")),
                fluidRow(selectInput("petChoice", "Please select cats or dogs", c('cat','dog'))),
                fluidRow(dataTableOutput("table"))
              )
      )
    )
  )
)

server <- function(input, output, session) {

  #min reprex of a reactive dataframe I create
  myDF <- reactive({
    t<- data.frame(Months = month.name[1:10],
              Letters = letters[1:10],
              Numbers = c(1:10),
              Animal = paste(rep(input$petChoice,10), 1:10)) %>%
      mutate(Select = if_else(row_number()==1,
                             '<input type="radio" name="%s" value="%s" checked="checked"/>',
                             '<input type="radio" name="%s" value="%s"/>'),
            .before="Months")
    if(input$petChoice == 'dog') {
      t<- t %>%
        filter(Numbers>5)
    }
    t
  })

  output$table <- renderDataTable({
    DT::datatable(myDF(),
                  rownames = F, selection = 'single',
                  escape = FALSE,
                  options = list(dom = 't', pageLength = 10)) %>%
      formatStyle(c(0:3), cursor = "pointer")
  })

  #give radio choices to the grouped by genotype table
  observeEvent(input$table_cell_clicked, {
    info = input$table_cell_clicked
    # do nothing if not clicked yet
    if (is.null(info$value)) return()

    #change the radio button
    output$table <- renderDataTable({
      DT::datatable(myDF() %>%
                      mutate(Select = if_else(row_number()==info$row,
                                              '<input type="radio" name="%s" value="%s" checked="checked"/>',
                                              '<input type="radio" name="%s" value="%s"/>')),
                    rownames = F, selection =  list(mode = 'single', selected = c(info$row)),
                    escape = FALSE,
                    options = list(dom = 't', ordering=F, pageLength = 10)) %>%
        formatStyle(c(0:3), cursor = "pointer")
    })

  })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

答:
Try this</p>
```<code>server <- function(input, output, session) {

  my <- reactiveValues(DF = NULL,newrow=1)

  observeEvent(input$petChoice, {
    my$newrow <- 1
    if(input$petChoice == 'dog') n <- 6 else n <- 1
    t<- data.frame(Months = month.name[n:10],
                   Letters = letters[n:10],
                   Numbers = c(n:10),
                   Animal = paste(rep(input$petChoice,(4+n)), n:10)) %>%
      mutate(Select = if_else(row_number()==my$newrow,
                              '<input type="radio" name="%s" value="%s" checked="checked"/>',
                              '<input type="radio" name="%s" value="%s"/>'),
             .before="Months")
    if(input$petChoice == 'dog') {
      t<- t %>%
        filter(row_number()<6)
    }
    my$DF <- t

  })

  output$table <- renderDataTable({
    DT::datatable(my$DF,
                  rownames = F, selection = 'single',
                  escape = FALSE,
                  options = list(dom = 't', pageLength = 10)) %>%
      formatStyle(c(0:3), cursor = "pointer")
  })

  #give radio choices to the grouped by genotype table
  observeEvent(input$table_cell_clicked, {
    info = input$table_cell_clicked
    # do nothing if not clicked yet
    if (is.null(info$value)) return()
    my$newrow <- info$row

    #change the radio button
    output$table <- renderDataTable({
      DT::datatable(my$DF %>%
                      mutate(Select = if_else(row_number()== my$newrow,
                                              '<input type="radio" name="%s" value="%s" checked="checked"/>',
                                              '<input type="radio" name="%s" value="%s"/>')),
                    rownames = F, selection =  list(mode = 'single', selected = c(info$row)),
                    escape = FALSE,
                    options = list(dom = 't', ordering=F, pageLength = 10)) %>%
        formatStyle(c(0:3), cursor = "pointer")
    })

  })
}
</code>```

Body:
I have a table where the first column contains a radio button. If a user clicks any cell in a row, it updates the table so that its radio button is selected. This then updates a second table with the values from the selected row. In my actual app, I get this to work, however as the first table is dynamically changed the cell_clicked value in an observeEvent still changes the value and the wrong radio button is showed. This only affects the display as the second table correctly updates.

For a reproducible example I made just the first table. If you change the pet choice to 'dog' the table only has 5 rows, while if 'cat' it will have 10 rows. Select any cell in the third row. Change the select to dog and the radio for the third row will automatically be selected. Now change the choice to cat, choose a row > 5 (7 for instance). Now change the input to dog and no radio button will be selected. This is because the observeEvent changes the selected row to 7, but there is no seventh row now.

I want the radio button to go back to the first row any time the reactive dataframe is changed. How do I go about doing this?

See reproducible example here:

library(shiny)
library(shinydashboard)
library(tidyverse)
library(DT)

ui <- dashboardPage(
  dashboardHeader(title = "Testing Observe Event on Cell Clicked"),
  #dashboard sidebar-----
  dashboardSidebar(
    sidebarMenu(id = "tabs",
                menuItem("Home", tabName = "home_tab")
    )
  ),
  #dashboard Body ----
  dashboardBody(
    tabItems(
      #Home page-----
      tabItem(tabName = "home_tab",
              fluidPage(
                fluidRow(h2("Home Page")),
                fluidRow(selectInput("petChoice", "Please select cats or dogs", c('cat','dog'))),
                fluidRow(dataTableOutput("table"))
              )
      )
    )
  )
)

server <- function(input, output, session) {

  #min reprex of a reactive dataframe I create
  myDF <- reactive({
    t<- data.frame(Months = month.name[1:10],
              Letters = letters[1:10],
              Numbers = c(1:10),
              Animal = paste(rep(input$petChoice,10), 1:10)) %>%
      mutate(Select = if_else(row_number()==1,
                             '<input type="radio" name="%s" value="%s" checked="checked"/>',
                             '<input type="radio" name="%s" value="%s"/>'),
            .before="Months")
    if(input$petChoice == 'dog') {
      t<- t %>%
        filter(Numbers>5)
    }
    t
  })

  output$table <- renderDataTable({
    DT::datatable(myDF(),
                  rownames = F, selection = 'single',
                  escape = FALSE,
                  options = list(dom = 't', pageLength = 10)) %>%
      formatStyle(c(0:3), cursor = "pointer")
  })

  #give radio choices to the grouped by genotype table
  observeEvent(input$table_cell_clicked, {
    info = input$table_cell_clicked
    # do nothing if not clicked yet
    if (is.null(info$value)) return()

    #change the radio button
    output$table <- renderDataTable({
      DT::datatable(myDF() %>%
                      mutate(Select = if_else(row_number()==info$row,
                                              '<input type="radio" name="%s" value="%s" checked="checked"/>',
                                              '<input type="radio" name="%s" value="%s"/>')),
                    rownames = F, selection =  list(mode = 'single', selected = c(info$row)),
                    escape = FALSE,
                    options = list(dom = 't', ordering=F, pageLength = 10)) %>%
        formatStyle(c(0:3), cursor = "pointer")
    })

  })
}

# Run the application
shinyApp(ui = ui, server = server)

Body:
Try this

server <- function(input, output, session) {

  my <- reactiveValues(DF = NULL,newrow=1)

  observeEvent(input$petChoice, {
    my$newrow <- 1
    if(input$petChoice == 'dog') n <- 6 else n <- 1
    t<- data.frame(Months = month.name[n:10],
                   Letters = letters[n:10],
                   Numbers = c(n:10),
                   Animal = paste(rep(input$petChoice,(4+n)), n:10)) %>%
      mutate(Select = if_else(row_number()==my$newrow,
                              '<input type="radio" name="%s" value="%s" checked="checked"/>',
                              '<input type="radio" name="%s" value="%s"/>'),
             .before="Months")
    if(input$petChoice == 'dog') {
      t<- t %>%
        filter(row_number()<6)
    }
    my$DF <- t

  })

  output$table <- renderDataTable({
    DT::datatable(my$DF,
                  rownames = F, selection = 'single',
                  escape = FALSE,
                  options = list(dom = 't', pageLength = 10)) %>%
      formatStyle(c(0:3), cursor = "pointer")
  })

  #give radio choices to the grouped by genotype table
  observeEvent(input$table_cell_clicked, {
    info = input$table_cell_clicked
    # do nothing if not clicked yet
    if (is.null(info$value)) return()
    my$newrow <- info$row

    #change the radio button
    output$table <- renderDataTable({
      DT::datatable(my$DF %>%
                      mutate(Select = if_else(row_number()== my$newrow,
                                              '<input type="radio" name="%s" value="%s" checked="checked"/>',
                                              '<input type="radio" name="%s" value="%s"/>')),
                    rownames = F, selection =  list(mode = 'single', selected = c(info$row)),
                    escape = FALSE,
                    options = list(dom = 't', ordering=F, pageLength = 10)) %>%
        formatStyle(c(0:3), cursor = "pointer")
    })

  })
}


问:
Discord.js Buttons doesn't work after bot restarts
The buttons work after doing the command but after restarting the bot and pressing the button, it says interaction failed

I tried putting the clickButton event in my event handler but it didn't work as I get a lot of errors. How do I still make the buttons work even after restart?

```<code>const { MessageEmbed, Client } = require('discord.js');
const client = new Client({ fetchAllMembers: true });
const buttons = require('discord-buttons')
buttons(client);
const { MessageMenu, MessageMenuOption } = require('discord-buttons');
client.settings = {
/////////////////////etkinlik rolleri///////////////////////
 menu_role_1: "940239454503837707",//csgo
 menu_role_2: "940239479753543690",//Valorant
 menu_role_3: "940239499705856001",//PUBG
 menu_role_4: "940239524334829658",//Minecraft
 menu_role_5: "940239546803691530",//Among Us
 menu_role_6: "940239566579826771",//Gartic.io
 menu_role_7: "940239590869049374",//League of Legends
 menu_role_8: "940220940569149491",//Risk: Global Domination
 menu_role_9: "940220945568788491",//Tabletop Simulator
/////////////////////etkinlik rolleri///////////////////////

  prefix: "ff",
 };

 /////////////////////////////////////Etkinlik Seçim////////////////////////////////

  client.on("message", async(message) => {
  let args = message.content.trim().split(" ")
  if(args[0] !== client.settings.prefix + "start" /* setup message */) { return false } else {

let option_1 = new MessageMenuOption()
.setLabel("CS:GO")
.setValue("1")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893176523840974848") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_2 = new MessageMenuOption()
.setLabel("Valorant")
.setValue("2")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893177016327757824") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_3 = new MessageMenuOption()
.setLabel("PUBG")
.setValue("3")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893191194966884433") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_4 = new MessageMenuOption()
  .setLabel("Minecraft")
  .setValue("4")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("893177569485148200") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz
let option_5 = new MessageMenuOption()
.setLabel("Among Us")
.setValue("5")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893193544741814322") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_6 = new MessageMenuOption()
  .setLabel("Gartic.io")
  .setValue("6")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("893191664313724999") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_7 = new MessageMenuOption()
.setLabel("League of Legends")
.setValue("7")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893188467352281088") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_8 = new MessageMenuOption()
  .setLabel("Risk: Global Domination")
  .setValue("8")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("940220653452267550") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

    let option_9 = new MessageMenuOption()
  .setLabel("Tabletop Simulator")
  .setValue("9")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("940220548741492756") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

  let option_55 = new MessageMenuOption()
  .setLabel("Rol İstemiyorum")
  .setValue("55")
  .setDescription("Aldığınız tüm rolleri kaldırmak için tıkla.")
  .setDefault()
  .setEmoji("") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let selection = new MessageMenu()
.setID("selector")

.setPlaceholder("Oyun rolleri seçmek için tıklayınız.")
.addOption(option_1)
.addOption(option_2)
    .addOption(option_3)
.addOption(option_4)
    .addOption(option_5)
.addOption(option_6)
    .addOption(option_7)
.addOption(option_8)
    .addOption(option_9)
.addOption(option_55)

var embed = new MessageEmbed()
.setColor("#ff4494")
.setTitle(":strawberry: Nympea Oyun Rolleri :strawberry:")
.setDescription("Aşağıdaki menüye tıklayarak dilediğin oyunu seçebilirsin. Bu sayede sunucumuz içerisinde gerçekleşen oyun etkinliklerinden haberdar olabilirsin.")
    .setImage(`https://cdn.discordapp.com/attachments/900389530748723270/903031735946739774/07c7170a904eeb3feabbbd783ba62b6b.gif`)
let msg = await message.channel.send(embed, selection)

client.on("clickMenu", async (menu) => {
  if(menu.message.id === msg.id) {
    menuselect(menu)
  }
})
};

 async function menuselect(menu) {
  switch(menu.values[0]) {
  case "1":
      menu.reply.send("**CS:GO** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_1)
    break;

  case "2":
      menu.reply.send("**Valorant** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_2)
    break;
              case "3":
      menu.reply.send("**PUBG** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_3)
    break;

  case "4":
      menu.reply.send("**Minecraft** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_4)
    break;
              case "5":
      menu.reply.send("**Among Us** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_5)
    break;

  case "6":
      menu.reply.send("**Gartic.io** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_6)
    break;
              case "7":
      menu.reply.send("**League of Legends** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_7)
    break;

  case "8":
      menu.reply.send("**Risk: Global Domination** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_8)
    break;
        case "9":
      menu.reply.send("**Tabletop Simulator** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_9)
    break;

  case "55":
      menu.reply.send("**Seçtiğin tüm oyun rolleri kaldırıldı!**", true)
     await menu.clicker.member.roles.remove(client.settings.menu_role_1)
     await menu.clicker.member.roles.remove(client.settings.menu_role_2)
           await menu.clicker.member.roles.remove(client.settings.menu_role_3)
     await menu.clicker.member.roles.remove(client.settings.menu_role_4)
           await menu.clicker.member.roles.remove(client.settings.menu_role_5)
     await menu.clicker.member.roles.remove(client.settings.menu_role_6)
           await menu.clicker.member.roles.remove(client.settings.menu_role_7)
     await menu.clicker.member.roles.remove(client.settings.menu_role_8)
           await menu.clicker.member.roles.remove(client.settings.menu_role_9)

       break;
     default:

      break;
       }
     }

       });

        /////////////////////////////////////Renk Seçim////////////////////////////////

         client.login(process.env.TOKEN)
         .then(() => console.log("\x1b[34m%s\x1b[1m", "[ Bot ] Discord API verified bot's token!"))
         .catch(err => console.error("\x1b[31m%s\x1b[0m", "[ Bot ] Discord API can't verified bot's token!"))

           client.on("ready", () => {

            });
</code>```

I've tried many methods and I'm still facing the same problem.

答: That is impossible, message component collectors are destroyed along with the client, so you can't run them after restaring the bot</p>

Body:
The buttons work after doing the command but after restarting the bot and pressing the button, it says interaction failed

I tried putting the clickButton event in my event handler but it didn't work as I get a lot of errors. How do I still make the buttons work even after restart?

const { MessageEmbed, Client } = require('discord.js');
const client = new Client({ fetchAllMembers: true });
const buttons = require('discord-buttons')
buttons(client);
const { MessageMenu, MessageMenuOption } = require('discord-buttons');
client.settings = {
/////////////////////etkinlik rolleri///////////////////////
 menu_role_1: "940239454503837707",//csgo
 menu_role_2: "940239479753543690",//Valorant
 menu_role_3: "940239499705856001",//PUBG
 menu_role_4: "940239524334829658",//Minecraft
 menu_role_5: "940239546803691530",//Among Us
 menu_role_6: "940239566579826771",//Gartic.io
 menu_role_7: "940239590869049374",//League of Legends
 menu_role_8: "940220940569149491",//Risk: Global Domination
 menu_role_9: "940220945568788491",//Tabletop Simulator
/////////////////////etkinlik rolleri///////////////////////

  prefix: "ff",
 };

 /////////////////////////////////////Etkinlik Seçim////////////////////////////////

  client.on("message", async(message) => {
  let args = message.content.trim().split(" ")
  if(args[0] !== client.settings.prefix + "start" /* setup message */) { return false } else {

let option_1 = new MessageMenuOption()
.setLabel("CS:GO")
.setValue("1")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893176523840974848") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_2 = new MessageMenuOption()
.setLabel("Valorant")
.setValue("2")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893177016327757824") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_3 = new MessageMenuOption()
.setLabel("PUBG")
.setValue("3")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893191194966884433") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_4 = new MessageMenuOption()
  .setLabel("Minecraft")
  .setValue("4")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("893177569485148200") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz
let option_5 = new MessageMenuOption()
.setLabel("Among Us")
.setValue("5")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893193544741814322") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_6 = new MessageMenuOption()
  .setLabel("Gartic.io")
  .setValue("6")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("893191664313724999") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_7 = new MessageMenuOption()
.setLabel("League of Legends")
.setValue("7")
.setDescription("Bu rolü almak için lütfen tıklayın.")
.setDefault()
.setEmoji("893188467352281088") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let option_8 = new MessageMenuOption()
  .setLabel("Risk: Global Domination")
  .setValue("8")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("940220653452267550") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

    let option_9 = new MessageMenuOption()
  .setLabel("Tabletop Simulator")
  .setValue("9")
  .setDescription("Bu rolü almak için lütfen tıklayın.")
  .setDefault()
  .setEmoji("940220548741492756") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

  let option_55 = new MessageMenuOption()
  .setLabel("Rol İstemiyorum")
  .setValue("55")
  .setDescription("Aldığınız tüm rolleri kaldırmak için tıkla.")
  .setDefault()
  .setEmoji("") //  emoji ekleyiniz burçların yanına yaptığım gibi id olarak giriniz

let selection = new MessageMenu()
.setID("selector")

.setPlaceholder("Oyun rolleri seçmek için tıklayınız.")
.addOption(option_1)
.addOption(option_2)
    .addOption(option_3)
.addOption(option_4)
    .addOption(option_5)
.addOption(option_6)
    .addOption(option_7)
.addOption(option_8)
    .addOption(option_9)
.addOption(option_55)

var embed = new MessageEmbed()
.setColor("#ff4494")
.setTitle(":strawberry: Nympea Oyun Rolleri :strawberry:")
.setDescription("Aşağıdaki menüye tıklayarak dilediğin oyunu seçebilirsin. Bu sayede sunucumuz içerisinde gerçekleşen oyun etkinliklerinden haberdar olabilirsin.")
    .setImage(`https://cdn.discordapp.com/attachments/900389530748723270/903031735946739774/07c7170a904eeb3feabbbd783ba62b6b.gif`)
let msg = await message.channel.send(embed, selection)

client.on("clickMenu", async (menu) => {
  if(menu.message.id === msg.id) {
    menuselect(menu)
  }
})
};

 async function menuselect(menu) {
  switch(menu.values[0]) {
  case "1":
      menu.reply.send("**CS:GO** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_1)
    break;

  case "2":
      menu.reply.send("**Valorant** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_2)
    break;
              case "3":
      menu.reply.send("**PUBG** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_3)
    break;

  case "4":
      menu.reply.send("**Minecraft** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_4)
    break;
              case "5":
      menu.reply.send("**Among Us** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_5)
    break;

  case "6":
      menu.reply.send("**Gartic.io** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_6)
    break;
              case "7":
      menu.reply.send("**League of Legends** Adlı Oyun Rolü Eklendi!", true)
     await menu.clicker.member.roles.add(client.settings.menu_role_7)
    break;

  case "8":
      menu.reply.send("**Risk: Global Domination** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_8)
    break;
        case "9":
      menu.reply.send("**Tabletop Simulator** Adlı Oyun Rolü Eklendi!", true)
    await menu.clicker.member.roles.add(client.settings.menu_role_9)
    break;

  case "55":
      menu.reply.send("**Seçtiğin tüm oyun rolleri kaldırıldı!**", true)
     await menu.clicker.member.roles.remove(client.settings.menu_role_1)
     await menu.clicker.member.roles.remove(client.settings.menu_role_2)
           await menu.clicker.member.roles.remove(client.settings.menu_role_3)
     await menu.clicker.member.roles.remove(client.settings.menu_role_4)
           await menu.clicker.member.roles.remove(client.settings.menu_role_5)
     await menu.clicker.member.roles.remove(client.settings.menu_role_6)
           await menu.clicker.member.roles.remove(client.settings.menu_role_7)
     await menu.clicker.member.roles.remove(client.settings.menu_role_8)
           await menu.clicker.member.roles.remove(client.settings.menu_role_9)

       break;
     default:

      break;
       }
     }

       });

        /////////////////////////////////////Renk Seçim////////////////////////////////

         client.login(process.env.TOKEN)
         .then(() => console.log("\x1b[34m%s\x1b[1m", "[ Bot ] Discord API verified bot's token!"))
         .catch(err => console.error("\x1b[31m%s\x1b[0m", "[ Bot ] Discord API can't verified bot's token!"))

           client.on("ready", () => {

            });

I've tried many methods and I'm still facing the same problem.


问:
React TypeScript: No warnings or errors are thrown for possibly undefined value in array state
I have an array state in React with TypeScript that contains object items. The array state is initialized to an emtpy array. However, TypeScript in VSCode doesn't throw any warnings or error when I try to reference an element in the array.

```<code>type Data = {
  field: string;
}[];

const [data, setData] = useState<Data>([]);

const clonedData: Data = [...data]; // Clone the data state
const firstData = clonedData[0];

const firstDataField = firstData.field; // Allowed to index, TS does not throw any warnings or errors that `firstData` may be undefined
</code>```

Does anyone what is the issue? Is there a field in tsconfig.json that allows setting of this particular TS warning?

答:
The issue is that Typescript will always assume your index is within bounds, and as such firstData will definitely have the type {field: string}.

What you are looking for is --noUncheckedIndexedAccess

https://github.com/microsoft/TypeScript/issues/13778

https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess

Here is a Playground that will show you the error as you want it.

Object is possibly 'undefined'.(2532)

Body:
I have an array state in React with TypeScript that contains object items. The array state is initialized to an emtpy array. However, TypeScript in VSCode doesn't throw any warnings or error when I try to reference an element in the array.

type Data = {
  field: string;
}[];

const [data, setData] = useState<Data>([]);

const clonedData: Data = [...data]; // Clone the data state
const firstData = clonedData[0];

const firstDataField = firstData.field; // Allowed to index, TS does not throw any warnings or errors that `firstData` may be undefined

Does anyone what is the issue? Is there a field in tsconfig.json that allows setting of this particular TS warning?


问:
how to create a table with different type values with Parse method?
```<code>public class Libro
    {
        public string Titolo { get; set; }
        public string Autore { get; set; }
        public string Editore { get; set; }
        public int ISBN { get; set; }
        public int Pagine { get; set; }
        public decimal Prezzo { get; set; }
        public int Quantità { get; set; }
</code>```

not being all of type string, I would not know how to convert the int and decimal values to have as a result a table in which to display a list of books (titles, authors, publishers and price) that I have on a file.txt

```<code>        public Libro BuildLibro(string input)
        {
            Libro result = null;

            if (!String.IsNullOrEmpty(input))
            {
                var inputArray = input.Split('*');

                if (inputArray.Length >= 6)
                {
                    result = new Libro();

                    result.Titolo = inputArray[0];
                    result.Autore = inputArray[1];
                    result.Editore = inputArray[2];

                    if (!string.IsNullOrEmpty(inputArray[3]))
                    {
                        int.TryParse(inputArray[3], out int num);
                        result.ISBN= num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[4]))
                    {
                        int.TryParse(inputArray[4], out int num);
                        result.Pagine = num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[5]))
                    {
                        decimal.TryParse(inputArray[5], out decimal num);
                        result.Prezzo = num/100;

                    }

                    if (!string.IsNullOrEmpty(inputArray[6]))
                    {
                        int.TryParse(inputArray[6], out int num);
                        result.Quantità = num;

                    }

                }
            }
            return result;
        }
    }
}
</code>```

答:
Foreword

The question has been edited massively since this answer was posted. I've advised that the edits should be reverted so this answer remains valid for the question as posted prior to the edit on Feb 14th (Revision 3), and a new question posted containing Rev 3's text

Original advice for Revision 2

You've switched tactic when you got to ISBN

```<code>ISBN = 4, Pagine = 5, Prezzo = 6, Quantità = 7
</code>```

Assigning the editore name like this makes sense:

```<code>Editore = content[3]
</code>```

It means "take the fourth element of the content array, which is a string array, and put it in the editors property, which is a string"

I guess you'll have tried the pattern of:

```<code>ISBN = content[4]
</code>```

But this won't have worked out because content is full of strings and ISBN is an int and even if a string purely only full of numerical chars that doesn't mean it's a number. This will have given some error like "there is no implicit conversion..."

I guess then you removed the content and just left a hard coded 4 assigned as the ISBN which will work in that it will compile syntactically, but it is incorrect logically. That will just fix every ISBN at being 4, literally

Instead you should parse the string to an int. it's easy, and we can do it with like:

```<code>ISBN = int.Parse(content[4])
</code>```

Similarly for the decimal there is a decimal.Parse

This may expose other problems like, if one of the values contains some non numerical chars (e.g. ISBNs that have hyphens in) but we can solve that later...

Body:
public class Libro
    {
        public string Titolo { get; set; }
        public string Autore { get; set; }
        public string Editore { get; set; }
        public int ISBN { get; set; }
        public int Pagine { get; set; }
        public decimal Prezzo { get; set; }
        public int Quantità { get; set; }

not being all of type string, I would not know how to convert the int and decimal values to have as a result a table in which to display a list of books (titles, authors, publishers and price) that I have on a file.txt

        public Libro BuildLibro(string input)
        {
            Libro result = null;

            if (!String.IsNullOrEmpty(input))
            {
                var inputArray = input.Split('*');

                if (inputArray.Length >= 6)
                {
                    result = new Libro();

                    result.Titolo = inputArray[0];
                    result.Autore = inputArray[1];
                    result.Editore = inputArray[2];

                    if (!string.IsNullOrEmpty(inputArray[3]))
                    {
                        int.TryParse(inputArray[3], out int num);
                        result.ISBN= num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[4]))
                    {
                        int.TryParse(inputArray[4], out int num);
                        result.Pagine = num;
                    }
                    if (!string.IsNullOrEmpty(inputArray[5]))
                    {
                        decimal.TryParse(inputArray[5], out decimal num);
                        result.Prezzo = num/100;

                    }

                    if (!string.IsNullOrEmpty(inputArray[6]))
                    {
                        int.TryParse(inputArray[6], out int num);
                        result.Quantità = num;

                    }

                }
            }
            return result;
        }
    }
}

Body:
Foreword

The question has been edited massively since this answer was posted. I've advised that the edits should be reverted so this answer remains valid for the question as posted prior to the edit on Feb 14th (Revision 3), and a new question posted containing Rev 3's text

Original advice for Revision 2

You've switched tactic when you got to ISBN

ISBN = 4, Pagine = 5, Prezzo = 6, Quantità = 7

Assigning the editore name like this makes sense:

Editore = content[3]

It means "take the fourth element of the content array, which is a string array, and put it in the editors property, which is a string"

I guess you'll have tried the pattern of:

ISBN = content[4]

But this won't have worked out because content is full of strings and ISBN is an int and even if a string purely only full of numerical chars that doesn't mean it's a number. This will have given some error like "there is no implicit conversion..."

I guess then you removed the content and just left a hard coded 4 assigned as the ISBN which will work in that it will compile syntactically, but it is incorrect logically. That will just fix every ISBN at being 4, literally

Instead you should parse the string to an int. it's easy, and we can do it with like:

ISBN = int.Parse(content[4])

Similarly for the decimal there is a decimal.Parse

This may expose other problems like, if one of the values contains some non numerical chars (e.g. ISBNs that have hyphens in) but we can solve that later...


问:
Conditional useNavigate(), within button, based on error response
I have a signup form. Upon submit, if the inputs fail any validations, I need for the errors to be visible to the user, and for the browser to stay on the /signup page. If the form inputs pass all validations, I need for the submit button to navigate away to another page ('/about', as a placeholder).

The form submit button has an onSubmit(). At the end of the onSubmit I am calling the useNavigate hook to navigate away from /signup. I need something like a ternary which could, for example, say

```<code>errors ? null : navigate('/about)
</code>```

"If there are errors, do not navigate, else navigate." I've tried many combinations but can't get it.

My full code:

```<code>import { React, useState } from 'react'
import './Signup.css'
import { useNavigate } from "react-router-dom";

export default function Signup() {

    const navigate = useNavigate()

    const [username, setUsername] = useState("");
    const [name, setName] = useState("");
    const [password, setPassword] = useState("");
    const [passwordConfirmation, setPasswordConfirmation] = useState("");
    const [errors, setErrors] = useState([])

    function onSubmit(e){
        e.preventDefault()
        const user = {
            name: name,
            username: username,
            password: password,
            password_confirmation: passwordConfirmation
        }
        fetch('http://localhost:3000/users', {
            method:'POST',
            headers:{'Content-Type': 'application/json'},
            body:JSON.stringify(user)
        })
        .then(res => res.json())
        .then(json => {
            if(json.errors) setErrors(Object.entries(json.errors))
        })
        // need something like a ternary which says,
        // if errors, stay on current page/render errors
        // else, navigate away
        navigate('/about')
    }

    return (
        <>
            <form onSubmit={onSubmit} className="form">
                {/* <div className="container1"> */}
                    <h3 className="login-h3">Sign ur ass uPPP</h3>
                    <input
                        type="text"
                        id="name"
                        placeholder="name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        />
                    <input
                        type="text"
                        id="username"
                        placeholder="username"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password"
                        placeholder="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password_confirmation"
                        placeholder="confirm password"
                        value={passwordConfirmation}
                        onChange={(e) => setPasswordConfirmation(e.target.value)}
                        />
                    <button

                        type="submit">Sign up!
                    </button>
                {/* </div> */}
            </form>
            { errors ? errors.map(e => <div>{e[0]+' : ' + e[1]}</div>) : null}
        </>
    )
}
</code>```

答:
You can use an if statement:

```<code>    function onSubmit(e){
    e.preventDefault()
    const user = {
        name: name,
        username: username,
        password: password,
        password_confirmation: passwordConfirmation
    }
    fetch('http://localhost:3000/users', {
        method:'POST',
        headers:{'Content-Type': 'application/json'},
        body:JSON.stringify(user)
    })
    .then(res => res.json())
    .then(json => {
        if(json.errors) setErrors(Object.entries(json.errors))
    })
    if(errors.length > 0){
     return null
    } else
    navigate('/about')
    }
</code>```

This is using your errors state. If your setErrors recorded something it will set in the errors state.

Body:
I have a signup form. Upon submit, if the inputs fail any validations, I need for the errors to be visible to the user, and for the browser to stay on the /signup page. If the form inputs pass all validations, I need for the submit button to navigate away to another page ('/about', as a placeholder).

The form submit button has an onSubmit(). At the end of the onSubmit I am calling the useNavigate hook to navigate away from /signup. I need something like a ternary which could, for example, say

errors ? null : navigate('/about)

"If there are errors, do not navigate, else navigate." I've tried many combinations but can't get it.

My full code:

import { React, useState } from 'react'
import './Signup.css'
import { useNavigate } from "react-router-dom";

export default function Signup() {

    const navigate = useNavigate()

    const [username, setUsername] = useState("");
    const [name, setName] = useState("");
    const [password, setPassword] = useState("");
    const [passwordConfirmation, setPasswordConfirmation] = useState("");
    const [errors, setErrors] = useState([])

    function onSubmit(e){
        e.preventDefault()
        const user = {
            name: name,
            username: username,
            password: password,
            password_confirmation: passwordConfirmation
        }
        fetch('http://localhost:3000/users', {
            method:'POST',
            headers:{'Content-Type': 'application/json'},
            body:JSON.stringify(user)
        })
        .then(res => res.json())
        .then(json => {
            if(json.errors) setErrors(Object.entries(json.errors))
        })
        // need something like a ternary which says,
        // if errors, stay on current page/render errors
        // else, navigate away
        navigate('/about')
    }

    return (
        <>
            <form onSubmit={onSubmit} className="form">
                {/*
 */}

Sign ur ass uPPP

                    <input
                        type="text"
                        id="name"
                        placeholder="name"
                        value={name}
                        onChange={(e) => setName(e.target.value)}
                        />
                    <input
                        type="text"
                        id="username"
                        placeholder="username"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password"
                        placeholder="password"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                        />
                    <input
                        type="password"
                        id="password_confirmation"
                        placeholder="confirm password"
                        value={passwordConfirmation}
                        onChange={(e) => setPasswordConfirmation(e.target.value)}
                        />
                    <button

                        type="submit">Sign up!
                    </button>
                {/*
 */}
            </form>
            { errors ? errors.map(e =>
{e[0]+' : ' + e[1]}
) : null}
        </>
    )
}

Body:
You can use an if statement:

    function onSubmit(e){
    e.preventDefault()
    const user = {
        name: name,
        username: username,
        password: password,
        password_confirmation: passwordConfirmation
    }
    fetch('http://localhost:3000/users', {
        method:'POST',
        headers:{'Content-Type': 'application/json'},
        body:JSON.stringify(user)
    })
    .then(res => res.json())
    .then(json => {
        if(json.errors) setErrors(Object.entries(json.errors))
    })
    if(errors.length > 0){
     return null
    } else
    navigate('/about')
    }

This is using your errors state. If your setErrors recorded something it will set in the errors state.


问:
How can I remove a dynamically created button?
I want to remove all children of a StackPanel except for a Label, but I can't get it to
remove a dynamically created Button.

```<code><StackPanel Name="myStackPanel">
    <Label Name="myLabel">Label text</Label>
    <TextBlock Name="myTextBlock">TextBlock text</TextBlock>
</StackPanel>
</code>```

```<code>private void button1_Click(object sender, RoutedEventArgs e)
    {
    Button buttonX= new Button();
    buttonX.Name = "ButtonInstall";
    buttonX.Content = "Click Me";
    buttonX.Width = 150;
    buttonX.HorizontalAlignment = HorizontalAlignment.Left;
    buttonX.Click += new RoutedEventHandler(buttonX_Click);
    myStackPanel.Children.Add(buttonX);
    }

private void button2_Click(object sender, RoutedEventArgs e)
    {
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myStackPanel); i++)
        {
        Visual childVisual = (Visual)VisualTreeHelper.GetChild(myStackPanel, i);
        string controlName = childVisual.GetValue(Control.NameProperty).ToString();

        if (childVisual.GetType() != typeof(Label))
        {
            myStackPanel.Children.Remove((UIElement)childVisual);
        }
    }
</code>```

答:
For your example, it's not necessary to use the VisualTreeHelper:

```<code>List<UIElement> delItems=new List<UIElement>();
foreach(UIElement uiElement in myStackPanel.Children){
 if(uiElement is Label) continue;
 delItems.Add(uiElement);
}
foreach(UIElement delItem in delItems){
  myStackPanel.Children.Remove(delItem);
}
</code>```

Body:
I want to remove all children of a StackPanel except for a Label, but I can't get it to
remove a dynamically created Button.

<StackPanel Name="myStackPanel">
    Label text
    <TextBlock Name="myTextBlock">TextBlock text</TextBlock>
</StackPanel>

private void button1_Click(object sender, RoutedEventArgs e)
    {
    Button buttonX= new Button();
    buttonX.Name = "ButtonInstall";
    buttonX.Content = "Click Me";
    buttonX.Width = 150;
    buttonX.HorizontalAlignment = HorizontalAlignment.Left;
    buttonX.Click += new RoutedEventHandler(buttonX_Click);
    myStackPanel.Children.Add(buttonX);
    }

private void button2_Click(object sender, RoutedEventArgs e)
    {
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(myStackPanel); i++)
        {
        Visual childVisual = (Visual)VisualTreeHelper.GetChild(myStackPanel, i);
        string controlName = childVisual.GetValue(Control.NameProperty).ToString();

        if (childVisual.GetType() != typeof(Label))
        {
            myStackPanel.Children.Remove((UIElement)childVisual);
        }
    }

Body:
For your example, it's not necessary to use the VisualTreeHelper:

List<UIElement> delItems=new List<UIElement>();
foreach(UIElement uiElement in myStackPanel.Children){
 if(uiElement is Label) continue;
 delItems.Add(uiElement);
}
foreach(UIElement delItem in delItems){
  myStackPanel.Children.Remove(delItem);
}


问:
Javascript - How to pass array elements in batches of 99 to HTTP POST request and continue HTTP POST's until all array elements have been passed
I am attempting to pass 99 elements/values of an Array at a time to an XMLHttpRequest for a web app I am finishing up. The Array has more than 99 records, and will grow over time, as it pulling from user information in a database. My goal is to be able to send numerous HTTP POST requests containing 99 elements from that array at a time, OR until all elements of the array have been passed already. That is, 99 elements per batch and/ora final batch containing the last few remaining elements (less than 99) in the array. The method that I am using seems like it SHOULD work, but it is not currently working. Here is the code i am using:

```<code>      function sendPushNotification(allRecipients) {
        var listComplete = allRecipients.length;
        var batchMaker = 0;
        var batchRecipients;
        var batchNumber = 0;
        var recipientsProcessed = 0;
        for (batchMaker = 0; batchMaker < 99; batchMaker++) {
          batchRecipients =
            allRecipients[batchMaker] + `","` + batchRecipients;
          console.log(
            "Building Batch #" +
              batchNumber +
              1 +
              ":" +
              batchRecipients.slice(0, -11)
          );
          recipientsProcessed++;
          if (batchMaker == 99 || listComplete == recipientsProcessed) {
            console.log(batchRecipients.slice(0, -11));
            var subjectLineRaw = document.getElementById("subject").value;
            var messageBodyRaw = document.getElementById("body").value;
            const subjectLine = subjectLineRaw.replace(/(\r\n|\n|\r)/gm, " ");
            const messageBody = messageBodyRaw.replace(/(\r\n|\n|\r)/gm, " ");
            var data =
              `{
                "to": "` +
              JSON.stringify(batchRecipients.slice(0, -11)) +
              `",
                "title": "` +
              subjectLine +
              `",
                "body": "` +
              messageBody +
              `",
                "sound": "default"
              }`;
            console.log(data);

            var xhr = new XMLHttpRequest();
            var url =
              "url goes here";
            xhr.open("POST", url);
            xhr.setRequestHeader("accept", "application/json");
            xhr.setRequestHeader("content-type", "application/json");

            xhr.onreadystatechange = function () {
              if (xhr.readyState === 4) {
                console.log(xhr.status);
                console.log(xhr.responseText);
              }
            };
            // console.log(data);
            console.log(xhr);
            xhr.send(data);
            console.log(
              "Push Notification POST batch #" + ++batchNumber + "complete!"
            );
            batchMaker = 0;
          }
        }
      }
</code>```

I can't seem to figure out why I am getting caught up, but my hunch is with regard to the criteria of the "for" and the "if" statements, that OR the reset of my counter "batchMaker" to be 0 at the end of my "if" statement.

When in debug mode, setting various breakpoints, as soon as batchMaker = 50, everything in my "if" statement does not get executed except resetting batchMaker = 0 again... which of course kills my loop. Setting the criteria in the "for" or "if" statement so that batchMaker is not the same for (batchMaker = 0; batchMaker < 99; batchMaker++) or if (batchMaker == 99 || listComplete == recipientsProcessed)... E.g. if both are not 99, I get an endless loop of console logs, and still never get a POST request executed... I feel like i am close, but maybe my method is flawed. I appreciate your help!

答:
I was able to figure this out. Adding another "counter" mechanism batchCounter below, modifying the and if criteria to use this new batchCounterinstead of the same batchMaker, then resetting the value of this batchCounter variable so that for every subsequent loop/batch batchCounter and batchMaker interact the same as they did the very first loop (i.e. batchMaker == batchCounter +1 before meeting the 'if' statement criteria), and lastly breaking the loop entirely when recipientsProcessed begins to process 'undefined', that is a non-existence index number within my array which is displayed in the code as listComplete + 1 == recipientsProcessed. Here is the entire updated code snippet that is currently working as intended:

```<code>        var pageSelecterRadioButton = document.querySelector(
          'input[name="page_selecter"]:checked'
        );
        var pageSelected = pageSelecterRadioButton.value;
        var listComplete = allRecipients.length;
        var batchCounter = 0;
        var batchMaker = 0;
        var batchRecipients;
        var batchNumber = 0;
        var recipientsProcessed = 0;
        for (batchMaker = 0; batchMaker < 99; batchMaker++) {
          batchRecipients =
            allRecipients[recipientsProcessed] + `","` + batchRecipients;
          console.log(
            "Building Batch #" +
              (batchNumber + 1) +
              ':"' +
              batchRecipients.slice(0, -11)
          );
          batchCounter++;
          recipientsProcessed++;
          if (batchCounter == 99 || listComplete == recipientsProcessed) {
            console.log(`"` + batchRecipients.slice(0, -11));
            var subjectLineRaw = document.getElementById("subject").value;
            var messageBodyRaw = document.getElementById("body").value;
            const subjectLine = subjectLineRaw.replace(/(\r\n|\n|\r)/gm, " ");
            const messageBody = messageBodyRaw.replace(/(\r\n|\n|\r)/gm, " ");
            var data =
              `{
                "to": ["` +
              batchRecipients.slice(0, -11) +
              `],
                "title": "` +
              subjectLine +
              `",
                "body": "` +
              messageBody +
              `",
                "sound": "default",
                "data": {"event": "` +
              pageSelected +
              `"}
              }`;
            console.log(data);

            var xhr = new XMLHttpRequest();
            var url =
              "https://stormy-peak-86652.herokuapp.com/https://exp.host/--/api/v2/push/send";
            xhr.open("POST", url);
            xhr.setRequestHeader("accept", "application/json");
            xhr.setRequestHeader("content-type", "application/json");

            xhr.onreadystatechange = function () {
              if (xhr.readyState === 4) {
                console.log(xhr.status);
                console.log(xhr.responseText);
              }
            };
            console.log(data);
            console.log(xhr);
            xhr.send(data);
            console.log(
              "Push Notification POST batch #" + ++batchNumber + "complete!"
            );
            batchCounter = 2;
            batchMaker = 0;
            var batchRecipients = "         ";
          }
          if (listComplete + 1 == recipientsProcessed) {
            alert(recipientsProcessed - 1 + " Push Notifications Sent!");
            break;
          }
        }
      }
</code>```

There were some other additions made in the snippet above as well, but nothing that really involves the question here (added task to handle radio button value, and inputting that additional content in the HTTP Post, etc.). Hope this helps someone else someday!

Body:
I am attempting to pass 99 elements/values of an Array at a time to an XMLHttpRequest for a web app I am finishing up. The Array has more than 99 records, and will grow over time, as it pulling from user information in a database. My goal is to be able to send numerous HTTP POST requests containing 99 elements from that array at a time, OR until all elements of the array have been passed already. That is, 99 elements per batch and/ora final batch containing the last few remaining elements (less than 99) in the array. The method that I am using seems like it SHOULD work, but it is not currently working. Here is the code i am using:

      function sendPushNotification(allRecipients) {
        var listComplete = allRecipients.length;
        var batchMaker = 0;
        var batchRecipients;
        var batchNumber = 0;
        var recipientsProcessed = 0;
        for (batchMaker = 0; batchMaker < 99; batchMaker++) {
          batchRecipients =
            allRecipients[batchMaker] + `","` + batchRecipients;
          console.log(
            "Building Batch #" +
              batchNumber +
              1 +
              ":" +
              batchRecipients.slice(0, -11)
          );
          recipientsProcessed++;
          if (batchMaker == 99 || listComplete == recipientsProcessed) {
            console.log(batchRecipients.slice(0, -11));
            var subjectLineRaw = document.getElementById("subject").value;
            var messageBodyRaw = document.getElementById("body").value;
            const subjectLine = subjectLineRaw.replace(/(\r\n|\n|\r)/gm, " ");
            const messageBody = messageBodyRaw.replace(/(\r\n|\n|\r)/gm, " ");
            var data =
              `{
                "to": "` +
              JSON.stringify(batchRecipients.slice(0, -11)) +
              `",
                "title": "` +
              subjectLine +
              `",
                "body": "` +
              messageBody +
              `",
                "sound": "default"
              }`;
            console.log(data);

            var xhr = new XMLHttpRequest();
            var url =
              "url goes here";
            xhr.open("POST", url);
            xhr.setRequestHeader("accept", "application/json");
            xhr.setRequestHeader("content-type", "application/json");

            xhr.onreadystatechange = function () {
              if (xhr.readyState === 4) {
                console.log(xhr.status);
                console.log(xhr.responseText);
              }
            };
            // console.log(data);
            console.log(xhr);
            xhr.send(data);
            console.log(
              "Push Notification POST batch #" + ++batchNumber + "complete!"
            );
            batchMaker = 0;
          }
        }
      }

I can't seem to figure out why I am getting caught up, but my hunch is with regard to the criteria of the "for" and the "if" statements, that OR the reset of my counter "batchMaker" to be 0 at the end of my "if" statement.

When in debug mode, setting various breakpoints, as soon as batchMaker = 50, everything in my "if" statement does not get executed except resetting batchMaker = 0 again... which of course kills my loop. Setting the criteria in the "for" or "if" statement so that batchMaker is not the same for (batchMaker = 0; batchMaker < 99; batchMaker++) or if (batchMaker == 99 || listComplete == recipientsProcessed)... E.g. if both are not 99, I get an endless loop of console logs, and still never get a POST request executed... I feel like i am close, but maybe my method is flawed. I appreciate your help!

Body:
I was able to figure this out. Adding another "counter" mechanism batchCounter below, modifying the and if criteria to use this new batchCounterinstead of the same batchMaker, then resetting the value of this batchCounter variable so that for every subsequent loop/batch batchCounter and batchMaker interact the same as they did the very first loop (i.e. batchMaker == batchCounter +1 before meeting the 'if' statement criteria), and lastly breaking the loop entirely when recipientsProcessed begins to process 'undefined', that is a non-existence index number within my array which is displayed in the code as listComplete + 1 == recipientsProcessed. Here is the entire updated code snippet that is currently working as intended:

        var pageSelecterRadioButton = document.querySelector(
          'input[name="page_selecter"]:checked'
        );
        var pageSelected = pageSelecterRadioButton.value;
        var listComplete = allRecipients.length;
        var batchCounter = 0;
        var batchMaker = 0;
        var batchRecipients;
        var batchNumber = 0;
        var recipientsProcessed = 0;
        for (batchMaker = 0; batchMaker < 99; batchMaker++) {
          batchRecipients =
            allRecipients[recipientsProcessed] + `","` + batchRecipients;
          console.log(
            "Building Batch #" +
              (batchNumber + 1) +
              ':"' +
              batchRecipients.slice(0, -11)
          );
          batchCounter++;
          recipientsProcessed++;
          if (batchCounter == 99 || listComplete == recipientsProcessed) {
            console.log(`"` + batchRecipients.slice(0, -11));
            var subjectLineRaw = document.getElementById("subject").value;
            var messageBodyRaw = document.getElementById("body").value;
            const subjectLine = subjectLineRaw.replace(/(\r\n|\n|\r)/gm, " ");
            const messageBody = messageBodyRaw.replace(/(\r\n|\n|\r)/gm, " ");
            var data =
              `{
                "to": ["` +
              batchRecipients.slice(0, -11) +
              `],
                "title": "` +
              subjectLine +
              `",
                "body": "` +
              messageBody +
              `",
                "sound": "default",
                "data": {"event": "` +
              pageSelected +
              `"}
              }`;
            console.log(data);

            var xhr = new XMLHttpRequest();
            var url =
              "https://stormy-peak-86652.herokuapp.com/https://exp.host/--/api/v2/push/send";
            xhr.open("POST", url);
            xhr.setRequestHeader("accept", "application/json");
            xhr.setRequestHeader("content-type", "application/json");

            xhr.onreadystatechange = function () {
              if (xhr.readyState === 4) {
                console.log(xhr.status);
                console.log(xhr.responseText);
              }
            };
            console.log(data);
            console.log(xhr);
            xhr.send(data);
            console.log(
              "Push Notification POST batch #" + ++batchNumber + "complete!"
            );
            batchCounter = 2;
            batchMaker = 0;
            var batchRecipients = "         ";
          }
          if (listComplete + 1 == recipientsProcessed) {
            alert(recipientsProcessed - 1 + " Push Notifications Sent!");
            break;
          }
        }
      }

There were some other additions made in the snippet above as well, but nothing that really involves the question here (added task to handle radio button value, and inputting that additional content in the HTTP Post, etc.). Hope this helps someone else someday!