问:
Rshiny : displaying chart when clicking on a polygon
I'm a Rshiny newbie very eager to learn but right now I'm facing an issue I cannot overcome alone and I would greatly appreciate if someone could help me out ! :)

My problem is (I guess) quite simple:

I have created a map with my polygons and I've managed to display some basic informations when I click on them (have a look on here) but I have no idea how to add a barplot (for example) below my map for each polygon I click.

Could someone help me on how doing that please ? (after hours and hours of attempts my eyesballs are really about to pop out of their sockets !!!)

Many thanks in advance !

Romain

My code:

```<code>library(shiny)
library(leaflet)
library(dplyr)
library(magrittr)
library(devtools)
library(RColorBrewer)
library(rgdal)
library(sp)

communes <- readOGR("G:/Ateliers/Projet/communes.shp")
commmunes@data

nom_commune                 INSEE  Variable_1   Variable_2  Variable_3 area_sqkm
1    AUZEVILLE-TOLOSANE     31035         289     8.727212    9.336384  6.979758
2      CASTANET-TOLOSAN     31113          85     4.384877    8.891650  8.460724
3                LABEGE     31254         288     5.047406    2.031651  7.663404
4            PECHBUSQUE     31411         443     6.577743    8.120896  3.099422
5 RAMONVILLE-SAINT-AGNE     31446          95     2.601305    8.909278  6.236784
>

ui <- fluidPage(
  leafletOutput("mymap"))

  #### SERVEUR R #####

  bins <- c(3,3.5,6,6.5,7,7.5,8,8.5)
  pal <- colorBin("YlOrRd", domain = communes$area_sqkm, bins = bins)
  labels <- sprintf(
    "<strong>%s</strong><br/>%g km2",
    communes$nom_commun, communes$area_sqkm
  ) %>% lapply(htmltools::HTML)

server <- function(input, output, session) {
  output$mymap<-renderLeaflet(
    leaflet(communes) %>%
      addProviderTiles(providers$Stamen.TonerLite,
                       options = providerTileOptions(noWrap = TRUE)
      ) %>%
      setView(1.50, 43.54, zoom = 12) %>%
      addTiles()  %>%
      addPolygons(fillColor = ~pal(area_sqkm),
                  weight = 2,
                  opacity = 1,
                  color = "white",
                  dashArray = "3",
                  fillOpacity = 0.7,
                  highlight = highlightOptions(
                    weight = 5,
                    color = "#666",
                    dashArray = "",
                    fillOpacity = 0.7,
                    bringToFront = TRUE),
                  label = labels,
                  labelOptions = labelOptions(
                    style = list("font-weight" = "normal", padding = "3px 8px"),
                    textsize = "15px",
                    direction = "auto")) %>%
      addLegend(pal = pal, values = ~area_sqkm, opacity = 0.7, title = NULL,
                position = "bottomright")
  )
}

shinyApp(ui = ui, server=server)
</code>```

The data I would like to display in my barplots are the variable 1,2 and 3 :

```<code>data <- read.csv("G:/Ateliers/Projet/communes.csv", sep=";")
data

nom_commune                 INSEE  Variable_1   Variable_2  Variable_3 area_sqkm
1    AUZEVILLE-TOLOSANE     31035         289     8.727212    9.336384  6.979758
2      CASTANET-TOLOSAN     31113          85     4.384877    8.891650  8.460724
3                LABEGE     31254         288     5.047406    2.031651  7.663404
4            PECHBUSQUE     31411         443     6.577743    8.120896  3.099422
5 RAMONVILLE-SAINT-AGNE     31446          95     2.601305    8.909278  6.236784
>
</code>```

答:
Here is an example shiny app with other data, since I do not have access to your shape data for the map. I believe this might do what you need it to do and can be adapted for your needs.

I would create a reactiveVal to store the id of the polygon region that is clicked on (this variable stores input$mymap_shape_click$id). You data used in addPolygons should have an id to reference.

In your plot (or in a separate reactive expression), you can filter the data based on the reactiveVal containing the id.

```<code>library(shiny)
library(leaflet)
library(rgdal)
library(sf)
library(ggplot2)
library(tidyverse)

arcgis_data = st_read("http://data.phl.opendata.arcgis.com/datasets/bc2b2e8e356742568e43b0128c344d03_0.geojson")

arcgis_data$id <- 1:nrow(arcgis_data)  ## Add an 'id' value to each shape

plot_data <- read.table(text =
"id nom_commune                 INSEE  Variable_1   Variable_2  Variable_3 area_sqkm
1    AUZEVILLE-TOLOSANE     31035         289     8.727212    9.336384  6.979758
2      CASTANET-TOLOSAN     31113          85     4.384877    8.891650  8.460724
3                LABEGE     31254         288     5.047406    2.031651  7.663404
4            PECHBUSQUE     31411         443     6.577743    8.120896  3.099422
5 RAMONVILLE-SAINT-AGNE     31446          95     2.601305    8.909278  6.236784", header = T, stringsAsFactors = F
)

ui <- fluidPage(
  leafletOutput(outputId = "mymap"),
  plotOutput(outputId = "myplot")
)

server <- function(input, output){

  ## use reactive value to store the id from observing the shape click
  rv <- reactiveVal()

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addPolygons(data = arcgis_data %>% slice(1:5), layerId = ~id) %>%
      addProviderTiles("CartoDB.Positron")
  })

  observeEvent(input$mymap_shape_click, {
    rv(input$mymap_shape_click$id)
  })

  ## you can now plot your plot based on the id of region selected
  output$myplot <- renderPlot({
    plot_data %>%
      filter(id == rv()) %>%
      pivot_longer(cols = starts_with("Variable"), names_to = "Variable", values_to = "Value") %>%
      ggplot(aes(x = Variable, y = Value)) +
        geom_col()
  })

}

shinyApp(ui, server)
</code>```

Edit: For your uploaded data, you don't need to add a separate id for communes. Instead, you could match by name (nom_commune). You can use that in your layerId instead. This looks like it should work. I did take out some of the additional label information as this appeared to be missing from the .shp file I downloaded.

```<code>library(shiny)
library(leaflet)
library(rgdal)
library(sf)
library(ggplot2)
library(tidyverse)

communes <- readOGR("communes_ok.shp")

ui <- fluidPage(
  leafletOutput(outputId = "mymap"),
  plotOutput(outputId = "myplot")
)

server <- function(input, output){

  ## use reactive values to store the id from observing the shape click
  rv <- reactiveVal()

  output$mymap<-renderLeaflet(
    leaflet(communes) %>%
      addProviderTiles(providers$Stamen.TonerLite,
                       options = providerTileOptions(noWrap = TRUE)) %>%
      setView(1.50, 43.54, zoom = 12) %>%
      addTiles()  %>%
      addPolygons(fillColor = "blue",
                  weight = 2,
                  opacity = 1,
                  color = "white",
                  dashArray = "3",
                  fillOpacity = 0.3,
                  highlight = highlightOptions(
                    weight = 5,
                    color = "#666",
                    dashArray = "",
                    fillOpacity = 0.7,
                    bringToFront = TRUE),
                  layerId = ~nm_cmmn)
  )

  observeEvent(input$mymap_shape_click, {
    rv(input$mymap_shape_click$id)
  })

  ## you can now 'output' your generated data however you want
  output$myplot <- renderPlot({
    if (is.null(rv())) return (NULL)
    plot_data %>%
      filter(nom_commune == rv()) %>%
      pivot_longer(cols = starts_with("Variable"), names_to = "Variable", values_to = "Value") %>%
      ggplot(aes(x = Variable, y = Value)) +
        geom_col()
  })

}

shinyApp(ui, server)
</code>```

Body:
I'm a Rshiny newbie very eager to learn but right now I'm facing an issue I cannot overcome alone and I would greatly appreciate if someone could help me out ! :)

My problem is (I guess) quite simple:

I have created a map with my polygons and I've managed to display some basic informations when I click on them (have a look on here) but I have no idea how to add a barplot (for example) below my map for each polygon I click.

Could someone help me on how doing that please ? (after hours and hours of attempts my eyesballs are really about to pop out of their sockets !!!)

Many thanks in advance !

Romain

My code:

library(shiny)
library(leaflet)
library(dplyr)
library(magrittr)
library(devtools)
library(RColorBrewer)
library(rgdal)
library(sp)

communes <- readOGR("G:/Ateliers/Projet/communes.shp")
commmunes@data

nom_commune                 INSEE  Variable_1   Variable_2  Variable_3 area_sqkm
1    AUZEVILLE-TOLOSANE     31035         289     8.727212    9.336384  6.979758
2      CASTANET-TOLOSAN     31113          85     4.384877    8.891650  8.460724
3                LABEGE     31254         288     5.047406    2.031651  7.663404
4            PECHBUSQUE     31411         443     6.577743    8.120896  3.099422
5 RAMONVILLE-SAINT-AGNE     31446          95     2.601305    8.909278  6.236784
>

ui <- fluidPage(
  leafletOutput("mymap"))

  #### SERVEUR R #####

  bins <- c(3,3.5,6,6.5,7,7.5,8,8.5)
  pal <- colorBin("YlOrRd", domain = communes$area_sqkm, bins = bins)
  labels <- sprintf(
    "%s
%g km2",
    communes$nom_commun, communes$area_sqkm
  ) %>% lapply(htmltools::HTML)

