问:
Flexdashboard checkboxGroupInput losing ggplot data
I have an issue that is related to this one, but was unable to come to a solution for mine.

I have a reactive ggplot that I would like to update using a check box based on group data.

Currently, when I have ONE box selected, the data displays correctly. If I select more than one check box, I lose data points. See pictures below. I think I have to change the way I'm filtering my data and use droplevels somewhere but not sure how to integrate that (I'm new to shiny!). Any suggestions are appreciated!

```<code>WHOC_Sum_CMJ <- structure(list(Athlete = structure(c(1L, 1L, 1L, 7L, 7L, 7L,
7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 11L,
11L, 11L, 11L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 14L, 14L,
14L, 14L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L), .Label = c("Athlete 1", "Athlete 10",
"Athlete 11", "Athlete 12", "Athlete 13", "Athlete 14", "Athlete 2",
"Athlete 3", "Athlete 4", "Athlete 5", "Athlete 6", "Athlete 7",
"Athlete 8", "Athlete 9"), class = "factor"), Date = structure(c(1L,
4L, 5L, 1L, 3L, 5L, 7L, 2L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L,
5L, 7L, 1L, 3L, 6L, 7L, 2L, 4L, 5L, 8L, 1L, 3L, 5L, 7L, 1L, 3L,
5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L,
6L, 7L, 1L, 3L, 5L, 7L), .Label = c("2020-01-06", "2020-01-07",
"2020-01-13", "2020-01-14", "2020-01-21", "2020-01-23", "2020-01-27",
"2020-01-28"), class = "factor"), Position = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L), .Label = c("DEF", "FWD", "GOALIE"), class = "factor"),
    Program = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L,
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L,
    4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L), .Label = c("Navy", "Red", "RTP", "White"), class = "factor"),
    mRSI = c(0.36, 0.38, 0.42, 0.46, 0.46, 0.47, 0.48, 0.31,
    0.3, 0.24, 0.3, 0.29, 0.26, 0.28, 0.28, 0.36, 0.35, 0.43,
    0.43, 0.28, 0.31, 0.28, 0.3, 0.33, 0.36, 0.35, 0.37, 0.37,
    0.36, 0.37, 0.36, 0.3, 0.36, 0.34, 0.37, 0.26, 0.28, 0.34,
    0.3, 0.39, 0.4, 0.43, 0.43, 0.43, 0.47, 0.46, 0.48, 0.34,
    0.36, 0.33, 0.37, 0.28, 0.28, 0.34, 0.33), SystemWeight = c(617.21,
    612.4, 620.45, 672.08, 682.23, 670.5, 663.41, 517.33, 515.23,
    511.62, 517.85, 697.55, 703.92, 689.43, 691.33, 859.06, 845.9,
    850.97, 851.84, 655.79, 665.09, 673.91, 667.92, 626.78, 632.92,
    634.52, 624.88, 637.55, 645.6, 648.78, 646.64, 558.03, 563.23,
    569.58, 560.95, 693.63, 695.54, 684.37, 684.58, 641.18, 660.8,
    663.95, 660, 594.92, 596.97, 591.36, 585.64, 522.35, 518.17,
    530.95, 523.5, 780.65, 789.81, 775.84, 775.48), FTCT = c(0.61,
    0.62, 0.67, 0.74, 0.75, 0.77, 0.77, 0.54, 0.55, 0.44, 0.53,
    0.53, 0.49, 0.53, 0.56, 0.6, 0.58, 0.68, 0.68, 0.53, 0.57,
    0.54, 0.55, 0.61, 0.63, 0.64, 0.65, 0.59, 0.58, 0.59, 0.59,
    0.51, 0.59, 0.59, 0.59, 0.53, 0.57, 0.63, 0.59, 0.76, 0.76,
    0.79, 0.78, 0.67, 0.72, 0.72, 0.74, 0.63, 0.65, 0.61, 0.63,
    0.49, 0.5, 0.53, 0.57), JumpHeight_cm = c(28.97, 29.78, 31.43,
    35.83, 35.41, 36.59, 36.92, 27.56, 26.11, 26.15, 26.82, 26.15,
    25.08, 24.98, 24.62, 29.39, 30.17, 32.42, 32.56, 26.6, 27.25,
    25.58, 27.88, 29.17, 31.58, 28.48, 31.24, 33.73, 32.78, 33.09,
    33.43, 29.73, 31.91, 30.65, 32.98, 24.15, 24.24, 27.57, 25.44,
    26.68, 26.39, 27.43, 28.87, 35.44, 36.29, 35.71, 36.06, 26.79,
    27.76, 26.82, 29.71, 28.69, 26.9, 31.12, 29.77), EJH = c(17.6,
    18.58, 21.11, 26.66, 26.69, 28.08, 28.38, 14.99, 14.39, 11.41,
    14.33, 13.8, 12.34, 13.29, 13.67, 17.58, 17.5, 22.03, 22.19,
    14.03, 15.59, 13.92, 15.39, 17.7, 19.75, 18.37, 20.3, 19.99,
    18.9, 19.62, 19.61, 15.09, 18.8, 18.18, 19.6, 12.78, 13.87,
    17.28, 15.06, 20.44, 20.12, 21.74, 22.52, 23.8, 26.25, 25.68,
    26.73, 16.99, 18.13, 16.42, 18.82, 14.09, 13.43, 16.61, 16.9
    ), Weight = c(62.94, 62.45, 63.27, 68.54, 69.57, 68.38, 67.65,
    52.76, 52.54, 52.17, 52.81, 71.13, 71.78, 70.31, 70.5, 87.61,
    86.26, 86.78, 86.87, 66.88, 67.82, 68.72, 68.11, 63.92, 64.54,
    64.71, 63.72, 65.02, 65.84, 66.16, 65.94, 56.91, 57.44, 58.09,
    57.2, 70.74, 70.93, 69.79, 69.81, 65.39, 67.39, 67.71, 67.31,
    60.67, 60.88, 60.31, 59.72, 53.27, 52.84, 54.15, 53.39, 79.61,
    80.54, 79.12, 79.08)), class = "data.frame", row.names = c(NA,
-55L))

</code>```
```<code>```
checkboxGroupInput("Program", label = "Program", choices = unique(WHOC_Sum_CMJ$Program), selected = "Red", inline = TRUE)
# (Note: for the code I cut out some of the styling to make it more readable. That's why it looks different than the pictures).
```

```
renderPlot({
  f <- WHOC_Sum_CMJ %>%
  select(Date, Athlete, JumpHeight_cm, Program)%>%
  filter(Program == input$Program)

p <- ggplot(f)+
  geom_line(aes(x=Date, y=JumpHeight_cm, colour = Athlete))+
  geom_point(aes(x=Date, y=JumpHeight_cm, colour = Athlete))+
  theme_bw() +
  labs(title = "Team Jump Height",
       x = "Date",
       y = "Jump Height (cm)")+
  scale_x_date(limits = c(min = min(WHOC_Sum_CMJ$Date), max = max(WHOC_Sum_CMJ$Date)), labels = date_format("%m/%d"),
               date_breaks = "2 weeks", expand = c(.08,0))+
  guides(col = guide_legend(nrow = 3))+
  geom_text_repel(data= subset(f, Date == min(Date)), aes(x=Date, y=JumpHeight_cm,label = unique(Athlete)),
                  force        = .1,
                  nudge_x      = -2,
                  direction    = "y",
                  hjust        = 1,
                  )
p
    })
```

Body:
I have an issue that is related to this one, but was unable to come to a solution for mine.

I have a reactive ggplot that I would like to update using a check box based on group data.

Currently, when I have ONE box selected, the data displays correctly. If I select more than one check box, I lose data points. See pictures below. I think I have to change the way I'm filtering my data and use droplevels somewhere but not sure how to integrate that (I'm new to shiny!). Any suggestions are appreciated!

WHOC_Sum_CMJ <- structure(list(Athlete = structure(c(1L, 1L, 1L, 7L, 7L, 7L,
7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 11L,
11L, 11L, 11L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 14L, 14L,
14L, 14L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L), .Label = c("Athlete 1", "Athlete 10",
"Athlete 11", "Athlete 12", "Athlete 13", "Athlete 14", "Athlete 2",
"Athlete 3", "Athlete 4", "Athlete 5", "Athlete 6", "Athlete 7",
"Athlete 8", "Athlete 9"), class = "factor"), Date = structure(c(1L,
4L, 5L, 1L, 3L, 5L, 7L, 2L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L,
5L, 7L, 1L, 3L, 6L, 7L, 2L, 4L, 5L, 8L, 1L, 3L, 5L, 7L, 1L, 3L,
5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L,
6L, 7L, 1L, 3L, 5L, 7L), .Label = c("2020-01-06", "2020-01-07",
"2020-01-13", "2020-01-14", "2020-01-21", "2020-01-23", "2020-01-27",
"2020-01-28"), class = "factor"), Position = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L), .Label = c("DEF", "FWD", "GOALIE"), class = "factor"),
    Program = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L,
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L,
    4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L), .Label = c("Navy", "Red", "RTP", "White"), class = "factor"),
    mRSI = c(0.36, 0.38, 0.42, 0.46, 0.46, 0.47, 0.48, 0.31,
    0.3, 0.24, 0.3, 0.29, 0.26, 0.28, 0.28, 0.36, 0.35, 0.43,
    0.43, 0.28, 0.31, 0.28, 0.3, 0.33, 0.36, 0.35, 0.37, 0.37,
    0.36, 0.37, 0.36, 0.3, 0.36, 0.34, 0.37, 0.26, 0.28, 0.34,
    0.3, 0.39, 0.4, 0.43, 0.43, 0.43, 0.47, 0.46, 0.48, 0.34,
    0.36, 0.33, 0.37, 0.28, 0.28, 0.34, 0.33), SystemWeight = c(617.21,
    612.4, 620.45, 672.08, 682.23, 670.5, 663.41, 517.33, 515.23,
    511.62, 517.85, 697.55, 703.92, 689.43, 691.33, 859.06, 845.9,
    850.97, 851.84, 655.79, 665.09, 673.91, 667.92, 626.78, 632.92,
    634.52, 624.88, 637.55, 645.6, 648.78, 646.64, 558.03, 563.23,
    569.58, 560.95, 693.63, 695.54, 684.37, 684.58, 641.18, 660.8,
    663.95, 660, 594.92, 596.97, 591.36, 585.64, 522.35, 518.17,
    530.95, 523.5, 780.65, 789.81, 775.84, 775.48), FTCT = c(0.61,
    0.62, 0.67, 0.74, 0.75, 0.77, 0.77, 0.54, 0.55, 0.44, 0.53,
    0.53, 0.49, 0.53, 0.56, 0.6, 0.58, 0.68, 0.68, 0.53, 0.57,
    0.54, 0.55, 0.61, 0.63, 0.64, 0.65, 0.59, 0.58, 0.59, 0.59,
    0.51, 0.59, 0.59, 0.59, 0.53, 0.57, 0.63, 0.59, 0.76, 0.76,
    0.79, 0.78, 0.67, 0.72, 0.72, 0.74, 0.63, 0.65, 0.61, 0.63,
    0.49, 0.5, 0.53, 0.57), JumpHeight_cm = c(28.97, 29.78, 31.43,
    35.83, 35.41, 36.59, 36.92, 27.56, 26.11, 26.15, 26.82, 26.15,
    25.08, 24.98, 24.62, 29.39, 30.17, 32.42, 32.56, 26.6, 27.25,
    25.58, 27.88, 29.17, 31.58, 28.48, 31.24, 33.73, 32.78, 33.09,
    33.43, 29.73, 31.91, 30.65, 32.98, 24.15, 24.24, 27.57, 25.44,
    26.68, 26.39, 27.43, 28.87, 35.44, 36.29, 35.71, 36.06, 26.79,
    27.76, 26.82, 29.71, 28.69, 26.9, 31.12, 29.77), EJH = c(17.6,
    18.58, 21.11, 26.66, 26.69, 28.08, 28.38, 14.99, 14.39, 11.41,
    14.33, 13.8, 12.34, 13.29, 13.67, 17.58, 17.5, 22.03, 22.19,
    14.03, 15.59, 13.92, 15.39, 17.7, 19.75, 18.37, 20.3, 19.99,
    18.9, 19.62, 19.61, 15.09, 18.8, 18.18, 19.6, 12.78, 13.87,
    17.28, 15.06, 20.44, 20.12, 21.74, 22.52, 23.8, 26.25, 25.68,
    26.73, 16.99, 18.13, 16.42, 18.82, 14.09, 13.43, 16.61, 16.9
    ), Weight = c(62.94, 62.45, 63.27, 68.54, 69.57, 68.38, 67.65,
    52.76, 52.54, 52.17, 52.81, 71.13, 71.78, 70.31, 70.5, 87.61,
    86.26, 86.78, 86.87, 66.88, 67.82, 68.72, 68.11, 63.92, 64.54,
    64.71, 63.72, 65.02, 65.84, 66.16, 65.94, 56.91, 57.44, 58.09,
    57.2, 70.74, 70.93, 69.79, 69.81, 65.39, 67.39, 67.71, 67.31,
    60.67, 60.88, 60.31, 59.72, 53.27, 52.84, 54.15, 53.39, 79.61,
    80.54, 79.12, 79.08)), class = "data.frame", row.names = c(NA,
-55L))

```
checkboxGroupInput("Program", label = "Program", choices = unique(WHOC_Sum_CMJ$Program), selected = "Red", inline = TRUE)
# (Note: for the code I cut out some of the styling to make it more readable. That's why it looks different than the pictures).
```

```
renderPlot({
  f <- WHOC_Sum_CMJ %>%
  select(Date, Athlete, JumpHeight_cm, Program)%>%
  filter(Program == input$Program)

p <- ggplot(f)+
  geom_line(aes(x=Date, y=JumpHeight_cm, colour = Athlete))+
  geom_point(aes(x=Date, y=JumpHeight_cm, colour = Athlete))+
  theme_bw() +
  labs(title = "Team Jump Height",
       x = "Date",
       y = "Jump Height (cm)")+
  scale_x_date(limits = c(min = min(WHOC_Sum_CMJ$Date), max = max(WHOC_Sum_CMJ$Date)), labels = date_format("%m/%d"),
               date_breaks = "2 weeks", expand = c(.08,0))+
  guides(col = guide_legend(nrow = 3))+
  geom_text_repel(data= subset(f, Date == min(Date)), aes(x=Date, y=JumpHeight_cm,label = unique(Athlete)),
                  force        = .1,
                  nudge_x      = -2,
                  direction    = "y",
                  hjust        = 1,
                  )
p
    })

