问:
App Engine HTTP Status Code message
I found an inconsistency between Java's dev_appserver and the live App Engine server.

On my local development server I have a Servlet which returns:

```<code>return response.sendError(response.SC_BAD_REQUEST, "Please log in to comment");
</code>```

When I access the page I get back a Status Code message in the header which is:

```<code>Status Code:400 Please log in to comment
</code>```

The issue comes when I deploy this to App Engine. When accessing that same servlet I get this "Bad Request" instead of "Please log in to comment":

```<code>Status Code:400 Bad Request
</code>```

The Please log in to comment Status Code message appears in the content HTML, but not in the header as it does in the development environment.

Why is this?

Edit

Here's the curl -vvvv traces for both dev_appserver and production:

dev_appserver curl trace:

```<code>> POST /add-comment HTTP/1.1
> User-Agent: Mozilla/4.0
> Host: localhost:8080
> Accept: */*
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 400 Please log in to comment
< Content-Type: text/html; charset=iso-8859-1
< Cache-Control: must-revalidate,no-cache,no-store
< Content-Length: 1406
< Server: Jetty(6.1.x)
</code>```

Production curl trace:

```<code>> POST /add-comment HTTP/1.1
> User-Agent: Mozilla/4.0
> Host: www.xxx.org
> Accept: */*
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 400 Bad Request
< Content-Type: text/html; charset=utf-8
< Vary: Accept-Encoding
< Date: Thu, 18 Aug 2011 14:04:26 GMT
< Server: Google Frontend
< Cache-Control: private
< Transfer-Encoding: chunked
</code>```

答:
I would say the prod system is the correct implementation. The javadocs for sendError() say:

Sends an error response to the client using the specified status. The
  server defaults to creating the response to look like an
  HTML-formatted server error page containing the specified message,
  setting the content type to "text/html", leaving cookies and other
  headers unmodified. If an error-page declaration has been made for the
  web application corresponding to the status code passed in, it will be
  served back in preference to the suggested msg parameter.

If the response has already been committed, this method throws an
  IllegalStateException. After using this method, the response should be
  considered to be committed and should not be written to.

I highlighted a part. This says it just returns a html page with the message when possible. It doesn't say it uses it in the HTTP Status code (which I personally haven't seen anywhere as well :()

Title: App Engine HTTP Status Code message

Body:
I found an inconsistency between Java's dev_appserver and the live App Engine server.

On my local development server I have a Servlet which returns:

return response.sendError(response.SC_BAD_REQUEST, "Please log in to comment");

When I access the page I get back a Status Code message in the header which is:

Status Code:400 Please log in to comment

The issue comes when I deploy this to App Engine. When accessing that same servlet I get this "Bad Request" instead of "Please log in to comment":

Status Code:400 Bad Request

The Please log in to comment Status Code message appears in the content HTML, but not in the header as it does in the development environment.

Why is this?

Edit

Here's the curl -vvvv traces for both dev_appserver and production:

dev_appserver curl trace:

> POST /add-comment HTTP/1.1
> User-Agent: Mozilla/4.0
> Host: localhost:8080
> Accept: */*
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 400 Please log in to comment
< Content-Type: text/html; charset=iso-8859-1
< Cache-Control: must-revalidate,no-cache,no-store
< Content-Length: 1406
< Server: Jetty(6.1.x)

Production curl trace:

> POST /add-comment HTTP/1.1
> User-Agent: Mozilla/4.0
> Host: www.xxx.org
> Accept: */*
> Content-Length: 9
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 400 Bad Request
< Content-Type: text/html; charset=utf-8
< Vary: Accept-Encoding
< Date: Thu, 18 Aug 2011 14:04:26 GMT
< Server: Google Frontend
< Cache-Control: private
< Transfer-Encoding: chunked


来源: stackexchange

问:
how to create multiple boxplots from the same dataframe?
I have a data frame like this:

```<code>df <- data.frame(var_1 = c(1,2,3,4,5,6,7,8,9),
                 var_2 = c(21,23,34,45,23,56,76,54,65),
                 var_3 = c(6,5,4,3,5,7,3,2,5),
                 label = c(1,1,1,2,1,2,2,1,2))
</code>```

I want to create side by side (or  tile) box plots such that the first box plot is

```<code>boxplot(var_1~label, df)
</code>```

the second box plot is

```<code>boxplot(var_2~label, df)
</code>```

and so on. Is there a way to do this without me having to type box plot command each time? For example, some command that iteratively matches all the columns against label and draw a box plot for each?

答:
Using ggplot::facet_wrap() makes it easy to make a bunch of panels of a graph from one dataset. However for it to work the variable that defines the different panels has to be in a single column. In this case that means you have to get from the 'wide' format to a 'long' format of your data. For this I suggest tidyr::pivot_longer(). Last point is that you need to treat your label as a factor otherwise you won't get separate boxes as you do in base R because I think that converts the x variable into a factor by default which {ggplot2} won't do (although it will give an informative warning). Finally, if you want to have separate y axes for each plot you can set scales = "free_y" inside facet_wrap().

library(tidyverse)

df <- data.frame(var_1 = c(1,2,3,4,5,6,7,8,9),
                 var_2 = c(21,23,34,45,23,56,76,54,65),
                 var_3 = c(6,5,4,3,5,7,3,2,5),
                 label = c(1,1,1,2,1,2,2,1,2))

df %>%
  pivot_longer(-label) %>%
  ggplot(aes(factor(label), value)) +
  geom_boxplot() +
  facet_wrap(vars(name), nrow = 1)
```

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

ContentLicense: CC BY-SA 4.0

Body:
I have a data frame like this:

df <- data.frame(var_1 = c(1,2,3,4,5,6,7,8,9),
                 var_2 = c(21,23,34,45,23,56,76,54,65),
                 var_3 = c(6,5,4,3,5,7,3,2,5),
                 label = c(1,1,1,2,1,2,2,1,2))

I want to create side by side (or  tile) box plots such that the first box plot is

boxplot(var_1~label, df)

the second box plot is

boxplot(var_2~label, df)

and so on. Is there a way to do this without me having to type box plot command each time? For example, some command that iteratively matches all the columns against label and draw a box plot for each?

Body:
Using ggplot::facet_wrap() makes it easy to make a bunch of panels of a graph from one dataset. However for it to work the variable that defines the different panels has to be in a single column. In this case that means you have to get from the 'wide' format to a 'long' format of your data. For this I suggest tidyr::pivot_longer(). Last point is that you need to treat your label as a factor otherwise you won't get separate boxes as you do in base R because I think that converts the x variable into a factor by default which {ggplot2} won't do (although it will give an informative warning). Finally, if you want to have separate y axes for each plot you can set scales = "free_y" inside facet_wrap().

library(tidyverse)

df <- data.frame(var_1 = c(1,2,3,4,5,6,7,8,9),
                 var_2 = c(21,23,34,45,23,56,76,54,65),
                 var_3 = c(6,5,4,3,5,7,3,2,5),
                 label = c(1,1,1,2,1,2,2,1,2))

df %>%
  pivot_longer(-label) %>%
  ggplot(aes(factor(label), value)) +
  geom_boxplot() +
  facet_wrap(vars(name), nrow = 1)

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


问:
material UI styled() doesn't show up
In my index.jsx file, I tried to use the MUI styled() utility, but the style isn't applied to <MyComponent>Styled div</MyComponent>. Why?

```<code>    import Button from '@mui/material/Button'
    import Grid from '@mui/material/Grid';
    import Card from '@mui/material/Card'
    import CardActions from '@mui/material/CardActions'
    import CardContent from '@mui/material/CardContent'
    import CardMedia from '@mui/material/CardMedia'
    import Typography from '@mui/material/Typography'
    import { styled } from '@mui/system';
    import Head from 'next/head'
    import Image from 'next/image'

    const MyComponent = styled('div')({
      color: 'darkslategray',
      backgroundColor: 'aliceblue',
      padding: 8,
      borderRadius: 4,
    });

    export const index = () => {

      return (
        <>
          <Head>
            ...
            <link rel="icon" href="/favicon.ico" />
            <link
              rel="stylesheet"
              href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600&family=Mukta:wght@500;600&display=swap"
            />
          </Head>

          <MyComponent>Styled div</MyComponent>
    ...
</code>```

答:
can you use it like this?</p>
```<code>import * as React from 'react';
import { makeStyles } from '@mui/styles';
import Button from '@mui/material/Button';

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;
}
</code>```

Title: material UI styled() doesn't show up

Body:
In my index.jsx file, I tried to use the MUI styled() utility, but the style isn't applied to <MyComponent>Styled div</MyComponent>. Why?

    import Button from '@mui/material/Button'
    import Grid from '@mui/material/Grid';
    import Card from '@mui/material/Card'
    import CardActions from '@mui/material/CardActions'
    import CardContent from '@mui/material/CardContent'
    import CardMedia from '@mui/material/CardMedia'
    import Typography from '@mui/material/Typography'
    import { styled } from '@mui/system';
    import Head from 'next/head'
    import Image from 'next/image'

    const MyComponent = styled('div')({
      color: 'darkslategray',
      backgroundColor: 'aliceblue',
      padding: 8,
      borderRadius: 4,
    });

    export const index = () => {

      return (
        <>

            ...
            <link rel="icon" href="/favicon.ico" />
            <link
              rel="stylesheet"
              href="https://fonts.googleapis.com/css2?family=Montserrat:wght@600&family=Mukta:wght@500;600&display=swap"
            />

          <MyComponent>Styled div</MyComponent>
    ...

Body:
can you use it like this?

import * as React from 'react';
import { makeStyles } from '@mui/styles';
import Button from '@mui/material/Button';

const useStyles = makeStyles({
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
});

export default function Hook() {
  const classes = useStyles();
  return <Button className={classes.root}>Hook</Button>;
}


问:
How To Convert a String With Characters That Are Not Numbers (E.G. "a" or "/") To an Int
So I am making a calculator that takes a pointer string and does the calculation, the problem is I have to convert it to a int but any type of conversion function won't covert any characters that are not numbers, so in this case the multiplication operator. Help will be much appreciated, thanks!</p>
```<code>char* x = "2 * 1"

int y = x

Printf("%d", y) //I want it to print "2"
</code>```

答:
A better way to do this is to take X as input and Y as input both as an int and then apply the math to it and all you would need to print is the result of both of them.

```<code>int x = 2;
int y = 1;
int z = x * y;
printf("%i", z);
</code>```

or if you want you can use ctype.h library and make a for loop to go over each letter of the string and assign it on an array if it's a number using the isdigit function which would return if that one letter is a digit or not and if it is a digit you can assaign it a varible like int z[x] = *string-name*[i]
so it would be like

```<code>char *anything = "thi2sst3ringhasnumber5";
int length = strlen(anything);
int x = 0;
for (int i = 0; i < length; i++)
{
  if (isdigit(anything[i]))
  {
    int numbers[x] = anything[i];
    x++;
  }
}
</code>```

and that would return to you an array of [2, 3, 5] as numbers[0, 1 ,2]
so if you wanted to take multiply them you can do *something* = numbers[0] * numbers[1]; which is 2 * 3 and you can assign it to a variable and print it out.

Body:
So I am making a calculator that takes a pointer string and does the calculation, the problem is I have to convert it to a int but any type of conversion function won't covert any characters that are not numbers, so in this case the multiplication operator. Help will be much appreciated, thanks!

char* x = "2 * 1"

int y = x

Printf("%d", y) //I want it to print "2"

Body:
A better way to do this is to take X as input and Y as input both as an int and then apply the math to it and all you would need to print is the result of both of them.

int x = 2;
int y = 1;
int z = x * y;
printf("%i", z);

or if you want you can use ctype.h library and make a for loop to go over each letter of the string and assign it on an array if it's a number using the isdigit function which would return if that one letter is a digit or not and if it is a digit you can assaign it a varible like int z[x] = *string-name*[i]
so it would be like

char *anything = "thi2sst3ringhasnumber5";
int length = strlen(anything);
int x = 0;
for (int i = 0; i < length; i++)
{
  if (isdigit(anything[i]))
  {
    int numbers[x] = anything[i];
    x++;
  }
}

and that would return to you an array of [2, 3, 5] as numbers[0, 1 ,2]
so if you wanted to take multiply them you can do *something* = numbers[0] * numbers[1]; which is 2 * 3 and you can assign it to a variable and print it out.


问:
How to add legend to plot from CausalImpact package?
I see the other post here about this, but I'm relatively new to R so the answers weren't helpful to me. I'd really appreciate some more in-depth help with how to do this.

I've already made a plot using the commands from the Causal Impact package. In the package documentation, it clearly says that the plots are ggplot2 objects and can be customized the same way as any other object like that. I've successfully done that, adding titles and customizing colors. I need to add a legend (it's required at the journal I'm submitting to). Here is an example of what my graph currently looks like and the code I used to get there.

```<code>library(ggplot2)
devtools::install_github("google/CausalImpact")
library(CausalImpact)

## note that I took this example code from the package documentation up until I customize the plot

#create data
set.seed(1)
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)
y <- 1.2 * x1 + rnorm(100)
y[71:100] <- y[71:100] + 10
data <- cbind(y, x1)