server <- function(input, output, session) {
  output$mymap<-renderLeaflet(
    leaflet(communes) %>%
      addProviderTiles(providers$Stamen.TonerLite,
                       options = providerTileOptions(noWrap = TRUE)
      ) %>%
      setView(1.50, 43.54, zoom = 12) %>%
      addTiles()  %>%
      addPolygons(fillColor = ~pal(area_sqkm),
                  weight = 2,
                  opacity = 1,
                  color = "white",
                  dashArray = "3",
                  fillOpacity = 0.7,
                  highlight = highlightOptions(
                    weight = 5,
                    color = "#666",
                    dashArray = "",
                    fillOpacity = 0.7,
                    bringToFront = TRUE),
                  label = labels,
                  labelOptions = labelOptions(
                    style = list("font-weight" = "normal", padding = "3px 8px"),
                    textsize = "15px",
                    direction = "auto")) %>%
      addLegend(pal = pal, values = ~area_sqkm, opacity = 0.7, title = NULL,
                position = "bottomright")
  )
}

shinyApp(ui = ui, server=server)

The data I would like to display in my barplots are the variable 1,2 and 3 :

data <- read.csv("G:/Ateliers/Projet/communes.csv", sep=";")
data

nom_commune                 INSEE  Variable_1   Variable_2  Variable_3 area_sqkm
1    AUZEVILLE-TOLOSANE     31035         289     8.727212    9.336384  6.979758
2      CASTANET-TOLOSAN     31113          85     4.384877    8.891650  8.460724
3                LABEGE     31254         288     5.047406    2.031651  7.663404
4            PECHBUSQUE     31411         443     6.577743    8.120896  3.099422
5 RAMONVILLE-SAINT-AGNE     31446          95     2.601305    8.909278  6.236784
>

Body:
Here is an example shiny app with other data, since I do not have access to your shape data for the map. I believe this might do what you need it to do and can be adapted for your needs.

I would create a reactiveVal to store the id of the polygon region that is clicked on (this variable stores input$mymap_shape_click$id). You data used in addPolygons should have an id to reference.

In your plot (or in a separate reactive expression), you can filter the data based on the reactiveVal containing the id.

library(shiny)
library(leaflet)
library(rgdal)
library(sf)
library(ggplot2)
library(tidyverse)

arcgis_data = st_read("http://data.phl.opendata.arcgis.com/datasets/bc2b2e8e356742568e43b0128c344d03_0.geojson")

arcgis_data$id <- 1:nrow(arcgis_data)  ## Add an 'id' value to each shape

plot_data <- read.table(text =
"id nom_commune                 INSEE  Variable_1   Variable_2  Variable_3 area_sqkm
1    AUZEVILLE-TOLOSANE     31035         289     8.727212    9.336384  6.979758
2      CASTANET-TOLOSAN     31113          85     4.384877    8.891650  8.460724
3                LABEGE     31254         288     5.047406    2.031651  7.663404
4            PECHBUSQUE     31411         443     6.577743    8.120896  3.099422
5 RAMONVILLE-SAINT-AGNE     31446          95     2.601305    8.909278  6.236784", header = T, stringsAsFactors = F
)

ui <- fluidPage(
  leafletOutput(outputId = "mymap"),
  plotOutput(outputId = "myplot")
)

server <- function(input, output){

  ## use reactive value to store the id from observing the shape click
  rv <- reactiveVal()

  output$mymap <- renderLeaflet({
    leaflet() %>%
      addPolygons(data = arcgis_data %>% slice(1:5), layerId = ~id) %>%
      addProviderTiles("CartoDB.Positron")
  })

  observeEvent(input$mymap_shape_click, {
    rv(input$mymap_shape_click$id)
  })

  ## you can now plot your plot based on the id of region selected
  output$myplot <- renderPlot({
    plot_data %>%
      filter(id == rv()) %>%
      pivot_longer(cols = starts_with("Variable"), names_to = "Variable", values_to = "Value") %>%
      ggplot(aes(x = Variable, y = Value)) +
        geom_col()
  })

}

shinyApp(ui, server)

Edit: For your uploaded data, you don't need to add a separate id for communes. Instead, you could match by name (nom_commune). You can use that in your layerId instead. This looks like it should work. I did take out some of the additional label information as this appeared to be missing from the .shp file I downloaded.

library(shiny)
library(leaflet)
library(rgdal)
library(sf)
library(ggplot2)
library(tidyverse)

communes <- readOGR("communes_ok.shp")

ui <- fluidPage(
  leafletOutput(outputId = "mymap"),
  plotOutput(outputId = "myplot")
)

server <- function(input, output){

  ## use reactive values to store the id from observing the shape click
  rv <- reactiveVal()

  output$mymap<-renderLeaflet(
    leaflet(communes) %>%
      addProviderTiles(providers$Stamen.TonerLite,
                       options = providerTileOptions(noWrap = TRUE)) %>%
      setView(1.50, 43.54, zoom = 12) %>%
      addTiles()  %>%
      addPolygons(fillColor = "blue",
                  weight = 2,
                  opacity = 1,
                  color = "white",
                  dashArray = "3",
                  fillOpacity = 0.3,
                  highlight = highlightOptions(
                    weight = 5,
                    color = "#666",
                    dashArray = "",
                    fillOpacity = 0.7,
                    bringToFront = TRUE),
                  layerId = ~nm_cmmn)
  )

  observeEvent(input$mymap_shape_click, {
    rv(input$mymap_shape_click$id)
  })

  ## you can now 'output' your generated data however you want
  output$myplot <- renderPlot({
    if (is.null(rv())) return (NULL)
    plot_data %>%
      filter(nom_commune == rv()) %>%
      pivot_longer(cols = starts_with("Variable"), names_to = "Variable", values_to = "Value") %>%
      ggplot(aes(x = Variable, y = Value)) +
        geom_col()
  })

}

shinyApp(ui, server)


来源: stackexchange

问:
Weird Issue in dotnet core website using MailKit to send email
I just inherited a website from a vendor and going through the bugs and source code for the website.

The application is built on dotnet core 1.1 and uses Mailkit to send emails via SMTP thorugh our corporate proxy.

The issue is that the mail send feature behaves erratically in sending emails. Most of the times I debug the send method it errors out. We use the Authentication Required Flag and pass the userId and Password to MailKit Authenticate Method

StackTrace message

AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful

at MailKit.Net.Smtp.SmtpClient.Authenticate(Encoding encoding,
  ICredentials credentials, CancellationToken cancellationToken)    at
  MailKit.MailService.Authenticate(String userName, String password,
  CancellationToken cancellationToken)    at
  Rules.Emailer.SendNotification.Send(String to, String from, String
  subject, String body) in
  C:\Workspace\G\Rules\Emailer\SendNotification.cs:line
  94    at G.Rules.Emailer.UserNotifications.ResetPassword(String

Code snippet

```<code>using (var client = new SmtpClient())
{
    client.Connect(EmailConfiguration.SmtpServer, EmailConfiguration.SmtpPort, EmailConfiguration.UseSsl);

    if (EmailConfiguration.RequiresAuthentication)
    {
        client.Authenticate(EmailConfiguration.Username, EmailConfiguration.Password);
    }

    //TODO: Only Send if PROD
    client.Send(message);
    client.Disconnect(true);
}

return true;
}
</code>```

答:
To NTLM connection, you can try that:

await client.ConnectAsync(SmtpServer.SenderServer, SmtpServer.Port).ConfigureAwait(false);

if (client.AuthenticationMechanisms.Contains("NTLM"))
{
    var ntlm = new SaslMechanismNtlm(SmtpServer.UserName, SmtpServer.Password);
    await client.AuthenticateAsync(ntlm).ConfigureAwait(false);
}
else
{
    await client.AuthenticateAsync(SmtpServer.UserName, SmtpServer.Password).ConfigureAwait(false);
}
```

ContentLicense: CC BY-SA 3.0

Body:
I just inherited a website from a vendor and going through the bugs and source code for the website.

The application is built on dotnet core 1.1 and uses Mailkit to send emails via SMTP thorugh our corporate proxy.

The issue is that the mail send feature behaves erratically in sending emails. Most of the times I debug the send method it errors out. We use the Authentication Required Flag and pass the userId and Password to MailKit Authenticate Method

StackTrace message

AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful

at MailKit.Net.Smtp.SmtpClient.Authenticate(Encoding encoding,
  ICredentials credentials, CancellationToken cancellationToken)    at
  MailKit.MailService.Authenticate(String userName, String password,
  CancellationToken cancellationToken)    at
  Rules.Emailer.SendNotification.Send(String to, String from, String
  subject, String body) in
  C:\Workspace\G\Rules\Emailer\SendNotification.cs:line
  94    at G.Rules.Emailer.UserNotifications.ResetPassword(String

Code snippet

using (var client = new SmtpClient())
{
    client.Connect(EmailConfiguration.SmtpServer, EmailConfiguration.SmtpPort, EmailConfiguration.UseSsl);

    if (EmailConfiguration.RequiresAuthentication)
    {
        client.Authenticate(EmailConfiguration.Username, EmailConfiguration.Password);
    }

    //TODO: Only Send if PROD
    client.Send(message);
    client.Disconnect(true);
}

return true;
}

ContentLicense: CC BY-SA 4.0


问:
What's the difference between DAX and Power Query (or M)?
I have been working on Power BI for a while now and I often get confused when I browse through help topics of it. They often refer to the functions and formulas being used as DAX functions or Power Query, but I am unable to tell the difference between these two. Please guide me.</p>

答: One other thing worth mentioning re performance optimisation is that you should "prune" your datatset (remove rows / remove columns) as far "upstream" - of the data processing sequence - as possible; this means such operations are better done in Power Query than DAX; some further advice from MS here: https://learn.microsoft.com/en-us/power-bi/power-bi-reports-performance</p>


问:
How can I wrap lines of code into an function that I can run with one command in R?
So I'm working in a script and doing multiple tasks with the same sets of data. But because each task takes a few hundred lines of code, I end up clearing my global environment so I can move onto the next task. Then I have to rerun the lines of code at the top of the script to import my data again and work on my next task. I want to just type a command that will automatically reimport the data once I'm done with one task and can work on the other.

Here is essentially what I run every time I need to work on the next task. I import my data with the read.csv function and then filter by certain rows I need.

```<code>d2015 <- read_csv("Data 2015 CSV.csv")
d2016  <- read_csv("Data 2016 CSV.csv")
d2017 <- read_csv("Data 2017 CSV.csv")
d2018 <- read_csv("Data 2018 CSV.csv")

dta_15 <- d2015 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_16 <- d2016 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_17 <- d2017 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_18 <- d2018 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))