Body:
The issue in your code indeed is based on the filter call. You'll need to use %in%instead of ==, when filtering a vector of statements. Please see the following:

---
title: "Test"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{r global, include=FALSE}
library(ggplot2)
library(dplyr)
library(scales)
library(ggrepel)

WHOC_Sum_CMJ <- structure(list(Athlete = structure(c(1L, 1L, 1L, 7L, 7L, 7L,
7L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 11L,
11L, 11L, 11L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 14L, 14L,
14L, 14L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L), .Label = c("Athlete 1", "Athlete 10",
"Athlete 11", "Athlete 12", "Athlete 13", "Athlete 14", "Athlete 2",
"Athlete 3", "Athlete 4", "Athlete 5", "Athlete 6", "Athlete 7",
"Athlete 8", "Athlete 9"), class = "factor"), Date = structure(c(1L,
4L, 5L, 1L, 3L, 5L, 7L, 2L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L,
5L, 7L, 1L, 3L, 6L, 7L, 2L, 4L, 5L, 8L, 1L, 3L, 5L, 7L, 1L, 3L,
5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L, 5L, 7L, 1L, 3L,
6L, 7L, 1L, 3L, 5L, 7L), .Label = c("2020-01-06", "2020-01-07",
"2020-01-13", "2020-01-14", "2020-01-21", "2020-01-23", "2020-01-27",
"2020-01-28"), class = "factor"), Position = structure(c(2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L), .Label = c("DEF", "FWD", "GOALIE"), class = "factor"),
    Program = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 1L, 1L, 1L, 1L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L,
    1L, 1L, 1L, 2L, 2L, 2L, 2L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L,
    4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L), .Label = c("Navy", "Red", "RTP", "White"), class = "factor"),
    mRSI = c(0.36, 0.38, 0.42, 0.46, 0.46, 0.47, 0.48, 0.31,
    0.3, 0.24, 0.3, 0.29, 0.26, 0.28, 0.28, 0.36, 0.35, 0.43,
    0.43, 0.28, 0.31, 0.28, 0.3, 0.33, 0.36, 0.35, 0.37, 0.37,
    0.36, 0.37, 0.36, 0.3, 0.36, 0.34, 0.37, 0.26, 0.28, 0.34,
    0.3, 0.39, 0.4, 0.43, 0.43, 0.43, 0.47, 0.46, 0.48, 0.34,
    0.36, 0.33, 0.37, 0.28, 0.28, 0.34, 0.33), SystemWeight = c(617.21,
    612.4, 620.45, 672.08, 682.23, 670.5, 663.41, 517.33, 515.23,
    511.62, 517.85, 697.55, 703.92, 689.43, 691.33, 859.06, 845.9,
    850.97, 851.84, 655.79, 665.09, 673.91, 667.92, 626.78, 632.92,
    634.52, 624.88, 637.55, 645.6, 648.78, 646.64, 558.03, 563.23,
    569.58, 560.95, 693.63, 695.54, 684.37, 684.58, 641.18, 660.8,
    663.95, 660, 594.92, 596.97, 591.36, 585.64, 522.35, 518.17,
    530.95, 523.5, 780.65, 789.81, 775.84, 775.48), FTCT = c(0.61,
    0.62, 0.67, 0.74, 0.75, 0.77, 0.77, 0.54, 0.55, 0.44, 0.53,
    0.53, 0.49, 0.53, 0.56, 0.6, 0.58, 0.68, 0.68, 0.53, 0.57,
    0.54, 0.55, 0.61, 0.63, 0.64, 0.65, 0.59, 0.58, 0.59, 0.59,
    0.51, 0.59, 0.59, 0.59, 0.53, 0.57, 0.63, 0.59, 0.76, 0.76,
    0.79, 0.78, 0.67, 0.72, 0.72, 0.74, 0.63, 0.65, 0.61, 0.63,
    0.49, 0.5, 0.53, 0.57), JumpHeight_cm = c(28.97, 29.78, 31.43,
    35.83, 35.41, 36.59, 36.92, 27.56, 26.11, 26.15, 26.82, 26.15,
    25.08, 24.98, 24.62, 29.39, 30.17, 32.42, 32.56, 26.6, 27.25,
    25.58, 27.88, 29.17, 31.58, 28.48, 31.24, 33.73, 32.78, 33.09,
    33.43, 29.73, 31.91, 30.65, 32.98, 24.15, 24.24, 27.57, 25.44,
    26.68, 26.39, 27.43, 28.87, 35.44, 36.29, 35.71, 36.06, 26.79,
    27.76, 26.82, 29.71, 28.69, 26.9, 31.12, 29.77), EJH = c(17.6,
    18.58, 21.11, 26.66, 26.69, 28.08, 28.38, 14.99, 14.39, 11.41,
    14.33, 13.8, 12.34, 13.29, 13.67, 17.58, 17.5, 22.03, 22.19,
    14.03, 15.59, 13.92, 15.39, 17.7, 19.75, 18.37, 20.3, 19.99,
    18.9, 19.62, 19.61, 15.09, 18.8, 18.18, 19.6, 12.78, 13.87,
    17.28, 15.06, 20.44, 20.12, 21.74, 22.52, 23.8, 26.25, 25.68,
    26.73, 16.99, 18.13, 16.42, 18.82, 14.09, 13.43, 16.61, 16.9
    ), Weight = c(62.94, 62.45, 63.27, 68.54, 69.57, 68.38, 67.65,
    52.76, 52.54, 52.17, 52.81, 71.13, 71.78, 70.31, 70.5, 87.61,
    86.26, 86.78, 86.87, 66.88, 67.82, 68.72, 68.11, 63.92, 64.54,
    64.71, 63.72, 65.02, 65.84, 66.16, 65.94, 56.91, 57.44, 58.09,
    57.2, 70.74, 70.93, 69.79, 69.81, 65.39, 67.39, 67.71, 67.31,
    60.67, 60.88, 60.31, 59.72, 53.27, 52.84, 54.15, 53.39, 79.61,
    80.54, 79.12, 79.08)), class = "data.frame", row.names = c(NA,
-55L))

WHOC_Sum_CMJ$Date <- as.Date(WHOC_Sum_CMJ$Date)

```

Column {.sidebar}
-----------------------------------------------------------------------

```{r}
checkboxGroupInput("Program", label = "Program", choices = unique(WHOC_Sum_CMJ$Program), selected = "Red", inline = TRUE)
# (Note: for the code I cut out some of the styling to make it more readable. That's why it looks different than the pictures).
```

Column
-----------------------------------------------------------------------

```{r}
renderPlot({
  f <- WHOC_Sum_CMJ %>%
  dplyr::select(Date, Athlete, JumpHeight_cm, Program) %>%
  filter(Program %in% input$Program)

p <- ggplot(f) +
  geom_line(aes(x=Date, y=JumpHeight_cm, colour = Athlete)) +
  geom_point(aes(x=Date, y=JumpHeight_cm, colour = Athlete)) +
  theme_bw() +
  labs(title = "Team Jump Height",
       x = "Date",
       y = "Jump Height (cm)") +
  scale_x_date(limits = c(min = min(WHOC_Sum_CMJ$Date), max = max(WHOC_Sum_CMJ$Date)), labels = date_format("%m/%d"),
               date_breaks = "2 weeks", expand = c(.08,0)) +
  guides(col = guide_legend(nrow = 3)) +
  geom_text_repel(data= subset(f, Date == min(Date)), aes(x=Date, y=JumpHeight_cm,label = unique(Athlete)),
                  force        = .1,
                  nudge_x      = -2,
                  direction    = "y",
                  hjust        = 1,
                  )
p
    })
```


来源: stackexchange

问:
Floated buttons won't go beneath an inline edit popup
I have a table, and in the tbody I have an inline edit popup that is absolute positioned.

I have a table footer that has display inline-block that contains buttons that are floated to the left and right. It looks like:

```<code><div class="table-footer">
        <div class="new-row-button">
            <lightning-button variant="base" label="New Row" title="Add new row" icon-name="utility:add" onclick={addNewRow}></lightning-button>
        </div>

        <template if:true={changesWereMade}>
            <div class="save-cancel-wrapper">
                <lightning-button variant="brand" label="Ok" title="Make changes" onclick={handleSave}></lightning-button>
                <lightning-button label="Cancel" title="Discard changes" onclick={revertChanges} class="slds-m-left_xx-small"></lightning-button>
            </div>
        </template>
    </div>
</code>```

What happens is I end up with this:

Even though the drop down supposedly has a z-index of 9001. The inline editor is inside the tbody tag. I have tried to raise the z-index of the tbody element, the table element, the inline editor, no luck in getting it to go over those buttons. The only thing I got to work was make the table-footer relative positioned and assign a z-index of -1. But this makes my buttons unclickable as they are now 'below' the page.

Does anyone have any css advice on how to get these buttons underneath the inline editor? (The table element and table-footer div are at the same level in the element hierarchy)

答:
You can use the display flex css property for your footer to replace the float. Something like this :

footer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

footer .button {
  flex: 1;
}

footer .button:first-of-type {
  align-self:start;
}

footer .button:last-of-type {
  align-self:end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
  <button> Add me </button>
  <button> Delete me </button>
</footer></code>```