#causal impact analysis
> pre.period <- c(1, 70)
> post.period <- c(71, 100)
> impact <- CausalImpact(data, pre.period, post.period)

#graph
example<-plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank())  # get rid of minor grid

</code>```

In my head, the solution I'd like is to have a legend for each panel of the plot. The first legend (next to the 'original' panel) would show a solid line represents the observed data, the dotted line represents the estimated counterfactual, and the colored band represents the 95% CrI around the estimated counterfactual. The second legend (next to the 'cumulative' panel) would show the dotted line represents the estimated change in trend associated with the intervention and the colored band again represents the 95% CrI around the estimation. Maybe there's a better solution than that, but that's what I've thought of.

Here is a section of the underlying code that runs when you plot:

```<code># Initialize plot
  q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
  q <- q + xlab("") + ylab("")
  if (length(metrics) > 1) {
    q <- q + facet_grid(metric ~ ., scales = "free_y")
  }

  # Add prediction intervals
  q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
                       data, fill = "slategray2")

  # Add pre-period markers
  xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                    impact$model$post.period,
                                    time(impact$series))
  q <- q + geom_vline(xintercept = xintercept,
                      colour = "darkgrey", size = 0.8, linetype = "dashed")

  # Add zero line to pointwise and cumulative plot
  q <- q + geom_line(aes(y = baseline),
                     colour = "darkgrey", size = 0.8, linetype = "solid",
                     na.rm = TRUE)

  # Add point predictions
  q <- q + geom_line(aes(y = mean), data,
                     size = 0.6, colour = "darkblue", linetype = "dashed",
                     na.rm = TRUE)

  # Add observed data
  q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)
  return(q)
}
</code>```

One of the answers in that older post here said that I'd have to adapt the pre-existing function to get a legend, and I don't really have the skills yet to see what I'd have to change or add. I thought that legends were supposed to be automatically added according to what's in the aes() bit of the ggplot code, so I'm a little confused why there isn't one in the first place. Can someone help me with this?

答:
I rewrote the plot function. Instead of using facet_wrap(), I created individual plots with their own legends and used patchwork to group them together into a single plot. In order to run this you need to memory all of the source code including impact_analysis.R, impact_misc.R, impact_model.R, impact_inference.R and impact_plot.R with the exception of the CreateImpactPlot function which I recreated. So instead, run what I have below. You will also need to load ggplot2, tidyr, dplyr, and patchwork. This will only run for Original and Cumulative metrics. Though I revised to some extent for Pointwise, I did not want to do this as I didn't have an example to reproduce. I worked your theme preferences directly into the code in the function. You should be able to identify and change those elements now at your leisure. To be clear, the plots are q1 = original, q2 = pointwise, and q3 = cumulative. I don't see how to bring the confidence band into the legend as it is not part of aes(). Possibly could create a grob from scratch. I just referenced it in the title which you can change if it doesn't suit you. Hopefully this helps.

```<code>                                                 "cumulative")) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   impact:  \code{CausalImpact} results object returned by
    #            \code{CausalImpact()}.
    #   metrics: Which metrics to include in the plot. Can be any combination of
    #            "original", "pointwise", and "cumulative".
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().

    # Create data frame of: time, response, mean, lower, upper, metric
    data <- CreateDataFrameForPlot(impact)

    # Select metrics to display (and their order)
    assert_that(is.vector(metrics))
    metrics <- match.arg(metrics, several.ok = TRUE)
    data <- data[data$metric %in% metrics, , drop = FALSE]
    data$metric <- factor(data$metric, metrics)

    # Initialize plot
    #q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    #q <- q + xlab("") + ylab("")
    #if (length(metrics) > 1) {
    #    q <- q + facet_grid(metric ~ ., scales = "free_y")
    #}

    q1 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q1 <- q1 + xlab("") + ylab("")

    q2 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q2 <- q2 + xlab("") + ylab("")

    q3 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q3 <- q3 + xlab("") + ylab("")

    # Add prediction intervals
    #q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
    #                     data, fill = "slategray2")

    q1 <- q1 + geom_ribbon(data = data %>% dplyr::filter(metric == "original"), aes(x = time, ymin = lower, ymax = upper),
                         fill = "slategray2")

    q2 <- q2 + geom_ribbon(data = data %>% dplyr::filter(metric == "pointwise"), aes(x = time, ymin = lower, ymax = upper),
                           fill = "slategray2")

    q3 <- q3 + geom_ribbon(data = data %>% dplyr::filter(metric == "cumulative"), aes(x = time, ymin = lower, ymax = upper),
                           fill = "slategray2")

    # Add pre-period markers
    xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                      impact$model$post.period,
                                      time(impact$series))

    #q <- q + geom_vline(xintercept = xintercept,
    #                    colour = "darkgrey", size = 0.8, linetype = "dashed")

    q1 <- q1 + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dotted")

    q2 <- q2 + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dotted")

    q3 <- q3 + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dotted")

    data_long <- data %>%
        tidyr::pivot_longer(cols = c("baseline", "mean", "response"), names_to = "variable",
            values_to = "value", values_drop_na = TRUE)

    # Add zero line to pointwise and cumulative plot
    #q <- q + geom_line(aes(y = baseline),
    #                   colour = "darkgrey", size = 0.8, linetype = "solid",
    #                   na.rm = TRUE)

    q1 <- q1 + geom_line(data = data_long %>% dplyr::filter(metric == "original"),
                      aes(x = time, y = value, linetype = variable, group = variable,
                            size = variable),
                       na.rm = TRUE)+
                scale_linetype_manual(guide = "Legend", labels = c("estimated counterfactual", "oberserved"),
                                      values = c("dashed", "solid")) +
            scale_size_manual(values = c(0.6, 0.8)) +
            scale_color_manual(values = c("darkblue", "darkgrey")) +
            theme(legend.position = "right") +
            guides(linetype = guide_legend("Legend", nrow=2), size = "none", color = "none")+
            labs(title = "Original", y = "Clicks (Millions)") +
            theme(
                panel.background = element_rect(fill = "transparent"), # panel bg
                plot.background = element_rect(fill = "transparent", color = NA), # plot bg
                panel.grid.major = element_blank(), # get rid of major grid
                panel.grid.minor = element_blank())

    #q2 <- q2 + geom_line(data = data_long %>% dplyr::filter(metric == "pointwise"),
    #                     aes(x = time, y = value, linetype = Line, group = Line),
    #                     na.rm = TRUE) +
    #        scale_linetype_manual(title = "Legend", labels = c("estimated counterfactual", "observed"),
    #                          values = c("dashed", "solid")) +
    #        scale_size_manual(values = c(0.6, 0.8)) +
    #        scale_color_manual(values = c("darkblue", "darkgrey")) +
    #        theme(legend.position = "right") +
    #        guides(linetype = guide_legend("Legend", nrow=2), size = "none", color = "none")+
    #        labs(title = "Pointwise", y = "Clicks (Millions)")

    q3 <- q3 + geom_line(data = data_long %>% dplyr::filter(metric == "cumulative"),
                         aes(x = time, y = value, linetype = variable, group = variable),
                         na.rm = TRUE) +
        scale_linetype_manual(labels = c("observed", "estimated trend change"),
                              values = c("solid", "dashed")) +
            theme(legend.position = "right")+
            guides(linetype = guide_legend("Legend", nrow=2))+
            labs(title = "Cumulative",x = "Time",  y = "Clicks (Millions)")+
            theme(
                panel.background = element_rect(fill = "transparent"), # panel bg
                plot.background = element_rect(fill = "transparent", color = NA), # plot bg
                panel.grid.major = element_blank(), # get rid of major grid
                panel.grid.minor = element_blank())

    patchwork <- q1 / q3

    q <- patchwork + plot_annotation(title = "Figure. Analysis of click behavior after intervention with
                                95% Confidence Interval")

    # Add point predictions
    #q <- q + geom_line(aes(y = mean), data,
    #                   size = 0.6, colour = "darkblue", linetype = "dashed",
    #                   na.rm = TRUE)

    # Add observed data
    #q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)

    return(q)
}