</code>```

I tried putting it all in a loop but that didn't work,

```<code>rundata <- {
d2015 <- read_csv("Data 2015 CSV.csv")
d2016  <- read_csv("Data 2016 CSV.csv")
d2017 <- read_csv("Data 2017 CSV.csv")
d2018 <- read_csv("Data 2018 CSV.csv")

dta_15 <- d2015 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_16 <- d2016 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_17 <- d2017 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_18 <- d2018 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
}
</code>```

How  can i create one command that will rerun all these commands? Best.

答:
We can do this in map

```<code>library(dplyr)
library(purrr)
library(readr)
</code>```

As the values to filter are the same across all the datasets, we can create an object

```<code>nm1 <- c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                           "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510")
</code>```

Get the files that follow the  specific pattern in its names

```<code>files <- list.files(pattern = '^Data \\d{4} CSV\\.csv$")
</code>```

Loop over the files, read with read_csv from readr and filter the elements to create a list of subset of data.frame/tibble.  It is better to keep it in a list rather than individual objects in the global env

```<code>lst1 <- map(files, ~ read_csv(.x) %>%
                   filter(Number %in% nm1)
    )
</code>```

Body:
So I'm working in a script and doing multiple tasks with the same sets of data. But because each task takes a few hundred lines of code, I end up clearing my global environment so I can move onto the next task. Then I have to rerun the lines of code at the top of the script to import my data again and work on my next task. I want to just type a command that will automatically reimport the data once I'm done with one task and can work on the other.

Here is essentially what I run every time I need to work on the next task. I import my data with the read.csv function and then filter by certain rows I need.

d2015 <- read_csv("Data 2015 CSV.csv")
d2016  <- read_csv("Data 2016 CSV.csv")
d2017 <- read_csv("Data 2017 CSV.csv")
d2018 <- read_csv("Data 2018 CSV.csv")

dta_15 <- d2015 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_16 <- d2016 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_17 <- d2017 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_18 <- d2018 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))

I tried putting it all in a loop but that didn't work,

rundata <- {
d2015 <- read_csv("Data 2015 CSV.csv")
d2016  <- read_csv("Data 2016 CSV.csv")
d2017 <- read_csv("Data 2017 CSV.csv")
d2018 <- read_csv("Data 2018 CSV.csv")

dta_15 <- d2015 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_16 <- d2016 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_17 <- d2017 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
dta_18 <- d2018 %>% filter(`Number` %in% c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                                                   "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510"))
}

How  can i create one command that will rerun all these commands? Best.

Body:
We can do this in map

library(dplyr)
library(purrr)
library(readr)

As the values to filter are the same across all the datasets, we can create an object

nm1 <- c("TX-500", "TX-600", "TX-503", "TX-700", "TX-603",
                           "AZ-502", "MI-501", "LA-503", "GA-500", "FL-510")

Get the files that follow the  specific pattern in its names

files <- list.files(pattern = '^Data \\d{4} CSV\\.csv$")

Loop over the files, read with read_csv from readr and filter the elements to create a list of subset of data.frame/tibble.  It is better to keep it in a list rather than individual objects in the global env

lst1 <- map(files, ~ read_csv(.x) %>%
                   filter(Number %in% nm1)
    )


问:
Force Samza key/value store backed by RocksDB to reload from kafka changelog?
In order to debug a production problem, I am running Samza code locally using ProcessJobFactory.  Everything appears to run fine.

The code uses a Samza key/value store backed by RocksDB and Kafka as a changelog (Kafka running on a different machine in case that matters).

In order to populate the environment with real data to debug, I replayed live data into the Kafka changelog for the key/value store for the RocksDB database with the Samza job stopped.

Upon starting Samza, it does not resync the RocksDB database with the Kafka changelog.  I verified this using Keylord (tool) and looking at the contents of the RocksDB database directly.

How can Samza be forced to resync the RocksDB database (key/value store) with the changelog?  Is there a config setting or a code level call that can be made?

Related - I assume when the code does a key-value-store.all(); that even if the cache in the code is empty, it will go to RocksDB and pull "all entries" from there?

Thanks,

答:
Have you tried deleting the store directory where the samza job hosts its RocksDB stores?
It'd be under the job.logged.store.base.dir you have configured
https://samza.apache.org/learn/documentation/latest/jobs/configuration-table.html
, defaulting to user.dir environment property</p>


问:
Unable to clear text field with overridden submit method used for ajax implementation via Jquery 1.4
I have a functionality of posting messages to a group which works using AJAX via Jquery. When I click on the "Post" button which is the value of the submit_tag, javascript is rendered and the page without reloading displays the latest message posted. Basically the post_message.js.erb file is called. I am making use of the following tutorial to implement the same:- http://railscasts.com/episodes/136-jquery

The code for post_message.js.erb looks like this:-

```<code>$("#new_post").before('<div id ="new_post"><%= escape_javascript(flash.delete(:notice)) %></div>');<!--TO-DO the flash messages aren't yet enabled/working-->
$("#latest_post").prepend("<%= @group_post.message %> by <%=  Investor.find(@group_post.post_by).first_name %> <div class=contentdispgrp> <%=  distance_of_time_in_words(@group_post.created_at,Time.now) %> ago</div> <br/><br/><hr/>");
$("#post_msg")[0].reset();
</code>```

The part of the form which would otherwise render HTML and display the posted message with reloading the page looks like this:-

```<code><%form_for  :group_post, @group_post, :url => {:action => :post_message, :id => params[:id]},:html => {:multipart => 'true', :id => 'new_post'},:id => 'post_form' do |f| -%>
    Start Discussion:<label id="post_msg"><%=f.text_field :message%></label>
   <!--<%=f.file_field :photo%> -->
   <%=submit_tag "Post"  %></p>
<!--<input type="button" value="Reset Form" onClick="this.form.reset()" />-->
  <%end%>

<div id = "latest_post"> </div>
<%for a in @group_all_posts %>
<%= a.message %> by <%=  Investor.find(a.post_by).first_name %> <div class ="contentdispgrp" id="style_chck"> <%=  distance_of_time_in_words(a.created_at,Time.now) %> ago </div><br/><br/> <hr/>
<%end%>

</tr>
</code>```

I want to empty the text field also along with the above already implemented functionality. I guess , I need to some how make use of the Javascript reset method , but somewhere I am not using it correctly.

Kindly help me with the same.

Thanks for your help..

[EDIT]

Code for post_message in my groups controller.

```<code>def post_message
      @investor_group = InvestorGroup.find(params[:id])

      unless @current_user.is_an_existing_member_of_group(@investor_group)
        flash[:notice] = "Please join this group to participate in discussions"
        redirect_to :action => :show, :id => @investor_group and return # try to find out what exactly does this command do with return stmnt
      else
        @group_post = GroupPost.new(params[:group_post])
      end
      #@group_post = GroupPost.new(params[:group_post])

      investor_id = session['investor_id']
      @group_post.investor_group_id = @investor_group.id
      @group_post.post_by = investor_id
      if @group_post.message.blank?
         flash[:notice] = 'Post can\'t be blank.'
      end
      if @group_post.save
        flash[:notice] = 'Post was successfully created.'
       # redirect_to :action => :show, :id => params[:id] - removed after trying to implement ajax via jquery
      else
        flash[:notice] = 'Post was not successfully created.'
      end

      respond_to do |format|
        format.html {redirect_to :action => "show", :id => params[:id]}
        format.js
      end

  end
</code>```

答:
I assume you want something like this:

```<code>$('#post_msg input').val('');
</code>```

That will clear the message input box value.

Body:
I have a functionality of posting messages to a group which works using AJAX via Jquery. When I click on the "Post" button which is the value of the submit_tag, javascript is rendered and the page without reloading displays the latest message posted. Basically the post_message.js.erb file is called. I am making use of the following tutorial to implement the same:- http://railscasts.com/episodes/136-jquery

The code for post_message.js.erb looks like this:-

$("#new_post").before('
<%= escape_javascript(flash.delete(:notice)) %>
');
$("#latest_post").prepend("<%= @group_post.message %> by <%=  Investor.find(@group_post.post_by).first_name %>
 <%=  distance_of_time_in_words(@group_post.created_at,Time.now) %> ago

");
$("#post_msg")[0].reset();

The part of the form which would otherwise render HTML and display the posted message with reloading the page looks like this:-

<%form_for  :group_post, @group_post, :url => {:action => :post_message, :id => params[:id]},:html => {:multipart => 'true', :id => 'new_post'},:id => 'post_form' do |f| -%>
    Start Discussion:<%=f.text_field :message%>

   <%=submit_tag "Post"  %>

  <%end%>

<%for a in @group_all_posts %>
<%= a.message %> by <%=  Investor.find(a.post_by).first_name %>
 <%=  distance_of_time_in_words(a.created_at,Time.now) %> ago

<%end%>

I want to empty the text field also along with the above already implemented functionality. I guess , I need to some how make use of the Javascript reset method , but somewhere I am not using it correctly.

Kindly help me with the same.

Thanks for your help..

[EDIT]

Code for post_message in my groups controller.

def post_message
      @investor_group = InvestorGroup.find(params[:id])

      unless @current_user.is_an_existing_member_of_group(@investor_group)
        flash[:notice] = "Please join this group to participate in discussions"
        redirect_to :action => :show, :id => @investor_group and return # try to find out what exactly does this command do with return stmnt
      else
        @group_post = GroupPost.new(params[:group_post])
      end
      #@group_post = GroupPost.new(params[:group_post])

      investor_id = session['investor_id']
      @group_post.investor_group_id = @investor_group.id
      @group_post.post_by = investor_id
      if @group_post.message.blank?
         flash[:notice] = 'Post can\'t be blank.'
      end
      if @group_post.save
        flash[:notice] = 'Post was successfully created.'
       # redirect_to :action => :show, :id => params[:id] - removed after trying to implement ajax via jquery
      else
        flash[:notice] = 'Post was not successfully created.'
      end

      respond_to do |format|
        format.html {redirect_to :action => "show", :id => params[:id]}
        format.js
      end

  end

Body:
I assume you want something like this:

$('#post_msg input').val('');

That will clear the message input box value.


问:
Flutter - VS Code Debug Console Spam - Red error messages are missing
Hey since the last Flutter update I have been missing error messages of all kinds and my debug console is only spammed with the logs from background processes that are unimportant to me...
At the moment I can only find errors in my code through systematic printing, which is very tedious, especially because its difficult to find them in the spam of all the background processes!
has someone the same problem?
thx

FLUTTER VERSION [Channel stable, v1.12.13+hotfix.8]

答: I had the same issue and couldn't find a fix. For now, I adivse you to just downgrade to v1.12.13+hotfix.7 by running git checkout v1.12.13+hotfix.7 in your flutter directory.


问:
How can I fix error "decompiled .class file bytecode version 52.0 (Java 8)
When I test my app on the emulator it works fine but when I ran the application on a real android 10.0 (Version) phone the log-cat shows errors which i can't understand at all. It is very confusing as it works fine on one phone (A lower version) and does not work on the other phone (Android 10.0 version).

The errors which I receive are the following:

Decompiled .class file, byte code version 52.00(Java 8) to be exact.

Logcat in error tab:

```<code>2020-02-18 22:08:23.114 22232-22280/? E/AndroidRuntime: FATAL EXCEPTION: Thread-4
    Process: com.atmosphericproductiveinnovations.worldage, PID: 22232
    java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion;
        at bt.b(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bs.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bu.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):17)
        at com.google.maps.api.android.lib6.drd.ak.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):5)
        at ay.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):8)
        at ay.run(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):44)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/user_de/0/com.google.android.gms/app_chimera/m/000000f6/MapsDynamite.apk"],nativeLibraryDirectories=[/data/user_de/0/com.google.android.gms/app_chimera/m/000000f6/MapsDynamite.apk!/lib/arm64-v8a, /system/lib64, /system/product/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at dalvik.system.DelegateLastClassLoader.loadClass(DelegateLastClassLoader.java:137)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at bt.b(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bs.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bu.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):17)
        at com.google.maps.api.android.lib6.drd.ak.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):5)
        at ay.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):8)
        at ay.run(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):44)
