问:
Why is my syntax wrong in my JOIN statement?
I have a simple SQL query with a where and a join. I tried to execute this command :
SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id. The ? is by the value in the code :

```<code>persistent.transaction(tx => {
            tx.executeSql('SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id', [gym.id],
            (t, s) => {
                console.log(s)
            }, (t, e) => {
                console.log(e)
            })
        })
</code>```

However, I always get this strange error : Error code 1: near "JOIN": syntax error

I believe everything is done properly, what is the issue with my code ?

答:
You must specify the joins in the from clause

```<code>SELECT *
FROM
    gym_service g
    INNER JOIN services s ON g.service_id = s.id
WHERE
    g.gym_id = ?
</code>```

See: SQL Joins (w3schools.com)

Body:
I have a simple SQL query with a where and a join. I tried to execute this command :
SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id. The ? is by the value in the code :

persistent.transaction(tx => {
            tx.executeSql('SELECT * FROM gym_service WHERE gym_id = ? JOIN services ON service_id = id', [gym.id],
            (t, s) => {
                console.log(s)
            }, (t, e) => {
                console.log(e)
            })
        })

However, I always get this strange error : Error code 1: near "JOIN": syntax error

I believe everything is done properly, what is the issue with my code ?

Body:
You must specify the joins in the from clause

SELECT *
FROM
    gym_service g
    INNER JOIN services s ON g.service_id = s.id
WHERE
    g.gym_id = ?

See: SQL Joins (w3schools.com)


来源: stackexchange

问:
How can I sum up values over time and deduct them as soon as they are not needed anymore?
Hi and apologies if this was asked already, I could not find anything since an hour so I'll ask:

I have data in this style (sorry for the horrible formatting, how can I make these prettier?):

```<code>person start_time end_time amount
A   2019-10-04  2020-04-21  10
A   2019-12-10  2020-01-09  20
B   2019-11-04  2020-08-21  30
B   2019-12-10  2020-01-20  15
C   2019-12-20  2020-03-19  5
</code>```

So, I want to be able to plot the sum of the amount per person with ggplot2 over time until today (or sys_date).

This means, for person A, the plot should show 10 from 2019-10-04 until 2019-12-10, and afterwards it should jump to 30 (10+20). This is until 2020-01-09 (since this is in the past), where the amount should go back to 10.

Similarly, for person B the amount should be 30 between 2019-11-04 and 2019-12-10, afterwards it should be 45, and fall back to 30 on 2020-01-20.

I tried something along:

```<code>SumAmount <- data %>%
    group_by(person,start_time,end_time) %>%
    summarise(cumulatedAmount = sum(amount))
</code>```

But this isn't what I need...

Thanks a lot and apologies again for the poor formatting.

答:
Here is one idea. We can calculate the total amount of each date and then plot the total amount.

```<code>library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert to date class
  mutate_at(vars(ends_with("time")), ymd) %>%
  # Create a date sequence and expand it
  mutate(Date = map2(start_time, end_time, seq.Date, by = 1)) %>%
  unnest(cols = Date) %>%
  # Calculate the total amount for each date
  group_by(person, Date) %>%
  summarize(amount = sum(amount))

ggplot(dat2, aes(x = Date, y = amount, color = person)) +
  geom_point() +
  geom_line()
</code>```

Here is another option. This is the same way to expand the data frame based on date. After that, we can use stat_summary to plot the data.

```<code>library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert to date class
  mutate_at(vars(ends_with("time")), ymd) %>%
  # Create a date sequence and expand it
  mutate(Date = map2(start_time, end_time, seq.Date, by = 1)) %>%
  unnest(cols = Date)

ggplot(dat2, aes(x = Date, y = amount, color = person)) +
  stat_summary(fun.y = sum, geom = "path")
</code>```

Update

This solution add 0 to the next date of the last date for each person

```<code>library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert to date class
  mutate_at(vars(ends_with("time")), ymd) %>%
  # Create a date sequence and expand it
  mutate(Date = map2(start_time, end_time, seq.Date, by = 1)) %>%
  unnest(cols = Date) %>%
  # Calculate the total amount for each date
  group_by(person, Date) %>%
  summarize(amount = sum(amount))

dat3 <- dat2 %>%
  # Find the last date for each person
  filter(Date == max(Date)) %>%
  # Add one day to the last date for each person
  # Set amount to be 0
  mutate(Date = Date + 1, amount = 0)

# Combine data frames
dat4 <- bind_rows(dat2, dat3)

ggplot(dat4, aes(x = Date, y = amount, color = person)) +
  geom_point() +
  geom_line()
</code>```

DATA

```<code>dat <- read.table(text = "person start_time end_time amount
A   '2019-10-04'  '2020-04-21'  10
A   '2019-12-10'  '2020-01-09'  20
B   '2019-11-04'  '2020-08-21'  30
B   '2019-12-10'  '2020-01-20'  15
C   '2019-12-20'  '2020-03-19'  5",
                  stringsAsFactors = FALSE, header = TRUE)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Hi and apologies if this was asked already, I could not find anything since an hour so I'll ask:

I have data in this style (sorry for the horrible formatting, how can I make these prettier?):

person start_time end_time amount
A   2019-10-04  2020-04-21  10
A   2019-12-10  2020-01-09  20
B   2019-11-04  2020-08-21  30
B   2019-12-10  2020-01-20  15
C   2019-12-20  2020-03-19  5

So, I want to be able to plot the sum of the amount per person with ggplot2 over time until today (or sys_date).

This means, for person A, the plot should show 10 from 2019-10-04 until 2019-12-10, and afterwards it should jump to 30 (10+20). This is until 2020-01-09 (since this is in the past), where the amount should go back to 10.

Similarly, for person B the amount should be 30 between 2019-11-04 and 2019-12-10, afterwards it should be 45, and fall back to 30 on 2020-01-20.

I tried something along:

SumAmount <- data %>%
    group_by(person,start_time,end_time) %>%
    summarise(cumulatedAmount = sum(amount))

But this isn't what I need...

Thanks a lot and apologies again for the poor formatting.

Body:
Here is one idea. We can calculate the total amount of each date and then plot the total amount.

library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert to date class
  mutate_at(vars(ends_with("time")), ymd) %>%
  # Create a date sequence and expand it
  mutate(Date = map2(start_time, end_time, seq.Date, by = 1)) %>%
  unnest(cols = Date) %>%
  # Calculate the total amount for each date
  group_by(person, Date) %>%
  summarize(amount = sum(amount))

ggplot(dat2, aes(x = Date, y = amount, color = person)) +
  geom_point() +
  geom_line()

Here is another option. This is the same way to expand the data frame based on date. After that, we can use stat_summary to plot the data.

library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert to date class
  mutate_at(vars(ends_with("time")), ymd) %>%
  # Create a date sequence and expand it
  mutate(Date = map2(start_time, end_time, seq.Date, by = 1)) %>%
  unnest(cols = Date)

ggplot(dat2, aes(x = Date, y = amount, color = person)) +
  stat_summary(fun.y = sum, geom = "path")

Update

This solution add 0 to the next date of the last date for each person

library(tidyverse)
library(lubridate)

dat2 <- dat %>%
  # Convert to date class
  mutate_at(vars(ends_with("time")), ymd) %>%
  # Create a date sequence and expand it
  mutate(Date = map2(start_time, end_time, seq.Date, by = 1)) %>%
  unnest(cols = Date) %>%
  # Calculate the total amount for each date
  group_by(person, Date) %>%
  summarize(amount = sum(amount))

dat3 <- dat2 %>%
  # Find the last date for each person
  filter(Date == max(Date)) %>%
  # Add one day to the last date for each person
  # Set amount to be 0
  mutate(Date = Date + 1, amount = 0)

# Combine data frames
dat4 <- bind_rows(dat2, dat3)

ggplot(dat4, aes(x = Date, y = amount, color = person)) +
  geom_point() +
  geom_line()

DATA

dat <- read.table(text = "person start_time end_time amount
A   '2019-10-04'  '2020-04-21'  10
A   '2019-12-10'  '2020-01-09'  20
B   '2019-11-04'  '2020-08-21'  30
B   '2019-12-10'  '2020-01-20'  15
C   '2019-12-20'  '2020-03-19'  5",
                  stringsAsFactors = FALSE, header = TRUE)


问:
How to sort a multidimensional list based on multiple keys?
I have the following list.

initial =[('fanitst', 257.72815, 43.42322), ('st', 47.82522, 51.149788), ('hird', 572.8713, 60.59974), ('irces', 710.9375, 61.953125), ('income', 35.546875, 111.71875), ('tax', 155.39062, 112.734375), ('department', 213.42479, 111.97105), ('govt', 577.8906, 116.796875), ('of', 690.625, 116.796875), ('india', 742.4219, 116.796875), ('hitu', 56.875, 169.60938), ('biswas', 135.0781, 169.60936), ('biswas', 197.03125, 243.75), ('haridas', 54.84375, 244.76562), ('in', 648.0486, 272.82794), ('n', 726.6486, 303.17294), ('051031920', 51.569546, 320.44266), ('number', 283.35938, 355.46875), ('account', 181.64876, 357.539), ('permanent', 52.67427, 359.5602), ('czkpb5432z', 53.38768, 399.7318), ('s', 842.3438, 427.73975), ('biswas', 125.9375, 468.20312), ('hilu', 59.921875, 469.21875), ('signature', 50.868423, 528.95844)]

Every item is basically a tuple of a word, it's x-coordinate and it's y-coordinate.

I have to arrange them so the output looks like following. It is done by

grouping all the words whose y-coordinates have values close to each other(e.g. less than 5).

Then the words coming in the same line should be sorted on the basis of their x-coordinates.

How should I do this 2nd part?

```<code>fanitst
st
hird irces
income tax department govt of india
hitu biswas
haridas biswas
in
n
051031920
permanent account number
czkpb5432z
s
biswas hilu
</code>```

Currently I am getting the following output.

```<code>fanitst
st
hird irces
income tax department govt of india
hitu biswas
biswas haridas
in
n
051031920
number account permanent
czkpb5432z
s
biswas hilu
</code>```

The code I wrote to reach here is following.

```<code>for i in range(len(initial)-1):
    if abs(initial[i][2] - initial[i+1][2]) < 5:
        print(initial[i][0], end=" ")
    else:
        print(initial[i][0])
