问:
how to set several conditions on textAreaInput in shiny
My shiny works well. But I need some new conditions on textAreaInput().

My queston is:

Firstly, I mean I hope the upper genes input limit is 5 each time.

Secondly, if the input number is more than 5 and some input genes of them not match my total gene data, I hope it can be delete automatically.

Also, if the input number is more than 5 and all of them match my gene data, I hope only 5 input genes are selected and others should be removed.

I have add  tolower() and capitalize()and unique() to initialize the input gene to let all of the input genes and my total gene data be the same standard.

Here is my code, it works well:

```<code>library(shiny)
library(ggplot2)
library(DT)
library(pheatmap)
library(Hmisc)      ##  upper and lower

data<-structure(list(Name = c("A", "A", "A", "B", "B", "B", "C", "C",
                          "C", "D"), `0610005C13Rik` = c(0.424665254943466, 0.279103397038561,
                                                         0.158078889243373, 0.1439331633966, 0.226678169539756, 0.123022674203591,
                                                         0, 0.0575264589421532, 0.0941181834571747, 0.271984789609661),
                 `0610006L08Rik` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `0610007P14Rik` = c(12.806118142651,
                                                                                11.4382552893482, 13.9357832217265, 14.2645292042994, 14.945765717404,
                                                                                14.5469997037148, 6.60925104569544, 8.5208866040503, 7.67759477655631,
                                                                                5.1250399195198), `0610009B22Rik` = c(7.52603796214715, 6.55433995648707,
                                                                                7.32295752983399, 7.11970579975653, 6.33099006794741, 7.12373599276529,
                                                                                5.86943489378519, 3.56825071218655, 3.9535564719271, 3.48802886940983
                                                                                ), `0610009E02Rik` = c(0.185168046030845, 0.247821949927601,
                                                                                0.231596753511727, 0.175726887193673, 0.276749625923402,
                                                                                0.300394864975905, 0.263269726601418, 0.140467218570394,
                                                                                0.114908163045647, 0.110688042779122), `0610009L18Rik` = c(1.31956911898427,
                                                                                1.60969164366343, 1.26074937062469, 0.78268017446358, 1.11523776096204,
                                                                                0.947711828658839, 3.45263289541606, 1.35554269811025, 0.938292908100525,
                                                                                1.31466638208741), `0610009O20Rik` = c(18.7299635259571,
                                                                                17.3842871293536, 18.5627752307553, 21.4629852251455, 22.6402836654957,
                                                                                21.2444396709145, 20.8497978564997, 21.8549813492263, 17.9002684065608,
                                                                                23.4418304775222), `0610010B08Rik` = c(0, 0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0), `0610010F05Rik` = c(5.1366066315153, 4.4875410833769,
                                                                                4.68456790443224, 4.63427490124717, 4.49675344401973, 4.14533562229927,
                                                                                1.73688504460735, 2.29599806910547, 2.02824204009348, 2.27745145230829
                                                                                ), `0610010K14Rik` = c(34.965811473297, 28.7179970696566,
                                                                                32.5977715269141, 29.9814513489617, 29.9262002003054, 30.0479176240035,
                                                                                38.071647586648, 29.7626650589632, 28.6266691732093, 27.7424485401854
                                                                                )), row.names = c(NA, 10L), class = "data.frame")##

##

##
ui <- fluidPage(

    mainPanel("123",
      width = 9,
                  tabPanel("666",
                           hr(),
                           textAreaInput("n",
                                         width = 380,
                                         "555",
                                         rows = 4,
                                         cols = 1),

                           actionButton("submit", "Submit",width=120),
                           hr(),
                           uiOutput("all")

                  )
))

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

  observeEvent(list(input$submit), {
    updateTabsetPanel(session, "123",
                      selected = "666"
    )
  })

  ###########################
  global <- reactiveValues(out = NULL
  )

  output$all <- renderUI({
    global$out
  })

  observeEvent(input$submit,{

    global$out <- plotOutput("myPlot_enrichment")

  })

  #########################################
  myPlot_enrichment = reactiveVal()
  # ################################################################# enrichment
  observeEvent(input$submit, {

    names(data)<-names(data)%>%tolower()%>%capitalize()
    genes=as.vector(unlist(strsplit(input$n,"[ \n]")))
    genes<-genes%>%tolower()%>%capitalize()%>%unique()
    genes<-intersect(genes,names(data))
    validate(
      need(sum(unique(colnames(data[,-1])) %in% genes)<=5, "The number of genes is out of range."))

    data_new<-t(data[,genes])
    ##############
    myPlot_enrichment(
      if(nrow(data_new)>1){
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
  })

  ##################################  enrichment
  output$myPlot_enrichment = renderPlot({
    req(myPlot_enrichment())
    myPlot_enrichment()
  })
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)
</code>```

I hope somebody give me some advice.

update: 2022年02.10.14:45:49

I have solve my problem partly but I meet a problem again:
here is my new code:

```<code>myPlot_enrichment(
      if(0<length(genes)<6) {
        data_new<-t(data[,genes])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }else{
        data_new<-t(data[,genes[1:5]])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )

      }
    )
</code>```

It works well if I just run the if else module out of the myPlot_enrichment(). However, it doesn't work if I run the if else module in the myPlot_enrichment().

I don't know why. I hope somebody could give me some advice.

The error message below:

```<code>Error in nchar(sm[1L], type = "w") : invalid multibyte string, element 1
</code>```

答:
Wow, I find there always exist bug in R or shiny.

But I tried my best and find the perfect way to solve my problem.

Here is my new code:
it works well.

```<code>  observeEvent(input$submit, {
    names(data)<-names(data)%>%tolower()%>%capitalize()
    genes=as.vector(unlist(strsplit(input$n,"[ \n]")))
    genes<-genes%>%tolower()%>%capitalize()%>%unique()
    genes<-intersect(genes,names(data))
    validate(
      need(sum(unique(colnames(data_FPKM2[,-1])) %in% genes)>0, "The number of genes is out of range."))
    data_new<-t(data[,genes])
    data_new=round(data_new, 2)
    ##############
    myPlot_enrichment(

      if(length(genes)<6){
        data_new<-t(data[,genes])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      } else if(length(genes)>5){
        data_new<-t(data_FPKM2[,genes[1:5]])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
  })
</code>```

Body:
My shiny works well. But I need some new conditions on textAreaInput().

My queston is:

Firstly, I mean I hope the upper genes input limit is 5 each time.

Secondly, if the input number is more than 5 and some input genes of them not match my total gene data, I hope it can be delete automatically.

Also, if the input number is more than 5 and all of them match my gene data, I hope only 5 input genes are selected and others should be removed.

I have add  tolower() and capitalize()and unique() to initialize the input gene to let all of the input genes and my total gene data be the same standard.

Here is my code, it works well:

library(shiny)
library(ggplot2)
library(DT)
library(pheatmap)
library(Hmisc)      ##  upper and lower

data<-structure(list(Name = c("A", "A", "A", "B", "B", "B", "C", "C",
                          "C", "D"), `0610005C13Rik` = c(0.424665254943466, 0.279103397038561,
                                                         0.158078889243373, 0.1439331633966, 0.226678169539756, 0.123022674203591,
                                                         0, 0.0575264589421532, 0.0941181834571747, 0.271984789609661),
                 `0610006L08Rik` = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), `0610007P14Rik` = c(12.806118142651,
                                                                                11.4382552893482, 13.9357832217265, 14.2645292042994, 14.945765717404,
                                                                                14.5469997037148, 6.60925104569544, 8.5208866040503, 7.67759477655631,
                                                                                5.1250399195198), `0610009B22Rik` = c(7.52603796214715, 6.55433995648707,
                                                                                7.32295752983399, 7.11970579975653, 6.33099006794741, 7.12373599276529,
                                                                                5.86943489378519, 3.56825071218655, 3.9535564719271, 3.48802886940983
                                                                                ), `0610009E02Rik` = c(0.185168046030845, 0.247821949927601,
                                                                                0.231596753511727, 0.175726887193673, 0.276749625923402,
                                                                                0.300394864975905, 0.263269726601418, 0.140467218570394,
                                                                                0.114908163045647, 0.110688042779122), `0610009L18Rik` = c(1.31956911898427,
                                                                                1.60969164366343, 1.26074937062469, 0.78268017446358, 1.11523776096204,
                                                                                0.947711828658839, 3.45263289541606, 1.35554269811025, 0.938292908100525,
                                                                                1.31466638208741), `0610009O20Rik` = c(18.7299635259571,
                                                                                17.3842871293536, 18.5627752307553, 21.4629852251455, 22.6402836654957,
                                                                                21.2444396709145, 20.8497978564997, 21.8549813492263, 17.9002684065608,
                                                                                23.4418304775222), `0610010B08Rik` = c(0, 0, 0, 0, 0, 0,
                                                                                0, 0, 0, 0), `0610010F05Rik` = c(5.1366066315153, 4.4875410833769,
                                                                                4.68456790443224, 4.63427490124717, 4.49675344401973, 4.14533562229927,
                                                                                1.73688504460735, 2.29599806910547, 2.02824204009348, 2.27745145230829
                                                                                ), `0610010K14Rik` = c(34.965811473297, 28.7179970696566,
                                                                                32.5977715269141, 29.9814513489617, 29.9262002003054, 30.0479176240035,
                                                                                38.071647586648, 29.7626650589632, 28.6266691732093, 27.7424485401854
                                                                                )), row.names = c(NA, 10L), class = "data.frame")##

##

##
ui <- fluidPage(

    mainPanel("123",
      width = 9,
                  tabPanel("666",
                           hr(),
                           textAreaInput("n",
                                         width = 380,
                                         "555",
                                         rows = 4,
                                         cols = 1),

                           actionButton("submit", "Submit",width=120),
                           hr(),
                           uiOutput("all")

                  )
))

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

  observeEvent(list(input$submit), {
    updateTabsetPanel(session, "123",
                      selected = "666"
    )
  })

  ###########################
  global <- reactiveValues(out = NULL
  )

  output$all <- renderUI({
    global$out
  })

  observeEvent(input$submit,{

    global$out <- plotOutput("myPlot_enrichment")

  })

  #########################################
  myPlot_enrichment = reactiveVal()
  # ################################################################# enrichment
  observeEvent(input$submit, {

    names(data)<-names(data)%>%tolower()%>%capitalize()
    genes=as.vector(unlist(strsplit(input$n,"[ \n]")))
    genes<-genes%>%tolower()%>%capitalize()%>%unique()
    genes<-intersect(genes,names(data))
    validate(
      need(sum(unique(colnames(data[,-1])) %in% genes)<=5, "The number of genes is out of range."))

    data_new<-t(data[,genes])
    ##############
    myPlot_enrichment(
      if(nrow(data_new)>1){
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
  })

  ##################################  enrichment
  output$myPlot_enrichment = renderPlot({
    req(myPlot_enrichment())
    myPlot_enrichment()
  })
}
# Create Shiny app ----
shinyApp(ui = ui, server = server)

I hope somebody give me some advice.

update: 2022年02.10.14:45:49

I have solve my problem partly but I meet a problem again:
here is my new code:

myPlot_enrichment(
      if(0<length(genes)<6) {
        data_new<-t(data[,genes])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }else{
        data_new<-t(data[,genes[1:5]])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )

      }
    )