2020-02-18 22:08:23.128 22232-22232/? E/libprocessgroup: set_timerslack_ns write failed: Operation not permitted
2020-02-18 22:08:23.206 22232-22232/? E/BufferQueueConsumer: disconnect by : com.atmosphericproductiveinnovations.worldage my_pid = 22232

</code>```

MapsActivity.Java:

```<code>package com.atmosphericproductiveinnovations.worldage;

import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
                    LatLng India = new LatLng(23.52, 78.59);
                   mMap.addMarker(new MarkerOptions()
                           .position(India)
                          .title("India"))
                            //.setSnippet("Meow. My name is");
        .setSnippet("Information-"+"" +
                "\n"+"Location:South Asia"+
                "\n"+"Population:133.92 crores (2017)"+
                "\n"+"GDP:2.6 lakh crores USD (2017):");

        mMap.moveCamera(CameraUpdateFactory.newLatLng(India));

        mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivity.this));
    }
}

</code>```

Android manifest xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.atmosphericproductiveinnovations.worldage">

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/.
        -->
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyD7EYViNqAco_PXl-0CyCgJ6l2eEIzvTzY" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

BaseDexClassLoader.class:

```<code>package dalvik.system;

import java.io.File;
import java.net.URL;
import java.util.Enumeration;

public class BaseDexClassLoader extends ClassLoader {
    public BaseDexClassLoader(String dexPath, File optimizedDirectory, String librarySearchPath, ClassLoader parent) {
        throw new RuntimeException("Stub!");
    }

    protected Class<?> findClass(String name) throws ClassNotFoundException {
        throw new RuntimeException("Stub!");
    }

    protected URL findResource(String name) {
        throw new RuntimeException("Stub!");
    }

    protected Enumeration<URL> findResources(String name) {
        throw new RuntimeException("Stub!");
    }

    public String findLibrary(String name) {
        throw new RuntimeException("Stub!");
    }

    protected synchronized Package getPackage(String name) {
        throw new RuntimeException("Stub!");
    }

    public String toString() {
        throw new RuntimeException("Stub!");
    }
}
</code>```

DelegateLastClassLoader.class:

```<code>package dalvik.system;

import android.annotation.NonNull;
import android.annotation.Nullable;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

public final class DelegateLastClassLoader extends PathClassLoader {
    public DelegateLastClassLoader(String dexPath, ClassLoader parent) {
        super((String)null, (ClassLoader)null);
        throw new RuntimeException("Stub!");
    }

    public DelegateLastClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
        super((String)null, (ClassLoader)null);
        throw new RuntimeException("Stub!");
    }

    public DelegateLastClassLoader(@NonNull String dexPath, @Nullable String librarySearchPath, @Nullable ClassLoader parent, boolean delegateResourceLoading) {
        super((String)null, (ClassLoader)null);
        throw new RuntimeException("Stub!");
    }

    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        throw new RuntimeException("Stub!");
    }

    public URL getResource(String name) {
        throw new RuntimeException("Stub!");
    }

    public Enumeration<URL> getResources(String name) throws IOException {
        throw new RuntimeException("Stub!");
    }
}