</code>```

If I can store each line of the output in a separate list , I think I can work my way forward from there. However, I can't think of a way to store each line in a different list. Each time the number of lists will be different so I don't know how many lists we would need.

Body:
I have the following list.

initial =[('fanitst', 257.72815, 43.42322), ('st', 47.82522, 51.149788), ('hird', 572.8713, 60.59974), ('irces', 710.9375, 61.953125), ('income', 35.546875, 111.71875), ('tax', 155.39062, 112.734375), ('department', 213.42479, 111.97105), ('govt', 577.8906, 116.796875), ('of', 690.625, 116.796875), ('india', 742.4219, 116.796875), ('hitu', 56.875, 169.60938), ('biswas', 135.0781, 169.60936), ('biswas', 197.03125, 243.75), ('haridas', 54.84375, 244.76562), ('in', 648.0486, 272.82794), ('n', 726.6486, 303.17294), ('051031920', 51.569546, 320.44266), ('number', 283.35938, 355.46875), ('account', 181.64876, 357.539), ('permanent', 52.67427, 359.5602), ('czkpb5432z', 53.38768, 399.7318), ('s', 842.3438, 427.73975), ('biswas', 125.9375, 468.20312), ('hilu', 59.921875, 469.21875), ('signature', 50.868423, 528.95844)]

Every item is basically a tuple of a word, it's x-coordinate and it's y-coordinate.

I have to arrange them so the output looks like following. It is done by

grouping all the words whose y-coordinates have values close to each other(e.g. less than 5).

Then the words coming in the same line should be sorted on the basis of their x-coordinates.

How should I do this 2nd part?

fanitst
st
hird irces
income tax department govt of india
hitu biswas
haridas biswas
in
n
051031920
permanent account number
czkpb5432z
s
biswas hilu

Currently I am getting the following output.

fanitst
st
hird irces
income tax department govt of india
hitu biswas
biswas haridas
in
n
051031920
number account permanent
czkpb5432z
s
biswas hilu

The code I wrote to reach here is following.

for i in range(len(initial)-1):
    if abs(initial[i][2] - initial[i+1][2]) < 5:
        print(initial[i][0], end=" ")
    else:
        print(initial[i][0])

If I can store each line of the output in a separate list , I think I can work my way forward from there. However, I can't think of a way to store each line in a different list. Each time the number of lists will be different so I don't know how many lists we would need.

Body:
This seems to work:

initial =[('fanitst', 257.72815, 43.42322), ('st', 47.82522, 51.149788), ('hird', 572.8713, 60.59974), ('irces', 710.9375, 61.953125), ('income', 35.546875, 111.71875), ('tax', 155.39062, 112.734375), ('department', 213.42479, 111.97105), ('govt', 577.8906, 116.796875), ('of', 690.625, 116.796875), ('india', 742.4219, 116.796875), ('hitu', 56.875, 169.60938), ('biswas', 135.0781, 169.60936), ('biswas', 197.03125, 243.75), ('haridas', 54.84375, 244.76562), ('in', 648.0486, 272.82794), ('n', 726.6486, 303.17294), ('051031920', 51.569546, 320.44266), ('number', 283.35938, 355.46875), ('account', 181.64876, 357.539), ('permanent', 52.67427, 359.5602), ('czkpb5432z', 53.38768, 399.7318), ('s', 842.3438, 427.73975), ('biswas', 125.9375, 468.20312), ('hilu', 59.921875, 469.21875), ('signature', 50.868423, 528.95844)]

def group(lst):
    new = []
    i = 0
    while i < len(lst):
        if i == 0 or (not (abs(lst[i][2] - lst[i-1][2]) < 5)):
            new.append([])
        new[-1].append(lst[i])
        i += 1

    return new

def sort(lst):
    for row in lst:
        row.sort(key=lambda x: x[1])

lst = group(initial)
sort(lst)
print('\n'.join(' '.join(y[0] for y in x) for x in lst))

Output:

fanitst
st
hird irces
income tax department govt of india
hitu biswas
haridas biswas
in
n
051031920
permanent account number
czkpb5432z
s
hilu biswas
signature


问:
How to concatenate two unique arrays and remove 'nan'?
Using the Pokemon Dataset, I want to extract all the unique types in columns: "Type 1" & "Type 2" and print them out after. So far, I've been able to concatenate the unique values from both columns together into an array. Now I'm having trouble removing 'nan' from the array.

My code:

```<code>import pandas as pd
import numpy as np
df = pd.read_csv("/Users/edwinandrew/Documents/Datasets/Pokemon.csv")
type_class1 = df['Type 1'].unique()
type_class2 = df['Type 2'].unique()
all_types = np.concatenate((type_class1, type_class2))
print(all_types)
</code>```

Output:

```<code>['Grass' 'Fire' 'Water' 'Bug' 'Normal' 'Poison' 'Electric' 'Ground'
 'Fairy' 'Fighting' 'Psychic' 'Rock' 'Ghost' 'Ice' 'Dragon' 'Dark' 'Steel'
 'Flying' 'Poison' nan 'Flying' 'Dragon' 'Ground' 'Fairy' 'Grass'
 'Fighting' 'Psychic' 'Steel' 'Ice' 'Rock' 'Dark' 'Water' 'Electric'
 'Fire' 'Ghost' 'Bug' 'Normal']
</code>```

I tried using x = x[~numpy.isnan(x)] to see if that would remove the nan value but I got an error. What would be the best way to solve this problem?

答:
you need to use dropna

```<code>type_class1 = df['Type 1'].dropna().unique()
type_class2 = df['Type 2'].dropna().unique()
</code>```

Body:
Using the Pokemon Dataset, I want to extract all the unique types in columns: "Type 1" & "Type 2" and print them out after. So far, I've been able to concatenate the unique values from both columns together into an array. Now I'm having trouble removing 'nan' from the array.

My code:

import pandas as pd
import numpy as np
df = pd.read_csv("/Users/edwinandrew/Documents/Datasets/Pokemon.csv")
type_class1 = df['Type 1'].unique()
type_class2 = df['Type 2'].unique()
all_types = np.concatenate((type_class1, type_class2))
print(all_types)

Output:

['Grass' 'Fire' 'Water' 'Bug' 'Normal' 'Poison' 'Electric' 'Ground'
 'Fairy' 'Fighting' 'Psychic' 'Rock' 'Ghost' 'Ice' 'Dragon' 'Dark' 'Steel'
 'Flying' 'Poison' nan 'Flying' 'Dragon' 'Ground' 'Fairy' 'Grass'
 'Fighting' 'Psychic' 'Steel' 'Ice' 'Rock' 'Dark' 'Water' 'Electric'
 'Fire' 'Ghost' 'Bug' 'Normal']

I tried using x = x[~numpy.isnan(x)] to see if that would remove the nan value but I got an error. What would be the best way to solve this problem?

Body:
you need to use dropna

type_class1 = df['Type 1'].dropna().unique()
type_class2 = df['Type 2'].dropna().unique()


问:
map2 error "arguments imply differing number of rows"
I was trying to fit a step function to a dataframe and determine how many cut points produce the lowest mse. And I kept having the same error message:

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 149, 1332

My codes and the dummy dataframe go as follows:

```<code>library(tidyverse)
library{rsample)
library(broom)
library(rcfss)

set.seed(666)
df <- tibble(egalit_scale = runif(1481, 1, 35), income06 = runif(1481, 1, 25))
training_df <- vfold_cv(df, 10)
mse_df <- function(splits, cc){
  model <- glm(egalit_scale ~ cut(income06, cc),
              data = analysis(splits))
  model_mse <- augment(model, newdata = assessment(splits)) %>%
    mse(truth = egalit_scale, estimate = round(.fitted))
  model_mse$.estimate
}

tidyr::expand(training_df, id, cc = 2:15) %>%
  left_join(training_df) %>%
  mutate(mse = map2(splits, cc, mse_df))
</code>```

The error happens at the step with map2. I tried running each of the 10 folds CV with a specific number of cut points, say 6. It turned out 9 out of the 10 folds worked with the function, but one didn't. Could anyone please help me with this?

答:
The issue is coming from the

```<code>augment(model, newdata = assessment(splits))
</code>```

because in the previous step

```<code>model <- glm(egalit_scale ~ cut(income06, cc),
          data = analysis(splits))
</code>```

we do the analysis on the 'splits' instead of the assessment and this results in getting different number of rows, e.g.

```<code>out <- tidyr::expand(training_df, id, cc = 2:15) %>%
         left_join(training_df)

tmp <- out$splits[[1]]

analysis(tmp)
# A tibble: 1,332 x 2
#   egalit_scale income06
#          <dbl>    <dbl>
# 1        27.3      9.69
# 2         7.71     8.48
# 3        34.3     21.3
# 4         7.85    15.8
# 5        13.3     24.6
# 6        26.2      8.67
# 7        34.3      4.78
# 8        17.9     16.8
# 9         1.45    21.2
#10         9.84    15.7
# … with 1,322 more rows

assessment(tmp)
# A tibble: 149 x 2
#   egalit_scale income06
#          <dbl>    <dbl>
# 1        28.6     14.8
# 2        17.8      2.47
# 3         5.03    24.3
# 4        31.5      5.79
# 5        18.4     18.0
# 6         4.05     8.06
# 7         2.28     8.16
# 8        28.6     16.8
# 9        21.1      7.03
#10         3.67    14.2
# … with 139 more rows
</code>```

So, if we change the model statement with assessment

```<code>mse_df <- function(splits, cc){
  model <- glm(egalit_scale ~ cut(income06, cc),
              data = assessment(splits))
  model_mse <- augment(model, newdata = assessment(splits)) %>%
    mse(truth = egalit_scale, estimate = round(.fitted))
  model_mse$.estimate
}

library(yardstick)
out1 <- tidyr::expand(training_df, id, cc = 2:15) %>%
   left_join(training_df) %>%
   mutate(mse = map2_dbl(splits, cc, mse_df))