It works well if I just run the if else module out of the myPlot_enrichment(). However, it doesn't work if I run the if else module in the myPlot_enrichment().

I don't know why. I hope somebody could give me some advice.

The error message below:

Error in nchar(sm[1L], type = "w") : invalid multibyte string, element 1

Body:
Wow, I find there always exist bug in R or shiny.

But I tried my best and find the perfect way to solve my problem.

Here is my new code:
it works well.

  observeEvent(input$submit, {
    names(data)<-names(data)%>%tolower()%>%capitalize()
    genes=as.vector(unlist(strsplit(input$n,"[ \n]")))
    genes<-genes%>%tolower()%>%capitalize()%>%unique()
    genes<-intersect(genes,names(data))
    validate(
      need(sum(unique(colnames(data_FPKM2[,-1])) %in% genes)>0, "The number of genes is out of range."))
    data_new<-t(data[,genes])
    data_new=round(data_new, 2)
    ##############
    myPlot_enrichment(

      if(length(genes)<6){
        data_new<-t(data[,genes])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      } else if(length(genes)>5){
        data_new<-t(data_FPKM2[,genes[1:5]])
        pheatmap(log2(data_new+1), show_colnames = F,fontsize_row =8,
                 labels_row = as.expression(lapply(rownames(data_new), function(a) bquote(italic(.(a))))),
                 cluster_rows = T, cluster_cols = F,
                 fontsize = 11,
                 cellwidth=4
        )
      }
    )
  })


来源: stackexchange

问:
Cannot install R packages in Jupyter Notebook
I am trying to run R code in Jupyter and the R Kernel was added. Most of the time, packages can be installed successfully. However, some of the packages, such as RCurl and ggmap, would got error while installing.

Example:

```<code>install.packages("RCurl")
</code>```

Warning message in install.packages("RCurl"):
  “installation of package ‘RCurl’ had non-zero exit status”Updating HTML index of packages in '.Library'

Making 'packages.html' ... done

What should I do?

答:
You have to create a directory in which your package will be and do for eg:

install.packages('ggplot2',loc='your directory')

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run R code in Jupyter and the R Kernel was added. Most of the time, packages can be installed successfully. However, some of the packages, such as RCurl and ggmap, would got error while installing.

Example:

install.packages("RCurl")

Warning message in install.packages("RCurl"):
  “installation of package ‘RCurl’ had non-zero exit status”Updating HTML index of packages in '.Library'

Making 'packages.html' ... done

What should I do?

ContentLicense: CC BY-SA 4.0


问:
How to ovveride java method in Kotlin class
I have abstract java class. Also I have kotlin class which extends abstract java class. Why the overrides java methods doesn't calls in kotlin class? For example:</p>
```<code>public abstract class A {
    public void myMethod() {
   Log.d("test", "test");
    }
}

open class B:A(){
   override fun myMethod {
        super.myMethod()    // doesn't called
    }
}
</code>```

答:
Probably you just doesn't call myMethod from class B.

public abstract class A {
    public void myMethod() {
        System.out.println("test");
    }
}
```
<pre class="lang-kotlin prettyprint-override"><code>open class B : A() {
    override fun myMethod() {
        super.myMethod()
    }
}

fun main() {
    B().myMethod()
}
</code>```

Code above will print test in the console.

Body:
I have abstract java class. Also I have kotlin class which extends abstract java class. Why the overrides java methods doesn't calls in kotlin class? For example:

public abstract class A {
    public void myMethod() {
   Log.d("test", "test");
    }
}

open class B:A(){
   override fun myMethod {
        super.myMethod()    // doesn't called
    }
}

Body:
Probably you just doesn't call myMethod from class B.

public abstract class A {
    public void myMethod() {
        System.out.println("test");
    }
}

open class B : A() {
    override fun myMethod() {
        super.myMethod()
    }
}

fun main() {
    B().myMethod()
}

Code above will print test in the console.


答:
Finally, I solved this problem by below SQL, thanks so much for FanoFN's answer</p>
```<code>SELECT id,
       SUM(CASE WHEN rn = 1 THEN vals ELSE 0 END) AS 'day_1',
       SUM(CASE WHEN rn = 2 THEN vals ELSE 0 END) AS 'day_2',
       SUM(CASE WHEN rn = 3 THEN vals ELSE 0 END) AS 'day_3',
       SUM(CASE WHEN rn = 4 THEN vals ELSE 0 END) AS 'day_4',
       SUM(CASE WHEN rn = 5 THEN vals ELSE 0 END) AS 'day_5',
       SUM(CASE WHEN rn = 6 THEN vals ELSE 0 END) AS 'day_6',
       SUM(CASE WHEN rn = 7 THEN vals ELSE 0 END) AS 'day_7',
       SUM(CASE WHEN rn = 8 THEN vals ELSE 0 END) AS 'day_8',
       SUM(CASE WHEN rn = 9 THEN vals ELSE 0 END) AS 'day_9',
       SUM(CASE WHEN rn = 10 THEN vals ELSE 0 END) AS 'day_10',
       SUM(CASE WHEN rn = 11 THEN vals ELSE 0 END) AS 'day_11',
       SUM(CASE WHEN rn = 12 THEN vals ELSE 0 END) AS 'day_12',
       SUM(CASE WHEN rn = 13 THEN vals ELSE 0 END) AS 'day_13',
       SUM(CASE WHEN rn = 14 THEN vals ELSE 0 END) AS 'day_14',
       SUM(CASE WHEN rn = 15 THEN vals ELSE 0 END) AS 'day_15',
       SUM(CASE WHEN rn = 16 THEN vals ELSE 0 END) AS 'day_16',
       SUM(CASE WHEN rn = 17 THEN vals ELSE 0 END) AS 'day_17',
       SUM(CASE WHEN rn = 18 THEN vals ELSE 0 END) AS 'day_18',
       SUM(CASE WHEN rn = 19 THEN vals ELSE 0 END) AS 'day_19',
       SUM(CASE WHEN rn = 20 THEN vals ELSE 0 END) AS 'day_20',
       SUM(CASE WHEN rn > 20 THEN vals ELSE 0 END) AS 'day_others'
FROM
(SELECT SUM(value) AS vals, id, DATE_FORMAT(date,'%Y-%m-%d') AS dt,
       ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt DESC) AS rn
FROM test_table
GROUP BY id, dt) v
GROUP BY id;
</code>```

Title: how to sum value by DATE_FORMAT(date,'%Y-%m-%d'),the limit 20 sum(day by day), and sum remaining value if greater than 20?

Body:
How to sum value by DATE_FORMAT(date,'%Y-%m-%d') and id the first 20 rows of data(order by data desc), and sum the remaining value if greater than 20 else 0? supposed I have below data with below SQL, how to do it? thanks so much for any advice.

SELECT SUM(value), id, DATE_FORMAT(date,'%Y-%m-%d')
FROM test_table
GROUP BY id, DATE_FORMAT(date,'%Y-%m-%d')

sum(value)  id  DATE_FORMAT(date,'%Y-%m-%d')
--------------------------------------------
64.98   123456  2021-01-01
64.98   123456  2021-01-02
64.98   123456  2021-01-03
64.98   123456  2021-01-04
64.98   123456  2021-01-05
64.98   123456  2021-01-06
72.34   123456  2021-01-07
64.98   123456  2021-01-08
64.98   123456  2021-01-09
103.80  123456  2021-01-10
64.98   123456  2021-01-11
64.98   123456  2021-01-12
64.98   123456  2021-01-13
64.98   123456  2021-01-14
64.98   123456  2021-01-15
64.98   123456  2021-01-16
64.98   123456  2021-01-17
64.98   123456  2021-01-18
64.98   123456  2021-01-19
64.98   123456  2021-01-20
64.98   123456  2021-01-21
64.98   123456  2021-01-22
64.98   123456  2021-01-23
64.98   123456  2021-01-24
144.98  123456  2021-01-25
64.98   123456  2021-01-26
64.98   123456  2021-01-27
64.98   123456  2021-01-28
64.98   123456  2021-01-29
64.98   123456  2021-01-30
64.98   123456  2021-01-31
64.98   123456  2021-02-01
64.98   123456  2021-02-02
64.98   123456  2021-02-03
64.98   123456  2021-02-04
720.92  123456  2021-02-05
66.98   123456  2021-02-06
66.98   123456  2021-02-07
66.98   123456  2021-02-08
64.98   123456  2021-02-09
64.98   123456  2021-02-10
64.98   223456  2021-01-20
54.98   223456  2021-01-21

...................................

I need the output like below:

  id      day_1    day_2   .....  day_20   day_other
    --------------------------------------------
   123456  64.98   64.98  .....  234.67      2342.12
   223456  64.98   64.98  .....  234.67      2342.12

Body:
Finally, I solved this problem by below SQL, thanks so much for FanoFN's answer

SELECT id,
       SUM(CASE WHEN rn = 1 THEN vals ELSE 0 END) AS 'day_1',
       SUM(CASE WHEN rn = 2 THEN vals ELSE 0 END) AS 'day_2',
       SUM(CASE WHEN rn = 3 THEN vals ELSE 0 END) AS 'day_3',
       SUM(CASE WHEN rn = 4 THEN vals ELSE 0 END) AS 'day_4',
       SUM(CASE WHEN rn = 5 THEN vals ELSE 0 END) AS 'day_5',
       SUM(CASE WHEN rn = 6 THEN vals ELSE 0 END) AS 'day_6',
       SUM(CASE WHEN rn = 7 THEN vals ELSE 0 END) AS 'day_7',
       SUM(CASE WHEN rn = 8 THEN vals ELSE 0 END) AS 'day_8',
       SUM(CASE WHEN rn = 9 THEN vals ELSE 0 END) AS 'day_9',
       SUM(CASE WHEN rn = 10 THEN vals ELSE 0 END) AS 'day_10',
       SUM(CASE WHEN rn = 11 THEN vals ELSE 0 END) AS 'day_11',
       SUM(CASE WHEN rn = 12 THEN vals ELSE 0 END) AS 'day_12',
       SUM(CASE WHEN rn = 13 THEN vals ELSE 0 END) AS 'day_13',
       SUM(CASE WHEN rn = 14 THEN vals ELSE 0 END) AS 'day_14',
       SUM(CASE WHEN rn = 15 THEN vals ELSE 0 END) AS 'day_15',
       SUM(CASE WHEN rn = 16 THEN vals ELSE 0 END) AS 'day_16',
       SUM(CASE WHEN rn = 17 THEN vals ELSE 0 END) AS 'day_17',
       SUM(CASE WHEN rn = 18 THEN vals ELSE 0 END) AS 'day_18',
       SUM(CASE WHEN rn = 19 THEN vals ELSE 0 END) AS 'day_19',
       SUM(CASE WHEN rn = 20 THEN vals ELSE 0 END) AS 'day_20',
       SUM(CASE WHEN rn > 20 THEN vals ELSE 0 END) AS 'day_others'