Hope to help you.

ContentLicense: CC BY-SA 4.0

Body:
I have a table, and in the tbody I have an inline edit popup that is absolute positioned.

I have a table footer that has display inline-block that contains buttons that are floated to the left and right. It looks like:

            <lightning-button variant="base" label="New Row" title="Add new row" icon-name="utility:add" onclick={addNewRow}></lightning-button>

        <template if:true={changesWereMade}>

                <lightning-button variant="brand" label="Ok" title="Make changes" onclick={handleSave}></lightning-button>
                <lightning-button label="Cancel" title="Discard changes" onclick={revertChanges} class="slds-m-left_xx-small"></lightning-button>

        </template>

What happens is I end up with this:

Even though the drop down supposedly has a z-index of 9001. The inline editor is inside the tbody tag. I have tried to raise the z-index of the tbody element, the table element, the inline editor, no luck in getting it to go over those buttons. The only thing I got to work was make the table-footer relative positioned and assign a z-index of -1. But this makes my buttons unclickable as they are now 'below' the page.

Does anyone have any css advice on how to get these buttons underneath the inline editor? (The table element and table-footer div are at the same level in the element hierarchy)

Body:
You can use the display flex css property for your footer to replace the float. Something like this :

footer {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

footer .button {
  flex: 1;
}

footer .button:first-of-type {
  align-self:start;
}

footer .button:last-of-type {
  align-self:end;
}

<footer>
  <button> Add me </button>
  <button> Delete me </button>
</footer>

Hope to help you.


问:
PowerShell Remove all users from a specific group
I'm trying to clean all users from Local Group test_group by executing the following command below on Windows 2008 R2 Standard, PowerShell 2.0.

```<code>Get-ADGroupMember "test_group" | ForEach-Object {Remove-ADGroupMember "test_group" $_ -Confirm:$false}
</code>```

It throws the following error, most probably because I'm using v2.0?:

The term 'Get-ADGroupMember' is not recognized as the name of a
  cmdlet, function, script file, or operable program. Che ck the
  spelling of the name, or if a path was included, verify that the path
  is correct and try again. At line:1 char:18 + Get-ADGroupMember <<<<
  "test_group" | ForEach-Object {Remove-ADGroupMember "test_group" $_
  -Confirm:$false} + CategoryInfo : ObjectNotFound: (Get-ADGroupMember:String) [], CommandNotFoundException +
  FullyQualifiedErrorId : CommandNotFoundException

I tried many ideas from this article and its comments, and I couldn't get any to work but I'm not a sysadmin and I'm not sure if I'm not missing something?:
http://blogs.technet.com/b/heyscriptingguy/archive/2009/07/28/hey-scripting-guy-how-do-i-remove-all-group-members-in-active-directory.aspx

Please help, I have around 300 groups to clean on Monday and I don't want to do it manually...

答:
Building on Zhenia Shapiro's answer:</p>

```<code>Get-ADGroup "test_group" | Set-ADGroup -Clear member
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to clean all users from Local Group test_group by executing the following command below on Windows 2008 R2 Standard, PowerShell 2.0.

Get-ADGroupMember "test_group" | ForEach-Object {Remove-ADGroupMember "test_group" $_ -Confirm:$false}

It throws the following error, most probably because I'm using v2.0?:

The term 'Get-ADGroupMember' is not recognized as the name of a
  cmdlet, function, script file, or operable program. Che ck the
  spelling of the name, or if a path was included, verify that the path
  is correct and try again. At line:1 char:18 + Get-ADGroupMember <<<<
  "test_group" | ForEach-Object {Remove-ADGroupMember "test_group" $_
  -Confirm:$false} + CategoryInfo : ObjectNotFound: (Get-ADGroupMember:String) [], CommandNotFoundException +
  FullyQualifiedErrorId : CommandNotFoundException

I tried many ideas from this article and its comments, and I couldn't get any to work but I'm not a sysadmin and I'm not sure if I'm not missing something?:
http://blogs.technet.com/b/heyscriptingguy/archive/2009/07/28/hey-scripting-guy-how-do-i-remove-all-group-members-in-active-directory.aspx

Please help, I have around 300 groups to clean on Monday and I don't want to do it manually...

Body:
Building on Zhenia Shapiro's answer:

Get-ADGroup "test_group" | Set-ADGroup -Clear member


问:
Multi-language build tools
I have a build process for a large enterprise system comprising several dozen separate EXEs and DLLs. These use multiple languages, C, C++, Fortran, Python, Awk and a couple more. The build scripts are 4DOS batch processes which evolved over 4 decades. They are large and unwieldy and need constant care and feeding.

I must keep the Visual Studio solution and project files as the basic compile/link entities. What's the best tool for wrapping these disparate languages all together. 4DOS is very old and cumbersome.

EDIT:

Thanks gang. I think I'll try SCONS first because it's Python. We have plenty of people well versed in Python to be able to update and maintain it. I'm 61 now and it's not going to be me supporting this in the long term. I don't like anything requiring JAVA or XML because those are not languages already in our product mix and we have enough in play.

Those blog posts were good. He concluded that SCONS was best but simply too slow for his purposes. I'm not looking for speed in nightly builds. It's got until 7 AM. I want readability and maintainability.

答: For example Apache Ant</p>

OwnerDisplayName: SumoRunner

ContentLicense: CC BY-SA 2.5

Title: Multi-language build tools

LastEditorDisplayName: SumoRunner

Body: For example Apache Ant


问:
Problems with Dispatcher.Invoke and thread access
I've trying to handle threads in C#, but i've occurred in a wierd exception I don't know how to resolve. I've got a method running by BackgroundWorker, in which there's this piece of code:

```<code>GridView gridView;
DataView dataView;

queryTable.GetViewAndDataView(out gridView, out dataView);

this.listView.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
    delegate() {
        listViewView = gridView;
        listView.ItemsSource = dataView;
    }
));
</code>```

GetViewAndDataView fills a gridView and dataView, while the delegate code sets the current listView. The using of Invoke is supposed not to raise exceptions, but when I try to run it, I obtain this: The calling thread cannot access this object because a different thread owns it.

Anyone knows of to handle such exception, or at least, how to disable the thread object owning?

答:
You need save this.listView.Dispatcher to some local variable before you run the parallel thread. In the thred you must use dispatcher from this variable.

However @Polity is right - you must create controls/elements on UI thread. In parallel threads you can create only non-UI objects.

Body:
I've trying to handle threads in C#, but i've occurred in a wierd exception I don't know how to resolve. I've got a method running by BackgroundWorker, in which there's this piece of code:

GridView gridView;
DataView dataView;

queryTable.GetViewAndDataView(out gridView, out dataView);

this.listView.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(
    delegate() {
        listViewView = gridView;
        listView.ItemsSource = dataView;
    }
));

GetViewAndDataView fills a gridView and dataView, while the delegate code sets the current listView. The using of Invoke is supposed not to raise exceptions, but when I try to run it, I obtain this: The calling thread cannot access this object because a different thread owns it.

Anyone knows of to handle such exception, or at least, how to disable the thread object owning?


问:
Authentication and Authorization with Django GraphQL JWT and Graphene Relay
I would like to ask how I can do authentication and query tags limited to a specific user (owner) using Graphen Relay and Django JWT.
Here is my Model:

```<code>class Tag(models.Model):
"""Tag to be used for a objective"""
name = models.CharField(max_length=255)
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    related_name='tag',
    on_delete=models.CASCADE,
)
</code>```

Here is my Schema code:

```<code>class TagNode(DjangoObjectType):
class Meta:
    model = Tag
    filter_fields = ['name']
    interfaces = (relay.Node,)
</code>```

Here is my Query:

```<code>class Query(graphene.ObjectType):
    tag = relay.Node.Field(TagNode)
    all_tags = DjangoFilterConnectionField(TagNode)

    def resolve_all_tags(self, info):

        # context will reference to the Django request
        print(info.context.user)
        if not info.context.user.is_authenticated:
            return Tag.objects.none()
        else:
            return Tag.objects.filter(user=info.context.user)
</code>```

Here is the document for Django JWT: https://github.com/flavors/django-graphql-jwt but I do not know how to get the user (already use info.context.user) but it does not work,
when I tried to add Authorization (JWT token) in the header or as an argument. It also does not work.

答:
Basically you are doing everything correctly and your user should be fetched successfully.
I've just checked and it works in my case, I use JWT like a cookie but it doesn't matter.

Had you authorized your user when tried to get tags?

Because regarding JWT you need to authorize your user and receive the JWT token. Only after that the real user will be presented in the request when you call the tags query. Otherwise the user will be anonymous.

Body:
I would like to ask how I can do authentication and query tags limited to a specific user (owner) using Graphen Relay and Django JWT.
Here is my Model:

class Tag(models.Model):
"""Tag to be used for a objective"""
name = models.CharField(max_length=255)
user = models.ForeignKey(
    settings.AUTH_USER_MODEL,
    related_name='tag',
    on_delete=models.CASCADE,
)

Here is my Schema code:

class TagNode(DjangoObjectType):
class Meta:
    model = Tag
    filter_fields = ['name']
    interfaces = (relay.Node,)

Here is my Query:

class Query(graphene.ObjectType):
    tag = relay.Node.Field(TagNode)
    all_tags = DjangoFilterConnectionField(TagNode)

    def resolve_all_tags(self, info):

        # context will reference to the Django request
        print(info.context.user)
        if not info.context.user.is_authenticated:
            return Tag.objects.none()
        else:
            return Tag.objects.filter(user=info.context.user)

Here is the document for Django JWT: https://github.com/flavors/django-graphql-jwt but I do not know how to get the user (already use info.context.user) but it does not work,
when I tried to add Authorization (JWT token) in the header or as an argument. It also does not work.


问:
NodeJs express save image object to file system
I have a nodeJs express endpoint with the following code:

```<code>var express = require('express');

const fileUpload = require('express-fileupload');

var router = express.Router()

router.post("/upload",fileUpload(),(req, res) => {
    console.log(req.files);
    res.send('Received!!!');
 });
</code>```

The upload function works well. But how can I save the file uploaded to the file system? The file is an png image as a JSON object in the req.files variable, which contains name(string) and data(buffer).

答:
Try this:

var express = require('express');

const fileUpload = require('express-fileupload');

var router = express.Router()

router.post("/upload",fileUpload(),(req, res) => {
    let sampleFile = req.files.fileName;

  // Use the mv() method to place the file somewhere on your server
    sampleFile.mv('./'+sampleFile.name, function(err) {
        if (err)
            return res.status(500).send(err);

        res.send('Received!!!');
    });
 });```

Hope this help you

Body:
I have a nodeJs express endpoint with the following code:

var express = require('express');

const fileUpload = require('express-fileupload');

var router = express.Router()

router.post("/upload",fileUpload(),(req, res) => {
    console.log(req.files);
    res.send('Received!!!');
 });

The upload function works well. But how can I save the file uploaded to the file system? The file is an png image as a JSON object in the req.files variable, which contains name(string) and data(buffer).

Body:
Try this:

var express = require('express');

const fileUpload = require('express-fileupload');

var router = express.Router()

router.post("/upload",fileUpload(),(req, res) => {
    let sampleFile = req.files.fileName;

  // Use the mv() method to place the file somewhere on your server
    sampleFile.mv('./'+sampleFile.name, function(err) {
        if (err)
            return res.status(500).send(err);

        res.send('Received!!!');
    });
 });

Hope this help you