plot(impact, c("original", "cumulative"))

</code>```

Body:
I see the other post here about this, but I'm relatively new to R so the answers weren't helpful to me. I'd really appreciate some more in-depth help with how to do this.

I've already made a plot using the commands from the Causal Impact package. In the package documentation, it clearly says that the plots are ggplot2 objects and can be customized the same way as any other object like that. I've successfully done that, adding titles and customizing colors. I need to add a legend (it's required at the journal I'm submitting to). Here is an example of what my graph currently looks like and the code I used to get there.

library(ggplot2)
devtools::install_github("google/CausalImpact")
library(CausalImpact)

## note that I took this example code from the package documentation up until I customize the plot

#create data
set.seed(1)
x1 <- 100 + arima.sim(model = list(ar = 0.999), n = 100)
y <- 1.2 * x1 + rnorm(100)
y[71:100] <- y[71:100] + 10
data <- cbind(y, x1)

#causal impact analysis
> pre.period <- c(1, 70)
> post.period <- c(71, 100)
> impact <- CausalImpact(data, pre.period, post.period)

#graph
example<-plot(impact, c("original", "cumulative")) +
    labs(
        x = "Time",
        y = "Clicks (Millions)",
        title = "Figure. Analysis of click behavior after intervention.") +
    theme(plot.title = element_text(hjust = 0.5),
          plot.caption = element_text(hjust = 0),
          panel.background = element_rect(fill = "transparent"), # panel bg
          plot.background = element_rect(fill = "transparent", color = NA), # plot bg
          panel.grid.major = element_blank(), # get rid of major grid
          panel.grid.minor = element_blank())  # get rid of minor grid

In my head, the solution I'd like is to have a legend for each panel of the plot. The first legend (next to the 'original' panel) would show a solid line represents the observed data, the dotted line represents the estimated counterfactual, and the colored band represents the 95% CrI around the estimated counterfactual. The second legend (next to the 'cumulative' panel) would show the dotted line represents the estimated change in trend associated with the intervention and the colored band again represents the 95% CrI around the estimation. Maybe there's a better solution than that, but that's what I've thought of.

Here is a section of the underlying code that runs when you plot:

# Initialize plot
  q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
  q <- q + xlab("") + ylab("")
  if (length(metrics) > 1) {
    q <- q + facet_grid(metric ~ ., scales = "free_y")
  }

  # Add prediction intervals
  q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
                       data, fill = "slategray2")

  # Add pre-period markers
  xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                    impact$model$post.period,
                                    time(impact$series))
  q <- q + geom_vline(xintercept = xintercept,
                      colour = "darkgrey", size = 0.8, linetype = "dashed")

  # Add zero line to pointwise and cumulative plot
  q <- q + geom_line(aes(y = baseline),
                     colour = "darkgrey", size = 0.8, linetype = "solid",
                     na.rm = TRUE)

  # Add point predictions
  q <- q + geom_line(aes(y = mean), data,
                     size = 0.6, colour = "darkblue", linetype = "dashed",
                     na.rm = TRUE)

  # Add observed data
  q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)
  return(q)
}

One of the answers in that older post here said that I'd have to adapt the pre-existing function to get a legend, and I don't really have the skills yet to see what I'd have to change or add. I thought that legends were supposed to be automatically added according to what's in the aes() bit of the ggplot code, so I'm a little confused why there isn't one in the first place. Can someone help me with this?

Body:
I rewrote the plot function. Instead of using facet_wrap(), I created individual plots with their own legends and used patchwork to group them together into a single plot. In order to run this you need to memory all of the source code including impact_analysis.R, impact_misc.R, impact_model.R, impact_inference.R and impact_plot.R with the exception of the CreateImpactPlot function which I recreated. So instead, run what I have below. You will also need to load ggplot2, tidyr, dplyr, and patchwork. This will only run for Original and Cumulative metrics. Though I revised to some extent for Pointwise, I did not want to do this as I didn't have an example to reproduce. I worked your theme preferences directly into the code in the function. You should be able to identify and change those elements now at your leisure. To be clear, the plots are q1 = original, q2 = pointwise, and q3 = cumulative. I don't see how to bring the confidence band into the legend as it is not part of aes(). Possibly could create a grob from scratch. I just referenced it in the title which you can change if it doesn't suit you. Hopefully this helps.

                                                 "cumulative")) {
    # Creates a plot of observed data and counterfactual predictions.
    #
    # Args:
    #   impact:  \code{CausalImpact} results object returned by
    #            \code{CausalImpact()}.
    #   metrics: Which metrics to include in the plot. Can be any combination of
    #            "original", "pointwise", and "cumulative".
    #
    # Returns:
    #   A ggplot2 object that can be plotted using plot().

    # Create data frame of: time, response, mean, lower, upper, metric
    data <- CreateDataFrameForPlot(impact)

    # Select metrics to display (and their order)
    assert_that(is.vector(metrics))
    metrics <- match.arg(metrics, several.ok = TRUE)
    data <- data[data$metric %in% metrics, , drop = FALSE]
    data$metric <- factor(data$metric, metrics)

    # Initialize plot
    #q <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    #q <- q + xlab("") + ylab("")
    #if (length(metrics) > 1) {
    #    q <- q + facet_grid(metric ~ ., scales = "free_y")
    #}

    q1 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q1 <- q1 + xlab("") + ylab("")

    q2 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q2 <- q2 + xlab("") + ylab("")

    q3 <- ggplot(data, aes(x = time)) + theme_bw(base_size = 15)
    q3 <- q3 + xlab("") + ylab("")

    # Add prediction intervals
    #q <- q + geom_ribbon(aes(ymin = lower, ymax = upper),
    #                     data, fill = "slategray2")

    q1 <- q1 + geom_ribbon(data = data %>% dplyr::filter(metric == "original"), aes(x = time, ymin = lower, ymax = upper),
                         fill = "slategray2")

    q2 <- q2 + geom_ribbon(data = data %>% dplyr::filter(metric == "pointwise"), aes(x = time, ymin = lower, ymax = upper),
                           fill = "slategray2")

    q3 <- q3 + geom_ribbon(data = data %>% dplyr::filter(metric == "cumulative"), aes(x = time, ymin = lower, ymax = upper),
                           fill = "slategray2")

    # Add pre-period markers
    xintercept <- CreatePeriodMarkers(impact$model$pre.period,
                                      impact$model$post.period,
                                      time(impact$series))

    #q <- q + geom_vline(xintercept = xintercept,
    #                    colour = "darkgrey", size = 0.8, linetype = "dashed")

    q1 <- q1 + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dotted")

    q2 <- q2 + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dotted")

    q3 <- q3 + geom_vline(xintercept = xintercept,
                        colour = "darkgrey", size = 0.8, linetype = "dotted")

    data_long <- data %>%
        tidyr::pivot_longer(cols = c("baseline", "mean", "response"), names_to = "variable",
            values_to = "value", values_drop_na = TRUE)

    # Add zero line to pointwise and cumulative plot
    #q <- q + geom_line(aes(y = baseline),
    #                   colour = "darkgrey", size = 0.8, linetype = "solid",
    #                   na.rm = TRUE)

    q1 <- q1 + geom_line(data = data_long %>% dplyr::filter(metric == "original"),
                      aes(x = time, y = value, linetype = variable, group = variable,
                            size = variable),
                       na.rm = TRUE)+
                scale_linetype_manual(guide = "Legend", labels = c("estimated counterfactual", "oberserved"),
                                      values = c("dashed", "solid")) +
            scale_size_manual(values = c(0.6, 0.8)) +
            scale_color_manual(values = c("darkblue", "darkgrey")) +
            theme(legend.position = "right") +
            guides(linetype = guide_legend("Legend", nrow=2), size = "none", color = "none")+
            labs(title = "Original", y = "Clicks (Millions)") +
            theme(
                panel.background = element_rect(fill = "transparent"), # panel bg
                plot.background = element_rect(fill = "transparent", color = NA), # plot bg
                panel.grid.major = element_blank(), # get rid of major grid
                panel.grid.minor = element_blank())

    #q2 <- q2 + geom_line(data = data_long %>% dplyr::filter(metric == "pointwise"),
    #                     aes(x = time, y = value, linetype = Line, group = Line),
    #                     na.rm = TRUE) +
    #        scale_linetype_manual(title = "Legend", labels = c("estimated counterfactual", "observed"),
    #                          values = c("dashed", "solid")) +
    #        scale_size_manual(values = c(0.6, 0.8)) +
    #        scale_color_manual(values = c("darkblue", "darkgrey")) +
    #        theme(legend.position = "right") +
    #        guides(linetype = guide_legend("Legend", nrow=2), size = "none", color = "none")+
    #        labs(title = "Pointwise", y = "Clicks (Millions)")

    q3 <- q3 + geom_line(data = data_long %>% dplyr::filter(metric == "cumulative"),
                         aes(x = time, y = value, linetype = variable, group = variable),
                         na.rm = TRUE) +
        scale_linetype_manual(labels = c("observed", "estimated trend change"),
                              values = c("solid", "dashed")) +
            theme(legend.position = "right")+
            guides(linetype = guide_legend("Legend", nrow=2))+
            labs(title = "Cumulative",x = "Time",  y = "Clicks (Millions)")+
            theme(
                panel.background = element_rect(fill = "transparent"), # panel bg
                plot.background = element_rect(fill = "transparent", color = NA), # plot bg
                panel.grid.major = element_blank(), # get rid of major grid
                panel.grid.minor = element_blank())

    patchwork <- q1 / q3

    q <- patchwork + plot_annotation(title = "Figure. Analysis of click behavior after intervention with
                                95% Confidence Interval")

    # Add point predictions
    #q <- q + geom_line(aes(y = mean), data,
    #                   size = 0.6, colour = "darkblue", linetype = "dashed",
    #                   na.rm = TRUE)

    # Add observed data
    #q <- q + geom_line(aes(y = response), size = 0.6,  na.rm = TRUE)

    return(q)
}

plot(impact, c("original", "cumulative"))


问:
Static way to get 'Context' in Android?
Is there a way to get the current Context instance inside a static method?

I'm looking for that way because I hate saving the 'Context' instance each time it changes.

答:
I think you need a body for the getAppContext() method:

```<code>public static Context getAppContext()
   return MyApplication.context;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Static way to get 'Context' in Android?