FROM
(SELECT SUM(value) AS vals, id, DATE_FORMAT(date,'%Y-%m-%d') AS dt,
       ROW_NUMBER() OVER (PARTITION BY id ORDER BY dt DESC) AS rn
FROM test_table
GROUP BY id, dt) v
GROUP BY id;


问:
Webpack 5 - Uncaught ReferenceError: process is not defined
*** Edit - Ignore if you want answer only  ***

Seeing as this question is still receiving views and upvotes I feel responsible to share some knowledge after going through the webpack rabbithole and coming out the other end.

If you:

are building a greenfield/early-stage modern javascript project

are considering migrating from create-react-app

don't have much experience with bundling

do not need advanced features like module federation or server side rendering (which doesn't need webpack anymore)

Consider using the next generaton bundlers such as vite/parcel (easy setup), esbuild/rollup (more setup required)

Webpack was/is a fantastic contribution to the frontend world and I'm glad I learned all its intricacies, however, the new bundlers are much faster during development and easier to mantain. It's great when it works but for those inexperienced with it; despite fantastic docs the learning curve can make it a horrible pain to debug.

To clarify, I'm not a maintainer on any of these projects - just a dev who enjoys good tooling. In today's landscape, webpack is comparable to using a sledgehammer to crack a nut.

*** End of Edit ***

Webpack newbie here, I was told by webpack cli that I needed to provide an alias for crypto as webpack no longer includes default node libraries. Now I'm getting this error, other answers haven't helped so much. crypto-browserify is trying to access process.browser. Can anyone shed more light? I was told by cli to install stream-browserify too so i did.

React v17, Babel 7.12.9, webpack 5.6.0

webpack.common.js

```<code>const paths = require('./paths');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotenv = require('dotenv-webpack');

module.exports = {
  entry: [paths.src + '/index.js'],
  output: {
    path: paths.build,
    filename: '[name].bundle.js',
    publicPath: '/',
  },
  plugins: [
    new dotenv(),
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: paths.public,
          to: 'assets',
          globOptions: {
            ignore: ['*.DS_Store'],
          },
        },
      ],
    }),
    new HtmlWebpackPlugin({
      title: 'Webpack Boilerplate',
      // favicon: paths.src + '/images/favicon.png',
      template: paths.src + '/template.html',
      filename: 'index.html',
    }),
  ],
  resolve: {
    fallback: {
      crypto: require.resolve('crypto-browserify'),
      stream: require.resolve('stream-browserify'),
    },
  },
  module: {
    rules: [
      // javascript
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      // images
      {
        test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
        type: 'asset/resource',
      },
      // Fonts and SVGs
      {
        test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
        type: 'asset/inline',
      },
      // CSS, PostCSS, and Sass
      {
        test: /\.(scss|css)$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              esModule: true,
              sourceMap: true,
              importLoaders: 1,
              modules: {
                auto: true,
                namedExport: true,
              },
            },
          },
          { loader: 'postcss-loader', options: { sourceMap: true } },
          { loader: 'sass-loader', options: { sourceMap: true } },
        ],
      },
    ],
  },
};
</code>```

webpack.dev.js

```<code>const webpack = require('webpack');
const { merge } = require('webpack-merge');
const common = require('./webpack.common');

module.exports = merge(common, {
  mode: 'development',

  // Control how source maps are generated
  devtool: 'inline-source-map',

  // Spin up a server for quick development
  devServer: {
    historyApiFallback: true,
    contentBase: paths.build,
    open: true,
    compress: true,
    hot: true,
    port: 8080,
  },

  plugins: [
    // Only update what has changed on hot reload
    new webpack.HotModuleReplacementPlugin(),
  ],
});
</code>```

答:
I have this problem for HtmlWebpackPlugin, I added 'templateParameters' parameter to HtmlWebpackPlugin and it was fixed for me:</p>
```<code>new HtmlWebpackPlugin({
      baseUrl: '/',
      template: 'app/index.html',
      templateParameters(compilation, assets, options) {
        return {
          compilation,
          webpack: compilation.getStats().toJson(),
          webpackConfig: compilation.options,
          htmlWebpackPlugin: {
            files: assets,
            options,
          },
          process,
        }
      },
      chunksSortMode: 'auto',
      minify: {
        collapseWhitespace: false,
      },
      cache: true,
    }),
</code>```

Body:
*** Edit - Ignore if you want answer only  ***

Seeing as this question is still receiving views and upvotes I feel responsible to share some knowledge after going through the webpack rabbithole and coming out the other end.

If you:

are building a greenfield/early-stage modern javascript project

are considering migrating from create-react-app

don't have much experience with bundling

do not need advanced features like module federation or server side rendering (which doesn't need webpack anymore)

Consider using the next generaton bundlers such as vite/parcel (easy setup), esbuild/rollup (more setup required)

Webpack was/is a fantastic contribution to the frontend world and I'm glad I learned all its intricacies, however, the new bundlers are much faster during development and easier to mantain. It's great when it works but for those inexperienced with it; despite fantastic docs the learning curve can make it a horrible pain to debug.

To clarify, I'm not a maintainer on any of these projects - just a dev who enjoys good tooling. In today's landscape, webpack is comparable to using a sledgehammer to crack a nut.

*** End of Edit ***

Webpack newbie here, I was told by webpack cli that I needed to provide an alias for crypto as webpack no longer includes default node libraries. Now I'm getting this error, other answers haven't helped so much. crypto-browserify is trying to access process.browser. Can anyone shed more light? I was told by cli to install stream-browserify too so i did.

React v17, Babel 7.12.9, webpack 5.6.0

webpack.common.js

const paths = require('./paths');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotenv = require('dotenv-webpack');

module.exports = {
  entry: [paths.src + '/index.js'],
  output: {
    path: paths.build,
    filename: '[name].bundle.js',
    publicPath: '/',
  },
  plugins: [
    new dotenv(),
    new CleanWebpackPlugin(),
    new CopyWebpackPlugin({
      patterns: [
        {
          from: paths.public,
          to: 'assets',
          globOptions: {
            ignore: ['*.DS_Store'],
          },
        },
      ],
    }),
    new HtmlWebpackPlugin({
      title: 'Webpack Boilerplate',
      // favicon: paths.src + '/images/favicon.png',
      template: paths.src + '/template.html',
      filename: 'index.html',
    }),
  ],
  resolve: {
    fallback: {
      crypto: require.resolve('crypto-browserify'),
      stream: require.resolve('stream-browserify'),
    },
  },
  module: {
    rules: [
      // javascript
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ['babel-loader'],
      },
      // images
      {
        test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
        type: 'asset/resource',
      },
      // Fonts and SVGs
      {
        test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
        type: 'asset/inline',
      },
      // CSS, PostCSS, and Sass
      {
        test: /\.(scss|css)$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              esModule: true,
              sourceMap: true,
              importLoaders: 1,
              modules: {
                auto: true,
                namedExport: true,
              },
            },
          },
          { loader: 'postcss-loader', options: { sourceMap: true } },
          { loader: 'sass-loader', options: { sourceMap: true } },
        ],
      },
    ],
  },
};

webpack.dev.js

const webpack = require('webpack');
const { merge } = require('webpack-merge');
const common = require('./webpack.common');

module.exports = merge(common, {
  mode: 'development',

  // Control how source maps are generated
  devtool: 'inline-source-map',

  // Spin up a server for quick development
  devServer: {
    historyApiFallback: true,
    contentBase: paths.build,
    open: true,
    compress: true,
    hot: true,
    port: 8080,
  },

  plugins: [
    // Only update what has changed on hot reload
    new webpack.HotModuleReplacementPlugin(),
  ],
});

Body:
I have this problem for HtmlWebpackPlugin, I added 'templateParameters' parameter to HtmlWebpackPlugin and it was fixed for me:

new HtmlWebpackPlugin({
      baseUrl: '/',
      template: 'app/index.html',
      templateParameters(compilation, assets, options) {
        return {
          compilation,
          webpack: compilation.getStats().toJson(),
          webpackConfig: compilation.options,
          htmlWebpackPlugin: {
            files: assets,
            options,
          },
          process,
        }
      },
      chunksSortMode: 'auto',
      minify: {
        collapseWhitespace: false,
      },
      cache: true,
    }),


问:
How can I process this array more efficiently
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

```<code>       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }
</code>```

答:
You must process all elements in the array.

For every element, you must detect the spaces and retrieve the next letter.

Then you must build up the output array with concatenated capitals.

So I really don't see how you could avoid a double loop.

Only if part.count > 0 is unnecessary.

Alternatively, you can scan the strings yourself to avoid generating the intermediate array fullname.

You can probably also obtain the result by regex processing, but this would be a sledgehammer to crack nuts. Don't.