out1
# A tibble: 140 x 4
#   id        cc splits               mse
#   <chr>  <int> <named list>       <dbl>
# 1 Fold01     2 <split [1.3K/149]>  94.9
# 2 Fold01     3 <split [1.3K/149]>  94.6
# 3 Fold01     4 <split [1.3K/149]>  93.8
# 4 Fold01     5 <split [1.3K/149]>  94.5
# 5 Fold01     6 <split [1.3K/149]>  94.0
# 6 Fold01     7 <split [1.3K/149]>  92.0
# 7 Fold01     8 <split [1.3K/149]>  88.9
# 8 Fold01     9 <split [1.3K/149]>  91.2
# 9 Fold01    10 <split [1.3K/149]>  92.8
#10 Fold01    11 <split [1.3K/149]>  86.0
# … with 130 more rows
</code>```

Body:
I was trying to fit a step function to a dataframe and determine how many cut points produce the lowest mse. And I kept having the same error message:

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 149, 1332

My codes and the dummy dataframe go as follows:

library(tidyverse)
library{rsample)
library(broom)
library(rcfss)

set.seed(666)
df <- tibble(egalit_scale = runif(1481, 1, 35), income06 = runif(1481, 1, 25))
training_df <- vfold_cv(df, 10)
mse_df <- function(splits, cc){
  model <- glm(egalit_scale ~ cut(income06, cc),
              data = analysis(splits))
  model_mse <- augment(model, newdata = assessment(splits)) %>%
    mse(truth = egalit_scale, estimate = round(.fitted))
  model_mse$.estimate
}

tidyr::expand(training_df, id, cc = 2:15) %>%
  left_join(training_df) %>%
  mutate(mse = map2(splits, cc, mse_df))

The error happens at the step with map2. I tried running each of the 10 folds CV with a specific number of cut points, say 6. It turned out 9 out of the 10 folds worked with the function, but one didn't. Could anyone please help me with this?

Body:
The issue is coming from the

augment(model, newdata = assessment(splits))

because in the previous step

model <- glm(egalit_scale ~ cut(income06, cc),
          data = analysis(splits))

we do the analysis on the 'splits' instead of the assessment and this results in getting different number of rows, e.g.

out <- tidyr::expand(training_df, id, cc = 2:15) %>%
         left_join(training_df)

tmp <- out$splits[[1]]

analysis(tmp)
# A tibble: 1,332 x 2
#   egalit_scale income06
#          <dbl>    <dbl>
# 1        27.3      9.69
# 2         7.71     8.48
# 3        34.3     21.3
# 4         7.85    15.8
# 5        13.3     24.6
# 6        26.2      8.67
# 7        34.3      4.78
# 8        17.9     16.8
# 9         1.45    21.2
#10         9.84    15.7
# … with 1,322 more rows

assessment(tmp)
# A tibble: 149 x 2
#   egalit_scale income06
#          <dbl>    <dbl>
# 1        28.6     14.8
# 2        17.8      2.47
# 3         5.03    24.3
# 4        31.5      5.79
# 5        18.4     18.0
# 6         4.05     8.06
# 7         2.28     8.16
# 8        28.6     16.8
# 9        21.1      7.03
#10         3.67    14.2
# … with 139 more rows

So, if we change the model statement with assessment

mse_df <- function(splits, cc){
  model <- glm(egalit_scale ~ cut(income06, cc),
              data = assessment(splits))
  model_mse <- augment(model, newdata = assessment(splits)) %>%
    mse(truth = egalit_scale, estimate = round(.fitted))
  model_mse$.estimate
}

library(yardstick)
out1 <- tidyr::expand(training_df, id, cc = 2:15) %>%
   left_join(training_df) %>%
   mutate(mse = map2_dbl(splits, cc, mse_df))
out1
# A tibble: 140 x 4
#   id        cc splits               mse
#   <chr>  <int> <named list>       <dbl>
# 1 Fold01     2 <split [1.3K/149]>  94.9
# 2 Fold01     3 <split [1.3K/149]>  94.6
# 3 Fold01     4 <split [1.3K/149]>  93.8
# 4 Fold01     5 <split [1.3K/149]>  94.5
# 5 Fold01     6 <split [1.3K/149]>  94.0
# 6 Fold01     7 <split [1.3K/149]>  92.0
# 7 Fold01     8 <split [1.3K/149]>  88.9
# 8 Fold01     9 <split [1.3K/149]>  91.2
# 9 Fold01    10 <split [1.3K/149]>  92.8
#10 Fold01    11 <split [1.3K/149]>  86.0
# … with 130 more rows


问:
Resolve Relative Path from node_modules to Dist folder with Webpack
I'm using React component as an NPM Package. in the component, I have SCSS file
with url(../iamges/img..) path, but actually, the images folder located in the Dist folder, how can I point Webpack to take the relative path from node_modules and serve it from images folder located in the Dist?

```<code>located in node_modules =>
background: url('../images/some-icon.svg') no-repeat center center;
</code>```

Webpack config:

```<code>
const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: './src/index.js',
    devtool: 'inline-module-source-map',
    output: {
        path: path.resolve(__dirname, '/dist'),
        filename: 'bundle.js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    {
                        loader: 'resolve-url-loader',
                        // options: {
                        //  debug: true,
                        //  root: path.join(__dirname, './dist/images'),
                        //  includeRoot: true,
                        //  absolute: true,
                        // },
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true,
                            sourceMapContents: false,
                        },
                    },
                ],
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                use: {
                    loader: 'url-loader?name=/images/[name].[ext]',
                    options: {
                        limit: 10000,
                    },
                },
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        // modules: [path.resolve(__dirname, '/images'), 'node_modules'],
        alias: {
            'react-redux': path.resolve('./node_modules/react-redux'),
        },
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    devServer: {
        hot: true,
        publicPath: '/dist/',
    },
};

</code>```

babel.config.js

```<code>module.exports = {
    // presets: ['@babel/preset-env', '@babel/preset-react'],
    plugins: [
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-proposal-export-default-from',
        '@babel/transform-runtime',
    ],
    sourceType: 'unambiguous',
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
        '@babel/preset-react',
    ],
};

</code>```

```<code>dist
   -- images
   -- index.html
</code>```

ERROR:

```<code>ERROR in ./node_modules/comp/src/styles/details.scss (./node_modules/css-loader!./node_modules/resolve-url-loader!./node_modules/sass-loader/lib/loader.js??ref--5-3!./node_modules/compdetails/src/styles/details.scss)
Module not found: Error: Can't resolve '../images/icon.svg'
</code>```

答:
Anything referred through url('...') in css will be computed with reference to the path of deployed application (scss will not compute the path unless variable or function is not being used):

For example:
If your referred component SCSS module is having background: url('../images/some-icon.svg') no-repeat center center;

The final CSS compilation will be same (it is also because the component is not using any SCSS variables or functions to compute the final path).

So your application will always try to find that image as:

Example: http://localhost:3000/../images/some-icon.svg which is a problem.
(.. is referred as parent directory)

If you try to run your app with some sub-url (also known as sub context) as http://localhost:3000/sub-url/ and you keep your images parallel to sub-url folder it will automatically work.

```<code>-- /
   |
   |-- sub-url
         |
         |-- index.html
   |-- images
         |
         |-- some-icon.svg

</code>```

Another option can be override the component SCSS with yours.

You already found the solution to use resolve-url-loader, but in this case you need to import the component's scss file into you scss.

so your webpack config should look like:

```<code>const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: './src/index.js',
    devtool: 'inline-module-source-map',
    output: {
        path: path.resolve(__dirname, '/dist'),
        filename: 'bundle.js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    // CHANGE HERE
                    {
                        loader: 'resolve-url-loader',
                        options: {
                          root: '/images', // considering all your images are placed in specified folder. Note: this is just a string that will get as prefix to image path
                          includeRoot: true,
                          absolute: true,
                        },
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true,
                            sourceMapContents: false,
                        },
                    },

                ],
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                use: {
                    loader: 'url-loader?name=/images/[name].[ext]',
                    options: {
                        limit: 10000,
                    },
                },
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        // modules: [path.resolve(__dirname, '/images'), 'node_modules'],
        alias: {
            'react-redux': path.resolve('./node_modules/react-redux'),
        },
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    devServer: {
        hot: true,
        publicPath: '/dist/',
    },
};
</code>```

I hope it helps.

Body:
I'm using React component as an NPM Package. in the component, I have SCSS file
with url(../iamges/img..) path, but actually, the images folder located in the Dist folder, how can I point Webpack to take the relative path from node_modules and serve it from images folder located in the Dist?

located in node_modules =>
background: url('../images/some-icon.svg') no-repeat center center;

Webpack config:

const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: './src/index.js',
    devtool: 'inline-module-source-map',
    output: {
        path: path.resolve(__dirname, '/dist'),
        filename: 'bundle.js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    {
                        loader: 'resolve-url-loader',
                        // options: {
                        //  debug: true,
                        //  root: path.join(__dirname, './dist/images'),
                        //  includeRoot: true,
                        //  absolute: true,
                        // },
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true,
                            sourceMapContents: false,
                        },
                    },
                ],
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                use: {
                    loader: 'url-loader?name=/images/[name].[ext]',
                    options: {
                        limit: 10000,
                    },
                },
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        // modules: [path.resolve(__dirname, '/images'), 'node_modules'],
        alias: {
            'react-redux': path.resolve('./node_modules/react-redux'),
        },
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    devServer: {
        hot: true,
        publicPath: '/dist/',
    },
};

babel.config.js

module.exports = {
    // presets: ['@babel/preset-env', '@babel/preset-react'],
    plugins: [
        '@babel/plugin-proposal-class-properties',
        '@babel/plugin-proposal-export-default-from',
        '@babel/transform-runtime',
    ],
    sourceType: 'unambiguous',
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
        '@babel/preset-react',
    ],
};

dist
   -- images
   -- index.html

ERROR:

ERROR in ./node_modules/comp/src/styles/details.scss (./node_modules/css-loader!./node_modules/resolve-url-loader!./node_modules/sass-loader/lib/loader.js??ref--5-3!./node_modules/compdetails/src/styles/details.scss)
Module not found: Error: Can't resolve '../images/icon.svg'

Body:
Anything referred through url('...') in css will be computed with reference to the path of deployed application (scss will not compute the path unless variable or function is not being used):

For example:
If your referred component SCSS module is having background: url('../images/some-icon.svg') no-repeat center center;

The final CSS compilation will be same (it is also because the component is not using any SCSS variables or functions to compute the final path).

So your application will always try to find that image as:

Example: http://localhost:3000/../images/some-icon.svg which is a problem.
(.. is referred as parent directory)

If you try to run your app with some sub-url (also known as sub context) as http://localhost:3000/sub-url/ and you keep your images parallel to sub-url folder it will automatically work.

-- /
   |
   |-- sub-url
         |
         |-- index.html
   |-- images
         |
         |-- some-icon.svg

Another option can be override the component SCSS with yours.

You already found the solution to use resolve-url-loader, but in this case you need to import the component's scss file into you scss.

so your webpack config should look like:

const webpack = require('webpack');
const path = require('path');

module.exports = {
    entry: './src/index.js',
    devtool: 'inline-module-source-map',
    output: {
        path: path.resolve(__dirname, '/dist'),
        filename: 'bundle.js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: 'babel-loader',
                },
            },
            {
                test: /\.scss$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    // CHANGE HERE
                    {
                        loader: 'resolve-url-loader',
                        options: {
                          root: '/images', // considering all your images are placed in specified folder. Note: this is just a string that will get as prefix to image path
                          includeRoot: true,
                          absolute: true,
                        },
                    },
                    {
                        loader: 'sass-loader',
                        options: {
                            sourceMap: true,
                            sourceMapContents: false,
                        },
                    },

                ],
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader'],
            },
            {
                test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
                use: {
                    loader: 'url-loader?name=/images/[name].[ext]',
                    options: {
                        limit: 10000,
                    },
                },
            },
        ],
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        // modules: [path.resolve(__dirname, '/images'), 'node_modules'],
        alias: {
            'react-redux': path.resolve('./node_modules/react-redux'),
        },
    },
    plugins: [new webpack.HotModuleReplacementPlugin()],
    devServer: {
        hot: true,
        publicPath: '/dist/',
    },
};

I hope it helps.


问:
How to link to a specific tweet when you don't know the user.screen_name?
This has probably been asked, but I can't find it...

I want to link to a specific tweet, such as this:

http://twitter.com/TinyNietzsche/status/69440267110973440

But if @TinyNietzsche changes his screen_name it breaks my link.

Using the API, statuses/show I can get the raw data, and even build a link to twitter using that, but that doesn't really seem efficient.

I can create a persistent link to the user by using the redirect:

http://twitter.com/account/redirect_by_id?id=131891655

Is there a way to link a specific tweet that doesn't rely on the user.screen_name?

答:
You can just replace their user name with their user id:

http://twitter.com/#!/131891655/status/69440267110973440

ContentLicense: CC BY-SA 3.0


问:
How to create "add to favorites" functional using Django Rest Framework
I just can’t find any information about the implementation of the system of adding to favorites for registered users.

The model has a Post model. It has a couple of fields of format String. The author field, which indicates which user made the POST request, etc.

But how to make it so that the user can add this Post to his “favorites”, so that later you can get a JSON response with all the posts that he added to himself. Well, respectively, so that you can remove from favorites.

Are there any ideas?

答: You can add a favorite_posts field (many-to-many) in your Author model.


问:
How can I make a Selenium script undetectable using GeckoDriver and Firefox through Python?
Is there a way to make your Selenium script undetectable in Python using geckodriver?

I'm using Selenium for scraping. Are there any protections we need to use so websites can't detect Selenium?

答:
There are different methods to avoid websites detecting the use of Selenium.

The value of navigator.webdriver is set to true by default when using Selenium. This variable will be present in Chrome as well as Firefox. This variable should be set to "undefined" to avoid detection.

A proxy server can also be used to avoid detection.

Some websites are able to use the state of your browser to determine if you are using Selenium. You can set Selenium to use a custom browser profile to avoid this.

The code below uses all three of these approaches.

```<code>profile = webdriver.FirefoxProfile('C:\\Users\\You\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\something.default-release')