</code>```

I am new to IntelIJ

答:
If you are using com.google.android.gms:play-services-maps:16.0.0 or
  below and your app is targeting API level 28 (Android 9.0) or above,
  you must include the following declaration within the
  element of AndroidManifest.xml.

```<code><uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />
</code>```

This is handled for you if you are using
  com.google.android.gms:play-services-maps:16.1.0 and is not necessary
  if your app is targeting a lower API level.

specify requirement for apache http legacy library

Body:
When I test my app on the emulator it works fine but when I ran the application on a real android 10.0 (Version) phone the log-cat shows errors which i can't understand at all. It is very confusing as it works fine on one phone (A lower version) and does not work on the other phone (Android 10.0 version).

The errors which I receive are the following:

Decompiled .class file, byte code version 52.00(Java 8) to be exact.

Logcat in error tab:

2020-02-18 22:08:23.114 22232-22280/? E/AndroidRuntime: FATAL EXCEPTION: Thread-4
    Process: com.atmosphericproductiveinnovations.worldage, PID: 22232
    java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/ProtocolVersion;
        at bt.b(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bs.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bu.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):17)
        at com.google.maps.api.android.lib6.drd.ak.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):5)
        at ay.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):8)
        at ay.run(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):44)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "org.apache.http.ProtocolVersion" on path: DexPathList[[zip file "/data/user_de/0/com.google.android.gms/app_chimera/m/000000f6/MapsDynamite.apk"],nativeLibraryDirectories=[/data/user_de/0/com.google.android.gms/app_chimera/m/000000f6/MapsDynamite.apk!/lib/arm64-v8a, /system/lib64, /system/product/lib64]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
        at dalvik.system.DelegateLastClassLoader.loadClass(DelegateLastClassLoader.java:137)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at bt.b(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bs.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):2)
        at bu.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):17)
        at com.google.maps.api.android.lib6.drd.ak.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):5)
        at ay.a(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):8)
        at ay.run(:com.google.android.gms.dynamite_mapsdynamite@20104081@20.1.04 (120400-0):44)
2020-02-18 22:08:23.128 22232-22232/? E/libprocessgroup: set_timerslack_ns write failed: Operation not permitted
2020-02-18 22:08:23.206 22232-22232/? E/BufferQueueConsumer: disconnect by : com.atmosphericproductiveinnovations.worldage my_pid = 22232

MapsActivity.Java:

package com.atmosphericproductiveinnovations.worldage;

import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
                    LatLng India = new LatLng(23.52, 78.59);
                   mMap.addMarker(new MarkerOptions()
                           .position(India)
                          .title("India"))
                            //.setSnippet("Meow. My name is");
        .setSnippet("Information-"+"" +
                "\n"+"Location:South Asia"+
                "\n"+"Population:133.92 crores (2017)"+
                "\n"+"GDP:2.6 lakh crores USD (2017):");

        mMap.moveCamera(CameraUpdateFactory.newLatLng(India));

        mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(MapsActivity.this));
    }
}

Android manifest xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.atmosphericproductiveinnovations.worldage">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyD7EYViNqAco_PXl-0CyCgJ6l2eEIzvTzY" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

BaseDexClassLoader.class:

package dalvik.system;

import java.io.File;
import java.net.URL;
import java.util.Enumeration;

public class BaseDexClassLoader extends ClassLoader {
    public BaseDexClassLoader(String dexPath, File optimizedDirectory, String librarySearchPath, ClassLoader parent) {
        throw new RuntimeException("Stub!");
    }

    protected Class<?> findClass(String name) throws ClassNotFoundException {
        throw new RuntimeException("Stub!");
    }

    protected URL findResource(String name) {
        throw new RuntimeException("Stub!");
    }

    protected Enumeration<URL> findResources(String name) {
        throw new RuntimeException("Stub!");
    }

    public String findLibrary(String name) {
        throw new RuntimeException("Stub!");
    }

    protected synchronized Package getPackage(String name) {
        throw new RuntimeException("Stub!");
    }

    public String toString() {
        throw new RuntimeException("Stub!");
    }
}

DelegateLastClassLoader.class:

package dalvik.system;

import android.annotation.NonNull;
import android.annotation.Nullable;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;

public final class DelegateLastClassLoader extends PathClassLoader {
    public DelegateLastClassLoader(String dexPath, ClassLoader parent) {
        super((String)null, (ClassLoader)null);
        throw new RuntimeException("Stub!");
    }

    public DelegateLastClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
        super((String)null, (ClassLoader)null);
        throw new RuntimeException("Stub!");
    }

    public DelegateLastClassLoader(@NonNull String dexPath, @Nullable String librarySearchPath, @Nullable ClassLoader parent, boolean delegateResourceLoading) {
        super((String)null, (ClassLoader)null);
        throw new RuntimeException("Stub!");
    }

    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        throw new RuntimeException("Stub!");
    }

    public URL getResource(String name) {
        throw new RuntimeException("Stub!");
    }

    public Enumeration<URL> getResources(String name) throws IOException {
        throw new RuntimeException("Stub!");
    }
}

I am new to IntelIJ

Body:
If you are using com.google.android.gms:play-services-maps:16.0.0 or
  below and your app is targeting API level 28 (Android 9.0) or above,
  you must include the following declaration within the
  element of AndroidManifest.xml.

<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

This is handled for you if you are using
  com.google.android.gms:play-services-maps:16.1.0 and is not necessary
  if your app is targeting a lower API level.

specify requirement for apache http legacy library


问:
R Paste All Variables With Specific Prefix
I would like to paste the content of a set of variables with a given prefix. For example, given this data:

```<code>data <- data.frame(var_1=c(1,2,3,4,5),
                   var_2=c(1,2,3,4,5),
                   var_3=c(1,2,3,4,5))
</code>```

I want to replicate the following behavior without listing each variable name individually, instead pasting all variables with the prefix "var_":

```<code>my_strings <- paste(toy_data$var_1,
                    toy_data$var_2,
                    toy_data$var_3)