A possible implementation of the inner loop. (Sorry if this is invalid, I don't know Swift).

```<code>var space: Bool = true
for c in name {
  if space && c != ' ' {
    initials+= c
  }
  space= c == ' '
}
</code>```

Notice that the (optional) extra condition c != ' ' protects against double spaces.

Body:
I have an array of names that looks like the following.
["John Doe", "Mary Blog"]

What I want to do is process this array and return an array with the initials like the following.

["JD", "MB"]

I have already done this but my code is ugly and inefficient (nested loops).
It's probably fine for a small array like in my example.

How can I process my array more efficiently?

       let contacts = ["John Doe", "Mary Blog"]
       var initalsArray: [String] = []
       let names = contacts.map {$0}

            for name in names {
                var initals: String = ""
                let fullname = name.components(separatedBy: " ")
                for part in fullname {
                    if part.count > 0 {
                        initals += part[0]
                    }
                }
                initalsArray.append(initals)
            }

Body:
You must process all elements in the array.

For every element, you must detect the spaces and retrieve the next letter.

Then you must build up the output array with concatenated capitals.

So I really don't see how you could avoid a double loop.

Only if part.count > 0 is unnecessary.

Alternatively, you can scan the strings yourself to avoid generating the intermediate array fullname.

You can probably also obtain the result by regex processing, but this would be a sledgehammer to crack nuts. Don't.

A possible implementation of the inner loop. (Sorry if this is invalid, I don't know Swift).

var space: Bool = true
for c in name {
  if space && c != ' ' {
    initials+= c
  }
  space= c == ' '
}

Notice that the (optional) extra condition c != ' ' protects against double spaces.


问:
Javascript setTimeout is returning my function parameter value as undefined
Please refer to my below code:

//Principal Function
function greet3(name, sayName) {
  document.getElementById("jac3").innerHTML = "Hello " + name;
  sayName(name);
};
//Callback Function

function sayName(name) {
  document.getElementById("jac3").innerHTML += ". How are you? " + name;
}
//Calling the function after 10 seconds

greet3("Neha", setTimeout(sayName,3000));
//greet3("Neha", sayName);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="jac3"></p></code>```

When I use setTimeout function,

```<code>greet3("Neha", setTimeout(sayName,3000));
</code>```

the output of name gets undefined.

Please help me with correct syntax.

答:
When you write setTimeout(param1, param2) you are executing the function due to the parenthesis.

//Principal Function
function greet3(name, callback, timeout) {
  document.getElementById("jac3").innerHTML = "Hello " + name;
  setTimeout(() => callback(name), timeout);
};

//Callback Function
function sayName(name) {
  document.getElementById("jac3").innerHTML += ". How are you? " + name;
}

//Calling the function after 3 seconds
greet3("Neha", sayName, 3000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="jac3"></p></code>```

Body:
Please refer to my below code:

//Principal Function
function greet3(name, sayName) {
  document.getElementById("jac3").innerHTML = "Hello " + name;
  sayName(name);
};
//Callback Function

function sayName(name) {
  document.getElementById("jac3").innerHTML += ". How are you? " + name;
}
//Calling the function after 10 seconds

greet3("Neha", setTimeout(sayName,3000));
//greet3("Neha", sayName);

When I use setTimeout function,

greet3("Neha", setTimeout(sayName,3000));

the output of name gets undefined.

Please help me with correct syntax.

Body:
When you write setTimeout(param1, param2) you are executing the function due to the parenthesis.

//Principal Function
function greet3(name, callback, timeout) {
  document.getElementById("jac3").innerHTML = "Hello " + name;
  setTimeout(() => callback(name), timeout);
};

//Callback Function
function sayName(name) {
  document.getElementById("jac3").innerHTML += ". How are you? " + name;
}

//Calling the function after 3 seconds
greet3("Neha", sayName, 3000);

<p id="jac3"></p>


问:
restructure array in php
I have the following source array which I'm trying to restructure using group_name to give me the require output below.

Any help or pointers appreciated.
Thanks, Lk

Source:

```<code>Array
(
[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_b] => Array
    (
        [type] => number_integer
        [group_name] => group_other
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_d] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_e] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_f] => Array
    (
        [type] => text
        [group_name] => group_web_links
    )

)
</code>```

Output:

```<code>Array
(
[group_other] => Array
    (
        [field_b] => Array
           (
               [type] => number_integer
               [group_name] => group_other
           )
    )

[group_web_links] => Array
    (
        [field_d] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_e] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_f] => Array
            (
                [type] => text
                [group_name] => group_web_links
            )
    )

[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )
)
</code>```

答:
```<code>$new_array = array();
foreach( $old_array as $field_id => $field ) {
    if( $field[ 'group_name' ] == '' ) {
       $new_array[ $field_id ] = $field;
    } else {
       $new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;
    }
}
</code>```

I suppose those who are down voting this are doing it because I am not initializing $new_array[ $field[ 'group_name' ] ]. Well, that is not necessary in PHP, it will be automatically initialized with an empty array when you do $new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;.

Title: restructure array in php

Body:
I have the following source array which I'm trying to restructure using group_name to give me the require output below.

Any help or pointers appreciated.
Thanks, Lk

Source:

Array
(
[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_b] => Array
    (
        [type] => number_integer
        [group_name] => group_other
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_d] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_e] => Array
    (
        [type] => link
        [group_name] => group_web_links
    )

[field_f] => Array
    (
        [type] => text
        [group_name] => group_web_links
    )

)

Output:

Array
(
[group_other] => Array
    (
        [field_b] => Array
           (
               [type] => number_integer
               [group_name] => group_other
           )
    )

[group_web_links] => Array
    (
        [field_d] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_e] => Array
            (
                [type] => link
                [group_name] => group_web_links
            )

        [field_f] => Array
            (
                [type] => text
                [group_name] => group_web_links
            )
    )

[field_a] => Array
    (
        [type] => text
        [group_name] =>
    )

[field_c] => Array
    (
        [type] => text
        [group_name] =>
    )
)

Body:
$new_array = array();
foreach( $old_array as $field_id => $field ) {
    if( $field[ 'group_name' ] == '' ) {
       $new_array[ $field_id ] = $field;
    } else {
       $new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;
    }
}

I suppose those who are down voting this are doing it because I am not initializing $new_array[ $field[ 'group_name' ] ]. Well, that is not necessary in PHP, it will be automatically initialized with an empty array when you do $new_array[ $field[ 'group_name' ] ][ $field_id ] = $field;.


问:
How do you stage Camel K integrations?
If you are using Camel K with its operator on Kubernetes or OpenShift, how do you implement staging? Do I have to build the image for every stage - e.g. three times for test, ua and production? Or is there another way to deploy the once built image with the Camel K operator on further stages?</p>

答:
Once you have your Integration tested and staged, you can get the resulting IntegrationKit image as a reference for your production Integration, ie:

```<code>$ k get integrationkit
NAME                       PHASE   TYPE       IMAGE
kit-c82emh1c11s7ki7ijq0g   Ready   platform   10.108.177.66/default/camel-k-kit-c82emh1c11s7ki7ijq0g@sha256:10cd5eea251bc7992f08c9d96fc61d004ed220fbec7fefa20321e0956172a737

$ kamel run Sample.java -t container.image=10.108.177.66/default/camel-k-kit-c82emh1c11s7ki7ijq0g@sha256:10cd5eea251bc7992f08c9d96fc61d004ed220fbec7fefa20321e0956172a737 --dev
</code>```

Title: How do you stage Camel K integrations?

Body:
Once you have your Integration tested and staged, you can get the resulting IntegrationKit image as a reference for your production Integration, ie:

$ k get integrationkit
NAME                       PHASE   TYPE       IMAGE
kit-c82emh1c11s7ki7ijq0g   Ready   platform   10.108.177.66/default/camel-k-kit-c82emh1c11s7ki7ijq0g@sha256:10cd5eea251bc7992f08c9d96fc61d004ed220fbec7fefa20321e0956172a737

$ kamel run Sample.java -t container.image=10.108.177.66/default/camel-k-kit-c82emh1c11s7ki7ijq0g@sha256:10cd5eea251bc7992f08c9d96fc61d004ed220fbec7fefa20321e0956172a737 --dev


问:
Delphi 7 and SQLite
How can i connect an SQLite Database with Delphi 7 with dbexpress?
When i choose DB2Connection there cames an "Failure rto connect:Unable to load db2cli.dll" Error.

Is it possible to use Delphi 7 and SQLite?

Thanks for the Help.

答: To connect from Delphi 7 to SQLite using the dbExpress driver, you need to find a dbExpress Driver for SQLite.</p>

Title: Delphi 7 and SQLite


问:
c# splitting and retrieving values from a string
I have a string like this:

```<code>"http://localhost:55164/Images/photos/2/2.jpg"
</code>```

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

答:
You could cheat and use the Path class. This is easier and adds extra readability at the same time.

```<code>string path = "http://localhost:55164/Images/photos/2/2.jpg";
Console.WriteLine(Path.GetFileName(path));
string[] dirSplit = Path.GetDirectoryName(path).Split('\\');
Console.WriteLine(dirSplit[dirSplit.Length - 1]);
</code>```

Body:
I have a string like this:

"http://localhost:55164/Images/photos/2/2.jpg"

I need to retrieve the filename and the 2 out of the /2/ and put them into their own strings. I've been messing around with StringBuilder and replace and substr to no avail since the filename length is variable.  Anyone have a quick way to do this?

Thanks

Body:
You could cheat and use the Path class. This is easier and adds extra readability at the same time.

string path = "http://localhost:55164/Images/photos/2/2.jpg";
Console.WriteLine(Path.GetFileName(path));
string[] dirSplit = Path.GetDirectoryName(path).Split('\\');
Console.WriteLine(dirSplit[dirSplit.Length - 1]);


问:
Getting "16: Cannot find a matching credential" when doing One Tap sign-in and sign-up on Android
I have been following the guide for setting up One Tap sign-in and sign-up on Android, and have used the example code to set up the One Tap client, but every time I call oneTapClient.beginSignIn(signInRequest) I get a callback to OnFailureListener's onFailure():

```<code>com.google.android.gms.common.api.ApiException: 16: Cannot find a matching credential.
    at com.google.android.gms.common.api.internal.TaskUtil.setResultOrApiException(com.google.android.gms:play-services-base@@17.2.1:6)
    at com.google.android.gms.internal.auth-api.zzaj.zzc(com.google.android.gms:play-services-auth@@18.0.0:2)
    at com.google.android.gms.internal.auth-api.zzaa.dispatchTransaction(com.google.android.gms:play-services-auth@@18.0.0:6)
    at com.google.android.gms.internal.auth-api.zzc.onTransact(com.google.android.gms:play-services-auth@@18.0.0:13)
    at android.os.Binder.execTransactInternal(Binder.java:1021)
    at android.os.Binder.execTransact(Binder.java:994)
</code>```

What does this mean? Why am I getting this? I'm sure I must have missed something somewhere in the setup.

答:
It may be obvious but do also ensure that Package name in OAuth Client ID matches your build.

I had forgotten I had applicationIdSuffix in my build and I was using the wrong package name until I checked BuildConfig.APPLICATION_ID for my build's package name.

Body:
I have been following the guide for setting up One Tap sign-in and sign-up on Android, and have used the example code to set up the One Tap client, but every time I call oneTapClient.beginSignIn(signInRequest) I get a callback to OnFailureListener's onFailure():

com.google.android.gms.common.api.ApiException: 16: Cannot find a matching credential.
    at com.google.android.gms.common.api.internal.TaskUtil.setResultOrApiException(com.google.android.gms:play-services-base@@17.2.1:6)
    at com.google.android.gms.internal.auth-api.zzaj.zzc(com.google.android.gms:play-services-auth@@18.0.0:2)
    at com.google.android.gms.internal.auth-api.zzaa.dispatchTransaction(com.google.android.gms:play-services-auth@@18.0.0:6)
    at com.google.android.gms.internal.auth-api.zzc.onTransact(com.google.android.gms:play-services-auth@@18.0.0:13)
    at android.os.Binder.execTransactInternal(Binder.java:1021)
    at android.os.Binder.execTransact(Binder.java:994)

What does this mean? Why am I getting this? I'm sure I must have missed something somewhere in the setup.


问:
How to return only one closest value?
I have a table, which looks like this:

aircraft
flight
check_schedule
next_flight_schedule

Boeing
123
10.02.2022 21:00
11.02.2022 14:30

Boeing
234
10.02.2022 19:00
11.02.2022 22:50

Boeing
345
10.02.2022 21:00
11.02.2022 04:30

Airbus
789
21.02.2022 16:30
22.02.2022 01:20

Airbus
890
21.02.2022 22:30
22.02.2022 02:20

I need to extract only one row with the closest 'next_flight_schedule' that happened after 'check_schedule'. Like this:

aircraft
flight
check_schedule
next_flight_schedule

Boeing
345
10.02.2022 21:00
11.02.2022 04:30

Airbus
789
21.02.2022 16:30
22.02.2022 01:20

One column for each aircraft, but with the smallest date which happened after check_schedule. All columns should be displayed in the query.

答:
I need smallest value from next_flight_schedule for each aircraft

You can use the ROW_NUMBER analytic function:

SELECT aircraft,
       flight,
       check_schedule,
       next_flight_schedule
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER (
           PARTITION BY aircraft
           ORDER BY next_flight_schedule
         ) AS rn
  FROM   table_name t
)
WHERE  rn = 1
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name (
  aircraft             VARCHAR2(10),
  flight               NUMBER,
  check_schedule       DATE,
  next_flight_schedule DATE
);

INSERT INTO table_name (aircraft, flight, check_schedule, next_flight_schedule)
  SELECT 'Boeing', 123, TIMESTAMP '2022-02-10 21:00:00', TIMESTAMP '2022-02-11 14:30:00' FROM DUAL UNION ALL
  SELECT 'Boeing', 234, TIMESTAMP '2022-02-10 19:00:00', TIMESTAMP '2022-02-11 22:50:00' FROM DUAL UNION ALL
  SELECT 'Boeing', 345, TIMESTAMP '2022-02-10 21:00:00', TIMESTAMP '2022-02-11 04:30:00' FROM DUAL UNION ALL
  SELECT 'Airbus', 789, TIMESTAMP '2022-02-21 16:30:00', TIMESTAMP '2022-02-22 01:20:00' FROM DUAL UNION ALL
  SELECT 'Airbus', 890, TIMESTAMP '2022-02-21 22:30:00', TIMESTAMP '2022-02-22 02:20:00' FROM DUAL;
</code>```