PROXY_HOST = "12.12.12.123"
PROXY_PORT = "1234"
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", PROXY_HOST)
profile.set_preference("network.proxy.http_port", int(PROXY_PORT))
profile.set_preference("dom.webdriver.enabled", False)
profile.set_preference('useAutomationExtension', False)
profile.update_preferences()
desired = DesiredCapabilities.FIREFOX

driver = webdriver.Firefox(firefox_profile=profile, desired_capabilities=desired)
</code>```

Once the code is run, you will be able to manually check that the browser run by Selenium now has your Firefox history and extensions. You can also type "navigator.webdriver" into the devtools console to check that it is undefined.

Body:
There are different methods to avoid websites detecting the use of Selenium.

The value of navigator.webdriver is set to true by default when using Selenium. This variable will be present in Chrome as well as Firefox. This variable should be set to "undefined" to avoid detection.

A proxy server can also be used to avoid detection.

Some websites are able to use the state of your browser to determine if you are using Selenium. You can set Selenium to use a custom browser profile to avoid this.

The code below uses all three of these approaches.

profile = webdriver.FirefoxProfile('C:\\Users\\You\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\something.default-release')

PROXY_HOST = "12.12.12.123"
PROXY_PORT = "1234"
profile.set_preference("network.proxy.type", 1)
profile.set_preference("network.proxy.http", PROXY_HOST)
profile.set_preference("network.proxy.http_port", int(PROXY_PORT))
profile.set_preference("dom.webdriver.enabled", False)
profile.set_preference('useAutomationExtension', False)
profile.update_preferences()
desired = DesiredCapabilities.FIREFOX

driver = webdriver.Firefox(firefox_profile=profile, desired_capabilities=desired)

Once the code is run, you will be able to manually check that the browser run by Selenium now has your Firefox history and extensions. You can also type "navigator.webdriver" into the devtools console to check that it is undefined.


问:
read indefinite amount of integers and print on file
*this program read integers until one is negative then prints on a file a characteristic of each of them: how many integers it can be divided by. the problem is that it keeps asking for integers even when i inseert negative ones. please let me know if you can a way to fix this without changing too much of the code</p>

```<code>#include <stdio.h>
#include <stdlib.h>
int checkdiv(int *n);
int main(int argc, char * argv[]){
    int *p;
    int i, j;
    FILE *fp;
    int amount;
    i=0;
    p=NULL;

    if(fp = fopen("ris.txt", "w")){
        do{i++;
        p=realloc(p,sizeof(int)*i);
        scanf("%d", (p+i-1));
        amount=checkdiv(p+i-1);
        if(amount!= -1);
        fprintf(fp,"%d  %d\n", *(p+i-1),amount);
        }while(p+i-1>0);

    }else{
        printf("errore");
    }
    fclose(fp);
    free(p);
    return 0;
}
int checkdiv(int *n){
int i;
int amount=0;
for(i = 2;i < *n; i++){
    if(*n % i == 0){
        amount++;
    }
}
if(*n <= 0){
    amount= -1;
}
return amount;
}
</code>```

答:
You should remove semi colon in line

```<code>if(amount!=-1);
</code>```

so that the statement below it can be included in if block.

Body:
*this program read integers until one is negative then prints on a file a characteristic of each of them: how many integers it can be divided by. the problem is that it keeps asking for integers even when i inseert negative ones. please let me know if you can a way to fix this without changing too much of the code

#include <stdio.h>
#include <stdlib.h>
int checkdiv(int *n);
int main(int argc, char * argv[]){
    int *p;
    int i, j;
    FILE *fp;
    int amount;
    i=0;
    p=NULL;

    if(fp = fopen("ris.txt", "w")){
        do{i++;
        p=realloc(p,sizeof(int)*i);
        scanf("%d", (p+i-1));
        amount=checkdiv(p+i-1);
        if(amount!= -1);
        fprintf(fp,"%d  %d\n", *(p+i-1),amount);
        }while(p+i-1>0);

    }else{
        printf("errore");
    }
    fclose(fp);
    free(p);
    return 0;
}
int checkdiv(int *n){
int i;
int amount=0;
for(i = 2;i < *n; i++){
    if(*n % i == 0){
        amount++;
    }
}
if(*n <= 0){
    amount= -1;
}
return amount;
}

Body:
You should remove semi colon in line

if(amount!=-1);

so that the statement below it can be included in if block.


问:
How to echo result from query
Maybe I am overthinking this, but I have narrowed my query to find a row down to 1 result that I need, and it will not display. Wondering if someone could tell me what I am doing wrong.

```<code>$result = mysqli_query($link, "SELECT pageid FROM article ORDER BY id DESC LIMIT 1");
$row = mysqli_use_result($result);

echo $row;
</code>```

I have it selecting the last row and supplying me with the stored data from the pageid of the last row.

答:
mysqli doesn't have any function to get a single column from a single row. You need to use one of the fetch methods e.g. fetch_array(). You don't need any loop if you use LIMIT 1.

Just fetch a single row and get the column from the returned array:

```<code>$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);

$row = $resultpageid->fetch_assoc();
// or
$row = $resultpageid->fetch_array();

if ($row) {
    echo $row["pageid"];
} else {
    echo "No record found!";
}
</code>```

Title: How to echo result from query

Body:
Maybe I am overthinking this, but I have narrowed my query to find a row down to 1 result that I need, and it will not display. Wondering if someone could tell me what I am doing wrong.

$result = mysqli_query($link, "SELECT pageid FROM article ORDER BY id DESC LIMIT 1");
$row = mysqli_use_result($result);

echo $row;

I have it selecting the last row and supplying me with the stored data from the pageid of the last row.

Body:
mysqli doesn't have any function to get a single column from a single row. You need to use one of the fetch methods e.g. fetch_array(). You don't need any loop if you use LIMIT 1.

Just fetch a single row and get the column from the returned array:

$pageid = "SELECT pageid FROM articles ORDER BY id DESC LIMIT 1";
$resultpageid = $link->query($pageid);

$row = $resultpageid->fetch_assoc();
// or
$row = $resultpageid->fetch_array();

if ($row) {
    echo $row["pageid"];
} else {
    echo "No record found!";
}


问:
Store related items in a single request in Laravel
I have a dynamic form that submits data in a relation:
A Routine can have multiple sections and each section can have multiple exercises.

Here is a example request that gets sent:

```<code>{"_token":"Z1sF2K5LHU1bsQ4l3JRaOLCTQDmJ47qakigmrfI5","name":"New Routine 111","sections":{"section-1":{"section-name":"Section 1","exercises":{"1":{"name":"Exercise 11"},"2":{"name":"Exercise 12"}}},"section-2":{"section-name":"Section 2","exercises":{"3":{"name":"Exercise 21"},"4":{"name":"Exercise 22"},"5":{"name":"Exercise 23"}}},"section-3":{"section-name":"Section 3","exercises":{"6":{"name":"Exercise 31"},"7":{"name":"Exercise 32"}}}},"submit":"Submit"}
</code>```

So i attempted to foreach through the whol request, but i got a bit stuck to how i can save them all with the required relations:

```<code>    $routine = new Routine;
    $routine->title = $request->title;
    $routine->user_id = 1;
    $routine->create();
    foreach($data as $item){
        $section = new Section;
        $section->title = $item->title;
        $routine->sections()->create();
        foreach($item['exercises'] as $exercise){
            $section->exercises()->create(['title' => $exercise->title]);
        }
    }
</code>```

答:
You can do this:

foreach($data as $item){
    $section = new Section;
    $section->title = $item->title;
    $section->create();
    foreach($item['exercises'] as $exercise){
        $section->exercises()->create([
              'title' => $exercise->title,
              'user_id' => User::where('token',$token)->first()->id
        ]);
    }
}

```

Dont forget to define the relation exercises() into your Section model.

You can see more info about this in here:

https://laravel.com/docs/5.8/eloquent-relationships#the-create-method

Body:
I have a dynamic form that submits data in a relation:
A Routine can have multiple sections and each section can have multiple exercises.

Here is a example request that gets sent:

{"_token":"Z1sF2K5LHU1bsQ4l3JRaOLCTQDmJ47qakigmrfI5","name":"New Routine 111","sections":{"section-1":{"section-name":"Section 1","exercises":{"1":{"name":"Exercise 11"},"2":{"name":"Exercise 12"}}},"section-2":{"section-name":"Section 2","exercises":{"3":{"name":"Exercise 21"},"4":{"name":"Exercise 22"},"5":{"name":"Exercise 23"}}},"section-3":{"section-name":"Section 3","exercises":{"6":{"name":"Exercise 31"},"7":{"name":"Exercise 32"}}}},"submit":"Submit"}

So i attempted to foreach through the whol request, but i got a bit stuck to how i can save them all with the required relations:

    $routine = new Routine;
    $routine->title = $request->title;
    $routine->user_id = 1;
    $routine->create();
    foreach($data as $item){
        $section = new Section;
        $section->title = $item->title;
        $routine->sections()->create();
        foreach($item['exercises'] as $exercise){
            $section->exercises()->create(['title' => $exercise->title]);
        }
    }

Body:
You can do this:

foreach($data as $item){
    $section = new Section;
    $section->title = $item->title;
    $section->create();
    foreach($item['exercises'] as $exercise){
        $section->exercises()->create([
              'title' => $exercise->title,
              'user_id' => User::where('token',$token)->first()->id
        ]);
    }
}