Body:
I think you need a body for the getAppContext() method:

public static Context getAppContext()
   return MyApplication.context;


问:
Background covering the whole page (CSS)
I just switched from VSC to Adobe Dreamweaver and i don't know if I should keep it or not; but that's besides the point.

When I try to add a background to some text, it fills the whole screen with the background with the background, and if I try to change the width it only adds on to the background which is filling the whole screen.

I don't know if it's user error, something changed in HTML/CSS overnight or if it's because of the Dreamweaver display box thing on the top of my screen

@charset "utf-8";
* {
  margin: 0;
  padding: 0;
}

.Container {
  padding: 25%;
  padding-left: 50%;
  padding-right: 50%;
  font-family: comfortaa;
  font-style: normal;
  font-weight: 600;
  color: white;
  background: #00C3FF;
  margin: 0;
}

body {
  background-image: url(http://www.incomeactivator.com/images/freebg5.jpg);
  background-repeat: no-repeat;
  background-size: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>index</title>
  <link href="file:///C|/Users/REDACTED/Documents/style.css" rel="stylesheet" type="text/css">
  <!--The following script tag downloads a font from the Adobe Edge Web Fonts server for use within the web page. We recommend that you do not modify it.-->
  <script>
    var __adobewebfontsappname__ = "dreamweaver"
  </script>
  <script src="http://use.edgefonts.net/comfortaa:n3:default.js" type="text/javascript"></script>

</head>

<body>

  <div class="Container">
    <h1>Hello</h1>
  </div>
</body>

</html></code>```

p.s: let me know if you need a ss of the results I get.

答:
Instead of using the class, you can change the texts background color by adding
background-color: rgb(255, 236, 139)
in the h1 tag

Demo:

YOURTEXT

Body:
I just switched from VSC to Adobe Dreamweaver and i don't know if I should keep it or not; but that's besides the point.

When I try to add a background to some text, it fills the whole screen with the background with the background, and if I try to change the width it only adds on to the background which is filling the whole screen.

I don't know if it's user error, something changed in HTML/CSS overnight or if it's because of the Dreamweaver display box thing on the top of my screen

@charset "utf-8";
* {
  margin: 0;
  padding: 0;
}

.Container {
  padding: 25%;
  padding-left: 50%;
  padding-right: 50%;
  font-family: comfortaa;
  font-style: normal;
  font-weight: 600;
  color: white;
  background: #00C3FF;
  margin: 0;
}

body {
  background-image: url(http://www.incomeactivator.com/images/freebg5.jpg);
  background-repeat: no-repeat;
  background-size: 100%;
}

<!doctype html>

  <meta charset="utf-8">
  <title>index</title>
  <link href="file:///C|/Users/REDACTED/Documents/style.css" rel="stylesheet" type="text/css">

Hello

p.s: let me know if you need a ss of the results I get.


问:
MongoDB - Aggregate (join two collection) with nested array as join key
I have two collections. (updated)

I need to join them and return only a few fields.
As I understand, I should use aggregate and projection features.
I try to find examples, but can't find the right, in my case foreign key is placed in the array in the nested field.

It is not easy for me, I’m new at this, and I couldn’t win against this MongoDB query.

In the code block below I wrote the simplified equivalent models (doc1, doc2) and expected results.

Does anyone have any ideas?

```<code>db.doc1.deleteMany({});
db.doc2.deleteMany({});

// tow related documents

db.doc1.insert( [
    {
    "version" : 123456,
    "doc" : {
      "code":"A1",
      "name":"some document A1",
      "doc2CodeArray":[
          {"code":"B01"},
          {"code":"B02"},
          {"code":"B03"},
          {"code":"B04"},
          {"code":"B05"},
          {"code":"B06"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":[
          {"code":"B07"},
          {"code":"B08"},
          {"code":"B09"},
          {"code":"B10"},
          {"code":"B11"},
          {"code":"B12"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":null
      }
    }

]);

db.doc2.insert( [
    {
        "version" : 567890,
        "doc" : {
          "code":"B01",
          "valueArray":[{"valueType":"int","valueData":"1"}],
          "doc2Type":{"code":"C1"}
        }
    },
    {"version" : 567890,"doc" : { "code":"B02", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B03", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B04", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B05", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B06", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false},
                                                              {"valueType":"str","valueData":"F","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},

    {"version" : 567890,"doc" : { "code":"B07", "valueArray":[{"valueType":"int","valueData":"1","isDefault":false}],"doc2Type":{"code":"C1","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B08", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B09", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B10", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B11", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B12", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},
    ]);
</code>```

The result that I want

```<code>  I need join collections and select only few props
  {
      "doc":{code:"A1"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"3"}},
        {"code":"C3", "value":{"value":"4"}},
      ]
  },
  {
      "doc":{code:"A2"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"2"}},
        {"code":"C3", "value":{"value":"3"}},
        {"code":"C4", "value":{"value":"4"}},
      ]
  }
</code>```

答:
https://mongoplayground.net/p/1-1SU8SgbTQ</p>
```<code>db.doc1.aggregate([
  {
    $lookup: {
      from: "doc2",
      localField: "doc.doc2CodeArray.code",
      foreignField: "doc.code",
      as: "doc.doc2Items"
    }
  },
  {
    $replaceRoot: {
      newRoot: "$doc"
    }
  },
  {
    $addFields: {
      "doc2Items": {
        $map: {
          input: "$doc2Items",
          in: {
            doc2TypeCode: "$$this.doc.doc2Type.code",
            doc2ValueArray: "$$this.doc.valueArray"
          }
        }
      }
    }
  },
  {
    $unset: [
      "doc2CodeArray"
    ]
  }
])
</code>```

Body:
I have two collections. (updated)

I need to join them and return only a few fields.
As I understand, I should use aggregate and projection features.
I try to find examples, but can't find the right, in my case foreign key is placed in the array in the nested field.

It is not easy for me, I’m new at this, and I couldn’t win against this MongoDB query.

In the code block below I wrote the simplified equivalent models (doc1, doc2) and expected results.

Does anyone have any ideas?

db.doc1.deleteMany({});
db.doc2.deleteMany({});

// tow related documents

db.doc1.insert( [
    {
    "version" : 123456,
    "doc" : {
      "code":"A1",
      "name":"some document A1",
      "doc2CodeArray":[
          {"code":"B01"},
          {"code":"B02"},
          {"code":"B03"},
          {"code":"B04"},
          {"code":"B05"},
          {"code":"B06"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":[
          {"code":"B07"},
          {"code":"B08"},
          {"code":"B09"},
          {"code":"B10"},
          {"code":"B11"},
          {"code":"B12"}
          ]
      }
    },
    {
    "version" : 123457,
    "doc" : {
      "code":"A2",
      "name":"some document A2",
      "doc2CodeArray":null
      }
    }

]);

db.doc2.insert( [
    {
        "version" : 567890,
        "doc" : {
          "code":"B01",
          "valueArray":[{"valueType":"int","valueData":"1"}],
          "doc2Type":{"code":"C1"}
        }
    },
    {"version" : 567890,"doc" : { "code":"B02", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B03", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B04", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B05", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B06", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false},
                                                              {"valueType":"str","valueData":"F","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},

    {"version" : 567890,"doc" : { "code":"B07", "valueArray":[{"valueType":"int","valueData":"1","isDefault":false}],"doc2Type":{"code":"C1","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B08", "valueArray":[{"valueType":"int","valueData":"2","isDefault":false}],"doc2Type":{"code":"C2","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B09", "valueArray":[{"valueType":"int","valueData":"3","isDefault":false}],"doc2Type":{"code":"C3","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B10", "valueArray":[{"valueType":"int","valueData":"4","isDefault":false}],"doc2Type":{"code":"C4","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B11", "valueArray":[{"valueType":"int","valueData":"5","isDefault":false}],"doc2Type":{"code":"C5","addInfo":"1234567890"}}},
    {"version" : 567890,"doc" : { "code":"B12", "valueArray":[{"valueType":"int","valueData":"6","isDefault":false}],"doc2Type":{"code":"C6","addInfo":"1234567890"}}},
    ]);

The result that I want

  I need join collections and select only few props
  {
      "doc":{code:"A1"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"3"}},
        {"code":"C3", "value":{"value":"4"}},
      ]
  },
  {
      "doc":{code:"A2"},
      "doc2Items":[
        {"code":"C2", "value":{"value":"2"}},
        {"code":"C3", "value":{"value":"3"}},
        {"code":"C4", "value":{"value":"4"}},
      ]
  }

Body:
https://mongoplayground.net/p/1-1SU8SgbTQ

db.doc1.aggregate([
  {
    $lookup: {
      from: "doc2",
      localField: "doc.doc2CodeArray.code",
      foreignField: "doc.code",
      as: "doc.doc2Items"
    }
  },
  {
    $replaceRoot: {
      newRoot: "$doc"
    }
  },
  {
    $addFields: {
      "doc2Items": {
        $map: {
          input: "$doc2Items",
          in: {
            doc2TypeCode: "$$this.doc.doc2Type.code",
            doc2ValueArray: "$$this.doc.valueArray"
          }
        }
      }
    }
  },
  {
    $unset: [
      "doc2CodeArray"
    ]
  }
])


问:
Docker Build Error with Sockets and php-fpm 8.0 invalid application of 'sizeof' to incomplete type 'struct cmsgcred'
I have a custom Docker build of nginx and php-fpm that I am pretty sure was working until recently.  I am now getting the error mentioned above during a build using the DockerFile below when using 8.0-fpm, but not with 8.1.1-fpm-bullseye, although there are some other issues with using 8.1.1 in some of the PHP code (deprecations and warnings).

```<code>FROM php:8.0-fpm
#FROM php:8.1.1-fpm-bullseye
ENV DEBIAN_FRONTEND=noninteractive
# Install dependencies, libssl1.1-dev ?
# Debian GNU/Linux 11 (bullseye), xvfb and xorg are required for wkhtmltopdf, or the xfonts, fontconfig onwards

RUN apt-get update && apt-get install -y \
    wget \
    openssl \
    libssl1.1 \
    ca-certificates \
    build-essential \
    libpng-dev \
    libjpeg62-turbo-dev \
    libfreetype6-dev \
    locales \
    zip \
    jpegoptim optipng pngquant gifsicle \
    vim \
    unzip \
    git \
    curl \
    libzip-dev \
    dcmtk \
    nginx \
    supervisor \
    libpq-dev \
    geoip-database \
    libgeoip1 \
    fontconfig \
    xfonts-75dpi \
    xfonts-100dpi \
    xfonts-scalable \
    xfonts-base \
    libxrender1

# adjustments to php.ini base on the production version.
# application/wasm  wasm is missing from distro.

COPY php.ini /usr/local/etc/php/php.ini
COPY mime.types /etc/nginx/mime.types

# Install extensions and configure

RUN docker-php-ext-configure gd --with-freetype --with-jpeg
RUN docker-php-ext-configure zip
RUN docker-php-ext-install pdo_mysql zip exif pcntl gd sockets

# Install Postgre PDO

RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql
RUN docker-php-ext-install pdo pdo_pgsql pgsql

#  php.ini sort of takes care of these, but this is another option.
#  RUN sed -E -i -e 's/max_execution_time = 1200/max_execution_time = 120/' /etc/php.ini \
#  && sed -E -i -e 's/memory_limit = 128M/memory_limit = 512M/' /etc/php.ini \
#  && sed -E -i -e 's/post_max_size = 8M/post_max_size = 64M/' /etc/php.ini \
#  && sed -E -i -e 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' /etc/php.ini

# Clear cache

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install Composer

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

COPY entrypoint.sh /
ENTRYPOINT ["/bin/bash","/entrypoint.sh"]
</code>```

The error looks like it gets thrown here:

```<code>#36 34.46  cc -I. -I/usr/src/php/ext/sockets -I/usr/src/php/ext/sockets/include -I/usr/src/php/ext/sockets/main -I/usr/src/php/ext/sockets -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DZEND_ENABLE_STATIC_TSRMLS_CACHE=1 -c /usr/src/php/ext/sockets/sendrecvmsg.c  -fPIC -DPIC -o .libs/sendrecvmsg.o
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c: In function 'init_ancillary_registry':
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:128:19: error: invalid application of 'sizeof' to incomplete type 'struct cmsgcred'
#36 34.57   128 |  PUT_ENTRY(sizeof(struct cmsgcred), 0, 0, from_zval_write_ucred,
#36 34.57       |                   ^~~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:99:17: note: in definition of macro 'PUT_ENTRY'
#36 34.57    99 |  entry.size   = sizev; \
#36 34.57       |                 ^~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:129:36: error: 'SCM_CREDS' undeclared (first use in this function)
#36 34.57   129 |    to_zval_read_ucred, SOL_SOCKET, SCM_CREDS);
#36 34.57       |                                    ^~~~~~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:105:19: note: in definition of macro 'PUT_ENTRY'
#36 34.57   105 |  key.cmsg_type  = type; \
#36 34.57       |                   ^~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:129:36: note: each undeclared identifier is reported only once for each function it appears in
#36 34.57   129 |    to_zval_read_ucred, SOL_SOCKET, SCM_CREDS);
#36 34.57       |                                    ^~~~~~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:105:19: note: in definition of macro 'PUT_ENTRY'
#36 34.57   105 |  key.cmsg_type  = type; \
#36 34.57       |                   ^~~~
#36 34.59 make: *** [Makefile:216: sendrecvmsg.lo] Error 1
------
failed to solve: rpc error: code = Unknown desc = executor failed running [/bin/sh -c docker-php-ext-install pdo_mysql zip exif pcntl gd sockets]: exit code: 2
</code>```

Any suggestions regarding optimizing the build would also be appreciated.

I have another question about saving the built image to Docker Hub if I have an account to store private images.  e.g.  Below is a snippet from the docker-compose.yml file.  It isn't really clear to me if it is possible to bypass the build and just use a built image that I store on my Docker Hub account.  It seems like if I comment out the build line, then it will access the dockerhub image to build the container, but it isn't clear to me if some of the other commands in the DockerFile (i.e. entrypoint, composer install, etc.) are executed in that case.

My goal is to arrive at what I consider "stable" images and then make those available on DockerHub instead of having to build the image on a new machine everytime.  Also, probably going to run into some issues with an M1 Chip on a mac once I get one.

```<code>build: php-fpm-nginx  # comment out to use the built image
image: sdscotti/dockerhubimage
depends_on: [mysql_db]
restart: unless-stopped
ports: ["443:443"]
volumes:
  - xxx
extra_hosts:
  - xxx
environment:
  TARGETARCH:  "amd64"
</code>```

答:
PHP 8.0.15 and 8.1.2 has a bug which is breaks compile sockets extension.

You have a two options:

Skip this versions.

Apply a workaround to bypass bug and build sockets extenstension.

Source:

Issue at origin PHP source repository

Issue at official PHP Dokcer image source repository

Body:
I have a custom Docker build of nginx and php-fpm that I am pretty sure was working until recently.  I am now getting the error mentioned above during a build using the DockerFile below when using 8.0-fpm, but not with 8.1.1-fpm-bullseye, although there are some other issues with using 8.1.1 in some of the PHP code (deprecations and warnings).

FROM php:8.0-fpm
#FROM php:8.1.1-fpm-bullseye
ENV DEBIAN_FRONTEND=noninteractive
# Install dependencies, libssl1.1-dev ?
# Debian GNU/Linux 11 (bullseye), xvfb and xorg are required for wkhtmltopdf, or the xfonts, fontconfig onwards

RUN apt-get update && apt-get install -y \
    wget \
    openssl \
    libssl1.1 \
    ca-certificates \
    build-essential \
    libpng-dev \
    libjpeg62-turbo-dev \
    libfreetype6-dev \
    locales \
    zip \
    jpegoptim optipng pngquant gifsicle \
    vim \
    unzip \
    git \
    curl \
    libzip-dev \
    dcmtk \
    nginx \
    supervisor \
    libpq-dev \
    geoip-database \
    libgeoip1 \
    fontconfig \
    xfonts-75dpi \
    xfonts-100dpi \
    xfonts-scalable \
    xfonts-base \
    libxrender1

# adjustments to php.ini base on the production version.
# application/wasm  wasm is missing from distro.

COPY php.ini /usr/local/etc/php/php.ini
COPY mime.types /etc/nginx/mime.types

# Install extensions and configure

RUN docker-php-ext-configure gd --with-freetype --with-jpeg
RUN docker-php-ext-configure zip
RUN docker-php-ext-install pdo_mysql zip exif pcntl gd sockets

# Install Postgre PDO

RUN docker-php-ext-configure pgsql -with-pgsql=/usr/local/pgsql
RUN docker-php-ext-install pdo pdo_pgsql pgsql

#  php.ini sort of takes care of these, but this is another option.
#  RUN sed -E -i -e 's/max_execution_time = 1200/max_execution_time = 120/' /etc/php.ini \
#  && sed -E -i -e 's/memory_limit = 128M/memory_limit = 512M/' /etc/php.ini \
#  && sed -E -i -e 's/post_max_size = 8M/post_max_size = 64M/' /etc/php.ini \
#  && sed -E -i -e 's/upload_max_filesize = 2M/upload_max_filesize = 64M/' /etc/php.ini

# Clear cache

RUN apt-get clean && rm -rf /var/lib/apt/lists/*

# Install Composer

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

COPY entrypoint.sh /
ENTRYPOINT ["/bin/bash","/entrypoint.sh"]

The error looks like it gets thrown here:

#36 34.46  cc -I. -I/usr/src/php/ext/sockets -I/usr/src/php/ext/sockets/include -I/usr/src/php/ext/sockets/main -I/usr/src/php/ext/sockets -I/usr/local/include/php -I/usr/local/include/php/main -I/usr/local/include/php/TSRM -I/usr/local/include/php/Zend -I/usr/local/include/php/ext -I/usr/local/include/php/ext/date/lib -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DHAVE_CONFIG_H -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -DZEND_ENABLE_STATIC_TSRMLS_CACHE=1 -c /usr/src/php/ext/sockets/sendrecvmsg.c  -fPIC -DPIC -o .libs/sendrecvmsg.o
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c: In function 'init_ancillary_registry':
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:128:19: error: invalid application of 'sizeof' to incomplete type 'struct cmsgcred'
#36 34.57   128 |  PUT_ENTRY(sizeof(struct cmsgcred), 0, 0, from_zval_write_ucred,
#36 34.57       |                   ^~~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:99:17: note: in definition of macro 'PUT_ENTRY'
#36 34.57    99 |  entry.size   = sizev; \
#36 34.57       |                 ^~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:129:36: error: 'SCM_CREDS' undeclared (first use in this function)
#36 34.57   129 |    to_zval_read_ucred, SOL_SOCKET, SCM_CREDS);
#36 34.57       |                                    ^~~~~~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:105:19: note: in definition of macro 'PUT_ENTRY'
#36 34.57   105 |  key.cmsg_type  = type; \
#36 34.57       |                   ^~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:129:36: note: each undeclared identifier is reported only once for each function it appears in
#36 34.57   129 |    to_zval_read_ucred, SOL_SOCKET, SCM_CREDS);
#36 34.57       |                                    ^~~~~~~~~
#36 34.57 /usr/src/php/ext/sockets/sendrecvmsg.c:105:19: note: in definition of macro 'PUT_ENTRY'
#36 34.57   105 |  key.cmsg_type  = type; \
#36 34.57       |                   ^~~~
#36 34.59 make: *** [Makefile:216: sendrecvmsg.lo] Error 1
------
failed to solve: rpc error: code = Unknown desc = executor failed running [/bin/sh -c docker-php-ext-install pdo_mysql zip exif pcntl gd sockets]: exit code: 2

Any suggestions regarding optimizing the build would also be appreciated.

I have another question about saving the built image to Docker Hub if I have an account to store private images.  e.g.  Below is a snippet from the docker-compose.yml file.  It isn't really clear to me if it is possible to bypass the build and just use a built image that I store on my Docker Hub account.  It seems like if I comment out the build line, then it will access the dockerhub image to build the container, but it isn't clear to me if some of the other commands in the DockerFile (i.e. entrypoint, composer install, etc.) are executed in that case.

My goal is to arrive at what I consider "stable" images and then make those available on DockerHub instead of having to build the image on a new machine everytime.  Also, probably going to run into some issues with an M1 Chip on a mac once I get one.

build: php-fpm-nginx  # comment out to use the built image
image: sdscotti/dockerhubimage
depends_on: [mysql_db]
restart: unless-stopped
ports: ["443:443"]
volumes:
  - xxx
extra_hosts:
  - xxx
environment:
  TARGETARCH:  "amd64"


问:
Refactor nested API calls with RxJS
Here's what I need to refactor:

Call API/GetUser, get result, extract user.id, save result (user)

Call API/GetMoreUserData/{userId} with id from first call, save result (moreData)

Construct object with both results {u: user, d: moreData } and return it to the caller

I'm currently using nested calls to accomplish this, but I'm sure there's a better way of doing it with RxJS.

答:
You can use pipe and switchMap, here is a random example:</p>
```<code>this.activatedRoute.params.pipe(                            //params returns an observable
      switchMap(({id}) => this.buyerService.getDetails(id)) //getDetails returns an observable
    )
    .subscribe(h => {
      console.log(h)
}
</code>```

Title: Refactor nested API calls with RxJS

Body:
You can use pipe and switchMap, here is a random example:

this.activatedRoute.params.pipe(                            //params returns an observable
      switchMap(({id}) => this.buyerService.getDetails(id)) //getDetails returns an observable
    )
    .subscribe(h => {
      console.log(h)
}


问:
How to add +9 hours on my jQuery script?
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

```<code>$end = mktime(16, 54, 0, 8, 18, 2011);
</code>```

and the copy it below

Countdown Script

```<code><script type="text/javascript">
var end_date = new Date(<?php echo $end; ?>*1000);

$(document).ready(function() {
    $("#time").countdown({
        date: end_date,
        onComplete: function( event ){
            $(this).html("completed");
        },
        leadingZero: true
    });
});
</script>

<p id="time" class="time"></p>
</code>```

答:
I'm going to read between the lines here a bit. I assume based on this and previous questions that you want a countdown for some event in the future and you're pulling a timestamp from a database and adding 9 hours to it to get the time of that future event.

Assuming this, you can't use most (any?) of the previous answers because of time zones and the fact that the user's clock might be more or less off. So if you calculate on the server that the event should fire at 5 o'clock and send that info to the user who's 3 time zones away from the server, the countdown will also be 3 hours off (because when it's 5 o'clock where the user is it's either 2 or 8 o'clock where the server is.)

The solution is to calculate the time left until the event and send that information to the browser. This way the countdown will be independent of the user's timezone or their computer's clock. For example if the event is at 5 o'clock and it's now 4 o'clock tell the browser to put 60*60*1=3600 seconds on the timer.

Using part of Christian's answer, do something like this on the server (assuming $db_time contains a Unix timestamp retrieved from the database):

```<code>$date = strtotime('+9 hours', (int)$db_time);
$timeUntilEvent = $date - time();
</code>```

Now $timeUntilEvent contains the amount of seconds until the event. In JavaScript add that number to the timer:

```<code>var end_date = new Date();
end_date.setTime( end_date.getTime() + <?php echo $timeUntilEvent; ?> * 1000 );
</code>```

Now the timer will fire at the correct time regardless of what time the user's clock is set to.

Body:
How can I add +9 hours on my script below ? I don't prefer to just add 9 hours to the correct time, for example if I want it 13:22:54 to make it 22:22:54 for this to work but on the script.

I create the unix timestamp in a php file doing

$end = mktime(16, 54, 0, 8, 18, 2011);

and the copy it below

Countdown Script

Body:
I'm going to read between the lines here a bit. I assume based on this and previous questions that you want a countdown for some event in the future and you're pulling a timestamp from a database and adding 9 hours to it to get the time of that future event.

Assuming this, you can't use most (any?) of the previous answers because of time zones and the fact that the user's clock might be more or less off. So if you calculate on the server that the event should fire at 5 o'clock and send that info to the user who's 3 time zones away from the server, the countdown will also be 3 hours off (because when it's 5 o'clock where the user is it's either 2 or 8 o'clock where the server is.)

The solution is to calculate the time left until the event and send that information to the browser. This way the countdown will be independent of the user's timezone or their computer's clock. For example if the event is at 5 o'clock and it's now 4 o'clock tell the browser to put 60*60*1=3600 seconds on the timer.

Using part of Christian's answer, do something like this on the server (assuming $db_time contains a Unix timestamp retrieved from the database):

$date = strtotime('+9 hours', (int)$db_time);
$timeUntilEvent = $date - time();

Now $timeUntilEvent contains the amount of seconds until the event. In JavaScript add that number to the timer:

var end_date = new Date();
end_date.setTime( end_date.getTime() + <?php echo $timeUntilEvent; ?> * 1000 );

Now the timer will fire at the correct time regardless of what time the user's clock is set to.


问:
Change the text with specific checkbox is clicked
I have an array of object. I want to change the text to available when checkbox is clicked and unavailable when checkbox is not clicked. The problem I am facing is when I select one item, it changes all the text to the available. How can I change the particular item text that is checked?</p>
```<code>import "./styles.css";
import React, { useState } from "react";

const weekSchedule = [
   { day: "Sun", id: 0 },
   { day: "Mon", id: 2 }
];

export default function App() {
   const [checkbox, setCheckbox] = useState(false);

   const handleClick = (e) => {
       setCheckbox(!checkbox);
   };
   return (
      <div className="App">
         {weekSchedule.map((day, i) => (
            <div
               key={i}
               style={{
                  display: "flex",
                  flexDirection: "row",
                  justifyContent: "center",
                  alignItems: "center"
               }}
            >
                <input type="checkbox" checkbox={checkbox} onClick={handleClick} />
                <h1>{day.day}</h1>`**enter code here**`
                <h2>{checkbox ? "Available" : "Unavailable"}</h2>
            </div>
          ))}
       </div>
    );
}
</code>```

答:
You have only one state for checkbox. You're mapping all the elements in weekSchedule to one checkbox. If you want them to be separate, you need to keep track of them separately.

```<code>import "./styles.css";
import React, { useState } from "react";

export default function App() {
   const [weekSchedule, setWeekSchedule] = useState([
    { day: "Sun", id: 0, checked: false },
    { day: "Mon", id: 2, checked: false}
 ]);

   const handleClick = (e,id) => {
     let newWeeklySchedArray = [...weekSchedule]
     newWeeklySchedArray[id].checked = !e.target.checked;
     setWeekSchedule(newWeeklySchedArray)
   };
   return (
      <div className="App">
         {weekSchedule.map((day, i) => (
            <div
               key={i}
               style={{
                  display: "flex",
                  flexDirection: "row",
                  justifyContent: "center",
                  alignItems: "center"
               }}
            >
                <input type="checkbox" onChange={(e)=>{handleClick(e,i)}} />
                <h1>{day.day}</h1>`**enter code here**`
                <h2>{!weekSchedule[i].checked ? "Available" : "Unavailable"}</h2>
            </div>
          ))}
       </div>
    );
}

</code>```

Here's a link for the demo above :)

https://codesandbox.io/s/nostalgic-jones-u11ux?file=/src/App.js

Body:
I have an array of object. I want to change the text to available when checkbox is clicked and unavailable when checkbox is not clicked. The problem I am facing is when I select one item, it changes all the text to the available. How can I change the particular item text that is checked?

import "./styles.css";
import React, { useState } from "react";

const weekSchedule = [
   { day: "Sun", id: 0 },
   { day: "Mon", id: 2 }
];

export default function App() {
   const [checkbox, setCheckbox] = useState(false);

   const handleClick = (e) => {
       setCheckbox(!checkbox);
   };
   return (

         {weekSchedule.map((day, i) => (

                <input type="checkbox" checkbox={checkbox} onClick={handleClick} />

{day.day}
`**enter code here**`

{checkbox ? "Available" : "Unavailable"}

          ))}

    );
}

Body:
You have only one state for checkbox. You're mapping all the elements in weekSchedule to one checkbox. If you want them to be separate, you need to keep track of them separately.

import "./styles.css";
import React, { useState } from "react";

export default function App() {
   const [weekSchedule, setWeekSchedule] = useState([
    { day: "Sun", id: 0, checked: false },
    { day: "Mon", id: 2, checked: false}
 ]);

   const handleClick = (e,id) => {
     let newWeeklySchedArray = [...weekSchedule]
     newWeeklySchedArray[id].checked = !e.target.checked;
     setWeekSchedule(newWeeklySchedArray)
   };
   return (
      <div className="App">
         {weekSchedule.map((day, i) => (
            <div
               key={i}
               style={{
                  display: "flex",
                  flexDirection: "row",
                  justifyContent: "center",
                  alignItems: "center"
               }}
            >
                <input type="checkbox" onChange={(e)=>{handleClick(e,i)}} />
                <h1>{day.day}</h1>`**enter code here**`
                <h2>{!weekSchedule[i].checked ? "Available" : "Unavailable"}</h2>
            </div>
          ))}
       </div>
    );
}

Here's a link for the demo above :)

https://codesandbox.io/s/nostalgic-jones-u11ux?file=/src/App.js


问:
Why is my MariaDB query not working on host but works locally?
This is my code that works fine locally, but not on Namecheap host:

```<code>//data connection pool
const pool = require('../models/database');
const bcrypt = require('bcrypt');

module.exports = async (req, res) => {
    try {
        const {user_name, password, email} = req.body;
        const hashedPassword = await bcrypt.hash(password, 10);
        console.log(hashedPassword);

        let sql = `INSERT INTO userdb (user_name, password, email)
        SELECT ?, ?, ?
        WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?);
        SHOW WARNINGS;`;

        let result = await pool.query(sql, [user_name, hashedPassword, email, email, user_name]);

        console.log(result);
        console.log("the id: ", result[0].insertId);
        res.status(200).send("Success Comrad!");

        } catch (error) {
        res.status(400).send(error.message);
    }

}//module.export end
</code>```

These are my dependencies:

```<code>"dependencies": {
    "bcrypt": "^5.0.1",
    "dotenv": "^16.0.0",
    "express": "^4.17.2",
    "mariadb": "^2.5.5",
    "pug": "^3.0.2"
  }
</code>```

This is the error I'm getting:

```<code>(conn=1698954, no: 1064, SQLState: 42000) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = 'dookie@gmail.com' OR us...' at line 3 sql: INSERT INTO userdb (user_name, password, email) SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?); SHOW WARNINGS; - parameters:['dookie','$2b$10$OQp5lovlqmMfKNQtuvBK9e7t4rX39nVW22XdhzDZqBnSgDKv6G0ky','d...]
</code>```

I also do have this set: multipleStatements: true
Any ideas why this may be?

答:
Are you sure this works locally ? Maybe to forgot some part of it

Your SELECT needs a FROM to work.

SELECT ?, ?, ?
WHERE NOT EXISTS (/* removed */);
```

To answer to your second question, multipleStatements: true allow you to pass multiple queries at once. Here you ask to insert some data and to show possible warnings on it.

Body:
This is my code that works fine locally, but not on Namecheap host:

//data connection pool
const pool = require('../models/database');
const bcrypt = require('bcrypt');

module.exports = async (req, res) => {
    try {
        const {user_name, password, email} = req.body;
        const hashedPassword = await bcrypt.hash(password, 10);
        console.log(hashedPassword);

        let sql = `INSERT INTO userdb (user_name, password, email)
        SELECT ?, ?, ?
        WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?);
        SHOW WARNINGS;`;

        let result = await pool.query(sql, [user_name, hashedPassword, email, email, user_name]);

        console.log(result);
        console.log("the id: ", result[0].insertId);
        res.status(200).send("Success Comrad!");

        } catch (error) {
        res.status(400).send(error.message);
    }

}//module.export end

These are my dependencies:

"dependencies": {
    "bcrypt": "^5.0.1",
    "dotenv": "^16.0.0",
    "express": "^4.17.2",
    "mariadb": "^2.5.5",
    "pug": "^3.0.2"
  }

This is the error I'm getting:

(conn=1698954, no: 1064, SQLState: 42000) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = 'dookie@gmail.com' OR us...' at line 3 sql: INSERT INTO userdb (user_name, password, email) SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?); SHOW WARNINGS; - parameters:['dookie','$2b$10$OQp5lovlqmMfKNQtuvBK9e7t4rX39nVW22XdhzDZqBnSgDKv6G0ky','d...]

I also do have this set: multipleStatements: true
Any ideas why this may be?

Body:
Are you sure this works locally ? Maybe to forgot some part of it

Your SELECT needs a FROM to work.

SELECT ?, ?, ?
WHERE NOT EXISTS (/* removed */);

To answer to your second question, multipleStatements: true allow you to pass multiple queries at once. Here you ask to insert some data and to show possible warnings on it.


问:
Find the Duplicate Number
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

My solution:

```<code>def findDuplicate(nums):
    slow = fast = finder = 0
    while fast is not None:

        slow = nums[slow]
        fast = nums[nums[fast]]

        if fast is slow:
            return slow

   return False

nums = [1,2,2,3,4]
print findDuplicate(nums)
</code>```

My above solution works and gives me o/p 2 but it doesn't work for every input for example it doesn't work for [11,15,17,17,14] or [3,1,2,6,2,3] and gives me error IndexError: list index out of range. I am not able to find patterns and am not able to track down the exact problem. Also tried to change my while condition:

```<code>while fast is not None and nums[nums[fast]] is not None:
</code>```

your help will be greatly appreciated! Thank you.

答:
The answer is unfinished. It tries to convert the array to a linked list. So far it found where the slow pointer and fast pointer met, but this is the halfway solution. To get the solution, we need to initialize another pointer from the beginning of the linked list and walk towards each other. When they meet, that point is the where cycle is detected, in our question it is where the single point is:</p>
```<code>class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        slow,fast=0,0
        while True:
            slow=nums[slow]
            fast=nums[nums[fast]]
            if slow==fast:
                break
        slow2=0
        while True:
            slow2=nums[slow2]
            slow=nums[slow]
            if slow==slow2:
                return slow2
</code>```

Title: Find the Duplicate Number

Body:
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

My solution:

def findDuplicate(nums):
    slow = fast = finder = 0
    while fast is not None:

        slow = nums[slow]
        fast = nums[nums[fast]]

        if fast is slow:
            return slow

   return False

nums = [1,2,2,3,4]
print findDuplicate(nums)

My above solution works and gives me o/p 2 but it doesn't work for every input for example it doesn't work for [11,15,17,17,14] or [3,1,2,6,2,3] and gives me error IndexError: list index out of range. I am not able to find patterns and am not able to track down the exact problem. Also tried to change my while condition:

while fast is not None and nums[nums[fast]] is not None:

your help will be greatly appreciated! Thank you.

Body:
The answer is unfinished. It tries to convert the array to a linked list. So far it found where the slow pointer and fast pointer met, but this is the halfway solution. To get the solution, we need to initialize another pointer from the beginning of the linked list and walk towards each other. When they meet, that point is the where cycle is detected, in our question it is where the single point is:

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        slow,fast=0,0
        while True:
            slow=nums[slow]
            fast=nums[nums[fast]]
            if slow==fast:
                break
        slow2=0
        while True:
            slow2=nums[slow2]
            slow=nums[slow]
            if slow==slow2:
                return slow2


答:
This is what switchMap is for.

```<code>@Injectable({ providedIn: 'root' })
export class UserService {
  getUser(): Observable<any> {
    //mock implementation, probably would be an HTTP get
    return of({ id: 42 });
  }

  getMoreUserData(id: number): Observable<any> {
    //mock implementation, probably would be an HTTP get
    return of({ username: 'batman', id: id });
  }

  getAllTheUserData(): Observable<any> {
    return this.getUser().pipe(
      switchMap((userResp) => {
        const userId = userResp.id;

        return this.getMoreUserData(userId).pipe(
          map((moreUserResp) => {
            //spread operator to combine to two objects
            return {
              ...userResp,
              ...moreUserResp,
            };
          })
        );
      })
    );
  }
}
</code>```

Here's a stackblitz demonstrating the service and it's usage.

Title: Refactor nested API calls with RxJS

Body:
Here's what I need to refactor:

Call API/GetUser, get result, extract user.id, save result (user)

Call API/GetMoreUserData/{userId} with id from first call, save result (moreData)

Construct object with both results {u: user, d: moreData } and return it to the caller

I'm currently using nested calls to accomplish this, but I'm sure there's a better way of doing it with RxJS.

Body:
This is what switchMap is for.

@Injectable({ providedIn: 'root' })
export class UserService {
  getUser(): Observable<any> {
    //mock implementation, probably would be an HTTP get
    return of({ id: 42 });
  }

  getMoreUserData(id: number): Observable<any> {
    //mock implementation, probably would be an HTTP get
    return of({ username: 'batman', id: id });
  }

  getAllTheUserData(): Observable<any> {
    return this.getUser().pipe(
      switchMap((userResp) => {
        const userId = userResp.id;

        return this.getMoreUserData(userId).pipe(
          map((moreUserResp) => {
            //spread operator to combine to two objects
            return {
              ...userResp,
              ...moreUserResp,
            };
          })
        );
      })
    );
  }
}

Here's a stackblitz demonstrating the service and it's usage.


问:
Switch from PHP to Java or .Net
I currently run a website on LAMP, I am currently in the process of refactoring my code from normal php to Zend framework with Doctrine. I am happy with setup but often find function not found errors on live site cause I have renamed function. Which is frustrating as most of time is wasted is patching these errors.
So I have decided to switch from php to java as the code gets compiled, so just error will not go to live site. With java netbeans will work better.

But as I have not been in touch to j2ee for many years. What is the best replacement for my above setup in java?

Option 1. Jsf 2 with Hibernate

Option 2. Seam

Option 3. Spring

Option 4. Struts with Hibernate

My server has 24 gig ram and 2 core i7 processor and ssd drive on raid 0

Will my server handle the same amount of visitors if java was used without any performance issues?

I like the way I can update my site without losing live sessions(logged-in users). Can I do the same in Java? from my experience each update to site will redeploy the App which resets all the Active Sessions.

I love to consider .Net but from what I have read on most forums, no one recommends it?

Kind regards

Zerone

答:
Java will perform better, but switching to Java seems like overkill for this situation. That said, I would recommend something based on Spring and Hibernate. Spring can be a real godsend for configuring just about anything in Java and Hibernate is similar to Doctrine.

Apache Tapestry would make a good presentation toolkit for your site. It's a great templating library that is cleaner than JSP.

Title: Switch from PHP to Java or .Net


答:
You would want to make the checkboxes controlled components: https://reactjs.org/docs/forms.html#controlled-components. Then we can use the index from the map to target changes in state.</p>
```<code>import "./styles.css";
import React, { useState } from "react";

const weekSchedule = [
   { day: "Sun", id: 0, checked:false },
   { day: "Mon", id: 2, checked:false }
];

export default function App() {
   const [checkbox, setCheckbox] = useState(weekSchedule);

   const handleClick = (e,i) => {
    const newWeekSchedule = [...checkbox];
    newWeekSchedule[i].checked = !newWeekSchedule[i].checked;
    setCheckbox(newWeekSchedule);
   };
   return (
      <div className="App">
         {checkbox.map((day, i) => (
            <div
               key={i}
               style={{
                  display: "flex",
                  flexDirection: "row",
                  justifyContent: "center",
                  alignItems: "center"
               }}
            >
                <input value={checkbox[i].checked} type="checkbox" checkbox={checkbox} onClick={(e)=> handleClick(e,i)} />
                <h1>{day.day}</h1>`**enter code here**`
                <h2>{day.checked ? "Available" : "Unavailable"}</h2>
            </div>
          ))}
       </div>
    );
}
</code>```

Title: Change the text with specific checkbox is clicked

Body:
You would want to make the checkboxes controlled components: https://reactjs.org/docs/forms.html#controlled-components. Then we can use the index from the map to target changes in state.

import "./styles.css";
import React, { useState } from "react";

const weekSchedule = [
   { day: "Sun", id: 0, checked:false },
   { day: "Mon", id: 2, checked:false }
];

export default function App() {
   const [checkbox, setCheckbox] = useState(weekSchedule);

   const handleClick = (e,i) => {
    const newWeekSchedule = [...checkbox];
    newWeekSchedule[i].checked = !newWeekSchedule[i].checked;
    setCheckbox(newWeekSchedule);
   };
   return (
      <div className="App">
         {checkbox.map((day, i) => (
            <div
               key={i}
               style={{
                  display: "flex",
                  flexDirection: "row",
                  justifyContent: "center",
                  alignItems: "center"
               }}
            >
                <input value={checkbox[i].checked} type="checkbox" checkbox={checkbox} onClick={(e)=> handleClick(e,i)} />
                <h1>{day.day}</h1>`**enter code here**`
                <h2>{day.checked ? "Available" : "Unavailable"}</h2>
            </div>
          ))}
       </div>
    );
}


问:
SQL Server Transactional Replication - Can propagation of schema changes and data changes be controlled?
In transaction replication, if schema changes happen first and then the data changes, will it happen the same way in subscriber as well?

If no, is there a way to control the order?

答:
If schema changes happen first and then the data changes, will it happen the same way in subscriber as well?

Yes - replication keeps track of what needs to be done via reading the transaction log and replaying those transactions in LSN order to subscribers. You shouldn't have to worry about out-of-order operations in general.


问:
BeautifulSoup Isn't Producing A Result
I'm trying to web scrape a site that gives play by plays live. In this example though, the game is over but I still want to scrape the play by play. But when I use the code below, I'm unable to produce any results. The url variable is the real link to the site.

```<code>import requests
import re
import json
from bs4 import BeautifulSoup

url = "http://pointstreak.com/baseball/gamelive/?gameid=483832"
r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')
game = soup.findAll('tr',class_ = "inning_1 pbp-bottom-border")

print(game)
</code>```

My result is []

Can anyone help guide me in the right direction so I can grab the data inside the tag. On a side note, I am new to this so I may be making a rookie mistake

答:
Comments are correct, the content is sourced from another URL entirely.  You can view the source code for the page by adding the prefix view-source:http://pointstreak.com/baseball/gamelive/?gameid=483832.  You can see that the game is actually sourced from http://baseball.pointstreak.com/scoreboard.html?leagueid=120.  Plugging that into your request, you can get to the content, but you may need to add headers to your request (basically posing as a browser instead of a naked request from your ip address).  Something like this would get you the ability to parse the soup and get meaningful content:

```<code>import requests
from bs4 import BeautifulSoup

headers = requests.utils.default_headers()
headers.update({
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',
})
url = 'http://baseball.pointstreak.com/scoreboard.html?leagueid=120'
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html')
</code>```

Title: BeautifulSoup Isn't Producing A Result

Body:
I'm trying to web scrape a site that gives play by plays live. In this example though, the game is over but I still want to scrape the play by play. But when I use the code below, I'm unable to produce any results. The url variable is the real link to the site.

import requests
import re
import json
from bs4 import BeautifulSoup

url = "http://pointstreak.com/baseball/gamelive/?gameid=483832"
r = requests.get(url)
soup = BeautifulSoup(r.content,'html.parser')
game = soup.findAll('tr',class_ = "inning_1 pbp-bottom-border")

print(game)

My result is []

Can anyone help guide me in the right direction so I can grab the data inside the tag. On a side note, I am new to this so I may be making a rookie mistake

Body:
Comments are correct, the content is sourced from another URL entirely.  You can view the source code for the page by adding the prefix view-source:http://pointstreak.com/baseball/gamelive/?gameid=483832.  You can see that the game is actually sourced from http://baseball.pointstreak.com/scoreboard.html?leagueid=120.  Plugging that into your request, you can get to the content, but you may need to add headers to your request (basically posing as a browser instead of a naked request from your ip address).  Something like this would get you the ability to parse the soup and get meaningful content:

import requests
from bs4 import BeautifulSoup

headers = requests.utils.default_headers()
headers.update({
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0',
})
url = 'http://baseball.pointstreak.com/scoreboard.html?leagueid=120'
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html')


问:
What DB to use for a windows application?
I am developing a small windows application in .net. What DB should I use?

DB Structure

Table 1 : Not more than 3 fields : 50+ records (Add, Delete)

Table 2 : Not more than 10 fields : 10-20 records (Add, Delete)

I thought of using XMLDatabase but some say its not advisable to use it. What are the reasons for this?
If it is OK to use XML files as the DB then can you suggest some tutorials or best practices? I have worked with XML files before. Is there anything different when it comes to using it as a DB?

I am also planning to distribute the application to my friends some time later and these guys are not programmers and they are less tech savvy.

So If I am using SQL server how can I deploy it in others machine? How can I add it to the setup file?

Update: Thanks for the answers. I am going for SQLite and here is a tutorial about SQLite and .net if someone is interested.

答:
I agree with XML as the data source solution. There's a good XML book: No Nonsense XML Development with PHP. You can easily translate the PHP into ASP.NET. There's also free e-books around for XML and ASP.NET.

The advantages XML gives you is that it's a simple data-transfer language and you won't need a third party database server to install on machines you deploy to.

OwnerDisplayName: Shoban

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Shoban

OwnerDisplayName: Mohammad Ashour


问:
Improving a List Comprehension
The list comprehension below achieves the desired result/output:

Each tuple in the list is indexed sequentially

The names are grouped together by suit

The names are in a consistent order

Code (deck of cards toy example):

```<code>Suits = ["Hearts"]*3 +["Diamonds"]*3
Names = ["Two","Ten","King"]

z = [(i,Names[(i-1)%3],Suits[((i-1)%6)]) for i in range(1,7)]
</code>```

Output z:

```<code>[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]
</code>```

It works because the original Suits list was changed from ["Hearts","Diamonds"] to["Hearts"]*3 +["Diamonds"]*3.

This feels contrived; although it works, I'm looking for a better solution.

答:
Using enumerate and itertools.product:

from itertools import product

ranks = ["Two", "Ten", "King"]
suits = ["Hearts", "Diamonds"]
z = [(i, r, s) for i, (s, r) in enumerate(product(suits, ranks), start=1)]
```
<p>Output:</p>
<pre class="lang-py prettyprint-override"><code>[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]
</code>```

Title: Improving a List Comprehension

Body:
The list comprehension below achieves the desired result/output:

Each tuple in the list is indexed sequentially

The names are grouped together by suit

The names are in a consistent order

Code (deck of cards toy example):

Suits = ["Hearts"]*3 +["Diamonds"]*3
Names = ["Two","Ten","King"]

z = [(i,Names[(i-1)%3],Suits[((i-1)%6)]) for i in range(1,7)]

Output z:

[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]

It works because the original Suits list was changed from ["Hearts","Diamonds"] to["Hearts"]*3 +["Diamonds"]*3.

This feels contrived; although it works, I'm looking for a better solution.

Body:
Using enumerate and itertools.product:

from itertools import product

ranks = ["Two", "Ten", "King"]
suits = ["Hearts", "Diamonds"]
z = [(i, r, s) for i, (s, r) in enumerate(product(suits, ranks), start=1)]

Output:

[(1, 'Two', 'Hearts'),
 (2, 'Ten', 'Hearts'),
 (3, 'King', 'Hearts'),
 (4, 'Two', 'Diamonds'),
 (5, 'Ten', 'Diamonds'),
 (6, 'King', 'Diamonds')]