问:
How can I find the mistake in ASP.net SQL insert query?
hello iam making insert in a table using asp.net this my code below  ,i got this error System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'  can any body help me to figure out the problem                                                                                </p>

```<code>protected void ButtonSave_Click(object sender, EventArgs e)
       {

           SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");
           con.Open();
           //SqlCommand cmd = new SqlCommand("Invoice_Product", con);
           //cmd.CommandType = CommandType.StoredProcedure;

           SqlCommand cmd = new SqlCommand("insert into [Invoice_Product] (" + Convert.ToInt32(TextBoxInvoice.Text)
             + "','"+Convert.ToInt32(TextBoxInvoice.Text)+"','"+"'"+TextBoxDate.Text+"'"
             + "','"+"'"+DropDownList1.SelectedItem.Text+"'"
             +"','"+"'"+DropDownList2.SelectedItem.Text+"'"+"','"+Convert.ToDouble(LabelPrice1.Text)
             + "','"+Convert.ToInt32(TextBoxQty.Text)+"','"+Convert.ToDouble(LabelTot1.Text)
             + "','"+Convert.ToDouble(LabelDiscount1.Text)+"','"+Convert.ToDouble(LabelNet1.Text)
             + "','"+"'"+DropDownListStores.SelectedItem.Text+"'"+"','"+Convert.ToDouble(TextBoxFinalTot.Text)
             + "','"+Convert.ToDouble(TextBoxTaxes.Text)+ "','"+Convert.ToDouble(TextBoxFinalNet.Text)+")",con);

           int k = cmd.ExecuteNonQuery();
            if (k > 0)
           {
                Response.Write("<script> alert ('User Added')</Script>)");

           }
           else Response.Write("<script> alert ('Error')</Script>)");

           //con.Close();
       }
</code>```

答:
First of all, learn how to use parameter binding in inserts. You are SQL Injection exposed.

First achievement to find the error in syntax is to put the query in a string variable and stop the debugger right before execute statement.

You'll can copy and paste in SQL client.

A first approach of rewriting your code. Missing some columns, only for your guidance. Check the link at the bottom.

```<code>protected void ButtonSave_Click(object sender, EventArgs e)
{
       SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");

       con.Open();
       //SqlCommand cmd = new SqlCommand("Invoice_Product", con);
       //cmd.CommandType = CommandType.StoredProcedure;
       string sqlString = "INSERT INTO [Invoice_Product] VALUES (@FIELD1, @FIELD2)"

       //put the breakpoint on next line and check the value of sqlString
       SqlCommand cmd = new SqlCommand(sqlString,con);
       cmd.Parameters.Add("@FIELD1", SqlDbType.Int);
       cmd.Parameters["@FIELD1"].Value = TextBoxInvoice.Text;
       cmd.Parameters.Add("@FIELD2", SqlDbType.DateTime);
       cmd.Parameters["@FIELD2"].Value = TextBoxDate.Text;

       int k = cmd.ExecuteNonQuery();

       if (k > 0)
       {
            Response.Write("<script> alert ('User Added')</Script>)");
       }
       else
           Response.Write("<script> alert ('Error')</Script>)");

       //con.Close();
   }
</code>```

Check this link https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8

Body:
hello iam making insert in a table using asp.net this my code below  ,i got this error System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'  can any body help me to figure out the problem

protected void ButtonSave_Click(object sender, EventArgs e)
       {

           SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");
           con.Open();
           //SqlCommand cmd = new SqlCommand("Invoice_Product", con);
           //cmd.CommandType = CommandType.StoredProcedure;

           SqlCommand cmd = new SqlCommand("insert into [Invoice_Product] (" + Convert.ToInt32(TextBoxInvoice.Text)
             + "','"+Convert.ToInt32(TextBoxInvoice.Text)+"','"+"'"+TextBoxDate.Text+"'"
             + "','"+"'"+DropDownList1.SelectedItem.Text+"'"
             +"','"+"'"+DropDownList2.SelectedItem.Text+"'"+"','"+Convert.ToDouble(LabelPrice1.Text)
             + "','"+Convert.ToInt32(TextBoxQty.Text)+"','"+Convert.ToDouble(LabelTot1.Text)
             + "','"+Convert.ToDouble(LabelDiscount1.Text)+"','"+Convert.ToDouble(LabelNet1.Text)
             + "','"+"'"+DropDownListStores.SelectedItem.Text+"'"+"','"+Convert.ToDouble(TextBoxFinalTot.Text)
             + "','"+Convert.ToDouble(TextBoxTaxes.Text)+ "','"+Convert.ToDouble(TextBoxFinalNet.Text)+")",con);

           int k = cmd.ExecuteNonQuery();
            if (k > 0)
           {
                Response.Write(")");

           }
           else Response.Write(")");

           //con.Close();
       }

Body:
First of all, learn how to use parameter binding in inserts. You are SQL Injection exposed.

First achievement to find the error in syntax is to put the query in a string variable and stop the debugger right before execute statement.

You'll can copy and paste in SQL client.

A first approach of rewriting your code. Missing some columns, only for your guidance. Check the link at the bottom.

protected void ButtonSave_Click(object sender, EventArgs e)
{
       SqlConnection con = new SqlConnection("Data Source=LAPTOP-U11A4VS6;Initial Catalog=Task;Integrated Security=True");

       con.Open();
       //SqlCommand cmd = new SqlCommand("Invoice_Product", con);
       //cmd.CommandType = CommandType.StoredProcedure;
       string sqlString = "INSERT INTO [Invoice_Product] VALUES (@FIELD1, @FIELD2)"

       //put the breakpoint on next line and check the value of sqlString
       SqlCommand cmd = new SqlCommand(sqlString,con);
       cmd.Parameters.Add("@FIELD1", SqlDbType.Int);
       cmd.Parameters["@FIELD1"].Value = TextBoxInvoice.Text;
       cmd.Parameters.Add("@FIELD2", SqlDbType.DateTime);
       cmd.Parameters["@FIELD2"].Value = TextBoxDate.Text;

       int k = cmd.ExecuteNonQuery();

       if (k > 0)
       {
            Response.Write("<script> alert ('User Added')</Script>)");
       }
       else
           Response.Write("<script> alert ('Error')</Script>)");

       //con.Close();
   }

Check this link https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.8


问:
Opengl/Glut keyboard input trouble
i have an assignment to draw a pyramid onto the screen and then rotate after i press the 'k' key in my keyboard.
Everything works ok, except the rotation part as the program doesn't seem to be noting me pressing the key. The code goes as follows:

void changeSize(int w, int h) {

    if(h == 0)
        h = 1;

    float ratio = w * 1.0 / h;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glViewport(0, 0, w, h);

    // Set perspective
    gluPerspective(45.0f ,ratio, 1.0f ,1000.0f);

    // return to the model view matrix mode
    glMatrixMode(GL_MODELVIEW);
}