Dont forget to define the relation exercises() into your Section model.

You can see more info about this in here:

https://laravel.com/docs/5.8/eloquent-relationships#the-create-method


问:
jQuery variable scope within each
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

```<code>  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });
</code>```

Many thanks for your time,

答:
Your question was:

...all the values of every form element...

but your selector was only for input elements in one particular form. Presuming that you actually wanted the values of all the controls in a form, then the following POJS may suit:

```<code>function getFormValues(formId) {
  var data = {};
  var form = document.getElementById(formId);

  if (form) {
    var control, controls = form.elements;

    if (controls) {
      var i = controls.length;

      while (i--) {
        control = controls[i];
        data[control.id] = control.value;
      }
    }
  }
  return data;
}
</code>```

Presuming that every control has an ID, which is not a requirement. If some controls don't have an id, you might want to use the name property instead, so:

```<code>        data[control.id || control.name] = control.value;
</code>```

In some cases, your controls may not have an id or a name (e.g. controls that are needed for the form but whose values are not to be submitted, such as submit and reset buttons) so:

```<code>        var idOrName = control.id || control.name;
        if (idOrName) {
          data[idOrName] = control.value;
        }
</code>```

You may also need to deal with controls having the same name, since the value of whichever one is accessed last will replace the value of previous same-named controls.

Title: jQuery variable scope within each

Body:
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });

Many thanks for your time,

Body:
Your question was:

...all the values of every form element...

but your selector was only for input elements in one particular form. Presuming that you actually wanted the values of all the controls in a form, then the following POJS may suit:

function getFormValues(formId) {
  var data = {};
  var form = document.getElementById(formId);

  if (form) {
    var control, controls = form.elements;

    if (controls) {
      var i = controls.length;

      while (i--) {
        control = controls[i];
        data[control.id] = control.value;
      }
    }
  }
  return data;
}

Presuming that every control has an ID, which is not a requirement. If some controls don't have an id, you might want to use the name property instead, so:

        data[control.id || control.name] = control.value;

In some cases, your controls may not have an id or a name (e.g. controls that are needed for the form but whose values are not to be submitted, such as submit and reset buttons) so:

        var idOrName = control.id || control.name;
        if (idOrName) {
          data[idOrName] = control.value;
        }

You may also need to deal with controls having the same name, since the value of whichever one is accessed last will replace the value of previous same-named controls.


问:
Possible to do dynamic marshaling of structs in Go?
I have some redundant logic I'm extracting into a util to bind requests to structs and I was hoping I could do this dynamically somehow. What I want is to basically generically bind any request to the struct type I pass in. This would greatly reduce some code in my program.

I could have a Task struct or I could have an Information struct. All this information is coming into the server via JSON, but I want to be able to pass in the type name and have it auto-bind to reduce the code I'm writing.

Example Caller

```<code>func StoreTask(dbWrapper *database.DB) func(http.ResponseWriter, *http.Request) {
    return func(rw http.ResponseWriter, r *http.Request) {
        data := &utilities.DynamicStruct{entities.Task, r, rw}
        utilities.PersistRequest(data)
    }
}
</code>```

Here's my small example:

```<code>type DynamicStruct struct {
    cType  interface{}
    writer http.ResponseWriter
    req    *http.Request
}

func PersistRequest(s *DynamicStruct, decoderOpts *DecoderMetadata) {
    r := s.req
    rw := s.writer

    // I want the struct to basically be able to take any type
    data := s.cType

    err := r.ParseForm()
    if err != nil {
        log.Printf("HTTP %d - %s", 500, err.Error())
        http.Error(rw, err.Error(), 500)
    }

    // This is where the dynamic nature of the param would come into play that I'm looking for..
    newTask := new(data)

    decoder := utilities.GenerateDecoder(decoderOpts)

    // Using gorilla/schema here
    err = decoder.Decode(newTask, r.Form)

    if err != nil {
        log.Printf("HTTP %d - %s", 500, err.Error())
        http.Error(rw, err.Error(), 500)
    }

    rw.Header().Set("Content-Type", "application/json")
    json.NewEncoder(rw).Encode(newTask)

}
</code>```

答:
When you're marshaling, or decoding an unknown struct like this, there's nothing additional you need to do: just pass the interface value to the encoder, and it will encode the underlying value using reflection, or call the MashalJSON if it implements a custom marshaler.

```<code>dynamicStruct.cType=someStructValue
</code>```

If you're unmarshaling, you can do the same by passing a pointer to a struct:

```<code>dynamicStruct.cType=&SomeStruct{}
</code>```

Then you don't need to create a new instance of an unknown type, just pass the interface to unmarshal.

Body:
I have some redundant logic I'm extracting into a util to bind requests to structs and I was hoping I could do this dynamically somehow. What I want is to basically generically bind any request to the struct type I pass in. This would greatly reduce some code in my program.

I could have a Task struct or I could have an Information struct. All this information is coming into the server via JSON, but I want to be able to pass in the type name and have it auto-bind to reduce the code I'm writing.

Example Caller

func StoreTask(dbWrapper *database.DB) func(http.ResponseWriter, *http.Request) {
    return func(rw http.ResponseWriter, r *http.Request) {
        data := &utilities.DynamicStruct{entities.Task, r, rw}
        utilities.PersistRequest(data)
    }
}

Here's my small example:

type DynamicStruct struct {
    cType  interface{}
    writer http.ResponseWriter
    req    *http.Request
}

func PersistRequest(s *DynamicStruct, decoderOpts *DecoderMetadata) {
    r := s.req
    rw := s.writer

    // I want the struct to basically be able to take any type
    data := s.cType

    err := r.ParseForm()
    if err != nil {
        log.Printf("HTTP %d - %s", 500, err.Error())
        http.Error(rw, err.Error(), 500)
    }

    // This is where the dynamic nature of the param would come into play that I'm looking for..
    newTask := new(data)

    decoder := utilities.GenerateDecoder(decoderOpts)

    // Using gorilla/schema here
    err = decoder.Decode(newTask, r.Form)

    if err != nil {
        log.Printf("HTTP %d - %s", 500, err.Error())
        http.Error(rw, err.Error(), 500)
    }

    rw.Header().Set("Content-Type", "application/json")
    json.NewEncoder(rw).Encode(newTask)

}

Body:
When you're marshaling, or decoding an unknown struct like this, there's nothing additional you need to do: just pass the interface value to the encoder, and it will encode the underlying value using reflection, or call the MashalJSON if it implements a custom marshaler.

dynamicStruct.cType=someStructValue

If you're unmarshaling, you can do the same by passing a pointer to a struct:

dynamicStruct.cType=&SomeStruct{}

Then you don't need to create a new instance of an unknown type, just pass the interface to unmarshal.


问:
Scrapy spider not found error
This is Windows 7 with python 2.7

I have a scrapy project in a directory called caps (this is where scrapy.cfg is)

My spider is located in caps\caps\spiders\campSpider.py

I cd into the scrapy project  and try to run

```<code>scrapy crawl campSpider -o items.json -t json
</code>```

I get an error that the spider can't be found. The class name is campSpider

```<code>...
    spider = self.crawler.spiders.create(spname, **opts.spargs)
  File "c:\Python27\lib\site-packages\scrapy-0.14.0.2841-py2.7-win32.egg\scrapy\spidermanager.py", l
ine 43, in create
    raise KeyError("Spider not found: %s" % spider_name)
KeyError: 'Spider not found: campSpider'
</code>```

Am I missing some configuration item?

答:
If you are following the tutorial from https://docs.scrapy.org/en/latest/intro/tutorial.html

Then do something like:

```<code>$ sudo apt install python-pip
$ pip install Scrapy
(logout, login)
$ cd
$ scrapy startproject tutorial
$ vi ~/tutorial/tutorial/spiders/quotes_spider.py
$ cd ~/tutorial/tutorial
$ scrapy crawl quotes
</code>```

The error happens if you try to create the spiders directory yourself under ~/tutorial

Title: Scrapy spider not found error

Body:
This is Windows 7 with python 2.7

I have a scrapy project in a directory called caps (this is where scrapy.cfg is)

My spider is located in caps\caps\spiders\campSpider.py

I cd into the scrapy project  and try to run

scrapy crawl campSpider -o items.json -t json

I get an error that the spider can't be found. The class name is campSpider

...
    spider = self.crawler.spiders.create(spname, **opts.spargs)
  File "c:\Python27\lib\site-packages\scrapy-0.14.0.2841-py2.7-win32.egg\scrapy\spidermanager.py", l
ine 43, in create
    raise KeyError("Spider not found: %s" % spider_name)
KeyError: 'Spider not found: campSpider'

Am I missing some configuration item?

Body:
If you are following the tutorial from https://docs.scrapy.org/en/latest/intro/tutorial.html

Then do something like:

$ sudo apt install python-pip
$ pip install Scrapy
(logout, login)
$ cd
$ scrapy startproject tutorial
$ vi ~/tutorial/tutorial/spiders/quotes_spider.py
$ cd ~/tutorial/tutorial
$ scrapy crawl quotes

The error happens if you try to create the spiders directory yourself under ~/tutorial


问:
Kafka MirrorMaker2 - not mirroring consumer group offsets
I have setup MirrorMaker2 for replicating data between 2 DCs.

My mm2.properties:

```<code># mm2.properties
name=source->dest
clusters=source, dest

source.bootstrap.servers=localhost:9091
dest.bootstrap.servers=localhost:9092

source->dest.enabled=true

offset.storage.partitions=2
config.storage.replication.factor=1
status.storage.replication.factor=1
</code>```

Seeing the below on MM2 startup:

```<code>[2020-02-16 07:31:07,547] INFO MirrorConnectorConfig values:
    admin.timeout.ms = 60000
    checkpoints.topic.replication.factor = 3
    config.action.reload = restart
    config.properties.blacklist = [follower\.replication\.throttled\.replicas, leader\.replication\.throttled\.replicas, message\.timestamp\.difference\.max\.ms, message\.timestamp\.type, unclean\.leader\.election\.enable, min\.insync\.replicas]
    config.property.filter.class = class org.apache.kafka.connect.mirror.DefaultConfigPropertyFilter
    connector.class = org.apache.kafka.connect.mirror.MirrorCheckpointConnector
    consumer.poll.timeout.ms = 1000
    emit.checkpoints.enabled = true
    emit.checkpoints.interval.seconds = 60
    emit.heartbeats.enabled = true
    emit.heartbeats.interval.seconds = 1
    enabled = true
    errors.log.enable = false
    errors.log.include.messages = false
    errors.retry.delay.max.ms = 60000
    errors.retry.timeout = 0
    errors.tolerance = none
    group.filter.class = class org.apache.kafka.connect.mirror.DefaultGroupFilter
    groups = [.*]
    groups.blacklist = [console-consumer-.*, connect-.*, __.*]
    header.converter = null
    heartbeats.topic.replication.factor = 3
    key.converter = null
    metric.reporters = null
    name = source->dest
    offset-syncs.topic.replication.factor = 3
    offset.lag.max = 100
    refresh.groups.enabled = true
    refresh.groups.interval.seconds = 600
    refresh.topics.enabled = true
    refresh.topics.interval.seconds = 600
    replication.factor = 2
    replication.policy.class = class org.apache.kafka.connect.mirror.DefaultReplicationPolicy
    replication.policy.separator = .
    sasl.client.callback.handler.class = null
    sasl.jaas.config = null
    sasl.kerberos.kinit.cmd = /usr/bin/kinit
    sasl.kerberos.min.time.before.relogin = 60000
    sasl.kerberos.service.name = null
    sasl.kerberos.ticket.renew.jitter = 0.05
    sasl.kerberos.ticket.renew.window.factor = 0.8
    sasl.login.callback.handler.class = null
    sasl.login.class = null
    sasl.login.refresh.buffer.seconds = 300
    sasl.login.refresh.min.period.seconds = 60
    sasl.login.refresh.window.factor = 0.8
    sasl.login.refresh.window.jitter = 0.05
    sasl.mechanism = GSSAPI
    security.protocol = PLAINTEXT
    source.cluster.alias = source
    ssl.cipher.suites = null
    ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
    ssl.endpoint.identification.algorithm = https
    ssl.key.password = null
    ssl.keymanager.algorithm = SunX509
    ssl.keystore.location = null
    ssl.keystore.password = null
    ssl.keystore.type = JKS
    ssl.protocol = TLS
    ssl.provider = null
    ssl.secure.random.implementation = null
    ssl.trustmanager.algorithm = PKIX
    ssl.truststore.location = null
    ssl.truststore.password = null
    ssl.truststore.type = JKS
    sync.topic.acls.enabled = true
    sync.topic.acls.interval.seconds = 600
    sync.topic.configs.enabled = true
    sync.topic.configs.interval.seconds = 600
    target.cluster.alias = dest
    task.assigned.groups = null
    task.assigned.partitions = null
    tasks.max = 1
    topic.filter.class = class org.apache.kafka.connect.mirror.DefaultTopicFilter
    topics = [.*]
    topics.blacklist = [.*[\-\.]internal, .*\.replica, __.*]
    transforms = []
    value.converter = null
 (org.apache.kafka.connect.mirror.MirrorConnectorConfig:347)
</code>```

My data is being replicated as expected. Source topic gets created in the destination cluster as source.<TOPIC>. But, the consumer group offset is not being replicated.

Started a consumer group in the source cluster.

```<code>./kafka-console-consumer.sh --bootstrap-server localhost:9091 --topic test-1 --group test-1-group
</code>```

Consumed few messages and stopped it. Posted new messages in this topic and mirror maker also mirrored the data to the target cluster.

I tried to consume message from the target cluster as follows.

```<code>./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic source.test-1 --group test-1-group
</code>```

Since, I use the same consumer group, I was expecting my offset also to be synced and won't consume the same message which I consumed in the cluster1. But, still consume all the messages. Is there anything I am missing here?

答:
there are several fundamental reasons why replicating offsets is non-trivial:

kafka is an at-least-once system (ignoring the hype). this means that mirror maker, because its built on top of kafka consumers and producers that can each timeout/disconnect, will result in some degree of duplicate records being delivered to the destination. this means that offsets dont map 1:1 between source and destination. even if you were to try and use the "exactly once" support (which the MM2 KIP clearly says its not using) all it would do is skip over partially-delivered batches, but those batches would still occupy offsets at the destination

if you setup mirroring long after the source topic has started expiring records, your destination topic will start at offset 0 while the source will have much higher "oldest" offsets. there has been an attempt to address this (see KIP-391) but it was never accepted

in general there's no guarantee that your mirroring topology mirrors from a single source to a single destination. the linkedin topology, for example, mirrors from multiple source clusters into "aggregate" tier clusters. mapping offsets is meaningless for such topologies

looking at the MM2 KIP there's an "offset sync topic" mentioned.
in your code you can use class RemoteClusterUtils to translate checkpoints between clusters:

```<code>Map<TopicPartition, Long> newOffsets = RemoteClusterUtils.translateOffsets(
   newClusterProperties, oldClusterName, consumerGroupId
);
consumer.seek(newOffsets);
</code>```

this was taken out of the following presentation - https://www.slideshare.net/ConfluentInc/disaster-recovery-with-mirrormaker-20-ryanne-dolan-cloudera-kafka-summit-london-2019

alternatively, you could use the seek by timespamp API to start your consumer group on the destination to the rough time at which data was delivered to the destination (or delivered to source, if the broker settings for log append timestamps on the destination dont overwrite those times). you'd need to rewind a little for safety.

Body:
I have setup MirrorMaker2 for replicating data between 2 DCs.

My mm2.properties:

# mm2.properties
name=source->dest
clusters=source, dest

source.bootstrap.servers=localhost:9091
dest.bootstrap.servers=localhost:9092

source->dest.enabled=true

offset.storage.partitions=2
config.storage.replication.factor=1
status.storage.replication.factor=1

Seeing the below on MM2 startup:

[2020-02-16 07:31:07,547] INFO MirrorConnectorConfig values:
    admin.timeout.ms = 60000
    checkpoints.topic.replication.factor = 3
    config.action.reload = restart
    config.properties.blacklist = [follower\.replication\.throttled\.replicas, leader\.replication\.throttled\.replicas, message\.timestamp\.difference\.max\.ms, message\.timestamp\.type, unclean\.leader\.election\.enable, min\.insync\.replicas]
    config.property.filter.class = class org.apache.kafka.connect.mirror.DefaultConfigPropertyFilter
    connector.class = org.apache.kafka.connect.mirror.MirrorCheckpointConnector
    consumer.poll.timeout.ms = 1000
    emit.checkpoints.enabled = true
    emit.checkpoints.interval.seconds = 60
    emit.heartbeats.enabled = true
    emit.heartbeats.interval.seconds = 1
    enabled = true
    errors.log.enable = false
    errors.log.include.messages = false
    errors.retry.delay.max.ms = 60000
    errors.retry.timeout = 0
    errors.tolerance = none
    group.filter.class = class org.apache.kafka.connect.mirror.DefaultGroupFilter
    groups = [.*]
    groups.blacklist = [console-consumer-.*, connect-.*, __.*]
    header.converter = null
    heartbeats.topic.replication.factor = 3
    key.converter = null
    metric.reporters = null
    name = source->dest
    offset-syncs.topic.replication.factor = 3
    offset.lag.max = 100
    refresh.groups.enabled = true
    refresh.groups.interval.seconds = 600
    refresh.topics.enabled = true
    refresh.topics.interval.seconds = 600
    replication.factor = 2
    replication.policy.class = class org.apache.kafka.connect.mirror.DefaultReplicationPolicy
    replication.policy.separator = .
    sasl.client.callback.handler.class = null
    sasl.jaas.config = null
    sasl.kerberos.kinit.cmd = /usr/bin/kinit
    sasl.kerberos.min.time.before.relogin = 60000
    sasl.kerberos.service.name = null
    sasl.kerberos.ticket.renew.jitter = 0.05
    sasl.kerberos.ticket.renew.window.factor = 0.8
    sasl.login.callback.handler.class = null
    sasl.login.class = null
    sasl.login.refresh.buffer.seconds = 300
    sasl.login.refresh.min.period.seconds = 60
    sasl.login.refresh.window.factor = 0.8
    sasl.login.refresh.window.jitter = 0.05
    sasl.mechanism = GSSAPI
    security.protocol = PLAINTEXT
    source.cluster.alias = source
    ssl.cipher.suites = null
    ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
    ssl.endpoint.identification.algorithm = https
    ssl.key.password = null
    ssl.keymanager.algorithm = SunX509
    ssl.keystore.location = null
    ssl.keystore.password = null
    ssl.keystore.type = JKS
    ssl.protocol = TLS
    ssl.provider = null
    ssl.secure.random.implementation = null
    ssl.trustmanager.algorithm = PKIX
    ssl.truststore.location = null
    ssl.truststore.password = null
    ssl.truststore.type = JKS
    sync.topic.acls.enabled = true
    sync.topic.acls.interval.seconds = 600
    sync.topic.configs.enabled = true
    sync.topic.configs.interval.seconds = 600
    target.cluster.alias = dest
    task.assigned.groups = null
    task.assigned.partitions = null
    tasks.max = 1
    topic.filter.class = class org.apache.kafka.connect.mirror.DefaultTopicFilter
    topics = [.*]
    topics.blacklist = [.*[\-\.]internal, .*\.replica, __.*]
    transforms = []
    value.converter = null
 (org.apache.kafka.connect.mirror.MirrorConnectorConfig:347)

My data is being replicated as expected. Source topic gets created in the destination cluster as source.<TOPIC>. But, the consumer group offset is not being replicated.

Started a consumer group in the source cluster.

./kafka-console-consumer.sh --bootstrap-server localhost:9091 --topic test-1 --group test-1-group

Consumed few messages and stopped it. Posted new messages in this topic and mirror maker also mirrored the data to the target cluster.

I tried to consume message from the target cluster as follows.

./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic source.test-1 --group test-1-group

Since, I use the same consumer group, I was expecting my offset also to be synced and won't consume the same message which I consumed in the cluster1. But, still consume all the messages. Is there anything I am missing here?

Body:
there are several fundamental reasons why replicating offsets is non-trivial:

kafka is an at-least-once system (ignoring the hype). this means that mirror maker, because its built on top of kafka consumers and producers that can each timeout/disconnect, will result in some degree of duplicate records being delivered to the destination. this means that offsets dont map 1:1 between source and destination. even if you were to try and use the "exactly once" support (which the MM2 KIP clearly says its not using) all it would do is skip over partially-delivered batches, but those batches would still occupy offsets at the destination

if you setup mirroring long after the source topic has started expiring records, your destination topic will start at offset 0 while the source will have much higher "oldest" offsets. there has been an attempt to address this (see KIP-391) but it was never accepted

in general there's no guarantee that your mirroring topology mirrors from a single source to a single destination. the linkedin topology, for example, mirrors from multiple source clusters into "aggregate" tier clusters. mapping offsets is meaningless for such topologies

looking at the MM2 KIP there's an "offset sync topic" mentioned.
in your code you can use class RemoteClusterUtils to translate checkpoints between clusters:

Map<TopicPartition, Long> newOffsets = RemoteClusterUtils.translateOffsets(
   newClusterProperties, oldClusterName, consumerGroupId
);
consumer.seek(newOffsets);

this was taken out of the following presentation - https://www.slideshare.net/ConfluentInc/disaster-recovery-with-mirrormaker-20-ryanne-dolan-cloudera-kafka-summit-london-2019