Outputs:

AIRCRAFT
FLIGHT
CHECK_SCHEDULE
NEXT_FLIGHT_SCHEDULE

Airbus
789
2022-02-21 16:30:00
2022-02-22 01:20:00

Boeing
345
2022-02-10 21:00:00
2022-02-11 04:30:00

If you want to filter rows to get the earliest next_flight_schedule that is also after the maximum check_schedule then:

SELECT aircraft,
       flight,
       check_schedule,
       next_flight_schedule
FROM   (
  SELECT m.*,
         ROW_NUMBER() OVER (
           PARTITION BY aircraft
           ORDER BY next_flight_schedule
         ) AS rn
  FROM   (
    SELECT t.*,
           MAX(check_schedule) OVER (PARTITION BY aircraft) AS max_check
    FROM   table_name t
  ) m
  WHERE  next_flight_schedule >= max_check
)
WHERE  rn = 1
```

db<>fiddle here

Title: How to return only one closest value?

Body:
I need smallest value from next_flight_schedule for each aircraft

You can use the ROW_NUMBER analytic function:

SELECT aircraft,
       flight,
       check_schedule,
       next_flight_schedule
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER (
           PARTITION BY aircraft
           ORDER BY next_flight_schedule
         ) AS rn
  FROM   table_name t
)
WHERE  rn = 1

Which, for the sample data:

CREATE TABLE table_name (
  aircraft             VARCHAR2(10),
  flight               NUMBER,
  check_schedule       DATE,
  next_flight_schedule DATE
);

INSERT INTO table_name (aircraft, flight, check_schedule, next_flight_schedule)
  SELECT 'Boeing', 123, TIMESTAMP '2022-02-10 21:00:00', TIMESTAMP '2022-02-11 14:30:00' FROM DUAL UNION ALL
  SELECT 'Boeing', 234, TIMESTAMP '2022-02-10 19:00:00', TIMESTAMP '2022-02-11 22:50:00' FROM DUAL UNION ALL
  SELECT 'Boeing', 345, TIMESTAMP '2022-02-10 21:00:00', TIMESTAMP '2022-02-11 04:30:00' FROM DUAL UNION ALL
  SELECT 'Airbus', 789, TIMESTAMP '2022-02-21 16:30:00', TIMESTAMP '2022-02-22 01:20:00' FROM DUAL UNION ALL
  SELECT 'Airbus', 890, TIMESTAMP '2022-02-21 22:30:00', TIMESTAMP '2022-02-22 02:20:00' FROM DUAL;

Outputs:

AIRCRAFT
FLIGHT
CHECK_SCHEDULE
NEXT_FLIGHT_SCHEDULE

Airbus
789
2022-02-21 16:30:00
2022-02-22 01:20:00

Boeing
345
2022-02-10 21:00:00
2022-02-11 04:30:00

If you want to filter rows to get the earliest next_flight_schedule that is also after the maximum check_schedule then:

SELECT aircraft,
       flight,
       check_schedule,
       next_flight_schedule
FROM   (
  SELECT m.*,
         ROW_NUMBER() OVER (
           PARTITION BY aircraft
           ORDER BY next_flight_schedule
         ) AS rn
  FROM   (
    SELECT t.*,
           MAX(check_schedule) OVER (PARTITION BY aircraft) AS max_check
    FROM   table_name t
  ) m
  WHERE  next_flight_schedule >= max_check
)
WHERE  rn = 1

db<>fiddle here


问:
The named parameter isn't defined (data persistence)
There is my error , I want to solve this problem
enter image description here
The named parameter 'itemCount' isn't defined.
The named parameter 'itemBuilder' isn't defined.</p>

答:
A ListView() don't have thies properties but a ListView.builder() have they.

list view have children and not itembuilder.


问:
How to read audio files from Socket in C#?
I'm using socket programming to send live audio from my mobile to Desktop. I'm using C# language in Desktop side and JAVA in Mobile side. In desktop side I am receiving the audio that is send by mobile and is in the form of bytes. Can someone tell how I would convert these bytes that I have read from socket to audio file ? Below is, how I am reading bytes from socket

Console.WriteLine("Program started!!");
TcpClient client = null;
client = new TcpClient("192.168.0.113", 9999);
if (client.Connected)
{
    Console.Write("Client connected" );

    NetworkStream ns = client.GetStream();
    StreamReader sr = new StreamReader(ns);

    byte[] buffer = new byte[2048];
    ns.Read(buffer, 0, buffer.Length);
    Console.Write("Server>> " + sr.ReadLine());
    Console.Write("\n Audio Bytes are " );
    foreach (byte b in buffer )
    {
        if (b!=0)
        {
            Console.Write(b);
            //TODO Convert these bytes
        }
    }
    Console.Read();
}
```

Below is the output:

答:
If you want to write the bytes to a file, you can create a FileStream and copy the bytes from the network stream directly to the file stream with CopyTo:

```<code>var ns = client.GetStream();
using(var fileStream=File.Create(path))
{
    ns.CopyTo(fs);
}
</code>```

If you want to keep the bytes in memory and process them you can use a MemoryStream. This class is a Stream wrapper over a byte[] buffer.

```<code>using(var ms=new MemoryStream(2048))
{
    ns.CopyTo(ms);
}

var theBuffer=ms.GetBuffer();
</code>```

A MemoryStream grows by reallocating its internal buffer when it gets full. Specifying the capacity can eliminate or reduce reallocations, even if the initial capacity is a rough estimate.

Body:
I'm using socket programming to send live audio from my mobile to Desktop. I'm using C# language in Desktop side and JAVA in Mobile side. In desktop side I am receiving the audio that is send by mobile and is in the form of bytes. Can someone tell how I would convert these bytes that I have read from socket to audio file ? Below is, how I am reading bytes from socket

Console.WriteLine("Program started!!");
TcpClient client = null;
client = new TcpClient("192.168.0.113", 9999);
if (client.Connected)
{
    Console.Write("Client connected" );

    NetworkStream ns = client.GetStream();
    StreamReader sr = new StreamReader(ns);

    byte[] buffer = new byte[2048];
    ns.Read(buffer, 0, buffer.Length);
    Console.Write("Server>> " + sr.ReadLine());
    Console.Write("\n Audio Bytes are " );
    foreach (byte b in buffer )
    {
        if (b!=0)
        {
            Console.Write(b);
            //TODO Convert these bytes
        }
    }
    Console.Read();
}

Below is the output:

Body:
If you want to write the bytes to a file, you can create a FileStream and copy the bytes from the network stream directly to the file stream with CopyTo:

var ns = client.GetStream();
using(var fileStream=File.Create(path))
{
    ns.CopyTo(fs);
}

If you want to keep the bytes in memory and process them you can use a MemoryStream. This class is a Stream wrapper over a byte[] buffer.

using(var ms=new MemoryStream(2048))
{
    ns.CopyTo(ms);
}

var theBuffer=ms.GetBuffer();

A MemoryStream grows by reallocating its internal buffer when it gets full. Specifying the capacity can eliminate or reduce reallocations, even if the initial capacity is a rough estimate.


问:
How to pass env variable to client side in a nx workspace?
I'm running a nextJS app in a NX workspace and I need to get access to env variables on client side.

/apps/myproject/.local.env

```<code>NEXT_PUBLIC_PROJECT=my-super-project
</code>```

/apps/myproject/next.config.tsx

```<code>module.exports = {
  publicRuntimeConfig: {
    PROJECT: process.env.NEXT_PUBLIC_PROJECT
  }
}
</code>```

In my nextJS app I'm trying several things:

/apps/myproject/pages/_app.tsx

```<code>import nextConfig from 'next/config'
const { publicRuntimeConfig } = nextConfig()
// ...
console.log(process, publicRuntimeConfig)
</code>```

Running the app via nx serve myproject does not give me any output on client, but on server side I do see the NEXT_PUBLIC_PROJECT value. I'm not quite sure if my next.config.js file is read by nx at all...

答:
For anyone who is still having this issue.

For loading the env variables in react project, followings are required:

Create a .env file at application level.

Example: apps/myReactApp/.env

Add the variable ther with prefix NX

Example:
If you can variable called "APP_NAME", then add "NX_APP_NAME" in it.
NX loads only those variables which are prefixed with "NX".

If you want to load different env files for different configuration, then you can do it like this:

```<code>For QA: `npx env-cmd -f apps/web-client/.env.qa nx run web-client:build:qa`,
For staging: `npx env-cmd -f apps/web-client/.env.staging nx run web-client:build:staging`,
NOTE: you need to install env-cmd package
</code>```

More about loading environment variable in their doc.

Body:
I'm running a nextJS app in a NX workspace and I need to get access to env variables on client side.

/apps/myproject/.local.env

NEXT_PUBLIC_PROJECT=my-super-project

/apps/myproject/next.config.tsx

module.exports = {
  publicRuntimeConfig: {
    PROJECT: process.env.NEXT_PUBLIC_PROJECT
  }
}

In my nextJS app I'm trying several things:

/apps/myproject/pages/_app.tsx

import nextConfig from 'next/config'
const { publicRuntimeConfig } = nextConfig()
// ...
console.log(process, publicRuntimeConfig)

Running the app via nx serve myproject does not give me any output on client, but on server side I do see the NEXT_PUBLIC_PROJECT value. I'm not quite sure if my next.config.js file is read by nx at all...