void renderScene(void) {

    // clear buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // set the camera
    glLoadIdentity();
    gluLookAt(5.0,5.0,5.0,
              0.0,0.0,0.0,
              0.0f,2.0f,0.0f);

    // put the geometric transformations here

    // put drawing instructions here

    glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);

    glBegin(GL_LINES);
        glColor3f(1.0f, 0.0f, 0.0f);
        glVertex3f(-100.0f, 0.0f, 0.0f);
        glVertex3f( 100.0f, 0.0f, 0.0f);

        glColor3f(0.0f, 1.0f, 0.0f);
        glVertex3f(0.0f, -100.0f, 0.0f);
        glVertex3f(0.0f, 100.0f, 0.0f);

        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex3f(0.0f, 0.0f, -100.0f);
        glVertex3f(0.0f, 0.0f, 100.0f);
    glEnd();

    //triangulos da base
    glBegin(GL_TRIANGLES);
        glColor3f(255.0f,255.0f,255.0f);
        glVertex3f(1.0f,0.0f,1.0f);
        glVertex3f(-1.0f,0.0f,-1.0f);
        glVertex3f(-1.0f,0.0f,1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,1.0f);
        glVertex3f(1.0f,0.0f,-1.0f);
        glVertex3f(-1.0f,0.0f,-1.0f);
    glEnd();

    //triangulos das faces

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(-1.0f,0.0f,1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,-1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(1.0f,0.0f,1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,-1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(-1.0f,0.0f,-1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(-1.0f,0.0f,-1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(-1.0f,0.0f,1.0f);
    glEnd();

    // End of frame
    glutSwapBuffers();
}

// write function to process keyboard events

void rotate (unsigned char key, int x, int y) {
    if (key == 'k')
        glRotatef(45,1.0,1.0,0.0);

        glutPostRedisplay();
}

int main(int argc, char **argv) {

    // init GLUT and the window
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(1200,1200);
    glutCreateWindow("CG@DI-UM");

    // Required callback registry
        glutDisplayFunc(renderScene);
        glutReshapeFunc(changeSize);

    // put here the registration of the keyboard callbacks
        glutKeyboardFunc(rotate);

    //  OpenGL settings
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    // enter GLUT's main cycle
    glutMainLoop();

    return 0;
}
```

It seems that my program is not noting me pressing the key even tho i am. Im tried only printing the keys that are being pressed, and that works, so i'm really lost here.

答:
glRotatef seem to have no effect in rotate, because glLoadIdentity() is called at the begin of renderScene. Actually glRotatef changes the current matrix, but when the scene is rendered (renderScene), then glLoadIdentity() loads the Identity matrix to the current matrix.

Anyway it is a bad style to do changes to the current matrix in input event callbacks. Change states and values of variables in the input events and use the variables to set the current model view matrix before the scene is rendered in renderScene.

Add a global variable angle:

float angle = 0.0f;
```

<p>Change the value of the variable in <code>renderScene</code>. e.g:</p>

<pre class="lang-c prettyprint-override"><code>void rotate (unsigned char key, int x, int y) {
    if (key == 'k') {
        angle += 45.0f;
        glutPostRedisplay();
    }
}
</code>```

And apply the rotation to the current matrix in renderScene:

void renderScene(void) {

    // clear buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // set the camera
    glLoadIdentity();
    gluLookAt(5.0,5.0,5.0,
              0.0,0.0,0.0,
              0.0f,2.0f,0.0f);

    // apply rotation
    glRotatef(angle, 1.0f, 1.0f, 0.0f);

    // [...]

}
```

Title: Opengl/Glut keyboard input trouble

Body:
i have an assignment to draw a pyramid onto the screen and then rotate after i press the 'k' key in my keyboard.
Everything works ok, except the rotation part as the program doesn't seem to be noting me pressing the key. The code goes as follows:

void changeSize(int w, int h) {

    if(h == 0)
        h = 1;

    float ratio = w * 1.0 / h;

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glViewport(0, 0, w, h);

    // Set perspective
    gluPerspective(45.0f ,ratio, 1.0f ,1000.0f);

    // return to the model view matrix mode
    glMatrixMode(GL_MODELVIEW);
}

void renderScene(void) {

    // clear buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // set the camera
    glLoadIdentity();
    gluLookAt(5.0,5.0,5.0,
              0.0,0.0,0.0,
              0.0f,2.0f,0.0f);

    // put the geometric transformations here

    // put drawing instructions here

    glPolygonMode(GL_FRONT_AND_BACK,GL_LINE);

    glBegin(GL_LINES);
        glColor3f(1.0f, 0.0f, 0.0f);
        glVertex3f(-100.0f, 0.0f, 0.0f);
        glVertex3f( 100.0f, 0.0f, 0.0f);

        glColor3f(0.0f, 1.0f, 0.0f);
        glVertex3f(0.0f, -100.0f, 0.0f);
        glVertex3f(0.0f, 100.0f, 0.0f);

        glColor3f(0.0f, 0.0f, 1.0f);
        glVertex3f(0.0f, 0.0f, -100.0f);
        glVertex3f(0.0f, 0.0f, 100.0f);
    glEnd();

    //triangulos da base
    glBegin(GL_TRIANGLES);
        glColor3f(255.0f,255.0f,255.0f);
        glVertex3f(1.0f,0.0f,1.0f);
        glVertex3f(-1.0f,0.0f,-1.0f);
        glVertex3f(-1.0f,0.0f,1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,1.0f);
        glVertex3f(1.0f,0.0f,-1.0f);
        glVertex3f(-1.0f,0.0f,-1.0f);
    glEnd();

    //triangulos das faces

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(-1.0f,0.0f,1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,-1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(1.0f,0.0f,1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(1.0f,0.0f,-1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(-1.0f,0.0f,-1.0f);
    glEnd();

    glBegin(GL_TRIANGLES);
        glVertex3f(-1.0f,0.0f,-1.0f);
        glVertex3f(0.0f,2.0f,0.0f);
        glVertex3f(-1.0f,0.0f,1.0f);
    glEnd();

    // End of frame
    glutSwapBuffers();
}

// write function to process keyboard events

void rotate (unsigned char key, int x, int y) {
    if (key == 'k')
        glRotatef(45,1.0,1.0,0.0);

        glutPostRedisplay();
}

int main(int argc, char **argv) {

    // init GLUT and the window
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowPosition(100,100);
    glutInitWindowSize(1200,1200);
    glutCreateWindow("CG@DI-UM");

    // Required callback registry
        glutDisplayFunc(renderScene);
        glutReshapeFunc(changeSize);

    // put here the registration of the keyboard callbacks
        glutKeyboardFunc(rotate);

    //  OpenGL settings
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);

    // enter GLUT's main cycle
    glutMainLoop();

    return 0;
}

It seems that my program is not noting me pressing the key even tho i am. Im tried only printing the keys that are being pressed, and that works, so i'm really lost here.

Body:
glRotatef seem to have no effect in rotate, because glLoadIdentity() is called at the begin of renderScene. Actually glRotatef changes the current matrix, but when the scene is rendered (renderScene), then glLoadIdentity() loads the Identity matrix to the current matrix.

Anyway it is a bad style to do changes to the current matrix in input event callbacks. Change states and values of variables in the input events and use the variables to set the current model view matrix before the scene is rendered in renderScene.

Add a global variable angle:

float angle = 0.0f;

Change the value of the variable in renderScene. e.g:

void rotate (unsigned char key, int x, int y) {
    if (key == 'k') {
        angle += 45.0f;
        glutPostRedisplay();
    }
}

And apply the rotation to the current matrix in renderScene:

void renderScene(void) {

    // clear buffers
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // set the camera
    glLoadIdentity();
    gluLookAt(5.0,5.0,5.0,
              0.0,0.0,0.0,
              0.0f,2.0f,0.0f);

    // apply rotation
    glRotatef(angle, 1.0f, 1.0f, 0.0f);

    // [...]

}


问:
Filter string keys of array from a string in a Javascript object format in an SQL table
I would like to filter out keys (given in an array of strings - ["key2"]) in a given column on an SQL table, say:

{ key1: val1, key2: val2, key3: val3 }

```<code> |--row---|-object--|---value----|

 |---1----|--obj1---|--sum(obj1)-|

 |---2----|--obj2---|--sum(obj2)-|

 |---3----|--obj3---|--sum(obj3)-|
</code>```

I want to be able to do this with the use of SQL and filter all keys of an array for each row in parallel.

So for example, if I had these objects:

obj1 = "{ key1: val1, key2: val2, key3: val3 }"

obj2 = "{ key1: val1, key2: val2 }"

obj3 = "{ key1: val1, key2: val2, key3: val3, key4: val4, key5: val5 }"

and an array of ["key1", "key4"]

I would get new table with new objects and new values as:

obj1 = "{ key2: val2, key3: val3 }"              ,  val = val2+val3

obj2 = "{ key2: val2 }"                          ,  val = val2

obj3 = "{ key2: val2, key3: val3, key5: val5 }"  ,  val = val2+val3+val5

Is it possible?

I tried to use JSON_EXTRACTOR in order to extract the object as a JSON format and manipulate the rows with the filter function one by one but it is not very efficient when I think about it, and it is not using the query to do the filtering.

答:
as per my understanding you are using MySQL. The way that you have found I think is the proper, according to this article about JSON_EXTRACT() points that:

SELECT JSON_EXTRACT('{"a": 1, "b": 2, "c": 3}', '$.b') AS 'Result';

Here you can find the official documentation.

You can always use the Query Execution Plan to verify the efficiency of your queries, but it also depend on your tables, columns, indexes and the conditions in the Where clause.

Body:
I would like to filter out keys (given in an array of strings - ["key2"]) in a given column on an SQL table, say:

{ key1: val1, key2: val2, key3: val3 }

 |--row---|-object--|---value----|

 |---1----|--obj1---|--sum(obj1)-|

 |---2----|--obj2---|--sum(obj2)-|

 |---3----|--obj3---|--sum(obj3)-|

I want to be able to do this with the use of SQL and filter all keys of an array for each row in parallel.

So for example, if I had these objects:

obj1 = "{ key1: val1, key2: val2, key3: val3 }"

obj2 = "{ key1: val1, key2: val2 }"

obj3 = "{ key1: val1, key2: val2, key3: val3, key4: val4, key5: val5 }"

and an array of ["key1", "key4"]

I would get new table with new objects and new values as:

obj1 = "{ key2: val2, key3: val3 }"              ,  val = val2+val3

obj2 = "{ key2: val2 }"                          ,  val = val2

obj3 = "{ key2: val2, key3: val3, key5: val5 }"  ,  val = val2+val3+val5

Is it possible?

I tried to use JSON_EXTRACTOR in order to extract the object as a JSON format and manipulate the rows with the filter function one by one but it is not very efficient when I think about it, and it is not using the query to do the filtering.


问:
Views misplaced when setting frames
I am trying to make a view programatically, making a card with an image and some text and overlaying it with some color. I have turned off clip to bounds and added some colors to make it more visual.
So when I set

```<code>overlay.frame = self.frame
</code>```

or

```<code>overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
</code>```

the overlay should cover the entire view but it does not, why is this?

This is what is showing

This is what I want to see, but with each card having a blue layer on top

```<code>private var leftImage: UIImageView = {
  let i = UIImageView(frame: .zero)
  i.contentMode = .scaleAspectFill
  i.image = UIImage()
  return i
}()

private var topLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.font = UIFont.boldSystemFont(ofSize: 16.0)
  label.lineBreakMode = .byWordWrapping
  label.adjustsFontSizeToFitWidth = true
  label.numberOfLines = 2
  return label
}()

var bottomLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.lineBreakMode = .byWordWrapping
  label.font = UIFont.systemFont(ofSize: 12.0)
  label.numberOfLines = 1
  label.text = "60 seconds"
 return label
}()

private var stackView: UIStackView = {
  let stack = UIStackView(frame: .zero)
  stack.axis = .vertical
  stack.isUserInteractionEnabled = false
  stack.distribution = .fillEqually
  stack.layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  stack.isLayoutMarginsRelativeArrangement = true
  return stack
}()

private var overlay: UIView = {
  let view = UIView(frame: .zero)
  view.backgroundColor = .blue
  view.alpha = 0.8
  //view.isHidden = true
  return view
}()

override init(frame: CGRect) {
  super.init(frame: frame)
  create()
}

required init?(coder: NSCoder) {
  super.init(coder: coder)
  create()
}

private func create() {
  self.translatesAutoresizingMaskIntoConstraints = false

  //leftview
  leftImage.frame = CGRect(x: 0, y: 0, width: frame.width / 2, height: frame.height)
  addSubview(leftImage)

  //rightVIew
  stackView.frame = CGRect(x: frame.midX, y: 0, width: frame.width / 2, height: frame.height)

  clipsToBounds = false

  //add views to stack
  stackView.addArrangedSubview(topLabel)
  stackView.addArrangedSubview(bottomLabel)

  addSubview(stackView)

  overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
  addSubview(overlay)

  //card styling
  layer.cornerRadius = 10
}
</code>```

答:
The issue is that you're setting your overlay's dimensions like so:

```<code>overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
</code>```

before the superview has determined its final width and height. You'll need to do one of the following:

Call create() after the superview class has determined its final size

Continuously set the overlay's frame as the superview's width and height changes (see https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews)

Use AutoLayout constraints via a xib/storyboard file

Title: Views misplaced when setting frames

Body:
I am trying to make a view programatically, making a card with an image and some text and overlaying it with some color. I have turned off clip to bounds and added some colors to make it more visual.
So when I set

overlay.frame = self.frame

or

overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

the overlay should cover the entire view but it does not, why is this?

This is what is showing

This is what I want to see, but with each card having a blue layer on top

private var leftImage: UIImageView = {
  let i = UIImageView(frame: .zero)
  i.contentMode = .scaleAspectFill
  i.image = UIImage()
  return i
}()

private var topLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.font = UIFont.boldSystemFont(ofSize: 16.0)
  label.lineBreakMode = .byWordWrapping
  label.adjustsFontSizeToFitWidth = true
  label.numberOfLines = 2
  return label
}()

var bottomLabel: UILabel = {
  let label = UILabel(frame: .zero)
  label.isUserInteractionEnabled = false
  label.lineBreakMode = .byWordWrapping
  label.font = UIFont.systemFont(ofSize: 12.0)
  label.numberOfLines = 1
  label.text = "60 seconds"
 return label
}()

private var stackView: UIStackView = {
  let stack = UIStackView(frame: .zero)
  stack.axis = .vertical
  stack.isUserInteractionEnabled = false
  stack.distribution = .fillEqually
  stack.layoutMargins = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  stack.isLayoutMarginsRelativeArrangement = true
  return stack
}()

private var overlay: UIView = {
  let view = UIView(frame: .zero)
  view.backgroundColor = .blue
  view.alpha = 0.8
  //view.isHidden = true
  return view
}()

override init(frame: CGRect) {
  super.init(frame: frame)
  create()
}

required init?(coder: NSCoder) {
  super.init(coder: coder)
  create()
}

private func create() {
  self.translatesAutoresizingMaskIntoConstraints = false

  //leftview
  leftImage.frame = CGRect(x: 0, y: 0, width: frame.width / 2, height: frame.height)
  addSubview(leftImage)

  //rightVIew
  stackView.frame = CGRect(x: frame.midX, y: 0, width: frame.width / 2, height: frame.height)

  clipsToBounds = false

  //add views to stack
  stackView.addArrangedSubview(topLabel)
  stackView.addArrangedSubview(bottomLabel)

  addSubview(stackView)

  overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
  addSubview(overlay)

  //card styling
  layer.cornerRadius = 10
}

Body:
The issue is that you're setting your overlay's dimensions like so:

overlay.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)

before the superview has determined its final width and height. You'll need to do one of the following:

Call create() after the superview class has determined its final size

Continuously set the overlay's frame as the superview's width and height changes (see https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews)

Use AutoLayout constraints via a xib/storyboard file


问:
Stopping a vimeo video on close of a modal, when multiple videos are in one page
I have multiple pop ups on one page.  each pop up not coded with bootstrap, has a bootstrap carousel inside it.  within those bootstrap carousels there may or may not be a vimeo video.

The issue were having is stopping the video from playing on dismiss of the popup or pressing the left and right buttons because with there being multiple videos in different carousels the script below copies the video from the first src it finds and replaces every video with that src.

I've tried using closest() and find() and also tried both of those on the script within the click function to say (this).closest($frame) but this doesn't work either.

Any help would be greatly appreciated.

```<code>function stopVideo() {
 var $frame = $('iframe#nofocusvideo');

 // saves the current iframe source
var vidsrc = $frame.attr('src');

// sets the source to nothing, stopping the video
$frame.attr('src', '');

// sets it back to the correct link so that it reloads immediately on the next window open
$frame.attr('src', vidsrc);
}

$(".carousel-control-prev").click(function(){
stopVideo();
});

$(".carousel-control-next").click(function(){
stopVideo();
});

$(".fa-times").click(function(){
stopVideo();
});
</code>```

答: var $frame = $('.carousel-item.active').find('iframe'); fixed this issue</p>

Body:
I have multiple pop ups on one page.  each pop up not coded with bootstrap, has a bootstrap carousel inside it.  within those bootstrap carousels there may or may not be a vimeo video.

The issue were having is stopping the video from playing on dismiss of the popup or pressing the left and right buttons because with there being multiple videos in different carousels the script below copies the video from the first src it finds and replaces every video with that src.

I've tried using closest() and find() and also tried both of those on the script within the click function to say (this).closest($frame) but this doesn't work either.

Any help would be greatly appreciated.

function stopVideo() {
 var $frame = $('iframe#nofocusvideo');

 // saves the current iframe source
var vidsrc = $frame.attr('src');

// sets the source to nothing, stopping the video
$frame.attr('src', '');

// sets it back to the correct link so that it reloads immediately on the next window open
$frame.attr('src', vidsrc);
}

$(".carousel-control-prev").click(function(){
stopVideo();
});

$(".carousel-control-next").click(function(){
stopVideo();
});

$(".fa-times").click(function(){
stopVideo();
});


问:
How to check whether date is in past or not in moment js?
After going through lots of links, I could not find a condition that satisfy past date.

It should include today date as well.

```<code>todays_date = 2020-02-19T00:00:00.000Z
</code>```

Something like this:

```<code>moment(2020-02-19T00:00:00.000Z).isBefore();
</code>```

How can I write a condition that includes today's date, past date and return true/false.

答:
I did something similar the other day for a project.
I just compared moment() to the past date.

```<code>var isBefore = moment() > moment(pastDate);
</code>```

Or as you want a function

```<code>function isBefore(pastDate){
   return moment() > moment(pastDate);
}
</code>```

moment() returns the current date and dont forget to pass a string in for the pastDate: "2020-02-19T00:00:00.000Z"

Ex:

```<code>moment() > moment("2020-02-17T00:00:00.000Z")
</code>```

Body:
After going through lots of links, I could not find a condition that satisfy past date.

It should include today date as well.

todays_date = 2020-02-19T00:00:00.000Z

Something like this:

moment(2020-02-19T00:00:00.000Z).isBefore();

How can I write a condition that includes today's date, past date and return true/false.

Body:
I did something similar the other day for a project.
I just compared moment() to the past date.

var isBefore = moment() > moment(pastDate);

Or as you want a function

function isBefore(pastDate){
   return moment() > moment(pastDate);
}

moment() returns the current date and dont forget to pass a string in for the pastDate: "2020-02-19T00:00:00.000Z"

Ex:

moment() > moment("2020-02-17T00:00:00.000Z")


问:
python: child class cannot use parent variables
I have a Parent class which holds some variables. Then I want to extend it to several child classes. Depending on the child, I want to group some of the parent variables in a list. However, I get an error

```<code>NameError: name 'VARIABLE' is not defined
</code>```

This is the code I run, just to play around

```<code>class Parent(object):
    VARIABLE = 'parent variable'

class Child(Parent):
    list = [VARIABLE]

if __name__ == '__main__':
    child = Child()
    print(child.VARIABLE)
</code>```

How do I do this in python?

答:
This code will work

```<code>class Parent(object):
    VARIABLE = 'parent variable'

class Child(Parent):
     mylist = [Parent.VARIABLE]

if __name__ == '__main__':
    child = Child()
    print(child.VARIABLE)
</code>```

list is a reserved word of the language so you have to use some other name for your variable

Body:
I have a Parent class which holds some variables. Then I want to extend it to several child classes. Depending on the child, I want to group some of the parent variables in a list. However, I get an error

NameError: name 'VARIABLE' is not defined

This is the code I run, just to play around

class Parent(object):
    VARIABLE = 'parent variable'

class Child(Parent):
    list = [VARIABLE]

if __name__ == '__main__':
    child = Child()
    print(child.VARIABLE)

How do I do this in python?

Body:
This code will work

class Parent(object):
    VARIABLE = 'parent variable'

class Child(Parent):
     mylist = [Parent.VARIABLE]

if __name__ == '__main__':
    child = Child()
    print(child.VARIABLE)

list is a reserved word of the language so you have to use some other name for your variable


问:
R: How do I convert a dataframe of strings into POSIXt objects?
I have a dataframe of strings representing times, such as:

```<code>times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"),
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")),
                        row.names = c(NA, 3L), class = "data.frame")
</code>```

If I run strptime() on a single element of my dataframe times, it converts it into a nice POSIXt object:

```<code>strptime(times[1,1], '%H:%M:%S')
</code>```

[1] "2020-02-19 17:19:04 GMT"

Great, so now I'd like to convert my whole dataframe times into this format.

I cannot seem to find the solution to do this smoothly.

A few of the things I have tried so far:

```<code>strptime(times, '%H:%M:%S') # generates NA
strftime(times, '%H:%M:%S') # Error: do not know how to convert 'x' to class “POSIXlt”
apply(times, 2, function(x) strftime(x, '%H:%M:%S')) # Error: character string is not in a standard unambiguous format
</code>```

The closest I got to what I want is:

```<code>apply(times, 2, function(x) strptime(x, '%H:%M:%S'))
</code>```

It generates a messy list. I can probably find a way to use it, but there must be a more staightforward way?

答:
You could use lapply.

```<code>times[] <- lapply(times, strptime, '%H:%M:%S')
#                  exp1                exp2
# 1 2020-02-19 17:19:04 2020-02-19 17:22:04
# 2 2020-02-19 17:28:53 2020-02-19 17:31:53
# 3 2020-02-19 17:38:44 2020-02-19 17:41:45
</code>```

Note: apply also works.

```<code>times[] <- apply(times, 2, function(x) strptime(x, '%H:%M:%S'))
</code>```

The trick is to replace the columns (in contrast to overwriting the data frame with a list) with [] <-, which can be seen as abbreviated for times[1:2] <- lapply(times[1:2], ·) in this case.

Body:
I have a dataframe of strings representing times, such as:

times <- structure(list(exp1 = c("17:19:04 \r", "17:28:53 \r", "17:38:44 \r"),
                        exp2 = c("17:22:04 \r", "17:31:53 \r", "17:41:45 \r")),
                        row.names = c(NA, 3L), class = "data.frame")

If I run strptime() on a single element of my dataframe times, it converts it into a nice POSIXt object:

strptime(times[1,1], '%H:%M:%S')

[1] "2020-02-19 17:19:04 GMT"

Great, so now I'd like to convert my whole dataframe times into this format.

I cannot seem to find the solution to do this smoothly.

A few of the things I have tried so far:

strptime(times, '%H:%M:%S') # generates NA
strftime(times, '%H:%M:%S') # Error: do not know how to convert 'x' to class “POSIXlt”
apply(times, 2, function(x) strftime(x, '%H:%M:%S')) # Error: character string is not in a standard unambiguous format

The closest I got to what I want is:

apply(times, 2, function(x) strptime(x, '%H:%M:%S'))

It generates a messy list. I can probably find a way to use it, but there must be a more staightforward way?

Body:
You could use lapply.

times[] <- lapply(times, strptime, '%H:%M:%S')
#                  exp1                exp2
# 1 2020-02-19 17:19:04 2020-02-19 17:22:04
# 2 2020-02-19 17:28:53 2020-02-19 17:31:53
# 3 2020-02-19 17:38:44 2020-02-19 17:41:45

Note: apply also works.

times[] <- apply(times, 2, function(x) strptime(x, '%H:%M:%S'))

The trick is to replace the columns (in contrast to overwriting the data frame with a list) with [] <-, which can be seen as abbreviated for times[1:2] <- lapply(times[1:2], ·) in this case.


问:
want to download images from server
I want to transfer site from shared hosting server to dedicated server.current server has folder,which includes approx. 16000 images...we can not use FTP to download these much images.and i do not have SSH rights? how can i download images from this shared hosting server.</p>

答: Unless they are located within a directory that is within the web root of a web application server you are out of luck.</p>

Title: want to download images from server


问:
Combining json_arrayagg and json_object with json_table always returns the first line
The following source code doesn't return the expected values except when I remove the columns v_f_1000 and v_f_2:

```<code>SELECT
  (SELECT v_f
  FROM json_table(R_P.json_data, '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 1000
  ) AS "v_f_1000",
  (SELECT v_f
  FROM json_table(R_P.json_data, '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 2
  ) AS "v_f_2",
  R_P.json_data,
  R_P.r_c,
  R_P.r_r
FROM
  (SELECT json_arrayagg(json_object(KEY 'r_p_i' value r_p_i, KEY 'v_f' value v_f, KEY 'u_i' value u_i ABSENT ON NULL)
  ORDER BY NULL) json_data,
    r_c,
    r_r
  FROM
    (SELECT '26658' AS r_c,
      '00'          AS r_r,
      1000          AS r_p_i,
      8.5           AS v_f,
      'MM'          AS u_i
    FROM dual
    UNION ALL
    SELECT '26917' AS r_c,
      '00'         AS r_r,
      2            AS r_p_i,
      10           AS v_f,
      'R71'        AS u_i
    FROM dual
    )
  GROUP BY r_c,
    r_r
  ) R_P;
</code>```

Actual result:

```<code>8.5   null  [{"r_p_i":1000,"v_f":8.5,"u_i":"MM"}]   26658   00
8.5   null  [{"r_p_i":1000,"v_f":8.5,"u_i":"MM"}]   26917   00
</code>```

Expected result:

```<code>8.5   null  [{"r_p_i":1000,"v_f":8.5,"u_i":"MM"}]   26658   00
null  10    [{"r_p_i":2,"v_f":10,"u_i":"R71"}]      26917   00
</code>```

I use Oracle 12.2.0.1.0 and Oracle 19.0.0.0.0. I tried several optimizer hints without success, NO_QUERY_TRANSFORMATION produces an ORA-600 error. I think that it's a bug, R_P.json_data shouldn't be different when I add the columns v_f_1000 and v_f_2 into the select clause.

答:
I still think that my first implementation above should work as expected (it will be reported as a bug) but replacing json_arrayagg by json_objectagg and json_table by json_value makes it work:

```<code>SELECT JSON_VALUE(R_P.json_data, '$."1000".v_f') AS "v_f_1000",
  JSON_VALUE(R_P.json_data, '$."2".v_f')         AS "v_f_2",
  R_P.json_data,
  R_P.r_c,
  R_P.r_r
FROM
  (SELECT json_objectagg(KEY TO_CHAR(r_p_i) value json_object(KEY 'v_f' value v_f, KEY 'u_i' value u_i ABSENT ON NULL)) AS json_data,
    r_c,
    r_r
  FROM
    (SELECT '26658' AS r_c,
      '00'          AS r_r,
      1000          AS r_p_i,
      8.5           AS v_f,
      'MM'          AS u_i
    FROM dual
    UNION ALL
    SELECT '26917' AS r_c,
      '00'         AS r_r,
      2            AS r_p_i,
      10           AS v_f,
      'R71'        AS u_i
    FROM dual
    )
  GROUP BY r_c,
    r_r
  ) R_P;
</code>```

Important update:
Calling to_char() on the JSON data when passing it to json_table seems to be enough to solve my problem:

```<code>SELECT
  (SELECT v_f
  FROM json_table(to_char(R_P.json_data), '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 1000
  ) AS "v_f_1000",
  (SELECT v_f
  FROM json_table(to_char(R_P.json_data), '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 2
  ) AS "v_f_2",
  R_P.json_data,
  R_P.r_c,
  R_P.r_r
FROM
  (SELECT json_arrayagg(json_object(KEY 'r_p_i' value r_p_i, KEY 'v_f' value v_f, KEY 'u_i' value u_i ABSENT ON NULL)
  ORDER BY NULL) json_data,
    r_c,
    r_r
  FROM
    (SELECT '26658' AS r_c,
      '00'          AS r_r,
      1000          AS r_p_i,
      8.5           AS v_f,
      'MM'          AS u_i
    FROM dual
    UNION ALL
    SELECT '26917' AS r_c,
      '00'         AS r_r,
      2            AS r_p_i,
      10           AS v_f,
      'R71'        AS u_i
    FROM dual
    )
  GROUP BY r_c,
    r_r
  ) R_P;
</code>```

Body:
The following source code doesn't return the expected values except when I remove the columns v_f_1000 and v_f_2:

SELECT
  (SELECT v_f
  FROM json_table(R_P.json_data, '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 1000
  ) AS "v_f_1000",
  (SELECT v_f
  FROM json_table(R_P.json_data, '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 2
  ) AS "v_f_2",
  R_P.json_data,
  R_P.r_c,
  R_P.r_r
FROM
  (SELECT json_arrayagg(json_object(KEY 'r_p_i' value r_p_i, KEY 'v_f' value v_f, KEY 'u_i' value u_i ABSENT ON NULL)
  ORDER BY NULL) json_data,
    r_c,
    r_r
  FROM
    (SELECT '26658' AS r_c,
      '00'          AS r_r,
      1000          AS r_p_i,
      8.5           AS v_f,
      'MM'          AS u_i
    FROM dual
    UNION ALL
    SELECT '26917' AS r_c,
      '00'         AS r_r,
      2            AS r_p_i,
      10           AS v_f,
      'R71'        AS u_i
    FROM dual
    )
  GROUP BY r_c,
    r_r
  ) R_P;

Actual result:

8.5   null  [{"r_p_i":1000,"v_f":8.5,"u_i":"MM"}]   26658   00
8.5   null  [{"r_p_i":1000,"v_f":8.5,"u_i":"MM"}]   26917   00

Expected result:

8.5   null  [{"r_p_i":1000,"v_f":8.5,"u_i":"MM"}]   26658   00
null  10    [{"r_p_i":2,"v_f":10,"u_i":"R71"}]      26917   00

I use Oracle 12.2.0.1.0 and Oracle 19.0.0.0.0. I tried several optimizer hints without success, NO_QUERY_TRANSFORMATION produces an ORA-600 error. I think that it's a bug, R_P.json_data shouldn't be different when I add the columns v_f_1000 and v_f_2 into the select clause.

Body:
I still think that my first implementation above should work as expected (it will be reported as a bug) but replacing json_arrayagg by json_objectagg and json_table by json_value makes it work:

SELECT JSON_VALUE(R_P.json_data, '$."1000".v_f') AS "v_f_1000",
  JSON_VALUE(R_P.json_data, '$."2".v_f')         AS "v_f_2",
  R_P.json_data,
  R_P.r_c,
  R_P.r_r
FROM
  (SELECT json_objectagg(KEY TO_CHAR(r_p_i) value json_object(KEY 'v_f' value v_f, KEY 'u_i' value u_i ABSENT ON NULL)) AS json_data,
    r_c,
    r_r
  FROM
    (SELECT '26658' AS r_c,
      '00'          AS r_r,
      1000          AS r_p_i,
      8.5           AS v_f,
      'MM'          AS u_i
    FROM dual
    UNION ALL
    SELECT '26917' AS r_c,
      '00'         AS r_r,
      2            AS r_p_i,
      10           AS v_f,
      'R71'        AS u_i
    FROM dual
    )
  GROUP BY r_c,
    r_r
  ) R_P;

Important update:
Calling to_char() on the JSON data when passing it to json_table seems to be enough to solve my problem:

SELECT
  (SELECT v_f
  FROM json_table(to_char(R_P.json_data), '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 1000
  ) AS "v_f_1000",
  (SELECT v_f
  FROM json_table(to_char(R_P.json_data), '$[*]' columns (r_p_i NUMBER path '$.r_p_i', v_f path '$.v_f'))
  WHERE r_p_i = 2
  ) AS "v_f_2",
  R_P.json_data,
  R_P.r_c,
  R_P.r_r
FROM
  (SELECT json_arrayagg(json_object(KEY 'r_p_i' value r_p_i, KEY 'v_f' value v_f, KEY 'u_i' value u_i ABSENT ON NULL)
  ORDER BY NULL) json_data,
    r_c,
    r_r
  FROM
    (SELECT '26658' AS r_c,
      '00'          AS r_r,
      1000          AS r_p_i,
      8.5           AS v_f,
      'MM'          AS u_i
    FROM dual
    UNION ALL
    SELECT '26917' AS r_c,
      '00'         AS r_r,
      2            AS r_p_i,
      10           AS v_f,
      'R71'        AS u_i
    FROM dual
    )
  GROUP BY r_c,
    r_r
  ) R_P;


问:
How to handle dynamic images within a FittedBox
I am currently implementing a dropdown button as the title of a scaffold.

In this dropdown, some of the options do not have a relevant image and therefore just text is shown. I have it working great, my only problem is, an error is always thrown when the app runs (not hot reloaded) because the Image doesn't load instantaneously meaning that FittedBox is trying to fit an empty widget, once it loads it is fine, and then hot reloads work fine with no errors too because the image is already loaded. Here is my code for my DropDownMenuItems:

```<code>return DropdownMenuItem(
                    value: company.id.toString(),
                    child: Center(
                        child: FittedBox(
                            child: Center(
                                child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.all(10),
                          child: (config.companyLogos[company.id] != null)
                              ? FittedBox(
                                  child: Image.asset(
                                    config.companyLogosPath +
                                        config.companyLogos[company.id],
                                    height: 50,
                                  ),
                                  fit: BoxFit.contain,
                                )
                              : FittedBox(
                                  child: Text(
                                  company.name,
                                  style: TextStyle(fontSize: 30),
                                )),
                        ),
                      ],
                    )))));
</code>```

And here is the error that is thrown when the app runs, I am sure this is due to what I described above:

```<code>flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performLayout():
flutter: 'package:flutter/src/rendering/box.dart': Failed assertion: line 313 pos 12: 'width > 0.0': is not
flutter: true.
</code>```

Considered solutions:

A possible solution would be to supply the width of image, I could include this in my companyLogos map by making it a Map of Maps and including the filename and the width in the sub map.

However, I've trie this and it doesn't seem to work, it just makes my images a lot smaller than if I used an unset width.

I am not explicitly defining width to make it keep its aspect ratio whilst still fitting in the row.

I'm probably missing a trick here on how to handle images in flutter/dart, any help would be much appreciated, thank you!

答:
Thanks to @pskink I have solved the issue.

I solved it by scrapping the FittedBox completely and using Image's 'fit:' property.

Here is my fixed code:

```<code>return DropdownMenuItem(
                    value: company.id.toString(),
                    child: Center(
                        child: FittedBox(
                            child: Center(
                                child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.all(10),
                          child: (config.companyLogos[company.id] != null)
                              ? Container(
                                  child: Image.asset(
                                  config.companyLogosPath +
                                      config.companyLogos[company.id],
                                  height: 50,
                                  fit: BoxFit.contain,
                                ))
                              : FittedBox(
                                  child: Text(
                                  company.name,
                                  style: TextStyle(fontSize: 30),
                                )),
                        ),
                      ],
                    )))));
</code>```

Body:
I am currently implementing a dropdown button as the title of a scaffold.

In this dropdown, some of the options do not have a relevant image and therefore just text is shown. I have it working great, my only problem is, an error is always thrown when the app runs (not hot reloaded) because the Image doesn't load instantaneously meaning that FittedBox is trying to fit an empty widget, once it loads it is fine, and then hot reloads work fine with no errors too because the image is already loaded. Here is my code for my DropDownMenuItems:

return DropdownMenuItem(
                    value: company.id.toString(),
                    child: Center(
                        child: FittedBox(
                            child: Center(
                                child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.all(10),
                          child: (config.companyLogos[company.id] != null)
                              ? FittedBox(
                                  child: Image.asset(
                                    config.companyLogosPath +
                                        config.companyLogos[company.id],
                                    height: 50,
                                  ),
                                  fit: BoxFit.contain,
                                )
                              : FittedBox(
                                  child: Text(
                                  company.name,
                                  style: TextStyle(fontSize: 30),
                                )),
                        ),
                      ],
                    )))));

And here is the error that is thrown when the app runs, I am sure this is due to what I described above:

flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performLayout():
flutter: 'package:flutter/src/rendering/box.dart': Failed assertion: line 313 pos 12: 'width > 0.0': is not
flutter: true.

Considered solutions:

A possible solution would be to supply the width of image, I could include this in my companyLogos map by making it a Map of Maps and including the filename and the width in the sub map.

However, I've trie this and it doesn't seem to work, it just makes my images a lot smaller than if I used an unset width.

I am not explicitly defining width to make it keep its aspect ratio whilst still fitting in the row.

I'm probably missing a trick here on how to handle images in flutter/dart, any help would be much appreciated, thank you!

Body:
Thanks to @pskink I have solved the issue.

I solved it by scrapping the FittedBox completely and using Image's 'fit:' property.

Here is my fixed code:

return DropdownMenuItem(
                    value: company.id.toString(),
                    child: Center(
                        child: FittedBox(
                            child: Center(
                                child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.all(10),
                          child: (config.companyLogos[company.id] != null)
                              ? Container(
                                  child: Image.asset(
                                  config.companyLogosPath +
                                      config.companyLogos[company.id],
                                  height: 50,
                                  fit: BoxFit.contain,
                                ))
                              : FittedBox(
                                  child: Text(
                                  company.name,
                                  style: TextStyle(fontSize: 30),
                                )),
                        ),
                      ],
                    )))));