my_strings
[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"
</code>```

答:
Using purrr and dplyr, you can do:

```<code>reduce(select(data, starts_with("var")), paste)

[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"
</code>```

Body:
I would like to paste the content of a set of variables with a given prefix. For example, given this data:

data <- data.frame(var_1=c(1,2,3,4,5),
                   var_2=c(1,2,3,4,5),
                   var_3=c(1,2,3,4,5))

I want to replicate the following behavior without listing each variable name individually, instead pasting all variables with the prefix "var_":

my_strings <- paste(toy_data$var_1,
                    toy_data$var_2,
                    toy_data$var_3)

my_strings
[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"

Body:
Using purrr and dplyr, you can do:

reduce(select(data, starts_with("var")), paste)

[1] "1 1 1" "2 2 2" "3 3 3" "4 4 4" "5 5 5"


问:
Is there a maximum size for a file upload through HTML form?
I want users on my site to be able to upload large files (say up to 1GB), through html form. What I have so far, which works:

```<code>  <h1>Upload new File:</h1>
  <form method=post enctype=multipart/form-data>
    <input type=file name=file>
    <input type=submit value=Upload>
  </form>
</code>```

Will this work for large files ? Or should I use another way (considering that I'm a beginner in webdev) ?
I can't find references of a limitation on file size in html5 documentation, and only found ways to limit file size on SO (e.g. Limit the size of an file upload (html input)).

答:
No, there is no size upload limit in Html input type "file"...

Following are the way if you want to check file uploaded size.

```<code>if (typeof FileReader !== "undefined") {
var Filesize = document.getElementById('fileId').files[0].size;}
</code>```

There are several configuration parameters that can affect the file upload. These configuration parameters have to be setup right for the file uploads to work fine.

=> The folder in which the files are saved should be writable by the script. This is obvious but might be overlooked. The folder must be writable by the script means the web server user (usually www-data ) should have write access to the folder. So setup the folder permissions right. If you have shell access, the folder permissions can be updated using the 'chmod' command easily. If you don't have shell access, or if you have a shared hosting account, updating the folder permissions can be a little tricky. See if your hosting control panel has this feature.

=> The websever configuration The web server would have a configuration setting that (1) allows/disallows file uploads (2) sets a limit on the size of the file upload. Here are the typical settings you have to check (for PHP)

memory_limit

upload_max_filesize

post_max_size

Body:
I want users on my site to be able to upload large files (say up to 1GB), through html form. What I have so far, which works:

Upload new File:

  <form method=post enctype=multipart/form-data>
    <input type=file name=file>
    <input type=submit value=Upload>
  </form>

Will this work for large files ? Or should I use another way (considering that I'm a beginner in webdev) ?
I can't find references of a limitation on file size in html5 documentation, and only found ways to limit file size on SO (e.g. Limit the size of an file upload (html input)).

Body:
No, there is no size upload limit in Html input type "file"...

Following are the way if you want to check file uploaded size.

if (typeof FileReader !== "undefined") {
var Filesize = document.getElementById('fileId').files[0].size;}

There are several configuration parameters that can affect the file upload. These configuration parameters have to be setup right for the file uploads to work fine.

=> The folder in which the files are saved should be writable by the script. This is obvious but might be overlooked. The folder must be writable by the script means the web server user (usually www-data ) should have write access to the folder. So setup the folder permissions right. If you have shell access, the folder permissions can be updated using the 'chmod' command easily. If you don't have shell access, or if you have a shared hosting account, updating the folder permissions can be a little tricky. See if your hosting control panel has this feature.

=> The websever configuration The web server would have a configuration setting that (1) allows/disallows file uploads (2) sets a limit on the size of the file upload. Here are the typical settings you have to check (for PHP)

memory_limit

upload_max_filesize

post_max_size


问:
What might "interfere" with a DataTables AJAX scroll-bar in this way?
I know that this must have something to do with the CSS (or perhaps JS) on "this old site," but I haven't quite put my finger on what to look at first.

Basically, I have an AJAX-sourced DataTable, but when I try to select the scroll-bar to move it up and down, it "sticks."  Doesn't move smoothly and show the record-number indicator ... as it does when I use the demos on the DataTables home page in the very same browser.  I do see AJAX requests being sent for other row-ranges (and being properly returned), but when I finally let go of the mostly non-sliding slider it pops right back up to the top again.

Does this description of symptoms "ring bells" with anyone out there?  As in: "oh, yeah, this happened to me once, and I ..."

答:
"Well, isn't CSS always very strange ..."

Apparently, one(!) "uikit theme CSS-file" was not being loaded correctly, and everything just went downhill from there.  When I forced that file to be loaded, suddenly the DataTable began to work, as did quite a number of other things.

Of course, "I knew that it really wasn't a DataTables problem to begin with," but it's really quite remarkable just how disruptive the absence of a single CSS file turned out to be!


问:
Combine DataFrames in Pyspark
I have a vendor giving me multiple zipped data file on an S3 bucket which I need to read all together for analysis using Pyspark. How do I modify the sc.textFile() command?

Also, if I am loading 10 files, how do I reference them? Or are they all going into a single RDD?

On a broader level, how would I tweak the partitions, memory on an AMAZON EMR cluster? Each zipped file is 3MB in size or 1.3GB unzipped.
Thanks

答:
You can have a script which will move all the unzip files into a directory and then as part of yur spark code you can refer to that directory

```<code>rdd = sc.textFile(("s3://path/to/data/")
</code>```

As you mentioed it's 1.3 GB data which is not huge for spark to process, you can leave to spark to have required partitions, however you can define them while creating rdd.

For Amazon EMR, you can spin smaller nodes based on the type of reuirement
https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-supported-instance-types.html

Based on kind of processing(memory intensive/ compute intensive), choose machine type.

HTH

Title: Combine DataFrames in Pyspark

Body:
You can have a script which will move all the unzip files into a directory and then as part of yur spark code you can refer to that directory

rdd = sc.textFile(("s3://path/to/data/")

As you mentioed it's 1.3 GB data which is not huge for spark to process, you can leave to spark to have required partitions, however you can define them while creating rdd.

For Amazon EMR, you can spin smaller nodes based on the type of reuirement
https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-supported-instance-types.html

Based on kind of processing(memory intensive/ compute intensive), choose machine type.

HTH


问:
Copying Mysql Data files from failed sd card
My raspberry pi isn't booting to the os.  It is getting stalled with various errors.  However I can open the sd card on another computer.  I want the data from mysql could I copy the datadir to another filesystem and once I have my pi working.  Copy those files to the new pi's datadir? </p>

答:
Very vague question.

Pi can run different OS.

Different ways of storing data files by few versions of MySQL / MariaDB.

Copying datadir to another file system. Which FS?

Now, probable solutions.

Restore from backup. Should have taken backup (periodically).

Create a bootable SD for your Pi and place your datadir (of previous SD into the new SD. Do this after referring to
https://serverfault.com/questions/659048/can-i-copy-the-entire-var-lib-mysql-folder-to-a-different-server-mysql-vs-mar

Before doing anything on the main Pi, do a dry run using yet another SD.


问:
javascript - if and or (||) statement
```<code>if (window.location.pathname == "/" || window.location.pathname == "/yyy.asp") {
  runSlideShow();
}
if (
  window.location.pathname == "zzzz.html" ||
  window.location.pathname == "/xxx.html"
) {
  runSlideShow();
}
</code>```

How do I merge the if statements so there is only one {runSlideShow();} rather than two;

currently I cant seem to have more than two window.location.pathname statements with an || in between.

答:
It's possible to both merge your conditions and cut down your code significantly.

```<code>if (['/', '/yyy.asp', 'zzzz.html', '/xxx.html'].includes(location.pathname))
    runSlideShow();
</code>```

Or alternatively, for the hell of it, shorter still but less readable/scalable:

```<code>if (/^(?:(\/(yyy\.asp|xxx\.html)?)|zzzz\.html)$/.test(location.pathname))
</code>```

Title: javascript - if and or (||) statement

Body:
if (window.location.pathname == "/" || window.location.pathname == "/yyy.asp") {
  runSlideShow();
}
if (
  window.location.pathname == "zzzz.html" ||
  window.location.pathname == "/xxx.html"
) {
  runSlideShow();
}

How do I merge the if statements so there is only one {runSlideShow();} rather than two;

currently I cant seem to have more than two window.location.pathname statements with an || in between.

Body:
It's possible to both merge your conditions and cut down your code significantly.

if (['/', '/yyy.asp', 'zzzz.html', '/xxx.html'].includes(location.pathname))
    runSlideShow();

Or alternatively, for the hell of it, shorter still but less readable/scalable:

if (/^(?:(\/(yyy\.asp|xxx\.html)?)|zzzz\.html)$/.test(location.pathname))


问:
Microsoft Graph API - 503 Service Unavailable
I'm working to integrate Microsoft Graph with a Rails web application. We're trying to send multiple email messages via Graph, but every now and then we get a 503 Service Unavailable with the following headers and body:

Response headers:

{
  "content-type": [
    "text/html; charset=us-ascii"
  ],
  "server": [
    "Microsoft-HTTPAPI/2.0"
  ],
  "date": [
    "Wed, 30 May 2018 22:05:31 GMT"
  ],
  "connection": [
    "close"
  ],
  "content-length": [
    326
  ]
}
```

<p>Response body:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
    <TITLE>Service Unavailable</TITLE>
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">
</HEAD>
<BODY>
    <h2>Service Unavailable</h2>
    <hr>
    <p>HTTP Error 503. The service is unavailable.</p>
</BODY>
</HTML>
</code>```

We use the POST https://graph.microsoft.com/v1.0/me/sendMail call to send hundreds of outlook emails. After sending roughly 100-200 emails with the Graph API we get the 503 Service Unavailable error. This is problematic when we have to send 1000+ customized emails since it is unclear to me how we could properly handle the error without knowing how long to wait before retrying and other Graph API request.

I'm wondering if anyone has run into a similar issue before. I've read about something similar along the lines of client throttling (Microsoft Graph API - Throttling), but in this post, they're getting 409 (with a retry-after header), not 503.

Based on the Graph documentations, we're supposed to receive a JSON object that may contain a Retry-After header. However, as shown above, we're neither getting the Retry-After header nor a JSON object for the 503 error.

答:
As an update here. In future for any 500 error messages, you are best to raise these as service issues as per the instructions here https://developer.microsoft.com/en-us/graph/support

Have a paid Azure subscription?
Visit the Azure Admin Center.
https://ms.portal.azure.com/#blade/Microsoft_Azure_Support/HelpAndSupportBlade/newsupportreq

Have a Premier support contract for Microsoft 365?
Visit the Microsoft 365 Admin Center and use the Support menu.
https://admin.microsoft.com/

Body:
I'm working to integrate Microsoft Graph with a Rails web application. We're trying to send multiple email messages via Graph, but every now and then we get a 503 Service Unavailable with the following headers and body:

Response headers:

{
  "content-type": [
    "text/html; charset=us-ascii"
  ],
  "server": [
    "Microsoft-HTTPAPI/2.0"
  ],
  "date": [
    "Wed, 30 May 2018 22:05:31 GMT"
  ],
  "connection": [
    "close"
  ],
  "content-length": [
    326
  ]
}

Response body:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">

    <TITLE>Service Unavailable</TITLE>
    <META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Service Unavailable

HTTP Error 503. The service is unavailable.

We use the POST https://graph.microsoft.com/v1.0/me/sendMail call to send hundreds of outlook emails. After sending roughly 100-200 emails with the Graph API we get the 503 Service Unavailable error. This is problematic when we have to send 1000+ customized emails since it is unclear to me how we could properly handle the error without knowing how long to wait before retrying and other Graph API request.

I'm wondering if anyone has run into a similar issue before. I've read about something similar along the lines of client throttling (Microsoft Graph API - Throttling), but in this post, they're getting 409 (with a retry-after header), not 503.

Based on the Graph documentations, we're supposed to receive a JSON object that may contain a Retry-After header. However, as shown above, we're neither getting the Retry-After header nor a JSON object for the 503 error.


问:
In Eclipse, Variables does not show child variables of extended class
I have a class:

```<code>class MyArrayList extends ArrayList {
    public int dog;
    public MyArrayList(int v) {dog = v;}
}
</code>```

I then create one:

```<code>foo = new MyArrayList(23);
System.out.println("foo.dog is"+foo.dog);
</code>```

I put a breakpoint at the 'System.out.println' line.  When I hit that breakpoint I look at the 'Variables' pane.  There will be line for 'foo' with content assist available, BUT... there is no line which will show the value of foo.dog.  How can I examine the value of foo.dog in the Variables pane?

答: Sorry.  I got impatient.  There is a button called 'show logical structure' (a yellow arrow pointing to a structure).  Click it to see the locals.</p>

Body:
I have a class:

class MyArrayList extends ArrayList {
    public int dog;
    public MyArrayList(int v) {dog = v;}
}

I then create one:

foo = new MyArrayList(23);
System.out.println("foo.dog is"+foo.dog);

I put a breakpoint at the 'System.out.println' line.  When I hit that breakpoint I look at the 'Variables' pane.  There will be line for 'foo' with content assist available, BUT... there is no line which will show the value of foo.dog.  How can I examine the value of foo.dog in the Variables pane?


问:
Wrong data taken from the mySQL DB using mysql_fetch_assoc
With the below query, I'm taking data from different tables and almost all have the id field.

```<code>SELECT * FROM contracts AS co JOIN clients AS cl ON cl.id = co.client_id JOIN shops AS pv ON pv.id = co.shop_id
</code>```

table structure:
contracts (id, client_id, shop_id, offer, price ...)

clients (id, name, surname ..)

shops (id, code, address...)

now, using mysql_fetch_assoc, I'm printing the data in a table. All the fields are properly printed except for the id of the table contract. below the simplified PHP code:

```<code>$query = mysql_query ($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)){ echo $row["id"]; }
</code>```

The strange thing is that the ID is printed but it is not the proper one. if I try to use "co.id" it doesn't work at all. I know that this code is deprecated but I'm doing some update in an old project and I can't refactor the entire project now.

The question is: is there a way to define the id that I want? I would avoid to define all the fields that i need in the SELECT replacing *.

答:
I suggest you to mention each field in query instead of query.
field Alias can be use to prefer more suitable name, also you can skip the repeated fields, such as client_id & shop_id.

Following query will be used for the same.

```<code>SELECT
co.id AS contract_id, co.client_id, co.shop_id, co.offer, co.price,
cl.name, cl.surname,
pv.code, pv.address
FROM contracts AS co
JOIN clients AS cl ON cl.id = co.client_id
JOIN shops AS pv ON pv.id = co.shop_id;
</code>```

Note that, co.id will be displayed as contract_id in query result.

Body:
With the below query, I'm taking data from different tables and almost all have the id field.

SELECT * FROM contracts AS co JOIN clients AS cl ON cl.id = co.client_id JOIN shops AS pv ON pv.id = co.shop_id

table structure:
contracts (id, client_id, shop_id, offer, price ...)

clients (id, name, surname ..)

shops (id, code, address...)

now, using mysql_fetch_assoc, I'm printing the data in a table. All the fields are properly printed except for the id of the table contract. below the simplified PHP code:

$query = mysql_query ($sql) or die (mysql_error());
while($row = mysql_fetch_assoc($query)){ echo $row["id"]; }

The strange thing is that the ID is printed but it is not the proper one. if I try to use "co.id" it doesn't work at all. I know that this code is deprecated but I'm doing some update in an old project and I can't refactor the entire project now.

The question is: is there a way to define the id that I want? I would avoid to define all the fields that i need in the SELECT replacing *.

Body:
I suggest you to mention each field in query instead of query.
field Alias can be use to prefer more suitable name, also you can skip the repeated fields, such as client_id & shop_id.

Following query will be used for the same.

SELECT
co.id AS contract_id, co.client_id, co.shop_id, co.offer, co.price,
cl.name, cl.surname,
pv.code, pv.address
FROM contracts AS co
JOIN clients AS cl ON cl.id = co.client_id
JOIN shops AS pv ON pv.id = co.shop_id;

Note that, co.id will be displayed as contract_id in query result.


问:
Python Subprocess Invalid Syntax when passing variable to function
I have a python script and want to call a subprocess from it.
The following example works completely fine:

Script1:

```<code>from subprocess import Popen

p = Popen('python Script2.py', shell=True)
</code>```

Script2:

```<code>def execute():
    print('works!')

execute()
</code>```

However as soon as I want to pass a variable to the function, I get the following error:

```<code>def execute(random_variable: str):

SyntaxError: invalid syntax
</code>```

Script1:

```<code>from subprocess import Popen

p = Popen('python Script2.py', shell=True)
</code>```

Script2:

```<code>def execute(random_variable: str):
    print(random_variable)

execute(random_variable='does not work')
</code>```

Does anyone have an idea why that could be the case? Couldn't find anything about it online :(

答:
Python type hint is introduced in python3.5.
if you run this with less than version python3.5 then it will throw this error.

```<code>    def execute(random_variable: str):
                               ^
SyntaxError: invalid syntax
</code>```

thats why first script worked and later one failed.

Body:
I have a python script and want to call a subprocess from it.
The following example works completely fine:

Script1:

from subprocess import Popen

p = Popen('python Script2.py', shell=True)

Script2:

def execute():
    print('works!')

execute()

However as soon as I want to pass a variable to the function, I get the following error:

def execute(random_variable: str):

SyntaxError: invalid syntax

Script1:

from subprocess import Popen

p = Popen('python Script2.py', shell=True)

Script2:

def execute(random_variable: str):
    print(random_variable)

execute(random_variable='does not work')

Does anyone have an idea why that could be the case? Couldn't find anything about it online :(

Body:
Python type hint is introduced in python3.5.
if you run this with less than version python3.5 then it will throw this error.

    def execute(random_variable: str):
                               ^
SyntaxError: invalid syntax

thats why first script worked and later one failed.


问:
Android check null or empty string in Android
In my trying AsyncTask I get email address from my server. In onPostExecute() I have to check is email address empty or null. I used following code to check it:

```<code>if (userEmail != null && !userEmail.isEmpty()) {
    Toast.makeText(getActivity(), userEmail, Toast.LENGTH_LONG).show();
    UserEmailLabel.setText(userEmail);
}
</code>```

But in my Toast I see null is printed. My full code:

```<code>private class LoadPersonalData extends AsyncTask<String, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected Void doInBackground(String... res) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("user_id", PrefUserName));
        params.add(new BasicNameValuePair("type", type_data));
        JSONObject json = jsonParser.makeHttpRequest(Url, "POST", params);
        String result = "";
        try {
            result = json.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (result.equals("success")) {
            try {
                userEmail = json.getString("email");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (userEmail != null && !userEmail.isEmpty()) {
            Toast.makeText(getActivity(), userEmail, Toast.LENGTH_LONG).show();
            UserEmailLabel.setText(userEmail);
        }
    }
</code>```

How can I check for null and empty string?

答:
My simple solution to test if a string is null:

if (s.equals("null")){
  .....
}

There are two cases.

The variable (of type String) is null(doesn't exists):
== works.

The variable has a null value,
*.equals("null") gives te right boolean value.

See the picture.

Body:
In my trying AsyncTask I get email address from my server. In onPostExecute() I have to check is email address empty or null. I used following code to check it:

if (userEmail != null && !userEmail.isEmpty()) {
    Toast.makeText(getActivity(), userEmail, Toast.LENGTH_LONG).show();
    UserEmailLabel.setText(userEmail);
}

But in my Toast I see null is printed. My full code:

private class LoadPersonalData extends AsyncTask<String, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected Void doInBackground(String... res) {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("user_id", PrefUserName));
        params.add(new BasicNameValuePair("type", type_data));
        JSONObject json = jsonParser.makeHttpRequest(Url, "POST", params);
        String result = "";
        try {
            result = json.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (result.equals("success")) {
            try {
                userEmail = json.getString("email");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (userEmail != null && !userEmail.isEmpty()) {
            Toast.makeText(getActivity(), userEmail, Toast.LENGTH_LONG).show();
            UserEmailLabel.setText(userEmail);
        }
    }

How can I check for null and empty string?


问:
Absolute positioning in WPF
I have a long text and show first sentence in a TextBlock.
I wish by clicking the TextBlock or a button to show a panel below the TextBlock with full text. I wish this panel be absolutely positioned and be displayed above any other elements, you can do a similar thing in HTML showing and hiding absolutely positioned 'div' element.
How to do this in WPF?
Thank you for any suggestions.</p>

答:
Put the long text in an AdornerLayer is the best option. Check out some links
http://msdn.microsoft.com/en-us/library/ms743737.aspx
http://wangmo.wordpress.com/2008/10/19/relations-between-adorner-adornerlayer-and-adornerdecorator/</p>

OwnerDisplayName: Dmitry Kiev

ContentLicense: CC BY-SA 2.5

Title: Absolute positioning in WPF

OwnerDisplayName: Jobi Joy


问:
How to append some object arrays in C#?

Possible Duplicate:

  How do I concatenate two arrays in C#?

How do I append some object arrays into one big object array?

For example, I have 3 elements of type: object[] and want to make one of it. How to do this?

答:
Depending on how you need to use the combined list, the most performant solution would be to feed your arrays into an iterator block and return at enumerable :

```<code>IEnumerable<object> CombineArrays ( params object[] arrays )
{
     foreach (object[] arr in arrays )
     {
          foreach (object obj in arr)
          {
               yield return obj;
          }
     }
}

...

IEnumerable<object> result = CombineArrays ( array1, array2, array3);
</code>```

This way will not need any additional storage to for the new combined list. The  IEnumerable result will just enumerate over the arrays in turn. You can process the result using any of the Linq operators - so you can group, filter and select as much as you want.

If you need to create a writable list from this you will need to call ToList() or ToArray() on the result.

Title: How to append some object arrays in C#?

Body:
Depending on how you need to use the combined list, the most performant solution would be to feed your arrays into an iterator block and return at enumerable :

IEnumerable<object> CombineArrays ( params object[] arrays )
{
     foreach (object[] arr in arrays )
     {
          foreach (object obj in arr)
          {
               yield return obj;
          }
     }
}

...

IEnumerable<object> result = CombineArrays ( array1, array2, array3);

This way will not need any additional storage to for the new combined list. The  IEnumerable result will just enumerate over the arrays in turn. You can process the result using any of the Linq operators - so you can group, filter and select as much as you want.

If you need to create a writable list from this you will need to call ToList() or ToArray() on the result.


问:
UPDATE VALUE IN MYSQL MARIA DB WITH JOIN
I am trying to change the value of a column table with a sum function, this is my code:

```<code>For example
c.total = (10-2-3) - (3)
c.total = 2

update tabC c
JOIN tabB b ON b.c_id = c.id
set c.total = (c.v1 - c.v2 - c.v3) - IF(sum(b.payment) is not null, sum(b.payment), 0)
where c.id= 983;
</code>```

but I get the following error:

ERROR 1111 (HY000): Invalid use of group function

I think the error is sum, but how can I solve that?

Thanls in advance

答:
You need to join with a subquery that uses GROUP BY.

```<code>UPDATE tabC c
LEFT JOIN (
    SELECT c_id, SUM(payment) AS total_payment
    FROM tabB
    GROUP BY c_id) AS b ON b.c_id = c.id
SET c.total = (c.v1 - c.v2 - c.v3) - IFNULL(b.total_payment, 0)
WHERE c.id = 983
</code>```

Body:
I am trying to change the value of a column table with a sum function, this is my code:

For example
c.total = (10-2-3) - (3)
c.total = 2

update tabC c
JOIN tabB b ON b.c_id = c.id
set c.total = (c.v1 - c.v2 - c.v3) - IF(sum(b.payment) is not null, sum(b.payment), 0)
where c.id= 983;

but I get the following error:

ERROR 1111 (HY000): Invalid use of group function

I think the error is sum, but how can I solve that?

Thanls in advance

Body:
You need to join with a subquery that uses GROUP BY.

UPDATE tabC c
LEFT JOIN (
    SELECT c_id, SUM(payment) AS total_payment
    FROM tabB
    GROUP BY c_id) AS b ON b.c_id = c.id
SET c.total = (c.v1 - c.v2 - c.v3) - IFNULL(b.total_payment, 0)
WHERE c.id = 983


问:
Search for data from list and delete row
I have a table in Sheet1. I need to search in Sheet1 for terms in Sheet2-ColumnA.

The exclusion list in Sheet2-ColumnA does not match the cell contents in Sheet1, but is found within the cell contents (Ex: find "orange" in "yellow;orange" or "orange;yellow").

If that criteria is found, delete the row. If it doesn't find the criteria, continue on down the list until it reaches an empty cell.

I recorded one round of this, but I need to modify it to loop through the entire exclusion list until it reaches an empty cell in the exclusion list.

```<code>Sub ExclusionList()
'
' ExclusionList Macro
' Find terms from exclusion list and delete row
'
' Go to sheet2 and select first term in exclusion list
    Sheets("Sheet2").Select
    Range("A1").Select

' Copy cell contents and find in sheet 1
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Find(What:="orange", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

' Delete row if found
    Application.CutCopyMode = False
    Selection.EntireRow.Delete
End Sub
</code>```

In this example, "orange" is the criteria in Sheet2 A1. If it is possible to skip the copy/paste and refer directly to the exclusion list in the Cells.Find() function it seems like that would clean up the code and be more efficient overall.

答:
Try this.

Here is a useful resource on avoiding Select/Activate. This shortens code considerably and makes it more effective.

```<code>Sub ExclusionList()

Dim r As Range, rFind As Range

With Sheets("Sheet2")
    For Each r In .Range("A1", .Range("A" & Rows.Count).End(xlUp)) 'loop through every cell in sheet2 column A
        Set rFind = Sheets("Sheet1").Cells.Find(What:=r.Value, LookAt:=xlPart, MatchCase:=False, SearchFormat:=False)
        If Not rFind Is Nothing Then 'check that value is found to avoid error on next line
            rFind.EntireRow.Delete
        End If
    Next r
End With

End Sub
</code>```

Body:
I have a table in Sheet1. I need to search in Sheet1 for terms in Sheet2-ColumnA.

The exclusion list in Sheet2-ColumnA does not match the cell contents in Sheet1, but is found within the cell contents (Ex: find "orange" in "yellow;orange" or "orange;yellow").

If that criteria is found, delete the row. If it doesn't find the criteria, continue on down the list until it reaches an empty cell.

I recorded one round of this, but I need to modify it to loop through the entire exclusion list until it reaches an empty cell in the exclusion list.

Sub ExclusionList()
'
' ExclusionList Macro
' Find terms from exclusion list and delete row
'
' Go to sheet2 and select first term in exclusion list
    Sheets("Sheet2").Select
    Range("A1").Select

' Copy cell contents and find in sheet 1
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Sheet1").Select
    Cells.Find(What:="orange", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate

' Delete row if found
    Application.CutCopyMode = False
    Selection.EntireRow.Delete
End Sub

In this example, "orange" is the criteria in Sheet2 A1. If it is possible to skip the copy/paste and refer directly to the exclusion list in the Cells.Find() function it seems like that would clean up the code and be more efficient overall.

Body:
Try this.

Here is a useful resource on avoiding Select/Activate. This shortens code considerably and makes it more effective.

Sub ExclusionList()

Dim r As Range, rFind As Range

With Sheets("Sheet2")
    For Each r In .Range("A1", .Range("A" & Rows.Count).End(xlUp)) 'loop through every cell in sheet2 column A
        Set rFind = Sheets("Sheet1").Cells.Find(What:=r.Value, LookAt:=xlPart, MatchCase:=False, SearchFormat:=False)
        If Not rFind Is Nothing Then 'check that value is found to avoid error on next line
            rFind.EntireRow.Delete
        End If
    Next r
End With

End Sub


问:
How to align items in two cards side by side
How can I align booth names in the same line ?

The image above show the problem. I tried to use flex-box but is not working. I would like to position "John Dean" in the bottom of all cards. Depending the size of the p tag the names have differente positions.

.test {
   display: flex;
    flex-direction: row;

}

.card {
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
/*   line-height: 20px !important;
  font-size: 18px !important;
  font-weight: 500 !important; */
}

.card:hover {
  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.card .container {
  padding: 2px 14px;
}

.card p {
  margin: 14px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Card</h2>

<div class="test">

<div class="card">
  <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
  <div class="container">
  <p>
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  </p>
    <h4>john dean</h4>
  </div>
</div>

<div class="card">
  <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
  <div class="container">
   <p>
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  </p>
    <h4>john dean</h4>
  </div>
</div>

</div></code>```

答:
I think display: flex will do the trick for you. Making card flex with container and expanding both card and container with flex: 1 will push make content expand, pushing p to the bottom.

.test {
   display: flex;
    flex-direction: row;

}

.card {
  display: flex;
  flex-direction: column;
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
/*   line-height: 20px !important;
  font-size: 18px !important;
  font-weight: 500 !important; */
}

.card:hover {
  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.card .container {
  display: flex;
  flex: 1;
  height: 100%;
  flex-direction: column;
  padding: 2px 14px;
}

.card p {
  flex: 1;
  margin: 14px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Card</h2>

<div class="test">

<div class="card">
  <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
  <div class="container">
  <p>
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  </p>
    <h4>john dean</h4>
  </div>
</div>

<div class="card">
  <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
  <div class="container">
   <p>
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  </p>
    <h4>john dean</h4>
  </div>
</div>

</div></code>```

Body:
How can I align booth names in the same line ?

The image above show the problem. I tried to use flex-box but is not working. I would like to position "John Dean" in the bottom of all cards. Depending the size of the p tag the names have differente positions.

.test {
   display: flex;
    flex-direction: row;

}

.card {
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
/*   line-height: 20px !important;
  font-size: 18px !important;
  font-weight: 500 !important; */
}

.card:hover {
  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.card .container {
  padding: 2px 14px;
}

.card p {
  margin: 14px 0;
}

Card

  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.

john dean

  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.

john dean

Body:
I think display: flex will do the trick for you. Making card flex with container and expanding both card and container with flex: 1 will push make content expand, pushing p to the bottom.

.test {
   display: flex;
    flex-direction: row;

}

.card {
  display: flex;
  flex-direction: column;
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
/*   line-height: 20px !important;
  font-size: 18px !important;
  font-weight: 500 !important; */
}

.card:hover {
  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.card .container {
  display: flex;
  flex: 1;
  height: 100%;
  flex-direction: column;
  padding: 2px 14px;
}

.card p {
  flex: 1;
  margin: 14px 0;
}

<h2>Card</h2>

<div class="test">

<div class="card">
  <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
  <div class="container">
  <p>
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  </p>
    <h4>john dean</h4>
  </div>
</div>

<div class="card">
  <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
  <div class="container">
   <p>
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  Lorem Ipsum ie like Aldus Pa
  geMaker including versions of Lorem Ipsum.
  </p>
    <h4>john dean</h4>
  </div>
</div>

</div>


答:
You should usee a nested  subquery whit aggregated  resutl  for join  </p>

```<code>  update tabC c
  JOIN  (
    select   c_id, ifnull(sum(payment),0) tot_payment
    from tabB
    group by c_id
  ) b ON b.c_id = c.id
  set c.total = (c.v1 - c.v2 - c.v3) - b.tot_payment
  where c.id= 983;
</code>```

Title: UPDATE VALUE IN MYSQL MARIA DB WITH JOIN

Body:
You should usee a nested  subquery whit aggregated  resutl  for join

  update tabC c
  JOIN  (
    select   c_id, ifnull(sum(payment),0) tot_payment
    from tabB
    group by c_id
  ) b ON b.c_id = c.id
  set c.total = (c.v1 - c.v2 - c.v3) - b.tot_payment
  where c.id= 983;


答:
Make the card and the inner container flex-columns, then tell the container to xpand as much as possible with flex:1.

Then push the h4 to the bottom of the container with margin-top:auto.

.test {
  display: flex;
  flex-direction: row;
}

.card {
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
  display: flex;
  flex-direction: column;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
  /*   line-height: 20px !important;
  font-size: 18px !important;
  font-weight: 500 !important; */
}

.card:hover {
  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.card .container {
  padding: 2px 14px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card h4 {
  margin-top: auto;
}

.card p {
  margin: 14px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Card</h2>

<div class="test">

  <div class="card">
    <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <p>
        Lorem Ipsum ie like Aldus Pa geMaker including versions of Lorem Ipsum.
      </p>
      <h4>john dean</h4>
    </div>
  </div>

  <div class="card">
    <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <p>
        Lorem Ipsum ie like Aldus Pa geMaker including versions of Lorem Ipsum. Lorem Ipsum ie like Aldus Pa geMaker including versions of Lorem Ipsum.
      </p>
      <h4>john dean</h4>
    </div>
  </div>

</div></code>```

Title: How to align items in two cards side by side

Body:
Make the card and the inner container flex-columns, then tell the container to xpand as much as possible with flex:1.

Then push the h4 to the bottom of the container with margin-top:auto.

.test {
  display: flex;
  flex-direction: row;
}

.card {
  border: 1px solid #dadada;
  box-shadow: 4px 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.2s;
  width: 50%;
  display: flex;
  flex-direction: column;
}

.card h3 {
  padding: 2px;
  margin: 8px 0;
  /*   line-height: 20px !important;
  font-size: 18px !important;
  font-weight: 500 !important; */
}

.card:hover {
  box-shadow: 8px 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.card .container {
  padding: 2px 14px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card h4 {
  margin-top: auto;
}

.card p {
  margin: 14px 0;
}

<h2>Card</h2>

<div class="test">

  <div class="card">
    <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <p>
        Lorem Ipsum ie like Aldus Pa geMaker including versions of Lorem Ipsum.
      </p>
      <h4>john dean</h4>
    </div>
  </div>

  <div class="card">
    <img src="https://www.washingtonpost.com/resizer/9YWv-qOa9uW7CQZ9UGiW23eTZzU=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/BTCNJJN2Y43KPHPXPQWPASXRKM.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <p>
        Lorem Ipsum ie like Aldus Pa geMaker including versions of Lorem Ipsum. Lorem Ipsum ie like Aldus Pa geMaker including versions of Lorem Ipsum.
      </p>
      <h4>john dean</h4>
    </div>
  </div>

</div>