Body:
For anyone who is still having this issue.

For loading the env variables in react project, followings are required:

Create a .env file at application level.

Example: apps/myReactApp/.env

Add the variable ther with prefix NX

Example:
If you can variable called "APP_NAME", then add "NX_APP_NAME" in it.
NX loads only those variables which are prefixed with "NX".

If you want to load different env files for different configuration, then you can do it like this:

For QA: `npx env-cmd -f apps/web-client/.env.qa nx run web-client:build:qa`,
For staging: `npx env-cmd -f apps/web-client/.env.staging nx run web-client:build:staging`,
NOTE: you need to install env-cmd package

More about loading environment variable in their doc.


问:
Writing to shared memory in Python is very slow
I use python.multiprocessing.sharedctypes.RawArray to share large numpy arrays between multiple processes.  And I've noticed that when this array is large (> 1 or 2 Gb) it becomes very slow to initialize and also much slower to read/write to (and read/write time is not predictable, sometimes pretty fast, sometimes very very slow).

I've made a small sample script that uses just one process, initialize a shared array and write to it several times.  And measures time to do these operations.

```<code>import argparse
import ctypes
import multiprocessing as mp
import multiprocessing.sharedctypes as mpsc
import numpy as np
import time

def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-c', '--block-count', type=int, default=1,
                        help='Number of blocks to write')
    parser.add_argument('-w', '--block-width', type=int, default=20000,
                        help='Block width')
    parser.add_argument('-d', '--block-depth', type=int, default=15000,
                        help='Block depth')
    args = parser.parse_args()
    blocks = args.block_count
    blockwidth = args.block_width
    depth = args.block_depth
    start = time.perf_counter()
    shared_array = mpsc.RawArray(ctypes.c_uint16, blocks*blockwidth*depth)
    finish = time.perf_counter()
    print('Init shared array of size {:.2f} Gb: {:.2f} s'.format(blocks*blockwidth*depth*ctypes.sizeof(ctypes.c_uint16)/1024/1024/1024, (finish-start)))
    numpy_array = np.ctypeslib.as_array(shared_array).reshape(blocks*blockwidth, depth)
    start = time.perf_counter()
    for i in range(blocks):
        begin = time.perf_counter()
        numpy_array[i*blockwidth:(i+1)*blockwidth, :] = np.ones((blockwidth, depth), dtype=np.uint16)
        end = time.perf_counter()
        print('Write = %.2f s' % (end-begin))
    finish = time.perf_counter()
    print('Total time = %.2f s' % (finish-start))

if __name__ == '__main__':
    main()
</code>```

When I run this code I get the following on my PC:

```<code>$ python shared-minimal.py -c 1
Init shared array of size 0.56 Gb: 0.36 s
Write = 0.13 s
Total time = 0.13 s
$ python shared-minimal.py -c 2
Init shared array of size 1.12 Gb: 0.72 s
Write = 0.12 s
Write = 0.13 s
Total time = 0.25 s
$ python shared-minimal.py -c 4
Init shared array of size 2.24 Gb: 5.40 s
Write = 1.17 s
Write = 1.17 s
Write = 1.17 s
Write = 1.57 s
Total time = 5.08 s
</code>```

In the last case, when array size is more than 2 Gb, initialization time is not linearly dependent on array size, and assigning save size slices to the array is more than 5 times slower.

I wonder why that happens.  I'm running the script on Ubuntu 16.04 using Python 3.5.  I also noticed by using iotop that when initializing and writing to the array there is a disk writing activity with same size as shared array, but I'm not sure if a real file is created or it's only in-memory operation (I suppose it should be).  In general my system becomes less responsive as well in case of large shared array.  There is no swapping, checked with top, ipcs -mu and vmstat.

答:
Since python 3.8 you can use shared_memory, which seems to be much more efficient and plays nicely with numpy arrays. I did some rough testing and creating an array with shape (5000,5000) took cca 3s with multiprocessing.Array and only cca 0.015s with shared_memory.SharedMemory

Below is a use case for SharedMemory where I create, with multiple processes, an array for each item that comes into the input queue and read them from a separate process in the same order as they come in.

```<code>import os
import multiprocessing as mp
import numpy as np
import time
from multiprocessing import shared_memory

class FunctionTimer:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, type, value, traceback):
        self.end = time.time()
        self.exec_time = self.end - self.start
        print(f"{self.name} time: {self.exec_time}")

class MpArrayProcessor:
    def __init__(self, in_queue, out_queue):
        self.in_queue = in_queue
        self.out_queue = out_queue
        self.stop_event = mp.Event()
        self.processes = []
        self.cur_id = 0
        self.order_dict = {}

        self.writable_dict = {}
        self.array_locks = {}
        self.array_data_dict = {}

    @staticmethod
    def wrap_func(func, arr_shape, in_queue, out_queue, stop_event, writable, shmem_name):
        pid = os.getpid()

        while True:
            if stop_event.is_set():
                print("Stopping")
                break
            x = in_queue.get(block=True)

            if x is None:
                break
            else:
                res = func(arr_shape, x)
                with FunctionTimer("Wait and write"):
                    writable.wait()
                    shmem = shared_memory.SharedMemory(name=shmem_name, create=False)
                    c = np.ndarray(arr_shape, dtype=np.uint8, buffer=shmem.buf)
                    c[:] = res

                writable.clear()
                out_queue.put((pid, shmem_name, x))

    def start(self, func, arr_shape, n_proc):
        # TODO implement proper closing of SharedMemory
        for p in range(n_proc):
            writable = mp.Event()
            writable.set()

            shmem_name = f"ps_{p}"
            data = shared_memory.SharedMemory(create=True, size=arr_shape[0] * arr_shape[1], name=shmem_name)
            p = mp.Process(target=self.wrap_func,
                           args=(
                               func, arr_shape, self.in_queue, self.out_queue, self.stop_event, writable, shmem_name))

            p.start()
            self.writable_dict[p.pid] = writable
            self.array_data_dict[p.pid] = data
            self.processes.append(p)

    def get(self):
        while True:
            if self.cur_id in self.order_dict:
                pid, shmem_name, order = self.order_dict[self.cur_id]
                print(f"PID: {pid}, idx: {order}, dict_len: {len(self.order_dict)}")
                shmem = shared_memory.SharedMemory(name=shmem_name, create=False)
                result = np.copy(np.frombuffer(shmem.buf, dtype=np.uint8))
                self.writable_dict[pid].set()
                del self.order_dict[self.cur_id]
                self.cur_id += 1
                return result
            print(self.order_dict)
            pid, shmem_name, order = self.out_queue.get(block=True)
            if order == self.cur_id:
                print(f"PID: {pid}, idx: {order}, dict_len: {len(self.order_dict)}")
                shmem = shared_memory.SharedMemory(name=shmem_name, create=False)
                print(np.frombuffer(shmem.buf, dtype=np.uint8))
                result = np.copy(np.frombuffer(shmem.buf, dtype=np.uint8))
                self.writable_dict[pid].set()

                self.cur_id += 1
                return result
            else:
                self.order_dict[order] = (pid, shmem_name, order)

    def close(self):
        self.stop_event.set()
        print("Event set")
        for p in self.processes:
            self.array_data_dict[p.pid].close()
            self.array_data_dict[p.pid].unlink()
            p.join()
            print("Joined")
            p.close()
            print("Closed")

def create_data(shape, x):
    time.sleep(0.08)
    # np.random.randint(0, 255, shape, dtype=np.uint8)
    return np.ones(shape, dtype=np.uint8) * x

def fill_queue(queue, n_elements, n_processes):
    l = [x for x in range(n_elements)]
    for i in l:
        queue.put(i)
    for i in range(n_processes):
        queue.put(None)

    print("filling finished")

if __name__ == "__main__":
    print(f"Running: {__file__}")
    print(f"Script dir: {os.path.dirname(os.path.abspath(__file__))}")
    print(f"Working dir: {os.path.abspath(os.getcwd())}")

    n = 100
    n_proc = 4
    input_queue = mp.Queue()
    output_queue = mp.Queue(maxsize=50)
    # shape = (3, 3)
    # shape = (1280, 720)
    shape = (5000, 5000)

    in_proc = mp.Process(target=fill_queue, args=(input_queue, n, n_proc))
    in_proc.start()

    with FunctionTimer("MP processing"):
        arr_processor = MpArrayProcessor(input_queue, output_queue)
        arr_processor.start(create_data, shape, 4)

        results = []

        for i in range(n):
            print(f"Getting: {i}")
            r = arr_processor.get()[:shape[0]*shape[1]].reshape(shape)
            results.append(r)

        arr_processor.close()

    in_proc.join()
    in_proc.close()

    print(results)

    with FunctionTimer("Normal"):
        for i in range(n):
            a = create_data(shape, i)
</code>```

Body:
I use python.multiprocessing.sharedctypes.RawArray to share large numpy arrays between multiple processes.  And I've noticed that when this array is large (> 1 or 2 Gb) it becomes very slow to initialize and also much slower to read/write to (and read/write time is not predictable, sometimes pretty fast, sometimes very very slow).

I've made a small sample script that uses just one process, initialize a shared array and write to it several times.  And measures time to do these operations.

import argparse
import ctypes
import multiprocessing as mp
import multiprocessing.sharedctypes as mpsc
import numpy as np
import time

def main():
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-c', '--block-count', type=int, default=1,
                        help='Number of blocks to write')
    parser.add_argument('-w', '--block-width', type=int, default=20000,
                        help='Block width')
    parser.add_argument('-d', '--block-depth', type=int, default=15000,
                        help='Block depth')
    args = parser.parse_args()
    blocks = args.block_count
    blockwidth = args.block_width
    depth = args.block_depth
    start = time.perf_counter()
    shared_array = mpsc.RawArray(ctypes.c_uint16, blocks*blockwidth*depth)
    finish = time.perf_counter()
    print('Init shared array of size {:.2f} Gb: {:.2f} s'.format(blocks*blockwidth*depth*ctypes.sizeof(ctypes.c_uint16)/1024/1024/1024, (finish-start)))
    numpy_array = np.ctypeslib.as_array(shared_array).reshape(blocks*blockwidth, depth)
    start = time.perf_counter()
    for i in range(blocks):
        begin = time.perf_counter()
        numpy_array[i*blockwidth:(i+1)*blockwidth, :] = np.ones((blockwidth, depth), dtype=np.uint16)
        end = time.perf_counter()
        print('Write = %.2f s' % (end-begin))
    finish = time.perf_counter()
    print('Total time = %.2f s' % (finish-start))

if __name__ == '__main__':
    main()

When I run this code I get the following on my PC:

$ python shared-minimal.py -c 1
Init shared array of size 0.56 Gb: 0.36 s
Write = 0.13 s
Total time = 0.13 s
$ python shared-minimal.py -c 2
Init shared array of size 1.12 Gb: 0.72 s
Write = 0.12 s
Write = 0.13 s
Total time = 0.25 s
$ python shared-minimal.py -c 4
Init shared array of size 2.24 Gb: 5.40 s
Write = 1.17 s
Write = 1.17 s
Write = 1.17 s
Write = 1.57 s
Total time = 5.08 s