问:
Android studio- "SDK tools directory is missing"
When I start Android Studio, it displays a window entitled "Downloading components" which says:
 "Android SDK was installed to: C: / Users / user / AppData / Local / android / SDK2<code>  </code> SDK tools directory is missing "
I can not fix it and I need help!!</p>

答:
It was mentioned before but to be clear, It probably is due to your internet connection.

In my case it was that in my job I am behind a proxy, that means I should set a proxy in android studio for it to be able to download all SDK files.

You can set a proxy in the Android Studio Settings under Appearance & Behavior > System Settings > HTTP Proxy as stated here:
https://developer.android.com/studio/intro/studio-config#proxy

Test de proxy (there's a button for that).
Close Android Studio.
Reopen Android Studio, and it should be able to download all SDK files.

Body:
When I start Android Studio, it displays a window entitled "Downloading components" which says:
 "Android SDK was installed to: C: / Users / user / AppData / Local / android / SDK2   SDK tools directory is missing "
I can not fix it and I need help!!


问:
Bitwise operations in JavaScript
I know that numbers in JavaScript are stored in IEEE-754 format. But when we use integers, particularly bitwise operators, they're represented as two's complement with 32 bits.

So -1 would be 0xFFFFFFFF. But (-1).toString(2) is -1. And -1 >>> 31 is 1, that's right, but -1 >>> 32 must be 0, however it's 4294967295. And -1 << 32 must be 0, but it is -1.

Why do bitwise operations work in this way? And toString() shows number with sign -, why this minus is not in sign bit? Also why -1 >> 0 is -1, but -1 >>> 0 is 4294967295? I know what is the difference between >> and >>>, but the second operand is 0, so I can't understand why these operations work in different ways.

答:
Difference between >>> and >>

In an arithmetic shift, the sign bit is extended to preserve the
  signedness of the number.

-1 in 8 bit is 11111111 -2 is 11111110 ...

This is handled like that because if you count to the highest possible number +1, the lowest possible number will be shown (8 bit: 01111111 +1 = 10000000), Thats why 111111111 is -1

Logical right shift, however, does not care that the value could
  possibly represent a signed number; it simply moves everything to the
  right and fills in from the left with 0s.

so here, -1 >>> pushes the 11111111 one to the right so the "-" sign gets lost and the highest positive number 0111111 (in 8 bit) is shown

Also the reason why -1 >> 0 equals -1 is because 11111111 >> 0 does literally add nothing while -1 >>> 0 still moves everything and fills the left bits with 0, each step you raise this "0" will half the value until 0. You can try -1 >>> 31 to see it gets 1

Title: Bitwise operations in JavaScript


问:
Symfony validation not returning any violations for NotBlank
I'm using Symfony validation within my own app (not Symfony). I'm expecting it to return violations as I haven't populated the Id property:

```<code>$user = new User();
$user->setId('');
//...

$validator = \Symfony\Component\Validator\Validation::createValidator();
$errors = $validator->validate($user);
var_dump(count($errors)); exit; // outputs: 0
</code>```

However, validate returns no violations.

Here is my User class with constraint annotations:

```<code>use Symfony\Component\Validator\Constraints as Assert;

class User {

    /**
     * @Assert\NotBlank
     */
    private $id;

    //...

    public function getId(): string {
        return $this->id;
    }

    public function setId(string $id): void {
        $this->id = $id;
    }

    //...
</code>```

Where am I going wrong? According to the docs, a blank string should trigger a violation for this constraint - https://symfony.com/doc/current/reference/constraints/NotBlank.html

答:
You don't need Annotations if you use Validation.
Try this : </p>

```<code>$validator = Validation::createValidator();
$violations = $validator->validate($user->getId, [
    new NotBlank(),
]);
</code>```

Body:
I'm using Symfony validation within my own app (not Symfony). I'm expecting it to return violations as I haven't populated the Id property:

$user = new User();
$user->setId('');
//...

$validator = \Symfony\Component\Validator\Validation::createValidator();
$errors = $validator->validate($user);
var_dump(count($errors)); exit; // outputs: 0

However, validate returns no violations.

Here is my User class with constraint annotations:

use Symfony\Component\Validator\Constraints as Assert;

class User {

    /**
     * @Assert\NotBlank
     */
    private $id;

    //...

    public function getId(): string {
        return $this->id;
    }

    public function setId(string $id): void {
        $this->id = $id;
    }

    //...

Where am I going wrong? According to the docs, a blank string should trigger a violation for this constraint - https://symfony.com/doc/current/reference/constraints/NotBlank.html

Body:
You don't need Annotations if you use Validation.
Try this :

$validator = Validation::createValidator();
$violations = $validator->validate($user->getId, [
    new NotBlank(),
]);


问:
Why am I getting 500 http error when making serverside apollo client queries with cors?
I'm using Next.js + react-apollo + apollo-server + express for my website. Recently I added cookie authentication and therefore had to enable CORS in the server for cookies auth to work. However I see that apollo client queries result in http 500 status when performed serverside. The same queries when performed clientside successfully resolve. I'm puzzled because I'd actually expect issues to happen on the client side because CORS has more impact there. I'm not sure what is causing the issue, any suggestions will be very welcome!

The error itself i as follows:

ApolloError: Network error: request to https://example.com/graphql/
  failed, reason: write EPROTO 140152723232576:error:14094410:SSL
  routines:ssl3_read_bytes:sslv3 alert handshake
  failure:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL
  alert number 40

```<code>    at new ApolloError (/src/node_modules/apollo-client/bundle.umd.js:92:26)
    at /src/node_modules/apollo-client/bundle.umd.js:1588:34
    at /src/node_modules/apollo-client/bundle.umd.js:2008:15
    at Set.forEach (<anonymous>)
    at /src/node_modules/apollo-client/bundle.umd.js:2006:26
    at Map.forEach (<anonymous>)
    at QueryManager.broadcastQueries (/src/node_modules/apollo-client/bundle.umd.js:2004:20)
    at /src/node_modules/apollo-client/bundle.umd.js:1483:29
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  graphQLErrors: [],
</code>```

networkError: FetchError: request to https://example.com/graphql/
  failed, reason: write EPROTO 140152723232576:error:14094410:SSL
  routines:ssl3_read_bytes:sslv3 alert handshake
  failure:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL
  alert number 40

I'm using an SSL certificate supplied by Amazon Cloudfront.

This is my client code:

_app.js:

```<code>class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
      if (pageProps.errorStatusCode && ctx.res) {
        ctx.res.statusCode = pageProps.errorStatusCode;
      }
    }

    return { pageProps };
  }
  render() { //render... }
}
</code>```

I have a HOC for page queries:

```<code>const withQuery = (Page, query, variables, errorPolicy = 'none') => {
  Page.getInitialProps = async ctx => {
    const { apolloClient } = ctx;
    try {
      const { data } = await apolloClient.query({
        query,
        variables: vars,
        errorPolicy
      });
      return { data };
    } catch (error) {
      return { errorStatusCode: error.networkError ? '500' : '404' };
    }
  };
  // if (typeof window === 'undefined') { // THIS CODE IS CAUSING THE ISSUE
  //   return Page;
  // }
}
</code>```

This is how I initiate apollo client:

```<code>import withApollo from 'next-with-apollo';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import introspectionQueryResultData from '../../fragmentTypes.json';

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData
});

function createClient({ ctx, headers, initialState }) {
  return new ApolloClient({
    credentials: 'include',
    uri: 'some_graphql_url',
    cache: new InMemoryCache({ fragmentMatcher }).restore(initialState || {}),
    headers
  });
}

export default withApollo(createClient, { getDataFromTree: 'ssr' });
</code>```

This is my server code:

```<code>import cors from 'cors'
const express = require('express')
const { ApolloServer } = require('apollo-server-express')
const { schema } = require('./models')
const server = new ApolloServer({
  schema,
})

// required settings to accept cookies
const corsOptions = {
  origin: function (origin, callback) {
    if (corsWhitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true)
    } else {
      callback(new Error(`${origin} - not allowed by CORS`))
    }
  },
  credentials: true
}

let app = express()
app.use(cors(corsOptions))
server.applyMiddleware({ app, cors: false })
const serverUrl = `my_server_url`
app.listen({ port }, () => console.log(`  Server ready at ${serverUrl}`))
</code>```

To sum up my findings:

The issue originates when _app.js calls await Component.getInitialProps(ctx).

getInitialProps is defined in the withQuery HOC where the query is executed by apolloClient.query method.

Without CORS everything works as well.

EDIT: I noticed that the issue will start happening when headers option is added to createClient along with CORS.

EDIT2: the error occurs even without CORS, it's enough that headers option is added to createClient which create apollo client.

答:
your code was incomplete</p>

```<code>
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log(` Server ready at http://localhost:4000${server.graphqlPath}`)
);

</code>```

Body:
I'm using Next.js + react-apollo + apollo-server + express for my website. Recently I added cookie authentication and therefore had to enable CORS in the server for cookies auth to work. However I see that apollo client queries result in http 500 status when performed serverside. The same queries when performed clientside successfully resolve. I'm puzzled because I'd actually expect issues to happen on the client side because CORS has more impact there. I'm not sure what is causing the issue, any suggestions will be very welcome!

The error itself i as follows:

ApolloError: Network error: request to https://example.com/graphql/
  failed, reason: write EPROTO 140152723232576:error:14094410:SSL
  routines:ssl3_read_bytes:sslv3 alert handshake
  failure:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL
  alert number 40

    at new ApolloError (/src/node_modules/apollo-client/bundle.umd.js:92:26)
    at /src/node_modules/apollo-client/bundle.umd.js:1588:34
    at /src/node_modules/apollo-client/bundle.umd.js:2008:15
    at Set.forEach (<anonymous>)
    at /src/node_modules/apollo-client/bundle.umd.js:2006:26
    at Map.forEach (<anonymous>)
    at QueryManager.broadcastQueries (/src/node_modules/apollo-client/bundle.umd.js:2004:20)
    at /src/node_modules/apollo-client/bundle.umd.js:1483:29
    at processTicksAndRejections (internal/process/task_queues.js:93:5) {
  graphQLErrors: [],

networkError: FetchError: request to https://example.com/graphql/
  failed, reason: write EPROTO 140152723232576:error:14094410:SSL
  routines:ssl3_read_bytes:sslv3 alert handshake
  failure:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1544:SSL
  alert number 40

I'm using an SSL certificate supplied by Amazon Cloudfront.

This is my client code:

_app.js:

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};
    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
      if (pageProps.errorStatusCode && ctx.res) {
        ctx.res.statusCode = pageProps.errorStatusCode;
      }
    }

    return { pageProps };
  }
  render() { //render... }
}

I have a HOC for page queries:

const withQuery = (Page, query, variables, errorPolicy = 'none') => {
  Page.getInitialProps = async ctx => {
    const { apolloClient } = ctx;
    try {
      const { data } = await apolloClient.query({
        query,
        variables: vars,
        errorPolicy
      });
      return { data };
    } catch (error) {
      return { errorStatusCode: error.networkError ? '500' : '404' };
    }
  };
  // if (typeof window === 'undefined') { // THIS CODE IS CAUSING THE ISSUE
  //   return Page;
  // }
}

This is how I initiate apollo client:

import withApollo from 'next-with-apollo';
import ApolloClient, { InMemoryCache } from 'apollo-boost';
import { IntrospectionFragmentMatcher } from 'apollo-cache-inmemory';
import introspectionQueryResultData from '../../fragmentTypes.json';

const fragmentMatcher = new IntrospectionFragmentMatcher({
  introspectionQueryResultData
});

function createClient({ ctx, headers, initialState }) {
  return new ApolloClient({
    credentials: 'include',
    uri: 'some_graphql_url',
    cache: new InMemoryCache({ fragmentMatcher }).restore(initialState || {}),
    headers
  });
}

export default withApollo(createClient, { getDataFromTree: 'ssr' });

This is my server code:

import cors from 'cors'
const express = require('express')
const { ApolloServer } = require('apollo-server-express')
const { schema } = require('./models')
const server = new ApolloServer({
  schema,
})

// required settings to accept cookies
const corsOptions = {
  origin: function (origin, callback) {
    if (corsWhitelist.indexOf(origin) !== -1 || !origin) {
      callback(null, true)
    } else {
      callback(new Error(`${origin} - not allowed by CORS`))
    }
  },
  credentials: true
}

let app = express()
app.use(cors(corsOptions))
server.applyMiddleware({ app, cors: false })
const serverUrl = `my_server_url`
app.listen({ port }, () => console.log(`  Server ready at ${serverUrl}`))

To sum up my findings:

The issue originates when _app.js calls await Component.getInitialProps(ctx).

getInitialProps is defined in the withQuery HOC where the query is executed by apolloClient.query method.

Without CORS everything works as well.

EDIT: I noticed that the issue will start happening when headers option is added to createClient along with CORS.

EDIT2: the error occurs even without CORS, it's enough that headers option is added to createClient which create apollo client.

Body:
your code was incomplete

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4000 }, () =>
  console.log(` Server ready at http://localhost:4000${server.graphqlPath}`)
);


问:
Is it possible to use distccmon-text to see which distcc hosts are up and ready to work?
When I run distccmon-text 1 it creates a new empty line one time per second even though I (should) have one distcc daemon up and running.

Is it possible to list the host nodes in my ~/.distcc/hosts which are up and running, ready to work?

答:
It depends on where your distcc directory is. If it's not in ~/.distcc you have to declare DISTCC_DIR beforehand:

DISTCC_DIR=/some/where/over/the/rainbow distccmon-text

Also if the client isn't sending out requests to servers, you won't see any output.