alternatively, you could use the seek by timespamp API to start your consumer group on the destination to the rough time at which data was delivered to the destination (or delivered to source, if the broker settings for log append timestamps on the destination dont overwrite those times). you'd need to rewind a little for safety.


问:
Rendering HTML webpage with restful flask - Webpage not displaying properly
I am trying to render an HTML page on local host with restful flask api. The content of HTML page gets displayed as string with "" rather than the page.

```<code>class data(Resource):
    def get(self):
        #return "Welcome!"
        return render_template('index.html')

api.add_resource(data,'/')
</code>```

My index.html file contains the following content

```<code><!DOCTYPE html>
<html>
<body>
<h1>Welcome to the site!</h1>
</body>
</html>
</code>```

After running the code, on the webpage(http://localhost:5000/) I get the following content

```<code>"<!DOCTYPE html>\n<html>\n<body>\n<h1>Welcome to the Data Hosting Service</h1>\n</body>\n</html>"
</code>```

On the other hand,It is returning the text "Welcome!" normally. Can you help me ?

Update:
With the help from users, I have fixed this problem by changing the response type as follows,

```<code>from flask import Response, render_template
return Response(render_template('index.html'),mimetype='text/html')
</code>```

答:
You may need import make_repsone from flask to render your html with headers information.

```<code>from flask import make_response, render_template
headers = {'Content-Type': 'text/html'}
return make_response(render_template('index.html'),200,headers)
</code>```

Hope this could be helpful.

Body:
I am trying to render an HTML page on local host with restful flask api. The content of HTML page gets displayed as string with "" rather than the page.

class data(Resource):
    def get(self):
        #return "Welcome!"
        return render_template('index.html')

api.add_resource(data,'/')

My index.html file contains the following content

<!DOCTYPE html>

Welcome to the site!

After running the code, on the webpage(http://localhost:5000/) I get the following content

"<!DOCTYPE html>\n\n\n
Welcome to the Data Hosting Service
\n\n"

On the other hand,It is returning the text "Welcome!" normally. Can you help me ?

Update:
With the help from users, I have fixed this problem by changing the response type as follows,

from flask import Response, render_template
return Response(render_template('index.html'),mimetype='text/html')

Body:
You may need import make_repsone from flask to render your html with headers information.

from flask import make_response, render_template
headers = {'Content-Type': 'text/html'}
return make_response(render_template('index.html'),200,headers)

Hope this could be helpful.


问:
Why is the application not using my connection string?
Question.

Why is the application not using my connection string?

Used by:

Server - (LocalDB) \ MSSQLLocalDB;

Entity Framework (EF);

WPF Framework.

Goal.

Make the application work with the database NORTHWINDC.MDF.

Description.

 I am passing a connection string

сonnectionStringStart = @" Data Source = (localdb)\mssqllocaldb; Initial Catalog = NORTHWINDC.MDF; Integrated Security = True; MultipleActiveResultSets = True ";

into the constructor of the class

class ProductContext: DbContext.

 I am running the application.

 I get a connection string:
Data Source=(localdb)\mssqllocaldb;Initial Catalog=WpfAppFrm.ProductContext;Integrated Security=True;MultipleActiveResultSets=True

Result.

The application creates the database WpfAppFrm.ProductContext and each time it runs it works with the databaseWpfAppFrm.ProductContext.

Category.cs

```<code>//
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WpfAppFrm
{
    [Table("Categories")]
    public class Category
    {
        public Category()
        {
            // this.Products = new ObservableCollection<Product>();
        }

        public int CategoryId { get; set; }
        public string Name { get; set; }

        // public virtual ObservableCollection<Product> Products { get; private set; }

    }
}
</code>```

ProductContext.cs

```<code>using System.Data.Entity;

namespace WpfAppFrm
{
    public class ProductContext : DbContext
    {
        // public ProductContext() : base("DefaultConnection")
        public string ConnectionString_test { get; set; }
        public ProductContext(string сonnectionString)
        {
            this.ConnectionString_test = сonnectionString;
        }

        public DbSet<Category> Categories { get; set; }
        // public DbSet<Product> Products { get; set; }
    }
}
</code>```

MainWindow.xaml.cs

```<code>//
using System.ComponentModel;
using System.Data.Entity;

namespace WpfAppFrm
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static string сonnectionStringStart;
        private ProductContext _context;

        public MainWindow()
        {
            InitializeComponent();

            сonnectionStringStart = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=NORTHWINDC.MDF;Integrated Security=True;MultipleActiveResultSets=True";
            _context = new ProductContext(сonnectionStringStart);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Data.CollectionViewSource categoryViewSource =
                ((System.Windows.Data.CollectionViewSource)(this.FindResource("categoryViewSource")));

                _context.Categories.Load();

                BindingList<Category> _studBindList = _context.Categories.Local.ToBindingList();

                categoryViewSource.Source = _context.Categories.Local;

                AddEntity();
                // GetAll();
                string сonnectionStringStartDuplicate = сonnectionStringStart;
                string connectionStringResult1 = _context.Database.Connection.ConnectionString;
                string connectionStringResult2 = _context.ConnectionString_test;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void AddEntity()
        {
            Category category = new Category
            {
                Name = "Name_Category_4"
            };

            _context.Categories.Add(category);
            string connectionString_str = _context.Database.Connection.ConnectionString;
            _context.SaveChanges();
        }

        public void GetAll()
        {
            _context.Categories.Load();

            BindingList<Category> _studBindList = _context.Categories.Local.ToBindingList();
        }
    }
}
</code>```

Installing the Entity Framework

Database NORTHWINDC.MDF

Database WpfAppFrm.ProductContext

The result of debugging the application.

The result of the application.

Application tree.

答:
Instead of having property to store connection string like here

```<code>public string ConnectionString_test { get; set; }
public ProductContext(string сonnectionString)
{
    this.ConnectionString_test = сonnectionString;
}
</code>```

you need to pass connection string to the base constructor of DbContext, which actually uses it

```<code>public ProductContext(string сonnectionString) : base(connectionString)
{
}
</code>```

Body:
Question.

Why is the application not using my connection string?

Used by:

Server - (LocalDB) \ MSSQLLocalDB;

Entity Framework (EF);

WPF Framework.

Goal.

Make the application work with the database NORTHWINDC.MDF.

Description.

 I am passing a connection string

сonnectionStringStart = @" Data Source = (localdb)\mssqllocaldb; Initial Catalog = NORTHWINDC.MDF; Integrated Security = True; MultipleActiveResultSets = True ";

into the constructor of the class

class ProductContext: DbContext.

 I am running the application.

 I get a connection string:
Data Source=(localdb)\mssqllocaldb;Initial Catalog=WpfAppFrm.ProductContext;Integrated Security=True;MultipleActiveResultSets=True

Result.

The application creates the database WpfAppFrm.ProductContext and each time it runs it works with the databaseWpfAppFrm.ProductContext.

Category.cs

//
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WpfAppFrm
{
    [Table("Categories")]
    public class Category
    {
        public Category()
        {
            // this.Products = new ObservableCollection<Product>();
        }

        public int CategoryId { get; set; }
        public string Name { get; set; }

        // public virtual ObservableCollection<Product> Products { get; private set; }

    }
}

ProductContext.cs

using System.Data.Entity;

namespace WpfAppFrm
{
    public class ProductContext : DbContext
    {
        // public ProductContext() : base("DefaultConnection")
        public string ConnectionString_test { get; set; }
        public ProductContext(string сonnectionString)
        {
            this.ConnectionString_test = сonnectionString;
        }

        public DbSet<Category> Categories { get; set; }
        // public DbSet<Product> Products { get; set; }
    }
}

MainWindow.xaml.cs

//
using System.ComponentModel;
using System.Data.Entity;

namespace WpfAppFrm
{
    ///
    /// Логика взаимодействия для MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
        public static string сonnectionStringStart;
        private ProductContext _context;

        public MainWindow()
        {
            InitializeComponent();

            сonnectionStringStart = @"Data Source=(localdb)\mssqllocaldb;Initial Catalog=NORTHWINDC.MDF;Integrated Security=True;MultipleActiveResultSets=True";
            _context = new ProductContext(сonnectionStringStart);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Data.CollectionViewSource categoryViewSource =
                ((System.Windows.Data.CollectionViewSource)(this.FindResource("categoryViewSource")));

                _context.Categories.Load();

                BindingList<Category> _studBindList = _context.Categories.Local.ToBindingList();

                categoryViewSource.Source = _context.Categories.Local;

                AddEntity();
                // GetAll();
                string сonnectionStringStartDuplicate = сonnectionStringStart;
                string connectionStringResult1 = _context.Database.Connection.ConnectionString;
                string connectionStringResult2 = _context.ConnectionString_test;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public void AddEntity()
        {
            Category category = new Category
            {
                Name = "Name_Category_4"
            };

            _context.Categories.Add(category);
            string connectionString_str = _context.Database.Connection.ConnectionString;
            _context.SaveChanges();
        }

        public void GetAll()
        {
            _context.Categories.Load();

            BindingList<Category> _studBindList = _context.Categories.Local.ToBindingList();
        }
    }
}

Installing the Entity Framework

Database NORTHWINDC.MDF

Database WpfAppFrm.ProductContext

The result of debugging the application.

The result of the application.

Application tree.

Body:
Instead of having property to store connection string like here

public string ConnectionString_test { get; set; }
public ProductContext(string сonnectionString)
{
    this.ConnectionString_test = сonnectionString;
}

you need to pass connection string to the base constructor of DbContext, which actually uses it

public ProductContext(string сonnectionString) : base(connectionString)
{
}


问:
Why my Radio buttons are checked automatically? How can I send only one by default in Angular 9?
The problem I have now is that I have two radio-buttons, the thing I want is that when you click admin radio button you can see one form and when you click the user radio button you can see another form. Until now both are checked and I don't know why, only want one to be checked by default and that one will show one form at a time

Below I will post the code of the radios and the picture of them. I'm using angular-material.

Radio button's html

<mat-radio-group aria-label="Select an option" class="center">
    <mat-radio-button  (click)="radio_btn=true" >Admin</mat-radio-button>
    <mat-radio-button (click)="radio_btn=false">User</mat-radio-button>
  </mat-radio-group>

        <form class="example-form " [formGroup]="signupForm" (ngSubmit)="send(signupForm)">
          <mat-form-field class="example-full-width">
            <input matInput formControlName="email" placeholder="User" type="email">
          </mat-form-field>

Introduce an email

          <mat-form-field class="example-full-width">
            <input matInput formControlName="password" placeholder="Password" type="password">
          </mat-form-field>

Introduce the correctly password

          <button mat-raised-button [disabled]="signupForm.invalid" class="colour_button " type="submit">Register</button>
        </form>

```

<p><strong><em>TS file of the radio's</em></strong></p>

<pre class="lang-js prettyprint-override"><code>export class HomeComponent implements OnInit {
  radio_btn:boolean = true;
  ngOnInit(): void {
  }
}
</code>```

This is how they looks like

答:
Put this in your radio group:

```<code><mat-radio-group [(ngModel)]="radio_btn”
</code>```

Then have

```<code><mat-radio-button [value]=“true“
</code>```

And

```<code>    <mat-radio-button [value]=“false”
</code>```

Also remove the (click) handlers from the radio buttons.

To change the radio_btn value.

See Material radio example html.

Body:
The problem I have now is that I have two radio-buttons, the thing I want is that when you click admin radio button you can see one form and when you click the user radio button you can see another form. Until now both are checked and I don't know why, only want one to be checked by default and that one will show one form at a time

Below I will post the code of the radios and the picture of them. I'm using angular-material.

Radio button's html

<mat-radio-group aria-label="Select an option" class="center">
    <mat-radio-button  (click)="radio_btn=true" >Admin</mat-radio-button>
    <mat-radio-button (click)="radio_btn=false">User</mat-radio-button>
  </mat-radio-group>

        <form class="example-form " [formGroup]="signupForm" (ngSubmit)="send(signupForm)">
          <mat-form-field class="example-full-width">
            <input matInput formControlName="email" placeholder="User" type="email">
          </mat-form-field>

Introduce an email

          <mat-form-field class="example-full-width">
            <input matInput formControlName="password" placeholder="Password" type="password">
          </mat-form-field>

Introduce the correctly password

          <button mat-raised-button [disabled]="signupForm.invalid" class="colour_button " type="submit">Register</button>
        </form>

TS file of the radio's

export class HomeComponent implements OnInit {
  radio_btn:boolean = true;
  ngOnInit(): void {
  }
}

This is how they looks like

Body:
Put this in your radio group:

<mat-radio-group [(ngModel)]="radio_btn”

Then have

<mat-radio-button [value]=“true“

And

    <mat-radio-button [value]=“false”

Also remove the (click) handlers from the radio buttons.

To change the radio_btn value.

See Material radio example html.


问:
Value not assigning in for function
I am running a for function which dynamically creates elements based on an entered number. I have an event listener for when the div is clicked.

This is the function that I am using to make these buttons.

```<code>function createGame(value) {
  previousNo = value;
  for (i = 0; i < value; i++) {
    gameCircle = document.createElement("div");
    gameCircle.className = 'gameCircle';
    gameCircle.id = "circle" + i;
    gameCircle.onclick = function() {
      checkGame(i);
    };
    document.getElementById("circleGame").appendChild(gameCircle);
  }
}
</code>```

And this is the function I am calling.

```<code>function checkGame(j) {
  var nextNo = circleArr.shift();
  if (j == nextNo) {
    document.getElementById("circle" + i).style.backgroundColor = "#178a00";
  } else {
    console.log(j);
    getValueGame();
  }
}
</code>```

Everytime the function runs, it returns six. Additionally, checking the onclick listener assigned says it runs this function.

```<code>function () {
  checkGame(i);
}
</code>```

Why does the function return six on every button, and why is the i value not being assigned to the function?

答:
document.getElementById("circle" + i).style.backgroundColor = "#178a00";

i is not defined inside your function i think use j instead  i

Title: Value not assigning in for function

Body:
I am running a for function which dynamically creates elements based on an entered number. I have an event listener for when the div is clicked.

This is the function that I am using to make these buttons.

function createGame(value) {
  previousNo = value;
  for (i = 0; i < value; i++) {
    gameCircle = document.createElement("div");
    gameCircle.className = 'gameCircle';
    gameCircle.id = "circle" + i;
    gameCircle.onclick = function() {
      checkGame(i);
    };
    document.getElementById("circleGame").appendChild(gameCircle);
  }
}

And this is the function I am calling.

function checkGame(j) {
  var nextNo = circleArr.shift();
  if (j == nextNo) {
    document.getElementById("circle" + i).style.backgroundColor = "#178a00";
  } else {
    console.log(j);
    getValueGame();
  }
}

Everytime the function runs, it returns six. Additionally, checking the onclick listener assigned says it runs this function.

function () {
  checkGame(i);
}

Why does the function return six on every button, and why is the i value not being assigned to the function?


问:
Evil code from the Python standard library
So, we have had this: The 1000% Speedup, or, the stdlib sucks. It demonstrates a rather bad bug that is probably costing the universe a load of cycles even as we speak. It's fixed now, which is great.

So what parts of the standard library have you noticed to be evil?

I would expect all the responsible people to match up an answer with a bug report (if suitable) and a patch (if superman).

答:
(since this is a different module, placing it in a different answer)

cgitb has some weird threading issues.  See this bug report.

OwnerDisplayName: Ali A

OwnerDisplayName: Jason Baker

ContentLicense: CC BY-SA 2.5


问:
php Array how to iterate
I am using a code-igniter query which returns the the array below with additional calculated [year_totalsales] added to array.

```<code>Array ( [0] => Array ( [year] => 2009 [month] => November [month_sales] => 524 [year_totalsales] => 3610 ) [1] => Array ( [year] => 2009 [month] => December [month_sales] => 521 [year_totalsales] => 3610 ) [2] => Array ( [year] => 2010 [month] => January [month_sales] => 609 [year_totalsales] => 3610 ) [3] => Array ( [year] => 2010 [month] => February [month_sales] => 619 [year_totalsales] => 3610 ) [4] => Array ( [year] => 2010 [month] => March [month_sales] => 732 [year_totalsales] => 3610 ) [5] => Array ( [year] => 2010 [month] => April [month_sales] => 605 [year_totalsales] => 3610 ) )
</code>```

Is there a way to get the output result to look this:

```<code>year-------------------------

month---------------monthsales
</code>```

答:
printf could be used quite well to accomplish this. PHP.net docs for sprintf has the details on what the formatting options are.

```<code>foreach ($month_data as $m) {
    printf("%d\n%20s $%.2lf\n", $m['year'], $m['month'], $m['month_sales']);
}
</code>```

If you wanted to only print unique years, as suggested in the comments, you could try this.

```<code>$current_year = null;
foreach ($month_data as $m) {
    if ($current_year != $m['year']) {
        printf("%d\n", $m['year']);
        $current_year = $m['year'];
    }
    printf("%20s $%.2lf\n", $m['month'], $m['month_sales']);
}
</code>```

Title: php Array how to iterate

Body:
I am using a code-igniter query which returns the the array below with additional calculated [year_totalsales] added to array.

Array ( [0] => Array ( [year] => 2009 [month] => November [month_sales] => 524 [year_totalsales] => 3610 ) [1] => Array ( [year] => 2009 [month] => December [month_sales] => 521 [year_totalsales] => 3610 ) [2] => Array ( [year] => 2010 [month] => January [month_sales] => 609 [year_totalsales] => 3610 ) [3] => Array ( [year] => 2010 [month] => February [month_sales] => 619 [year_totalsales] => 3610 ) [4] => Array ( [year] => 2010 [month] => March [month_sales] => 732 [year_totalsales] => 3610 ) [5] => Array ( [year] => 2010 [month] => April [month_sales] => 605 [year_totalsales] => 3610 ) )

Is there a way to get the output result to look this:

year-------------------------

month---------------monthsales

Body:
printf could be used quite well to accomplish this. PHP.net docs for sprintf has the details on what the formatting options are.

foreach ($month_data as $m) {
    printf("%d\n%20s $%.2lf\n", $m['year'], $m['month'], $m['month_sales']);
}

If you wanted to only print unique years, as suggested in the comments, you could try this.

$current_year = null;
foreach ($month_data as $m) {
    if ($current_year != $m['year']) {
        printf("%d\n", $m['year']);
        $current_year = $m['year'];
    }
    printf("%20s $%.2lf\n", $m['month'], $m['month_sales']);
}


问:
I am doing codewars challenge Replace With Alphabet Position, but i don't understand it
The  challenge says given a string, replace every letter with its position in the alphabet.

For 4 hours i couldn't find a solution. I tried regex(don't really understand how does it works yet). And i tried to find a solution, but i don't understand it fully

The code is this

```<code>function alphabetPosition(text) {
var result = "";
for (var i = 0; i < text.length; i++){
var code = text.toUpperCase().charCodeAt(i)
if (code > 64 && code < 91) {
result += (code - 64) + " "
};
}

return result.slice(0, result.length-1);
}
</code>```

I don't understand after var code = ......
Why doing this

```<code>if (code > 64 && code < 91) {
result += (code - 64) + " "
};
</code>```

答:
```<code>for (var i = 0; i < text.length; i++)
</code>```

This simply loops over every letter in the text parameter.

```<code>var code = text.toUpperCase().charCodeAt(i)
</code>```

This begins to define the letter's alphabet position. It basically says: "for every character in text, return its character code charCodeAt(i).

```<code>if (code > 64 && code < 91) {
result += (code - 64) + " "
};
</code>```

Just what the first comment says, the character codes for uppercase letters A thru Z start at 65 (A) and end at 90 (Z). Therefore, we only want the codes for letters A thru Z (e.g., we don't care about codes for spaces or quotation marks).
Since we want A to equal 1, we must subtract 64 from the character code
(65 - 64 = 1, likewise for B, 66 - 64 = 2, etc).

```<code>result += (code - 64) + " "
</code>```

This portion adds our filtered letter codes to the result and adds a space for readability. It does it for every character code filtered by the if statement.

```<code>return result.slice(0, result.length-1);
</code>```

Then, we simply return the entire string and subtract the unnecessary space at the end.

Note: you could also simply return result.trim() to remove the whitespace at the end.

Body:
The  challenge says given a string, replace every letter with its position in the alphabet.

For 4 hours i couldn't find a solution. I tried regex(don't really understand how does it works yet). And i tried to find a solution, but i don't understand it fully

The code is this

function alphabetPosition(text) {
var result = "";
for (var i = 0; i < text.length; i++){
var code = text.toUpperCase().charCodeAt(i)
if (code > 64 && code < 91) {
result += (code - 64) + " "
};
}

return result.slice(0, result.length-1);
}

I don't understand after var code = ......
Why doing this

if (code > 64 && code < 91) {
result += (code - 64) + " "
};

Body:
for (var i = 0; i < text.length; i++)

This simply loops over every letter in the text parameter.

var code = text.toUpperCase().charCodeAt(i)

This begins to define the letter's alphabet position. It basically says: "for every character in text, return its character code charCodeAt(i).

if (code > 64 && code < 91) {
result += (code - 64) + " "
};

Just what the first comment says, the character codes for uppercase letters A thru Z start at 65 (A) and end at 90 (Z). Therefore, we only want the codes for letters A thru Z (e.g., we don't care about codes for spaces or quotation marks).
Since we want A to equal 1, we must subtract 64 from the character code
(65 - 64 = 1, likewise for B, 66 - 64 = 2, etc).

result += (code - 64) + " "

This portion adds our filtered letter codes to the result and adds a space for readability. It does it for every character code filtered by the if statement.

return result.slice(0, result.length-1);

Then, we simply return the entire string and subtract the unnecessary space at the end.

Note: you could also simply return result.trim() to remove the whitespace at the end.