In the last case, when array size is more than 2 Gb, initialization time is not linearly dependent on array size, and assigning save size slices to the array is more than 5 times slower.

I wonder why that happens.  I'm running the script on Ubuntu 16.04 using Python 3.5.  I also noticed by using iotop that when initializing and writing to the array there is a disk writing activity with same size as shared array, but I'm not sure if a real file is created or it's only in-memory operation (I suppose it should be).  In general my system becomes less responsive as well in case of large shared array.  There is no swapping, checked with top, ipcs -mu and vmstat.

Body:
Since python 3.8 you can use shared_memory, which seems to be much more efficient and plays nicely with numpy arrays. I did some rough testing and creating an array with shape (5000,5000) took cca 3s with multiprocessing.Array and only cca 0.015s with shared_memory.SharedMemory

Below is a use case for SharedMemory where I create, with multiple processes, an array for each item that comes into the input queue and read them from a separate process in the same order as they come in.

import os
import multiprocessing as mp
import numpy as np
import time
from multiprocessing import shared_memory

class FunctionTimer:
    def __init__(self, name):
        self.name = name

    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, type, value, traceback):
        self.end = time.time()
        self.exec_time = self.end - self.start
        print(f"{self.name} time: {self.exec_time}")

class MpArrayProcessor:
    def __init__(self, in_queue, out_queue):
        self.in_queue = in_queue
        self.out_queue = out_queue
        self.stop_event = mp.Event()
        self.processes = []
        self.cur_id = 0
        self.order_dict = {}

        self.writable_dict = {}
        self.array_locks = {}
        self.array_data_dict = {}

    @staticmethod
    def wrap_func(func, arr_shape, in_queue, out_queue, stop_event, writable, shmem_name):
        pid = os.getpid()

        while True:
            if stop_event.is_set():
                print("Stopping")
                break
            x = in_queue.get(block=True)

            if x is None:
                break
            else:
                res = func(arr_shape, x)
                with FunctionTimer("Wait and write"):
                    writable.wait()
                    shmem = shared_memory.SharedMemory(name=shmem_name, create=False)
                    c = np.ndarray(arr_shape, dtype=np.uint8, buffer=shmem.buf)
                    c[:] = res

                writable.clear()
                out_queue.put((pid, shmem_name, x))

    def start(self, func, arr_shape, n_proc):
        # TODO implement proper closing of SharedMemory
        for p in range(n_proc):
            writable = mp.Event()
            writable.set()

            shmem_name = f"ps_{p}"
            data = shared_memory.SharedMemory(create=True, size=arr_shape[0] * arr_shape[1], name=shmem_name)
            p = mp.Process(target=self.wrap_func,
                           args=(
                               func, arr_shape, self.in_queue, self.out_queue, self.stop_event, writable, shmem_name))

            p.start()
            self.writable_dict[p.pid] = writable
            self.array_data_dict[p.pid] = data
            self.processes.append(p)

    def get(self):
        while True:
            if self.cur_id in self.order_dict:
                pid, shmem_name, order = self.order_dict[self.cur_id]
                print(f"PID: {pid}, idx: {order}, dict_len: {len(self.order_dict)}")
                shmem = shared_memory.SharedMemory(name=shmem_name, create=False)
                result = np.copy(np.frombuffer(shmem.buf, dtype=np.uint8))
                self.writable_dict[pid].set()
                del self.order_dict[self.cur_id]
                self.cur_id += 1
                return result
            print(self.order_dict)
            pid, shmem_name, order = self.out_queue.get(block=True)
            if order == self.cur_id:
                print(f"PID: {pid}, idx: {order}, dict_len: {len(self.order_dict)}")
                shmem = shared_memory.SharedMemory(name=shmem_name, create=False)
                print(np.frombuffer(shmem.buf, dtype=np.uint8))
                result = np.copy(np.frombuffer(shmem.buf, dtype=np.uint8))
                self.writable_dict[pid].set()

                self.cur_id += 1
                return result
            else:
                self.order_dict[order] = (pid, shmem_name, order)

    def close(self):
        self.stop_event.set()
        print("Event set")
        for p in self.processes:
            self.array_data_dict[p.pid].close()
            self.array_data_dict[p.pid].unlink()
            p.join()
            print("Joined")
            p.close()
            print("Closed")

def create_data(shape, x):
    time.sleep(0.08)
    # np.random.randint(0, 255, shape, dtype=np.uint8)
    return np.ones(shape, dtype=np.uint8) * x

def fill_queue(queue, n_elements, n_processes):
    l = [x for x in range(n_elements)]
    for i in l:
        queue.put(i)
    for i in range(n_processes):
        queue.put(None)

    print("filling finished")

if __name__ == "__main__":
    print(f"Running: {__file__}")
    print(f"Script dir: {os.path.dirname(os.path.abspath(__file__))}")
    print(f"Working dir: {os.path.abspath(os.getcwd())}")

    n = 100
    n_proc = 4
    input_queue = mp.Queue()
    output_queue = mp.Queue(maxsize=50)
    # shape = (3, 3)
    # shape = (1280, 720)
    shape = (5000, 5000)

    in_proc = mp.Process(target=fill_queue, args=(input_queue, n, n_proc))
    in_proc.start()

    with FunctionTimer("MP processing"):
        arr_processor = MpArrayProcessor(input_queue, output_queue)
        arr_processor.start(create_data, shape, 4)

        results = []

        for i in range(n):
            print(f"Getting: {i}")
            r = arr_processor.get()[:shape[0]*shape[1]].reshape(shape)
            results.append(r)

        arr_processor.close()

    in_proc.join()
    in_proc.close()

    print(results)

    with FunctionTimer("Normal"):
        for i in range(n):
            a = create_data(shape, i)


问:
C vs C++ - cross-platform
I have a very quick question to which I havn't found an answer for.
Are there any major platforms (Windows, MacOS, unix, linux, Android, iOS, etc....) out there that supports C but not C++?

Thanks

答: C and C++ are not operating system dependant. If there is a compiler that can compile the C/C++ code to execute not he current CPU. All is good.</p>

Title: C vs C++ - cross-platform


问:
Where is Android Studio Markdown support plugin preview preference?
I want to show preview for markdown.
But it is not shown.

I am using Markdown support by JetBrains. And Android Studio 3.1

I found IntelliJ help.

https://www.jetbrains.com/help/idea/markdown.html

But I can not see that preference.

How can I see markdown preview?

答:
Updating JetBrains Runtime (JBR) will solve the issue.

Start the IDE, use Help -> Find Action, type "Choose Boot Java Runtime for the IDE", press Enter.

Select the newest version with JCEF to install.

Click the OK button and wait until the file with JetBrains Runtime is downloaded and configured.

Restart the IDE and Enjoy.

How to do Video: https://youtu.be/Mtu3dUgK480


问:
Filtered Group-How to group one column with and add calculated columns
DATASET I CURRENTLY HAVE-

```<code>COUNTRY city    id  tag dummy
India   ackno   1   2   1
China   open    0   0   1
India   ackno   1   2   1
China   open    0   0   1
USA     open    0   0   1
USA     open    0   0   1
China   ackno   1   2   1
USA     ackno   1   2   1
USA     resol   1   0   1
Russia  open    0   0   1
Italy   open    0   0   1
</code>```

country=df['country'].unique().tolist()
city=['resol','ackno']

#below are the preferred filters for calculating column percentage
df_looped=df[(df['city'].isin(city)) & (df['id']!=0) | (df['tag']!=0)]
percentage=(df_looped/df)*100

df_summed=df.groupby(['COUNTRY']).agg({'COUNTRY':'count'})
summed=df_summed['COUNTRY'].sum(axis=0)
```
<p>THE DATASET I WANT-</p>
```COUNTRY percentage  summed
india   100%          2
China   66.66%        3
USA     25%           4
Russia  0%            1
Italy   0%            1
```

percentage should be derived from the above formula for every unique country and same for the sum.
percentage variable and summed variable should populate the columns.

答:
You can use pivot_table with a dict of functions to apply to your dataframe. You have to assign before a new column with your conditions (looped):

```<code>funcs = {
    'looped': [
        ('percentage', lambda x: f"{round(sum(x) / len(x) * 100, 2)}%"),
        ('summed', 'size')
  ]
}

# Your code without df[...]
looped = (df['city'].isin(city)) & (df['id'] != 0) | (df['tag'] != 0)

out = df.assign(looped=looped).pivot_table('looped', 'COUNTRY', aggfunc=funcs)
</code>```

Output:

```<code>>>> out
        percentage  summed
COUNTRY
China       33.33%       3
India       100.0%       2
Italy         0.0%       1
Russia        0.0%       1
USA          50.0%       4
</code>```

Body:
DATASET I CURRENTLY HAVE-

COUNTRY city    id  tag dummy
India   ackno   1   2   1
China   open    0   0   1
India   ackno   1   2   1
China   open    0   0   1
USA     open    0   0   1
USA     open    0   0   1
China   ackno   1   2   1
USA     ackno   1   2   1
USA     resol   1   0   1
Russia  open    0   0   1
Italy   open    0   0   1

country=df['country'].unique().tolist()
city=['resol','ackno']

#below are the preferred filters for calculating column percentage
df_looped=df[(df['city'].isin(city)) & (df['id']!=0) | (df['tag']!=0)]
percentage=(df_looped/df)*100

df_summed=df.groupby(['COUNTRY']).agg({'COUNTRY':'count'})
summed=df_summed['COUNTRY'].sum(axis=0)

THE DATASET I WANT-

COUNTRY percentage  summed
india   100%          2
China   66.66%        3
USA     25%           4
Russia  0%            1
Italy   0%            1

percentage should be derived from the above formula for every unique country and same for the sum.
percentage variable and summed variable should populate the columns.

Body:
You can use pivot_table with a dict of functions to apply to your dataframe. You have to assign before a new column with your conditions (looped):

funcs = {
    'looped': [
        ('percentage', lambda x: f"{round(sum(x) / len(x) * 100, 2)}%"),
        ('summed', 'size')
  ]
}

# Your code without df[...]
looped = (df['city'].isin(city)) & (df['id'] != 0) | (df['tag'] != 0)

out = df.assign(looped=looped).pivot_table('looped', 'COUNTRY', aggfunc=funcs)

Output:

>>> out
        percentage  summed
COUNTRY
China       33.33%       3
India       100.0%       2
Italy         0.0%       1
Russia        0.0%       1
USA          50.0%       4


问:
Vue: new project, app div has margin around it, how to remove blank space
I have this code in a brand new Vue project:

App.vue:

```<code><template>

  <div id="app">
    <p>hey</p>
  </div>

</template>

<script>

export default {
  name: 'App',
  components: {

  }
}
</script>

<style>
#app {
  background-color: red;

  margin: 0px !important;
}
</style>
</code>```

It looks like this:

As can be seen, there is white space on top of and to the left and to the right of the app div. How do I remove it, so that it looks like this:

EDIT:

Adding

```<code>body  {
  padding: 0 !important;
  margin: 0 !important;
}
</code>```

resulted in this:

答:
You can try this :

body {
  margin: 0px !important;
}
p {
  background-color: red;
  margin: 0px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="app">
   <p>hey</p>
</div></code>```

Body:
I have this code in a brand new Vue project:

App.vue:

<template>

hey

</template>

It looks like this:

As can be seen, there is white space on top of and to the left and to the right of the app div. How do I remove it, so that it looks like this:

EDIT:

Adding

body  {
  padding: 0 !important;
  margin: 0 !important;
}

resulted in this:

Body:
You can try this :

body {
  margin: 0px !important;
}
p {
  background-color: red;
  margin: 0px !important;
}

<div id="app">
   <p>hey</p>
</div>


问:
Image Recongition with pyautogui: How do I search for multiple areas at once?
I'm using python to search for images and I can do that with one area but how can I adapt this code for multiple areas?</p>
```<code>found_image = pyautogui.locateOnScreen(image)
if found_image !=None:
    pyautogui.click(found_image)
</code>```

答:
welcome to stack! PIL has a flag for regions literally called region. If you specify where you regions are top left x and y and bottom right x and y you can them loop through the regions with for region_name, region in regions.items(): and then do something if your image is found in any of the regions.

```<code>regions = {
"Top left": (top, left, bottom, right),
"Bottom left": (top, left, bottom, right),
"Top right": (top, left, bottom, right),
"Bottom right": (top, left, bottom, right)
}

for region_name, region in regions.items():
    found_image = py.locateOnScreen(image, region=region)
    if found_image != None:
        print(f"Clicked found_image in {region_name} region.")
        py.click(found_image )
</code>```

Body:
I'm using python to search for images and I can do that with one area but how can I adapt this code for multiple areas?

found_image = pyautogui.locateOnScreen(image)
if found_image !=None:
    pyautogui.click(found_image)

Body:
welcome to stack! PIL has a flag for regions literally called region. If you specify where you regions are top left x and y and bottom right x and y you can them loop through the regions with for region_name, region in regions.items(): and then do something if your image is found in any of the regions.

regions = {
"Top left": (top, left, bottom, right),
"Bottom left": (top, left, bottom, right),
"Top right": (top, left, bottom, right),
"Bottom right": (top, left, bottom, right)
}

for region_name, region in regions.items():
    found_image = py.locateOnScreen(image, region=region)
    if found_image != None:
        print(f"Clicked found_image in {region_name} region.")
        py.click(found_image )


问:
How do I use `python -i 'script.py'` without closing terminal window after quitting interpreter?
How do I use python -i 'script.py' without closing terminal window after quitting the script in interactive mode on Linux?

I want to return to terminal bash environment without closing the terminal window when I just quit the interpreter environment.

I use the following command inside a .desktop file in exec= session to launch the python script by an icon or shortcut.

gnome-terminal --full-screen -- python3 -i "path/to/script.py"
```

答:
As per your comment, you launch the gnome-terminal with python as the main process. Per default, gnome-terminal closes itself, if the shell process, in your case python, exits. You have two options.

Modify the beahviour of gnome-terminal

In the settings for gnome-terminal navigate to your used profile (left sidebar), then to the 4th tab (named something like Command). In the bottom drowpdown menu (named something like When command exits) you can set gnome-terminal to keep running when the command exits.

However, this is most likely not what you want, since you'll be left with a non-functional terminal window without a running shell.

Wrap your command in a shell process

If you want an interactive shell after python exits, you need to start one in the first place. To make it fall back to a shell, you can tell it to execute the shell again, after python exits:

gnome-terminal --full-screen -- /bin/bash -c "python3 -i path/to/script.py; bash"
```

See also: How to invoke bash, run commands inside the new shell, and then give control back to user?

Body:
As per your comment, you launch the gnome-terminal with python as the main process. Per default, gnome-terminal closes itself, if the shell process, in your case python, exits. You have two options.

Modify the beahviour of gnome-terminal

In the settings for gnome-terminal navigate to your used profile (left sidebar), then to the 4th tab (named something like Command). In the bottom drowpdown menu (named something like When command exits) you can set gnome-terminal to keep running when the command exits.

However, this is most likely not what you want, since you'll be left with a non-functional terminal window without a running shell.

Wrap your command in a shell process

If you want an interactive shell after python exits, you need to start one in the first place. To make it fall back to a shell, you can tell it to execute the shell again, after python exits:

gnome-terminal --full-screen -- /bin/bash -c "python3 -i path/to/script.py; bash"

See also: How to invoke bash, run commands inside the new shell, and then give control back to user?


问:
how to pass values using @Input()
enter image description here
How should I do so that my card can get data from another file?

OneProcessItemComponent.ts

```<code>export class OneProcessItemComponent {
  @Input() item = processItem;
}
</code>```

OneProcessItemComponent.html

```<code><div class="process__item">
  <div class="process__wrap">
    <img src="{{ item.image }}" alt="process" class="process__img">
    <div class="process__item-title">{{ item.title }}</div>
    <div class="process__item-subtitle">{{ item.subtitle }}</div>
  </div>
</div>
</code>```

processItem.ts

```<code>export const processItem: IProcessItem[] = [
  {
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
    spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
  },
</code>```

答:
Your compilation errors occur because your component template expects item to be a single IProcessItem but processItem is an array of IProcessItems

You can fix it by removing the square brackets around the definition of processItem

Also you wouldn't normally assign a variable to an input like that, rather you would assign it in the parent template.

```<code><app-one-process-item [item]="processItem"><app-one-process-item>
</code>```

The idea being you can pass whatever item in you want, and it is not constrained to the specific one you currently have in your component.

Title: how to pass values using @Input()

Body:
enter image description here
How should I do so that my card can get data from another file?

OneProcessItemComponent.ts

export class OneProcessItemComponent {
  @Input() item = processItem;
}

OneProcessItemComponent.html

{{ item.title }}

{{ item.subtitle }}

processItem.ts

export const processItem: IProcessItem[] = [
  {
    title: `Buy Now`,
    subtitle: `Lock in a buy order now at the current
    spot price.`,
    image: `../../../../../../../assets/img/process-1.svg`,
  },

Body:
Your compilation errors occur because your component template expects item to be a single IProcessItem but processItem is an array of IProcessItems

You can fix it by removing the square brackets around the definition of processItem

Also you wouldn't normally assign a variable to an input like that, rather you would assign it in the parent template.

<app-one-process-item [item]="processItem"><app-one-process-item>

The idea being you can pass whatever item in you want, and it is not constrained to the specific one you currently have in your component.


问:
JQuery Mobile Add the Home Screen Options?
I know that there is no way of auto adding the JQuery Mobile App to the Home Screen.

I've read that the best way is to detect if the app is in full screen and if not give instructions. How would I do this?

What are the cross browser options available and are there any tutorials / samples anywhere?

Can anyone put some light on this please?

Thanks.

答:
Here's another script targeted at iOS browsers that seems similar to mobile-bookmark-bubble:

http://cubiq.org/add-to-home-screen

Some work has been done here to add support for Android:
http://code.google.com/p/mobile-bookmark-bubble/issues/detail?id=12
http://code.google.com/p/mobile-bookmark-bubble/issues/detail?id=17


问:
Border animation on hover with a transparent section moving left to right
I have this code trying to make an animation on hover. Something like this :

```<code>TextLink      hover: TextLink
--------             --  ----
</code>```

I am trying to have an animation that looks like the "transparent" portion is moving from left till the end of the text.

body {
  margin: 0;
  background: #16263d;
}

div {
  padding: 30px;
}

a {
  color: #fff;
  text-decoration: none;
  display: block;
  margin-top: 24px;
  transition: all 0.75s ease-in-out;
}

a span {
  border-bottom: 2px solid #fff;
}

a:hover:after {
  opacity: 1;
  -ms-filter: none;
  filter: none;
  transform: translateX(100%);
}

a:after {
  content: '';
  width: 35px;
  height: 2px;
  background: #16263d;
  display: block;
  position: relative;
  opacity: 1;
  transform: translateX(-35px);
  transition: all 0.75s ease-in-out;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <span>Text Link and something more than this</span>
</div></code>```

The problem is that 100% of the transform transition is not taken into consideration ... seems like only 100px are.

答:
First, you need to understand that percent values for transforms are a portion of the element's bounding box (size), not of it's parent.

As the pseudo element is 35px wide, the transform moves it 35px. (see MDN for more info)

This said, you could use a border on the pseudo element for the "transparent" portion like this :

body {
  background: #16263d;
}

a {
  font-size:20px;
  position:relative;
  color: #fff;
  text-decoration: none;
  display: inline-block;
  padding:.2em 0;
  border-bottom: 2px solid #fff;
}
a:after {
  content: '';
  position:absolute;
  bottom:-2px;
  right:100%;
  width:100%;
  height: 2px;
  border-right: 35px solid #16263d;
  transition: transform 0.75s ease-in-out;
}

a:hover:after {
  transform: translateX(100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Text Link and something more than this</code>```

Body:
I have this code trying to make an animation on hover. Something like this :

TextLink      hover: TextLink
--------             --  ----

I am trying to have an animation that looks like the "transparent" portion is moving from left till the end of the text.

body {
  margin: 0;
  background: #16263d;
}

div {
  padding: 30px;
}

a {
  color: #fff;
  text-decoration: none;
  display: block;
  margin-top: 24px;
  transition: all 0.75s ease-in-out;
}

a span {
  border-bottom: 2px solid #fff;
}

a:hover:after {
  opacity: 1;
  -ms-filter: none;
  filter: none;
  transform: translateX(100%);
}

a:after {
  content: '';
  width: 35px;
  height: 2px;
  background: #16263d;
  display: block;
  position: relative;
  opacity: 1;
  transform: translateX(-35px);
  transition: all 0.75s ease-in-out;
}

  Text Link and something more than this

The problem is that 100% of the transform transition is not taken into consideration ... seems like only 100px are.

Body:
First, you need to understand that percent values for transforms are a portion of the element's bounding box (size), not of it's parent.

As the pseudo element is 35px wide, the transform moves it 35px. (see MDN for more info)

This said, you could use a border on the pseudo element for the "transparent" portion like this :

body {
  background: #16263d;
}

a {
  font-size:20px;
  position:relative;
  color: #fff;
  text-decoration: none;
  display: inline-block;
  padding:.2em 0;
  border-bottom: 2px solid #fff;
}
a:after {
  content: '';
  position:absolute;
  bottom:-2px;
  right:100%;
  width:100%;
  height: 2px;
  border-right: 35px solid #16263d;
  transition: transform 0.75s ease-in-out;
}

a:hover:after {
  transform: translateX(100%);
}

<a href="#">Text Link and something more than this</a>