问:
Interactively selecting two points from a variable set of plots
I've been trying to develop a Shiny app to do de following:

Input data set with the following structure: a column called weekna with labels of the xaxis and a variable number of columns with different names that have different values.

My goal is, for each column with values, to interactively ask the user to select two points, one called first and another one called last.

When the user ended entering the points, to make some calculations and print some results.

Additional features:
- Each time the user select a point, it is coloured in the plot (red for first, blue for last).

My intention is:

Show the graph for the first column, allow to select first, last point.

Plot each point with a different colour in the graph.

Print them in a summary table below the plot.

Show a button called "Next plot", to go to the second column and repeat the process until the last one is done.

Alternatively, use "Previous/Next" buttons to go forward/backward.

Alternatively, use tabset with different plots for different columns.

Have a final "process" button that shows the results.

My work so far: I've achieved to plot all the graphs in the same frame (not a frame per plot) and placed a final table with the results (in this case to simplify things, I've just arranged the points and show what the user have clicked). I've tried to colour points, but seems it does not remember the previous selection.
Also, I've duplicated each graph, because I dont know how to get two points from the same graph.

Any help in any (or all) of my issues will be welcomed.

```<code>library(ggplot2)
library(shiny)

ui <- fluidPage(
  uiOutput("maintab"),
  fluidRow(
    column(width = 12,
           tableOutput("results_final")
    )
  )
)

server <- function(input, output) {

  inputdata<-data.frame(weekna=letters[1:20])
  inputdata$weekno=1:NROW(inputdata)
  inputdata$normal<-dnorm(inputdata$weekno,10)
  inputdata$beta<-dbeta(inputdata$weekno, 1, 1)
  inputdata$gamma<-dgamma(inputdata$weekno, 1, 1)
  inputdata$logistic<-dlogis(inputdata$weekno,10)
  inputdata$poisson<-dpois(inputdata$weekno, 2)
  namescol<-names(inputdata)[-(1:2)]
  nnamescol<-length(namescol)
  for (s in namescol) eval(parse(text=paste0("inputdata$'",s,"_color'<-'1'")))

  makeReactiveBinding('inputdata')

  output$maintab <- renderUI({
    fluidRow(
      do.call(column, c(width=6,
                        c(
                          lapply(namescol,function(s){
                            call("plotOutput", outputId=paste0("plot_",as.character(s),"_first"),
                                 height = 300, click = paste0("plot_",as.character(s),"_first_click"))
                          }),
                          lapply(namescol,function(s){
                            call("tableOutput", outputId=paste0("results_",as.character(s),"_first"))
                          })
                        )[c(rbind(1:nnamescol,1:nnamescol+nnamescol))]

      )),
      do.call(column, c(width=6,
                        c(
                          lapply(namescol,function(s){
                            call("plotOutput", outputId=paste0("plot_",as.character(s),"_last"),
                                 height = 300, click = paste0("plot_",as.character(s),"_last_click"))
                          }),
                          lapply(namescol,function(s){
                            call("tableOutput", outputId=paste0("results_",as.character(s),"_last"))
                          })
                        )[c(rbind(1:nnamescol,1:nnamescol+nnamescol))]

      ))
    )
  })

  lapply(namescol, function(s){output[[paste0("plot_",as.character(s),"_first")]] <- renderPlot({
    ggplot(inputdata, aes_string("weekno", s, color=paste0(s,"_color"))) + geom_point() + geom_line(color="#000000") +
      scale_x_continuous(breaks=inputdata$weekno, labels = inputdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })})

  lapply(namescol, function(s){output[[paste0("plot_",as.character(s),"_last")]] <- renderPlot({
    ggplot(inputdata, aes_string("weekno", s, color=paste0(s,"_color"))) + geom_point() + geom_line(color="#000000") +
      scale_x_continuous(breaks=inputdata$weekno, labels = inputdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })})

  lapply(namescol,function(s){
    observeEvent(input[[paste0("plot_",as.character(s),"_first_click")]], {
      np <- nearPoints(inputdata, input[[paste0("plot_",as.character(s),"_first_click")]], maxpoints=1 , threshold = 1000)
      output[[paste0("results_",as.character(s),"_first")]] <- renderTable({
        data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
      })
      inputdata[,paste0(as.character(s),"_color")] <<- rep("1",length(inputdata$weekno))
      inputdata[inputdata$weekno==np$weekno,paste0(as.character(s),"_color")] <<- "2"

      output$results_final <- renderTable({
        out1<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_first_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out1x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out1x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out1x)<-c("var1","weekno_first","weekna_first","value_first")
          out1<-rbind(out1,out1x)
        }
        out2<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_last_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out2x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out2x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out2x)<-c("var1","weekno_last","weekna_last","value_last")
          out2<-rbind(out2,out2x)
        }
        out3<-data.frame(var1=namescol)
        outf<-merge(out3,out1,all.x=T, by="var1")
        outf<-merge(outf,out2,all.x=T, by="var1")
        outf
      })

    })
  })

  lapply(namescol,function(s){
    observeEvent(input[[paste0("plot_",as.character(s),"_last_click")]], {
      np <- nearPoints(inputdata, input[[paste0("plot_",as.character(s),"_last_click")]], maxpoints=1 , threshold = 1000)
      output[[paste0("results_",as.character(s),"_last")]] <- renderTable({
        data.frame(var1=s, np[c("weekno","weekna",s)],stringsAsFactors=F)
      })
      inputdata[,paste0(as.character(s),"_color")] <<- rep("1",length(inputdata$weekno))
      inputdata[inputdata$weekno==np$weekno,paste0(as.character(s),"_color")] <<- "3"

      output$results_final <- renderTable({
        out1<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_first_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out1x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out1x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out1x)<-c("var1","weekno_first","weekna_first","value_first")
          out1<-rbind(out1,out1x)
        }
        out2<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_last_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out2x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out2x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out2x)<-c("var1","weekno_last","weekna_last","value_last")
          out2<-rbind(out2,out2x)
        }
        out3<-data.frame(var1=namescol)
        outf<-merge(out3,out1,all.x=T, by="var1")
        outf<-merge(outf,out2,all.x=T, by="var1")
        outf
      })

    })
  })

}

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

EDIT:

Today I have been thinking on my problem and I have a plan:

To create two datasets that must be reactive (with makereactivebinding) and can be updated interactively.

plotdataset: the same as input with another column for each column of the original dataset called as the original plus _color.

clickdataset: a data.frame that stores all the clicks in all the plots along with the time the click is done.

The plan is:

Use plotdataset to plot each original column along with the respective _color column to plot the two points in two different colors (name red/green)
use a tabsetpanel to plot a set of panels, each one with a different column.

Each time the user click anything, the clicked point is added with rbind to the  clickdataset.

Select the lastest two clicked points of each column in the clickdataset and order them to find out the first/last point.

update with this information the plotdataset _color column, so that the first is "red" and the last is "green", so that all plots are updated.

Selecting the lastest two clicked points of each columns allows the user to click three, four times if he doesnt like the selection, updating everytime to the lastest two clicks.

Now it is time to think on how to implement my plan.

答:
I have just programmed what I outlined this morning as my plan to solve this problem.

This is the result, with this procedure i can get any number of points from a single plot.

I've simplified the problem by not allowing the input dataset to have a variable number of columns (I've made an example with two columns only), but to adapt this example to a more general case should be easy seeing my original code.

```<code>library(ggplot2)
library(shiny)
library(shinydashboard)

inputdata<-data.frame(weekno=1:20, weekna=letters[1:20])
inputdata$normal<-dnorm(inputdata$weekno,10)
inputdata$beta<-dbeta(inputdata$weekno, 1, 1)
inputdata$gamma<-dgamma(inputdata$weekno, 1, 1)
inputdata$logistic<-dlogis(inputdata$weekno,10)
inputdata$poisson<-dpois(inputdata$weekno, 2)

tail.order<-function(i.data, i.n, i.order){
  res<-tail(i.data, n=i.n)
  res<-res[order(res[i.order]),]
  res$id.tail<-1:NROW(res)
  res
}

extract.two<-function(i.data, i.order, i.column){
  data<-unique(i.data, fromLast=T)
  results <- do.call("rbind", by(data, data[i.column], tail.order, i.n=2, i.order=i.order))
  return(results)
}

ui <- fluidPage(
  uiOutput("maintab")
)

server <- function(input, output) {
  origdata<-inputdata[c("weekno","weekna","normal","poisson")]
  plotdata<-origdata
  namescol<-names(plotdata)[-(1:2)]
  nnamescol<-length(namescol)
  for (s in namescol) eval(parse(text=paste0("plotdata$'",s,"_color'<-'1'")))

  values <- reactiveValues(plotdata = plotdata, clickdata=data.frame())

  output$maintab <- renderUI({
    tabsetPanel(tabPanel("normal", plotOutput("plot_normal"
                                              , click = paste0("plot_normal_click")
    )),
    tabPanel("poisson", plotOutput("plot_poisson"
                                   , click = paste0("plot_poisson_click")
    )),
    tabPanel("results",tableOutput("results")),
    tabPanel("resultsfull",tableOutput("resultsfull"))
    )
  })

  output$plot_normal <- renderPlot({
    ggplot(values$plotdata, aes_string("weekno", "normal")) +
      geom_point(aes_string("weekno", "normal", color="normal_color")) +
      scale_color_manual(values = c("1" = "grey", "2" = "red", "3" = "green")) +
      geom_line(aes_string("weekno", "normal"), color="#000000") +
      scale_x_continuous(breaks=origdata$weekno, labels = origdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })

  output$plot_poisson <- renderPlot({
    ggplot(values$plotdata, aes_string("weekno", "poisson")) +
      geom_point(aes_string("weekno", "poisson", color="poisson_color")) +
      scale_color_manual(values = c("1" = "grey", "2" = "red", "3" = "green")) +
      geom_line(aes_string("weekno", "poisson"), color="#000000") +
      scale_x_continuous(breaks=origdata$weekno, labels = origdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })

  output$results<-renderTable({
    if (NROW(values$clickdata)>0) extract.two(values$clickdata,"weekno","variable")
  })

  output$resultsfull<-renderTable({
    values$clickdata
  })

  observeEvent(input$plot_normal_click, {
    np <- nearPoints(origdata, input$plot_normal_click, maxpoints=1 , threshold = 1000)
    values$clickdata<-rbind(values$clickdata,data.frame(variable="normal", np, stringsAsFactors = F))
    if (NROW(values$clickdata)>0){
      p0<-extract.two(values$clickdata,"weekno","variable")
      p1<-subset(p0, variable=="normal" & id.tail==1)
      p2<-subset(p0, variable=="normal" & id.tail==2)
      if (NROW(p1)>0) {
        values$plotdata[values$plotdata["normal_color"]=="2","normal_color"]<-"1"
        values$plotdata[origdata$weekno==p1$weekno,"normal_color"]<-"2"
      }
      if (NROW(p2)>0){
        values$plotdata[values$plotdata["normal_color"]=="3","normal_color"]<-"1"
        values$plotdata[origdata$weekno==p2$weekno,"normal_color"]<-"3"
      }
    }
  })

  observeEvent(input$plot_poisson_click, {
    np <- nearPoints(origdata, input$plot_poisson_click, maxpoints=1 , threshold = 1000)
    values$clickdata<-rbind(values$clickdata,data.frame(variable="poisson", np, stringsAsFactors = F))
    if (NROW(values$clickdata)>0){
      p0<-extract.two(values$clickdata,"weekno","variable")
      p1<-subset(p0, variable=="poisson" & id.tail==1)
      p2<-subset(p0, variable=="poisson" & id.tail==2)
      if (NROW(p1)>0) {
        values$plotdata[values$plotdata["poisson_color"]=="2","poisson_color"]<-"1"
        values$plotdata[origdata$weekno==p1$weekno,"poisson_color"]<-"2"
      }
      if (NROW(p2)>0){
        values$plotdata[values$plotdata["poisson_color"]=="3","poisson_color"]<-"1"
        values$plotdata[origdata$weekno==p2$weekno,"poisson_color"]<-"3"
      }
    }
  })
}

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

Body:
I've been trying to develop a Shiny app to do de following:

Input data set with the following structure: a column called weekna with labels of the xaxis and a variable number of columns with different names that have different values.

My goal is, for each column with values, to interactively ask the user to select two points, one called first and another one called last.

When the user ended entering the points, to make some calculations and print some results.

Additional features:
- Each time the user select a point, it is coloured in the plot (red for first, blue for last).

My intention is:

Show the graph for the first column, allow to select first, last point.

Plot each point with a different colour in the graph.

Print them in a summary table below the plot.

Show a button called "Next plot", to go to the second column and repeat the process until the last one is done.

Alternatively, use "Previous/Next" buttons to go forward/backward.

Alternatively, use tabset with different plots for different columns.

Have a final "process" button that shows the results.

My work so far: I've achieved to plot all the graphs in the same frame (not a frame per plot) and placed a final table with the results (in this case to simplify things, I've just arranged the points and show what the user have clicked). I've tried to colour points, but seems it does not remember the previous selection.
Also, I've duplicated each graph, because I dont know how to get two points from the same graph.

Any help in any (or all) of my issues will be welcomed.

library(ggplot2)
library(shiny)

ui <- fluidPage(
  uiOutput("maintab"),
  fluidRow(
    column(width = 12,
           tableOutput("results_final")
    )
  )
)

server <- function(input, output) {

  inputdata<-data.frame(weekna=letters[1:20])
  inputdata$weekno=1:NROW(inputdata)
  inputdata$normal<-dnorm(inputdata$weekno,10)
  inputdata$beta<-dbeta(inputdata$weekno, 1, 1)
  inputdata$gamma<-dgamma(inputdata$weekno, 1, 1)
  inputdata$logistic<-dlogis(inputdata$weekno,10)
  inputdata$poisson<-dpois(inputdata$weekno, 2)
  namescol<-names(inputdata)[-(1:2)]
  nnamescol<-length(namescol)
  for (s in namescol) eval(parse(text=paste0("inputdata$'",s,"_color'<-'1'")))

  makeReactiveBinding('inputdata')

  output$maintab <- renderUI({
    fluidRow(
      do.call(column, c(width=6,
                        c(
                          lapply(namescol,function(s){
                            call("plotOutput", outputId=paste0("plot_",as.character(s),"_first"),
                                 height = 300, click = paste0("plot_",as.character(s),"_first_click"))
                          }),
                          lapply(namescol,function(s){
                            call("tableOutput", outputId=paste0("results_",as.character(s),"_first"))
                          })
                        )[c(rbind(1:nnamescol,1:nnamescol+nnamescol))]

      )),
      do.call(column, c(width=6,
                        c(
                          lapply(namescol,function(s){
                            call("plotOutput", outputId=paste0("plot_",as.character(s),"_last"),
                                 height = 300, click = paste0("plot_",as.character(s),"_last_click"))
                          }),
                          lapply(namescol,function(s){
                            call("tableOutput", outputId=paste0("results_",as.character(s),"_last"))
                          })
                        )[c(rbind(1:nnamescol,1:nnamescol+nnamescol))]

      ))
    )
  })

  lapply(namescol, function(s){output[[paste0("plot_",as.character(s),"_first")]] <- renderPlot({
    ggplot(inputdata, aes_string("weekno", s, color=paste0(s,"_color"))) + geom_point() + geom_line(color="#000000") +
      scale_x_continuous(breaks=inputdata$weekno, labels = inputdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })})

  lapply(namescol, function(s){output[[paste0("plot_",as.character(s),"_last")]] <- renderPlot({
    ggplot(inputdata, aes_string("weekno", s, color=paste0(s,"_color"))) + geom_point() + geom_line(color="#000000") +
      scale_x_continuous(breaks=inputdata$weekno, labels = inputdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })})

  lapply(namescol,function(s){
    observeEvent(input[[paste0("plot_",as.character(s),"_first_click")]], {
      np <- nearPoints(inputdata, input[[paste0("plot_",as.character(s),"_first_click")]], maxpoints=1 , threshold = 1000)
      output[[paste0("results_",as.character(s),"_first")]] <- renderTable({
        data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
      })
      inputdata[,paste0(as.character(s),"_color")] <<- rep("1",length(inputdata$weekno))
      inputdata[inputdata$weekno==np$weekno,paste0(as.character(s),"_color")] <<- "2"

      output$results_final <- renderTable({
        out1<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_first_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out1x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out1x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out1x)<-c("var1","weekno_first","weekna_first","value_first")
          out1<-rbind(out1,out1x)
        }
        out2<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_last_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out2x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out2x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out2x)<-c("var1","weekno_last","weekna_last","value_last")
          out2<-rbind(out2,out2x)
        }
        out3<-data.frame(var1=namescol)
        outf<-merge(out3,out1,all.x=T, by="var1")
        outf<-merge(outf,out2,all.x=T, by="var1")
        outf
      })

    })
  })

  lapply(namescol,function(s){
    observeEvent(input[[paste0("plot_",as.character(s),"_last_click")]], {
      np <- nearPoints(inputdata, input[[paste0("plot_",as.character(s),"_last_click")]], maxpoints=1 , threshold = 1000)
      output[[paste0("results_",as.character(s),"_last")]] <- renderTable({
        data.frame(var1=s, np[c("weekno","weekna",s)],stringsAsFactors=F)
      })
      inputdata[,paste0(as.character(s),"_color")] <<- rep("1",length(inputdata$weekno))
      inputdata[inputdata$weekno==np$weekno,paste0(as.character(s),"_color")] <<- "3"

      output$results_final <- renderTable({
        out1<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_first_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out1x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out1x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out1x)<-c("var1","weekno_first","weekna_first","value_first")
          out1<-rbind(out1,out1x)
        }
        out2<-data.frame()
        for (s in namescol){
          sname<-paste0("plot_",as.character(s),"_last_click")
          np<-nearPoints(inputdata, input[[sname]], addDist = F, threshold=1000, maxpoints=1)
          if (NROW(np)==0){
            out2x<-as.data.frame(t(rep(NA,4)),stringsAsFactors=F)
          }else{
            out2x<-data.frame(var1=s,np[c("weekno","weekna",s)],stringsAsFactors=F)
          }
          names(out2x)<-c("var1","weekno_last","weekna_last","value_last")
          out2<-rbind(out2,out2x)
        }
        out3<-data.frame(var1=namescol)
        outf<-merge(out3,out1,all.x=T, by="var1")
        outf<-merge(outf,out2,all.x=T, by="var1")
        outf
      })

    })
  })

}

shinyApp(ui, server)

EDIT:

Today I have been thinking on my problem and I have a plan:

To create two datasets that must be reactive (with makereactivebinding) and can be updated interactively.

plotdataset: the same as input with another column for each column of the original dataset called as the original plus _color.

clickdataset: a data.frame that stores all the clicks in all the plots along with the time the click is done.

The plan is:

Use plotdataset to plot each original column along with the respective _color column to plot the two points in two different colors (name red/green)
use a tabsetpanel to plot a set of panels, each one with a different column.

Each time the user click anything, the clicked point is added with rbind to the  clickdataset.

Select the lastest two clicked points of each column in the clickdataset and order them to find out the first/last point.

update with this information the plotdataset _color column, so that the first is "red" and the last is "green", so that all plots are updated.

Selecting the lastest two clicked points of each columns allows the user to click three, four times if he doesnt like the selection, updating everytime to the lastest two clicks.

Now it is time to think on how to implement my plan.

Body:
I have just programmed what I outlined this morning as my plan to solve this problem.

This is the result, with this procedure i can get any number of points from a single plot.

I've simplified the problem by not allowing the input dataset to have a variable number of columns (I've made an example with two columns only), but to adapt this example to a more general case should be easy seeing my original code.

library(ggplot2)
library(shiny)
library(shinydashboard)

inputdata<-data.frame(weekno=1:20, weekna=letters[1:20])
inputdata$normal<-dnorm(inputdata$weekno,10)
inputdata$beta<-dbeta(inputdata$weekno, 1, 1)
inputdata$gamma<-dgamma(inputdata$weekno, 1, 1)
inputdata$logistic<-dlogis(inputdata$weekno,10)
inputdata$poisson<-dpois(inputdata$weekno, 2)

tail.order<-function(i.data, i.n, i.order){
  res<-tail(i.data, n=i.n)
  res<-res[order(res[i.order]),]
  res$id.tail<-1:NROW(res)
  res
}

extract.two<-function(i.data, i.order, i.column){
  data<-unique(i.data, fromLast=T)
  results <- do.call("rbind", by(data, data[i.column], tail.order, i.n=2, i.order=i.order))
  return(results)
}

ui <- fluidPage(
  uiOutput("maintab")
)

server <- function(input, output) {
  origdata<-inputdata[c("weekno","weekna","normal","poisson")]
  plotdata<-origdata
  namescol<-names(plotdata)[-(1:2)]
  nnamescol<-length(namescol)
  for (s in namescol) eval(parse(text=paste0("plotdata$'",s,"_color'<-'1'")))

  values <- reactiveValues(plotdata = plotdata, clickdata=data.frame())

  output$maintab <- renderUI({
    tabsetPanel(tabPanel("normal", plotOutput("plot_normal"
                                              , click = paste0("plot_normal_click")
    )),
    tabPanel("poisson", plotOutput("plot_poisson"
                                   , click = paste0("plot_poisson_click")
    )),
    tabPanel("results",tableOutput("results")),
    tabPanel("resultsfull",tableOutput("resultsfull"))
    )
  })

  output$plot_normal <- renderPlot({
    ggplot(values$plotdata, aes_string("weekno", "normal")) +
      geom_point(aes_string("weekno", "normal", color="normal_color")) +
      scale_color_manual(values = c("1" = "grey", "2" = "red", "3" = "green")) +
      geom_line(aes_string("weekno", "normal"), color="#000000") +
      scale_x_continuous(breaks=origdata$weekno, labels = origdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })

  output$plot_poisson <- renderPlot({
    ggplot(values$plotdata, aes_string("weekno", "poisson")) +
      geom_point(aes_string("weekno", "poisson", color="poisson_color")) +
      scale_color_manual(values = c("1" = "grey", "2" = "red", "3" = "green")) +
      geom_line(aes_string("weekno", "poisson"), color="#000000") +
      scale_x_continuous(breaks=origdata$weekno, labels = origdata$weekna)+
      labs(title = s, x = "week", y = "rate")
  })

  output$results<-renderTable({
    if (NROW(values$clickdata)>0) extract.two(values$clickdata,"weekno","variable")
  })

  output$resultsfull<-renderTable({
    values$clickdata
  })

  observeEvent(input$plot_normal_click, {
    np <- nearPoints(origdata, input$plot_normal_click, maxpoints=1 , threshold = 1000)
    values$clickdata<-rbind(values$clickdata,data.frame(variable="normal", np, stringsAsFactors = F))
    if (NROW(values$clickdata)>0){
      p0<-extract.two(values$clickdata,"weekno","variable")
      p1<-subset(p0, variable=="normal" & id.tail==1)
      p2<-subset(p0, variable=="normal" & id.tail==2)
      if (NROW(p1)>0) {
        values$plotdata[values$plotdata["normal_color"]=="2","normal_color"]<-"1"
        values$plotdata[origdata$weekno==p1$weekno,"normal_color"]<-"2"
      }
      if (NROW(p2)>0){
        values$plotdata[values$plotdata["normal_color"]=="3","normal_color"]<-"1"
        values$plotdata[origdata$weekno==p2$weekno,"normal_color"]<-"3"
      }
    }
  })

  observeEvent(input$plot_poisson_click, {
    np <- nearPoints(origdata, input$plot_poisson_click, maxpoints=1 , threshold = 1000)
    values$clickdata<-rbind(values$clickdata,data.frame(variable="poisson", np, stringsAsFactors = F))
    if (NROW(values$clickdata)>0){
      p0<-extract.two(values$clickdata,"weekno","variable")
      p1<-subset(p0, variable=="poisson" & id.tail==1)
      p2<-subset(p0, variable=="poisson" & id.tail==2)
      if (NROW(p1)>0) {
        values$plotdata[values$plotdata["poisson_color"]=="2","poisson_color"]<-"1"
        values$plotdata[origdata$weekno==p1$weekno,"poisson_color"]<-"2"
      }
      if (NROW(p2)>0){
        values$plotdata[values$plotdata["poisson_color"]=="3","poisson_color"]<-"1"
        values$plotdata[origdata$weekno==p2$weekno,"poisson_color"]<-"3"
      }
    }
  })
}

shinyApp(ui, server)


来源: stackexchange

问:
Wpf binding problem
I have in my window a rectangle with a tooltip,
Clicking the button suppose to change the tooltip text but it doesn't.

XAML:

```<code> <Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.Resources>
        <ToolTip x:Key="@tooltip">
            <TextBlock Text="{Binding Name}" />
        </ToolTip>
    </Grid.Resources>

    <Rectangle Width="200" Height="200" Fill="LightBlue" VerticalAlignment="Center" HorizontalAlignment="Center"
            ToolTip="{DynamicResource @tooltip}" />
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>
</code>```

code behind:

```<code>public partial class Window1 : Window
{

    public Window1()
    {
        DataContext = new Person { Name = "A" };
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        DataContext = new Person { Name = "B" };
    }
}
</code>```

答:
Yes it works but not consistently.It works sometime but not all times.Seems more to be a timing bug to me.But you can change your approach a little to get it working

First you have to implement notification mechanism in your Person class

Sample

```<code> public class Person:INotifyPropertyChanged
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}
</code>```

Then you need to Create a Property for your person class and set as your datacontext.Now you can just change the name value on your button click and it works well

Sample

```<code>public Window1()
    {
        MyPerson = new Person();
        MyPerson.Name = "A";
        DataContext = MyPerson;
        InitializeComponent();
    }

    private Person myPerson;

    public Person MyPerson
    {
        get { return myPerson; }
        set { myPerson = value; OnPropertyChanged("MyPerson"); }
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPerson.Name = "B";
    }
</code>```

See if this helps...

ContentLicense: CC BY-SA 2.5

Title: Wpf binding problem

Body:
I have in my window a rectangle with a tooltip,
Clicking the button suppose to change the tooltip text but it doesn't.

XAML:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.Resources>
        <ToolTip x:Key="@tooltip">
            <TextBlock Text="{Binding Name}" />
        </ToolTip>
    </Grid.Resources>

    <Rectangle Width="200" Height="200" Fill="LightBlue" VerticalAlignment="Center" HorizontalAlignment="Center"
            ToolTip="{DynamicResource @tooltip}" />
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>

code behind:

public partial class Window1 : Window
{

    public Window1()
    {
        DataContext = new Person { Name = "A" };
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        DataContext = new Person { Name = "B" };
    }
}

Body:
Yes it works but not consistently.It works sometime but not all times.Seems more to be a timing bug to me.But you can change your approach a little to get it working

First you have to implement notification mechanism in your Person class

Sample

 public class Person:INotifyPropertyChanged
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

Then you need to Create a Property for your person class and set as your datacontext.Now you can just change the name value on your button click and it works well

Sample

public Window1()
    {
        MyPerson = new Person();
        MyPerson.Name = "A";
        DataContext = MyPerson;
        InitializeComponent();
    }

    private Person myPerson;

    public Person MyPerson
    {
        get { return myPerson; }
        set { myPerson = value; OnPropertyChanged("MyPerson"); }
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPerson.Name = "B";
    }

See if this helps...


问:
D3D12 Dynamic indexing of textures with different formats
In shader model 5.1 we can use dynamic indexing for textures like so:

```<code>Texture2D textures[5] : register(t0)
PixelShader(Input p) : SV_TARGET
{
     float4 color = textures[0].Sample(someSampler, p.UV);
     return color;
}
</code>```

Here it's assumed that all textures have 4 channels (rgba). However, I have no idea how to sample when my texture array is a mix of different formats like BC3 (rgba), BC4 (single channel R), BC5 (dual channel RG). For example, in case of BC4 I could try

```<code>float R = textures[0].Sample(someSampler, p.UV).r;
</code>```

But wouldn't this just skip over three texels?

答:
This is not a 'texture array'. This is just a way to declare 5 textures bound individually, and the syntax lets you use indices to select t0 through t1. A 'texture array' is declared as follows:

```<code>Texture2DArray textures : register(t0);
</code>```

Every texture in the texture array must be the same format (it's a single resource), and you use a float3 to index it for sampling.

```<code>float4 color = textures.Sample(someSampler, float3(p.UV,0) );
</code>```

What you are doing above is basically the same thing as:

```<code>Texture2D texture0 : register(t0);
Texture2D texture1 : register(t1);
Texture2D texture2 : register(t2);
Texture2D texture3 : register(t3);
Texture2D texture4 : register(t4);
</code>```

As such, the formats of each texture are completely independent, the code here:

```<code>float R = textures[0].Sample(someSampler, p.UV).r;
</code>```

This just samples the texture in t0 as normal, returning just the red channel. For a BC4, this will cause the hardware to decompress the correct 4x4 block (or blocks depending on the UV and sampler mode), and return the red channel from the reconstruction.

If you are new to DirectX and HLSL, I strongly recommend not using DirectX 12 to start. It's a fairly unforgiving API designed for graphics experts, so you should consider starting with DirectX 11 instead. The APIs both drive the same hardware, they just do it with different programmer abstractions. DirectX 12 documentation also generally assumes you are already an expert with DirectX 11 anyhow and the HLSL usage is basically the same (with the addition of programmatic control over root signatures). See DirectX Tool Kit for DirectX 11 and DirectX 12.

ContentLicense: CC BY-SA 3.0

Body:
In shader model 5.1 we can use dynamic indexing for textures like so:

Texture2D textures[5] : register(t0)
PixelShader(Input p) : SV_TARGET
{
     float4 color = textures[0].Sample(someSampler, p.UV);
     return color;
}

Here it's assumed that all textures have 4 channels (rgba). However, I have no idea how to sample when my texture array is a mix of different formats like BC3 (rgba), BC4 (single channel R), BC5 (dual channel RG). For example, in case of BC4 I could try

float R = textures[0].Sample(someSampler, p.UV).r;

But wouldn't this just skip over three texels?

Body:
This is not a 'texture array'. This is just a way to declare 5 textures bound individually, and the syntax lets you use indices to select t0 through t1. A 'texture array' is declared as follows:

Texture2DArray textures : register(t0);

Every texture in the texture array must be the same format (it's a single resource), and you use a float3 to index it for sampling.

float4 color = textures.Sample(someSampler, float3(p.UV,0) );

What you are doing above is basically the same thing as:

Texture2D texture0 : register(t0);
Texture2D texture1 : register(t1);
Texture2D texture2 : register(t2);
Texture2D texture3 : register(t3);
Texture2D texture4 : register(t4);

As such, the formats of each texture are completely independent, the code here:

float R = textures[0].Sample(someSampler, p.UV).r;

This just samples the texture in t0 as normal, returning just the red channel. For a BC4, this will cause the hardware to decompress the correct 4x4 block (or blocks depending on the UV and sampler mode), and return the red channel from the reconstruction.

If you are new to DirectX and HLSL, I strongly recommend not using DirectX 12 to start. It's a fairly unforgiving API designed for graphics experts, so you should consider starting with DirectX 11 instead. The APIs both drive the same hardware, they just do it with different programmer abstractions. DirectX 12 documentation also generally assumes you are already an expert with DirectX 11 anyhow and the HLSL usage is basically the same (with the addition of programmatic control over root signatures). See DirectX Tool Kit for DirectX 11 and DirectX 12.


问:
Bukkit/Spigot) Better MySQL stats updating no lag?
Hi there I'm having issues with SQL updating player stats which makes very huge  lag/timings drop I'm updating the stats on server stop this is my stats code:</p>

```<code>public int getDeaths(Player p) {
    if (!plugin.getConfig().getBoolean("mysql")) {
        return plugin.data.getConfig().getInt("Deaths." + p.getUniqueId() + ".death");
    }
    if (plugin.getConfig().getBoolean("mysql")) {
        int res = 0;
        ResultSet result = getMainSQLConnection()
                .executeQuery("SELECT * FROM `Account` WHERE playername='" + p.getName() + "'", false);
        try {
            if (result.next()) {
                res = Integer.parseInt(result.getString("deaths"));
            }
        } catch (SQLException localSQLException) {
        }
        return res;
    }
    return 0;
}

public void setDeaths(Player p, int number) {
    if (!plugin.getConfig().getBoolean("mysql")) {
        plugin.data.getConfig().set("Deaths." + p.getUniqueId() + ".death", number);
        plugin.data.save();
    }
    if (plugin.getConfig().getBoolean("mysql")) {
        plugin.sqlConnection.executeUpdate(
                "UPDATE `Account` SET deaths='" + number + "' WHERE playername='" + p.getName() + "'");
    }
}
</code>```

答:
If you're getting the death count for a command or something that doesn't require the value to be returned immediately, use a asynchronous scheduler to run the code on a separate thread. For a command you'd do something like this when it is executed:

```<code>Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
    try {
        int deaths = getMainSQLConnection()
                .executeQuery("SELECT * FROM `Account` WHERE playername='" + p.getName() + "'", false)
                .getInt("deaths");
        player.sendMessage("Player Deaths: " + deaths);
    } catch (SQLException ex) {
        player.sendMessage(ChatColor.RED + "That player does not exist!");
    }
});
</code>```

Otherwise, if you need the value in the code for whatever reason, you can use a connection pool such as HikariCP. A connection pool will allow you to maintain multiple connections to your database so when you need to execute a query you don't have to establish a new connection every time (which is what will cause most of the lag).

Better yet, use an asynchronous task in tandem with the connection pool. Here's a good tutorial for learning how to use HikariCP with Bukkit: https://www.spigotmc.org/threads/tutorial-implement-mysql-in-your-plugin-with-pooling.61678

As a side note, for basically zero performance impact on the server, you can load the data asynchronously when a player logs in (using the AsyncPlayerPreLoginEvent). Then store it in memory when they actually join the server (PlayerLoginEvent or PlayerJoinEvent), and remove it when they quit. This way you access the data through memory while they're logged in rather than the database. This is much more complicated and also requires a lot of code to implement correctly though, so I'm not going to go into detail here.

Body:
Hi there I'm having issues with SQL updating player stats which makes very huge  lag/timings drop I'm updating the stats on server stop this is my stats code:

public int getDeaths(Player p) {
    if (!plugin.getConfig().getBoolean("mysql")) {
        return plugin.data.getConfig().getInt("Deaths." + p.getUniqueId() + ".death");
    }
    if (plugin.getConfig().getBoolean("mysql")) {
        int res = 0;
        ResultSet result = getMainSQLConnection()
                .executeQuery("SELECT * FROM `Account` WHERE playername='" + p.getName() + "'", false);
        try {
            if (result.next()) {
                res = Integer.parseInt(result.getString("deaths"));
            }
        } catch (SQLException localSQLException) {
        }
        return res;
    }
    return 0;
}

public void setDeaths(Player p, int number) {
    if (!plugin.getConfig().getBoolean("mysql")) {
        plugin.data.getConfig().set("Deaths." + p.getUniqueId() + ".death", number);
        plugin.data.save();
    }
    if (plugin.getConfig().getBoolean("mysql")) {
        plugin.sqlConnection.executeUpdate(
                "UPDATE `Account` SET deaths='" + number + "' WHERE playername='" + p.getName() + "'");
    }
}

Body:
If you're getting the death count for a command or something that doesn't require the value to be returned immediately, use a asynchronous scheduler to run the code on a separate thread. For a command you'd do something like this when it is executed:

Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
    try {
        int deaths = getMainSQLConnection()
                .executeQuery("SELECT * FROM `Account` WHERE playername='" + p.getName() + "'", false)
                .getInt("deaths");
        player.sendMessage("Player Deaths: " + deaths);
    } catch (SQLException ex) {
        player.sendMessage(ChatColor.RED + "That player does not exist!");
    }
});

Otherwise, if you need the value in the code for whatever reason, you can use a connection pool such as HikariCP. A connection pool will allow you to maintain multiple connections to your database so when you need to execute a query you don't have to establish a new connection every time (which is what will cause most of the lag).

Better yet, use an asynchronous task in tandem with the connection pool. Here's a good tutorial for learning how to use HikariCP with Bukkit: https://www.spigotmc.org/threads/tutorial-implement-mysql-in-your-plugin-with-pooling.61678

As a side note, for basically zero performance impact on the server, you can load the data asynchronously when a player logs in (using the AsyncPlayerPreLoginEvent). Then store it in memory when they actually join the server (PlayerLoginEvent or PlayerJoinEvent), and remove it when they quit. This way you access the data through memory while they're logged in rather than the database. This is much more complicated and also requires a lot of code to implement correctly though, so I'm not going to go into detail here.


问:
Git - fatal: unknown error occured while reading the configuration files
Not sure if this is the correct place to post this problem, but:

When I try to do just about anything in my Git bash window, I get this error:

```<code>fatal: unknown error occured while reading the configuration files
</code>```

I tried several re-installs under different configurations and attempted numerous reboots to no help. I was questioning my username on Windows, since it has a dot (.) in it. Could that confuse Git for some reason? And if so: Is there a work-around?

I also cannot seem to locate where my config files are, since the command to find it is broken with the same error message.

I searched my computer for .gitconfig files. I found a total of 4 files:

C:\Program Files\Git\mingw64\etc\.gitconfig

C:\Program Files\Git\usr\share\vim\vim74\ftplugin\.gitconfig

C:\Program Files\Git\usr\share\vim\vim74\indent\.gitconfig

C:\Program Files\Git\usr\share\vim\vim74\syntax\.gitconfig

Here are the content of each file

...\Git\mingw64\etc.gitconfig

```<code>[credential]
helper = manager
</code>```

...\Git\usr\share\vim\vim74\ftplugin.gitconfig

```<code>" Vim filetype plugin
" Language: git config file
" Maintainer:   Tim Pope <vimNOSPAM@tpope.org>
" Last Change:  2009 Dec 24

" Only do this when not done yet for this buffer
if (exists("b:did_ftplugin"))
  finish
endif
let b:did_ftplugin = 1

setlocal formatoptions-=t formatoptions+=croql
setlocal comments=:#,:; commentstring=;\ %s

let b:undo_ftplugin = "setl fo< com< cms<"
</code>```

...\Git\usr\share\vim\vim74\indent.gitconfig

```<code>" Vim indent file
" Language: git config file
" Maintainer:   Tim Pope <vimNOSPAM@tpope.org>
" Last Change:  2013 May 30

if exists("b:did_indent")
  finish
endif
let b:did_indent = 1

setlocal autoindent
setlocal indentexpr=GetGitconfigIndent()
setlocal indentkeys=o,O,*<Return>,0[,],0;,0#,=,!^F

let b:undo_indent = 'setl ai< inde< indk<'

" Only define the function once.
if exists("*GetGitconfigIndent")
  finish
endif

function! GetGitconfigIndent()
  let line  = getline(prevnonblank(v:lnum-1))
  let cline = getline(v:lnum)
  if line =~  '\\\@<!\%(\\\\\)*\\$'
    " odd number of slashes, in a line continuation
    return 2 * &sw
  elseif cline =~ '^\s*\['
    return 0
  elseif cline =~ '^\s*\a'
    return &sw
  elseif cline == ''       && line =~ '^\['
    return &sw
  else
    return -1
  endif
endfunction
</code>```

Git\usr\share\vim\vim74\syntax.gitconfig

```<code>" Vim syntax file
" Language: git config file
" Maintainer:   Tim Pope <vimNOSPAM@tpope.org>
" Filenames:    gitconfig, .gitconfig, *.git/config
" Last Change:  2010 May 21

if exists("b:current_syntax")
  finish
endif

setlocal iskeyword+=-
setlocal iskeyword-=_
syn case ignore
syn sync minlines=10

syn match   gitconfigComment    "[#;].*"
syn match   gitconfigSection    "\%(^\s*\)\@<=\[[a-z0-9.-]\+\]"
syn match   gitconfigSection    '\%(^\s*\)\@<=\[[a-z0-9.-]\+ \+\"\%([^\\"]\|\\.\)*"\]'
syn match   gitconfigVariable    "\%(^\s*\)\@<=\a\k*\%(\s*\%([=#;]\|$\)\)\@=" nextgroup=gitconfigAssignment skipwhite
syn region  gitconfigAssignment  matchgroup=gitconfigNone start=+=\s*+ skip=+\\+ end=+\s*$+ contained contains=gitconfigBoolean,gitconfigNumber,gitConfigString,gitConfigEscape,gitConfigError,gitconfigComment keepend
syn keyword gitconfigBoolean true false yes no contained
syn match   gitconfigNumber  "\d\+" contained
syn region  gitconfigString  matchgroup=gitconfigDelim start=+"+ skip=+\\+ end=+"+ matchgroup=gitconfigError end=+[^\\"]\%#\@!$+ contained contains=gitconfigEscape,gitconfigEscapeError
syn match   gitconfigError  +\\.+    contained
syn match   gitconfigEscape +\\[\\"ntb]+ contained
syn match   gitconfigEscape +\\$+    contained

hi def link gitconfigComment        Comment
hi def link gitconfigSection        Keyword
hi def link gitconfigVariable       Identifier
hi def link gitconfigBoolean        Boolean
hi def link gitconfigNumber     Number
hi def link gitconfigString     String
hi def link gitconfigDelim      Delimiter
hi def link gitconfigEscape     Delimiter
hi def link gitconfigError      Error

let b:current_syntax = "gitconfig"
</code>```

I run Windows 7 x64 Professional. The computer is part of a domain network.

I Googled this problem and gave up when I came to page 11 with nothing useful.

答: None of the options provided above worked for me. What finally fixed it was setting the HOME environment variable to point to something reasonable. Once this was done, git started behaving properly again.</p>

Body:
Not sure if this is the correct place to post this problem, but:

When I try to do just about anything in my Git bash window, I get this error:

fatal: unknown error occured while reading the configuration files

I tried several re-installs under different configurations and attempted numerous reboots to no help. I was questioning my username on Windows, since it has a dot (.) in it. Could that confuse Git for some reason? And if so: Is there a work-around?

I also cannot seem to locate where my config files are, since the command to find it is broken with the same error message.

I searched my computer for .gitconfig files. I found a total of 4 files:

C:\Program Files\Git\mingw64\etc\.gitconfig

C:\Program Files\Git\usr\share\vim\vim74\ftplugin\.gitconfig

C:\Program Files\Git\usr\share\vim\vim74\indent\.gitconfig

C:\Program Files\Git\usr\share\vim\vim74\syntax\.gitconfig

Here are the content of each file

...\Git\mingw64\etc.gitconfig

[credential]
helper = manager

...\Git\usr\share\vim\vim74\ftplugin.gitconfig

" Vim filetype plugin
" Language: git config file
" Maintainer:   Tim Pope <vimNOSPAM@tpope.org>
" Last Change:  2009 Dec 24

" Only do this when not done yet for this buffer
if (exists("b:did_ftplugin"))
  finish
endif
let b:did_ftplugin = 1

setlocal formatoptions-=t formatoptions+=croql
setlocal comments=:#,:; commentstring=;\ %s

let b:undo_ftplugin = "setl fo< com< cms<"

...\Git\usr\share\vim\vim74\indent.gitconfig

" Vim indent file
" Language: git config file
" Maintainer:   Tim Pope <vimNOSPAM@tpope.org>
" Last Change:  2013 May 30

if exists("b:did_indent")
  finish
endif
let b:did_indent = 1

setlocal autoindent
setlocal indentexpr=GetGitconfigIndent()
setlocal indentkeys=o,O,*<Return>,0[,],0;,0#,=,!^F

let b:undo_indent = 'setl ai< inde< indk<'

" Only define the function once.
if exists("*GetGitconfigIndent")
  finish
endif

function! GetGitconfigIndent()
  let line  = getline(prevnonblank(v:lnum-1))
  let cline = getline(v:lnum)
  if line =~  '\\\@<!\%(\\\\\)*\\$'
    " odd number of slashes, in a line continuation
    return 2 * &sw
  elseif cline =~ '^\s*\['
    return 0
  elseif cline =~ '^\s*\a'
    return &sw
  elseif cline == ''       && line =~ '^\['
    return &sw
  else
    return -1
  endif
endfunction

Git\usr\share\vim\vim74\syntax.gitconfig

" Vim syntax file
" Language: git config file
" Maintainer:   Tim Pope <vimNOSPAM@tpope.org>
" Filenames:    gitconfig, .gitconfig, *.git/config
" Last Change:  2010 May 21

if exists("b:current_syntax")
  finish
endif

setlocal iskeyword+=-
setlocal iskeyword-=_
syn case ignore
syn sync minlines=10

syn match   gitconfigComment    "[#;].*"
syn match   gitconfigSection    "\%(^\s*\)\@<=\[[a-z0-9.-]\+\]"
syn match   gitconfigSection    '\%(^\s*\)\@<=\[[a-z0-9.-]\+ \+\"\%([^\\"]\|\\.\)*"\]'
syn match   gitconfigVariable    "\%(^\s*\)\@<=\a\k*\%(\s*\%([=#;]\|$\)\)\@=" nextgroup=gitconfigAssignment skipwhite
syn region  gitconfigAssignment  matchgroup=gitconfigNone start=+=\s*+ skip=+\\+ end=+\s*$+ contained contains=gitconfigBoolean,gitconfigNumber,gitConfigString,gitConfigEscape,gitConfigError,gitconfigComment keepend
syn keyword gitconfigBoolean true false yes no contained
syn match   gitconfigNumber  "\d\+" contained
syn region  gitconfigString  matchgroup=gitconfigDelim start=+"+ skip=+\\+ end=+"+ matchgroup=gitconfigError end=+[^\\"]\%#\@!$+ contained contains=gitconfigEscape,gitconfigEscapeError
syn match   gitconfigError  +\\.+    contained
syn match   gitconfigEscape +\\[\\"ntb]+ contained
syn match   gitconfigEscape +\\$+    contained

hi def link gitconfigComment        Comment
hi def link gitconfigSection        Keyword
hi def link gitconfigVariable       Identifier
hi def link gitconfigBoolean        Boolean
hi def link gitconfigNumber     Number
hi def link gitconfigString     String
hi def link gitconfigDelim      Delimiter
hi def link gitconfigEscape     Delimiter
hi def link gitconfigError      Error

let b:current_syntax = "gitconfig"

I run Windows 7 x64 Professional. The computer is part of a domain network.

I Googled this problem and gave up when I came to page 11 with nothing useful.


问:
Send Mouse Coordinates Over Tcp Issues
I am working on program in which I want to move cursor of remote pc from my pc but here is a little problem receiving mouse coordinates on remote pc the data receive by tcp server on remote machine due to delay not pushing immediately on some places here is the code and output coordinates which i saved in a file for both client send and server receive.

Client Code to Send Coordinates.

```<code>private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();
            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes($"{pX}#{pY}");
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\client.txt", $"{pX}#{pY}" + Environment.NewLine);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }
        catch (Exception ex)
        {
        }
    }
}
</code>```

Server Code to Receive Coordinates

```<code>while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    try
    {
        // Translate data bytes to a ASCII string.
        // Receive mouse coordinates here
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

        string Coordinates = data.ToString();
        string X = Coordinates.Substring(0, Coordinates.IndexOf('#'));
        string Y = Coordinates.Substring(Coordinates.IndexOf('#') + 1);
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));

        // Change coordinates
        System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
        Cursor.Clip = new Rectangle(this.Location, this.Size);
        System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

    }
    catch (Exception E)
    {
        //  MessageBox.Show(E.ToString());
    }
}
</code>```

Send Coordinates from client

653#492
659#490
669#489
677#486
684#483
693#476
699#470
709#460
715#453
720#444
724#437

Receive Coordinates on Server
653 and 492
659 and 490
669 and 489
677 and 486
684 and 483
693 and 476
699 and 470
709 and 460715#453720#444
724 and 437

Here problem is with709 and 460715#453720#444 because old coordinates were not pushed forward and appending with new which is not suitable for mouse position Please help.

答:
I think for this situation using binary format is better.

Like this:

```<code>private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();

            var BW = new BinaryWriter(serverStream);

            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            BW.Write(pX);
            BW.Write(pY);
        }
        catch (Exception ex)
        {

        }
    }

}

private void RecieveLoop()
{
    if (clientSocket.Available > 0)
    {
        NetworkStream serverStream = clientSocket.GetStream();
        var BR = new BinaryReader(serverStream);

        try
        {
            int X = BR.ReadInt32();
            int Y = BR.ReadInt32();

            coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

            coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
            coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));
            ////change coordinates
            System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
            Cursor.Clip = new Rectangle(this.Location, this.Size);
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

        }
        catch (Exception E)
        {

            //  MessageBox.Show(E.ToString());
        }
    }
}
</code>```

Title: Send Mouse Coordinates Over Tcp Issues

Body:
I am working on program in which I want to move cursor of remote pc from my pc but here is a little problem receiving mouse coordinates on remote pc the data receive by tcp server on remote machine due to delay not pushing immediately on some places here is the code and output coordinates which i saved in a file for both client send and server receive.

Client Code to Send Coordinates.

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();
            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            byte[] outStream = System.Text.Encoding.ASCII.GetBytes($"{pX}#{pY}");
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\client.txt", $"{pX}#{pY}" + Environment.NewLine);
            serverStream.Write(outStream, 0, outStream.Length);
            serverStream.Flush();
        }
        catch (Exception ex)
        {
        }
    }
}

Server Code to Receive Coordinates

while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
    try
    {
        // Translate data bytes to a ASCII string.
        // Receive mouse coordinates here
        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

        string Coordinates = data.ToString();
        string X = Coordinates.Substring(0, Coordinates.IndexOf('#'));
        string Y = Coordinates.Substring(Coordinates.IndexOf('#') + 1);
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
        coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));

        // Change coordinates
        System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
        Cursor.Clip = new Rectangle(this.Location, this.Size);
        System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

    }
    catch (Exception E)
    {
        //  MessageBox.Show(E.ToString());
    }
}

Send Coordinates from client

653#492
659#490
669#489
677#486
684#483
693#476
699#470
709#460
715#453
720#444
724#437

Receive Coordinates on Server
653 and 492
659 and 490
669 and 489
677 and 486
684 and 483
693 and 476
699 and 470
709 and 460715#453720#444
724 and 437

Here problem is with709 and 460715#453720#444 because old coordinates were not pushed forward and appending with new which is not suitable for mouse position Please help.

Body:
I think for this situation using binary format is better.

Like this:

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    if (isconnected)
    {
        try
        {
            NetworkStream serverStream = clientSocket.GetStream();

            var BW = new BinaryWriter(serverStream);

            this.Cursor = new Cursor(Cursor.Current.Handle);
            int pX = Cursor.Position.X;
            int pY = Cursor.Position.Y;
            BW.Write(pX);
            BW.Write(pY);
        }
        catch (Exception ex)
        {

        }
    }

}

private void RecieveLoop()
{
    if (clientSocket.Available > 0)
    {
        NetworkStream serverStream = clientSocket.GetStream();
        var BR = new BinaryReader(serverStream);

        try
        {
            int X = BR.ReadInt32();
            int Y = BR.ReadInt32();

            coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = ""));

            coordvalue.Invoke((MethodInvoker)(() => coordvalue.Text = $"{X} and {Y}"));
            coordvalue.Invoke((MethodInvoker)(() => coordvalue.Update()));
            ////change coordinates
            System.Windows.Forms.Cursor.Position = new Point(Convert.ToInt32(X), Convert.ToInt32(Y));
            Cursor.Clip = new Rectangle(this.Location, this.Size);
            System.IO.File.AppendAllText(@"F:\DOWNLOAD\server.txt", $"{X} and {Y}" + Environment.NewLine);

        }
        catch (Exception E)
        {

            //  MessageBox.Show(E.ToString());
        }
    }
}


问:
How to convert data table into SQLite table using RSQLite?
I am very comfortable using R, but I've never used RSQLite or even SQLite, so I have a question on how to best use RSQLite to add data from a data frame in R to an SQLite table.

I understand that I can create tables and add data like so:

```<code>db <- dbConnect(SQLite(), dbname="Test.sqlite")

dbSendQuery(conn = db,  "CREATE TABLE School (SchID INTEGER,
        Location TEXT, Authority TEXT, SchSize TEXT)")

dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (1, 'urban', 'state', 'medium')")
dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (2, 'urban', 'independent', 'large')")
dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (3, 'rural', 'state', 'small')")
</code>```

However, to do multiple INSERT statements like this, I'd need to parse all rows of the data frame using a for loop.  Is it possible to use vectors and a single INSERT to populate the SQLite table with all values from a data frame?

答: You can use dbWriteTable to write the table in one go. Read the vignette to see more examples.

Body:
I am very comfortable using R, but I've never used RSQLite or even SQLite, so I have a question on how to best use RSQLite to add data from a data frame in R to an SQLite table.

I understand that I can create tables and add data like so:

db <- dbConnect(SQLite(), dbname="Test.sqlite")

dbSendQuery(conn = db,  "CREATE TABLE School (SchID INTEGER,
        Location TEXT, Authority TEXT, SchSize TEXT)")

dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (1, 'urban', 'state', 'medium')")
dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (2, 'urban', 'independent', 'large')")
dbSendQuery(conn = db,
            "INSERT INTO School
         VALUES (3, 'rural', 'state', 'small')")

However, to do multiple INSERT statements like this, I'd need to parse all rows of the data frame using a for loop.  Is it possible to use vectors and a single INSERT to populate the SQLite table with all values from a data frame?


问:
2 rows of images (odd numbers of images)
I want to make 2 rows of images like this (from 5 images):

     Image Image

  Image Image Image

But how can I center the first row?

My result looks like this:

Image Image

  Image Image Image

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border="0">

  <tr>

    <td>
      <figure style="margin: 0;">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin:0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

  </tr>

  <tr>

    <td>
      <figure style="margin: 0;">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin:0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

    <td>
      <figure style="margin: 0">
        <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100">
      </figure>
    </td>

  </tr>

</table></code>```

View on JSFiddle

答:
Michael Coker has a correct answer, especially if it's appropriate to use tables for your problem. But if you're just using tables for layout/alignment, that's typically thought of as bad practice (see this SO post Why not use tables for layout in HTML?)

I thought I would offer an alternative solution that does not involve tables.

figure {
  display: inline-block;
  border: 1px solid cadetblue;
}

.wrapper {
  text-align:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="top-row">
    <figure style="margin: 0;"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></figure>

    <figure style="margin:0"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></figure>
    </div>

  <div class="second-row">
    <figure style="margin: 0;"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></figure>
    <figure style="margin:0"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></figure>
    <figure style="margin: 0"> <img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></figure>
  </div>
</div></code>```

Body:
I want to make 2 rows of images like this (from 5 images):

     Image Image

  Image Image Image

But how can I center the first row?

My result looks like this:

Image Image

  Image Image Image

figure img {
  -webkit-transform: scale(1);
  transform: scale(1);
  -webkit-transition: .3s ease-in-out;
  transition: .3s ease-in-out;
}

figure:hover img {
  -webkit-transform: scale(1.05);
  transform: scale(1.05);
  position: relative;
  height: auto;
  display: block;
  z-index: 999;
  border: 1px solid #ffffff;
  background-color: #ffffff;
}

View on JSFiddle

Body:
Michael Coker has a correct answer, especially if it's appropriate to use tables for your problem. But if you're just using tables for layout/alignment, that's typically thought of as bad practice (see this SO post Why not use tables for layout in HTML?)

I thought I would offer an alternative solution that does not involve tables.

figure {
  display: inline-block;
  border: 1px solid cadetblue;
}

.wrapper {
  text-align:center;
}

<div class="wrapper">
  <div class="top-row">
    <figure style="margin: 0;"><a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a></figure>

    <figure style="margin:0"><a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a></figure>
    </div>

  <div class="second-row">
    <figure style="margin: 0;"><a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a></figure>
    <figure style="margin:0"><a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a></figure>
    <figure style="margin: 0"> <a target="_blank" href="#"><img src="https://www.wegmans.com/content/dam/wegmans/products/768/56768.jpg" height="100" width="100"></a></figure>
  </div>
</div>


问:
Install postgres 9.0 in debian lenny
Dear all,

My system has the following distribution details

```<code>$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 5.0 (lenny)
Release:    5.0
Codename:   lenny
</code>```

I need to install postgres 9.0 in this machine , but I cannot find any stable lenny packages for postgres 9.0 , Is there any other way to do this

Any suggestion would be appreciated !

答:
Thanks to the new debian backports suite, here's how to install PostgreSQL 9.0 on Debian lenny:

Add the following to /etc/apt/sources.list:

```<code>deb http://backports.debian.org/debian-backports lenny-backports   main
deb http://backports.debian.org/debian-backports lenny-backports-sloppy main
</code>```

Then run these 2 commands

```<code>apt-get install -t lenny-backports postgresql-common
apt-get install -t lenny-backports-sloppy postgresql-9.0 postgresql-client-9.0 postgresql-contrib-9.0
</code>```

Note that this utilizes the new lenny-backports-sloppy backport suite - please read the announcement in order to be aware of the trade offs of using this suite.

Title: Install postgres 9.0 in debian lenny

Body:
Dear all,

My system has the following distribution details

$ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 5.0 (lenny)
Release:    5.0
Codename:   lenny

I need to install postgres 9.0 in this machine , but I cannot find any stable lenny packages for postgres 9.0 , Is there any other way to do this

Any suggestion would be appreciated !

Body:
Thanks to the new debian backports suite, here's how to install PostgreSQL 9.0 on Debian lenny:

Add the following to /etc/apt/sources.list:

deb http://backports.debian.org/debian-backports lenny-backports   main
deb http://backports.debian.org/debian-backports lenny-backports-sloppy main

Then run these 2 commands

apt-get install -t lenny-backports postgresql-common
apt-get install -t lenny-backports-sloppy postgresql-9.0 postgresql-client-9.0 postgresql-contrib-9.0

Note that this utilizes the new lenny-backports-sloppy backport suite - please read the announcement in order to be aware of the trade offs of using this suite.


问:
outputting pdf files using C++ file I/O
I was trying to output a string to a file using File I/O of C++, but I decided to change the extension of the output file to .pdf, .docx and so on.

None of them seem to open up.

So are there any more internal translations required in order to make that file a proper(file which opens) pdf or docx??

```<code>void convert(char *file){

    ifstream in(file);
    ofstream out("out.pdf",ios::out);

    char str;

    while(in && out){
        in.get(str);
        out.put(str);
    }

    in.close();
    out.close();
    cout<<"Done!!!";
}
</code>```

答:
PDF is (and also docx which actually is OOXML; and of course also OpenDocument & DocBook) a file format (and quite a complex one), specified in a complex English document (the ISO 32000 standard) defining which sequences of bytes are valid (and what they represent).

Grossly speaking a PDF file contains elementary steps to draw ink on paper or pixels on screen. With gross simplification, these steps include things like "move the pen to position x=23 y=50", "choose the Arial font of 10pt", "draw the word abc in that font at that position", "choose the pink color for the pen" etc etc, but the details are much more complex.

File extensions don't mean anything (except as an important convention).

To generate a PDF file, you either need to spend weeks or months to study the specification of that PDF format, or to use some library for that (see this question, and also podofo, poppler and several other libraries). Even with the help of a library, you need to understand something about that format.

Are there any more internal translations required in order to make that file

I'm not sure to understand what you mean by translation (a better word would be "converter"). You could generate PDF by sending some other content to a suitable program emitting PDF. You might consider using some document formatter (like LaTeX thru pdflatex, or Lout, or some older variant of troff, etc..) which you would feed with a higher-level file format containing text formatting directives mixed with (some encoding of) the text to be formatted. On Unix like systems you might even use some command pipeline (to avoid writing some "temporary" file), perhaps using popen(3) and related functions.

Title: outputting pdf files using C++ file I/O

Body:
I was trying to output a string to a file using File I/O of C++, but I decided to change the extension of the output file to .pdf, .docx and so on.

None of them seem to open up.

So are there any more internal translations required in order to make that file a proper(file which opens) pdf or docx??

void convert(char *file){

    ifstream in(file);
    ofstream out("out.pdf",ios::out);

    char str;

    while(in && out){
        in.get(str);
        out.put(str);
    }

    in.close();
    out.close();
    cout<<"Done!!!";
}


问:
How can I limit the length of a text field input in flutter?
The TextField widget doesn't seem to have a "limit" attribute to limit the number of characters that can be typed. How I can enforce that only a certain number of characters can be provided as input in a TextField Widget. I tried looking at the decoration property and potentially setting the limit there somehow but that didn't seem to work either. Is there a different widget I should be using?</p>

答:
I had to add an additional snippet to what RSproute mentioned. The full code is here: </p>

```<code>TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it
onChanged
int maxLength = ...
...
new TextField(
    controller: _controller,
    onChange: (String newVal) {
        if(newVal.length <= maxLength){
            text = newVal;
        }else{
            _controller.value = new TextEditingValue(
                text: text,
                selection: new TextSelection(
                    baseOffset: maxLength,
                    extentOffset: maxLength,
                    affinity: TextAffinity.downstream,
                    isDirectional: false
                ),
                composing: new TextRange(
                    start: 0, end: maxLength
                )
            );
            _controller.text = text;
        }
    }
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I had to add an additional snippet to what RSproute mentioned. The full code is here:

TextEditingController _controller = new TextEditingController();
String text = ""; // empty string to carry what was there before it
onChanged
int maxLength = ...
...
new TextField(
    controller: _controller,
    onChange: (String newVal) {
        if(newVal.length <= maxLength){
            text = newVal;
        }else{
            _controller.value = new TextEditingValue(
                text: text,
                selection: new TextSelection(
                    baseOffset: maxLength,
                    extentOffset: maxLength,
                    affinity: TextAffinity.downstream,
                    isDirectional: false
                ),
                composing: new TextRange(
                    start: 0, end: maxLength
                )
            );
            _controller.text = text;
        }
    }
);


问:
Use position_jitterdodge to plot points, and add highlighted points that are also dodged
I have some data where x is categorical, y is numeric, and color.var is another categorical variable that I would like to color by. My goal is to plot all of the points using position_jitterdodge(), and then highlight a couple of the points, draw a line between them, and add labels, while making sure these highlighted points line up with the corresponding strips of points that were plotted using position_jitterdodge(). The highlighted points are aligned properly when all factors are present in the variable used to dodge, but it does not work well when some factors are missing.

Minimal (non-)working example

```<code>library(ggplot2)
</code>```

Generate some data

```<code>d = data.frame(x = c(rep('x1', 1000), rep('x2', 1000)),
               y = runif(n=2000, min=0, max=1),
               color.var= rep(c('color1', 'color2'), 1000),
               facet.var = rep(c('facet1', 'facet1', 'facet2', 'facet2'), 500))
head(d)
dd = d[c(1,2,3,4,1997,1998, 1999,2000),]
dd
df1 = dd[dd$color.var=='color1',] ## data for first  set of points, labels, and the line connecting them
df2 = dd[dd$color.var=='color2',] ## data for second set of points, labels, and the line connecting them
df1
dw = .75 ## Define the dodge.width
</code>```

Plot all points

Here are all of the points, separated using position_jitterdodge() and the aesthetic fill.

```<code>ggplot() +
  geom_point(data=d, aes(x=x, y=y, fill=color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
  facet_wrap(~facet.var) +
  scale_fill_manual(values=c( 'lightblue','gray'))+
  theme(axis.title = element_blank()) +
  theme(legend.position="top")
</code>```

That works well.

Additional highlighted points.

Here is the same plot, with additional points in dd added.

```<code>ggplot() +
  geom_point(data=d,  aes(x=x, y=y, fill =color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
  geom_point(data=dd, aes(x=x, y=y, color=color.var                                   ), position=position_dodge(width=.75), size=4   ) +
   geom_line(data=dd, aes(x=x, y=y, color=color.var, group=color.var                  ), position=position_dodge(width=.75), size=1   ) +
  geom_label(data=dd, aes(x=x, y=y, color=color.var, group=color.var, label=round(y,1)), position=position_dodge(width=.75), vjust=-.5) +
  facet_wrap(~facet.var) +
  scale_fill_manual(values=c( 'lightblue','gray'))+
  scale_color_manual(values=c( 'blue', 'gray40')) +
  theme(axis.title = element_blank())+
  theme(legend.position="top")
</code>```

This is what I want it to look like. However, this only works properly if both factors of the color.var variable are in the set of points to highlight.
If both factors aren't present in the new data, the horizonal alignment fails.

Highlight points, only one factor present

Here is an example where only the 'color1' factor (blue) is present. Note that data=dd was replaced with data=df1 (data that only contains blue highlighted dots) in this code.

```<code>ggplot() +
      geom_point(data=d,  aes(x=x, y=y, fill =color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
      geom_point(data=df1, aes(x=x, y=y, color=color.var                                   ), position=position_dodge(width=.75), size=4   ) +
       geom_line(data=df1, aes(x=x, y=y, color=color.var, group=color.var                  ), position=position_dodge(width=.75), size=1   ) +
      geom_label(data=df1, aes(x=x, y=y, color=color.var, group=color.var, label=round(y,1)), position=position_dodge(width=.75), vjust=-.5) +
      facet_wrap(~facet.var) +
      scale_fill_manual(values=c( 'lightblue','gray'))+
      scale_color_manual(values=c( 'blue', 'gray40')) +
      theme(axis.title = element_blank())+
      theme(legend.position="top") +
      scale_x_discrete(drop=F)
</code>```

The highlight blue dots appear between the blue and gray dots, instead of aligned with the blue dots. Note that the additional code  scale_x_discrete(drop=F) had no apparent effect on the alignment.

A manual solution

One possible fix is to edit the x coordinate manually, like this

```<code> ggplot(data=d, aes(x=x, y=y)) +
      geom_point(aes(fill=color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
      geom_point(data=df1, aes(x=as.numeric(x)-dw/4, y=y), alpha=.9, size=4 , color='blue') +            ## first set of points
      geom_line( data=df1, aes(x=as.numeric(x)-dw/4, y=y , group=color.var     ), color='blue', size=1) +    ## first line
      geom_label(data=df1, aes(x=as.numeric(x)-dw/4, y=y , label=round(y,1)), color='blue', vjust=-.25)+ ## first set of labels
      facet_wrap(~facet.var) +
      scale_fill_manual(values=c( 'lightblue','gray'))+
      theme(axis.title = element_blank() +
      theme(legend.position="top")
</code>```

An adjustment of 1/4 of the dodge.width seems to work.  This works fine, but it seems like there should be a better way, especially since I will eventually want to do this with 4-5 sets of highlighted points/lines, which may all be all be the same color.var, like the blue 'color1' factor above.  Repeating this 4-5 times would be cumbersome. I will also eventually want to do this will 5-10 different figures. I suppose dodge.width*1/4 will always work, and copying and pasting might do the trick, but would like to know if there is a better way.

答:
Here is a solution based on @aosmith's comment.  Basically, just need to add this code before using ggplot:

```<code>library(dplyr) ## needed for group_by()
library(tidyr) ## needed for complete()
df1 = df1 %>% group_by(facet.var, x) %>% complete(color.var)
</code>```

That adds extra rows to the data so that all the levels of color.var are present. Then the code given in the question, along with a couple of small edits that fix the legend, can be used:

```<code>ggplot() +
  geom_point(data=d  , aes(x=x, y=y, fill =color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray', show.legend=T) +
  geom_point(data=df1, aes(x=x, y=y, color=color.var                                   ), position=position_dodge(width=.75), size=4, show.legend=T   ) +
  geom_line( data=df1, aes(x=x, y=y, color=color.var, group=color.var                  ), position=position_dodge(width=.75), size=1, show.legend=F   ) +
  geom_label(data=df1, aes(x=x, y=y, color=color.var, group=color.var, label=round(y,1)), position=position_dodge(width=.75), vjust=-.5, show.legend=F) +
  facet_wrap(~facet.var) +
  scale_fill_manual( values=c( 'lightblue','gray'), name='Background dots', guide=guide_legend(override.aes = list(color=c('lightblue', 'gray')))) +
  scale_color_manual(values=c( 'blue', 'gray40')  , name='Highlighted dots') +
  theme(axis.title = element_blank())+
  theme(legend.position="top")+
  scale_x_discrete(drop=F)
</code>```

Body:
I have some data where x is categorical, y is numeric, and color.var is another categorical variable that I would like to color by. My goal is to plot all of the points using position_jitterdodge(), and then highlight a couple of the points, draw a line between them, and add labels, while making sure these highlighted points line up with the corresponding strips of points that were plotted using position_jitterdodge(). The highlighted points are aligned properly when all factors are present in the variable used to dodge, but it does not work well when some factors are missing.

Minimal (non-)working example

library(ggplot2)

Generate some data

d = data.frame(x = c(rep('x1', 1000), rep('x2', 1000)),
               y = runif(n=2000, min=0, max=1),
               color.var= rep(c('color1', 'color2'), 1000),
               facet.var = rep(c('facet1', 'facet1', 'facet2', 'facet2'), 500))
head(d)
dd = d[c(1,2,3,4,1997,1998, 1999,2000),]
dd
df1 = dd[dd$color.var=='color1',] ## data for first  set of points, labels, and the line connecting them
df2 = dd[dd$color.var=='color2',] ## data for second set of points, labels, and the line connecting them
df1
dw = .75 ## Define the dodge.width

Plot all points

Here are all of the points, separated using position_jitterdodge() and the aesthetic fill.

ggplot() +
  geom_point(data=d, aes(x=x, y=y, fill=color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
  facet_wrap(~facet.var) +
  scale_fill_manual(values=c( 'lightblue','gray'))+
  theme(axis.title = element_blank()) +
  theme(legend.position="top")

That works well.

Additional highlighted points.

Here is the same plot, with additional points in dd added.

ggplot() +
  geom_point(data=d,  aes(x=x, y=y, fill =color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
  geom_point(data=dd, aes(x=x, y=y, color=color.var                                   ), position=position_dodge(width=.75), size=4   ) +
   geom_line(data=dd, aes(x=x, y=y, color=color.var, group=color.var                  ), position=position_dodge(width=.75), size=1   ) +
  geom_label(data=dd, aes(x=x, y=y, color=color.var, group=color.var, label=round(y,1)), position=position_dodge(width=.75), vjust=-.5) +
  facet_wrap(~facet.var) +
  scale_fill_manual(values=c( 'lightblue','gray'))+
  scale_color_manual(values=c( 'blue', 'gray40')) +
  theme(axis.title = element_blank())+
  theme(legend.position="top")

This is what I want it to look like. However, this only works properly if both factors of the color.var variable are in the set of points to highlight.
If both factors aren't present in the new data, the horizonal alignment fails.

Highlight points, only one factor present

Here is an example where only the 'color1' factor (blue) is present. Note that data=dd was replaced with data=df1 (data that only contains blue highlighted dots) in this code.

ggplot() +
      geom_point(data=d,  aes(x=x, y=y, fill =color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
      geom_point(data=df1, aes(x=x, y=y, color=color.var                                   ), position=position_dodge(width=.75), size=4   ) +
       geom_line(data=df1, aes(x=x, y=y, color=color.var, group=color.var                  ), position=position_dodge(width=.75), size=1   ) +
      geom_label(data=df1, aes(x=x, y=y, color=color.var, group=color.var, label=round(y,1)), position=position_dodge(width=.75), vjust=-.5) +
      facet_wrap(~facet.var) +
      scale_fill_manual(values=c( 'lightblue','gray'))+
      scale_color_manual(values=c( 'blue', 'gray40')) +
      theme(axis.title = element_blank())+
      theme(legend.position="top") +
      scale_x_discrete(drop=F)

The highlight blue dots appear between the blue and gray dots, instead of aligned with the blue dots. Note that the additional code  scale_x_discrete(drop=F) had no apparent effect on the alignment.

A manual solution

One possible fix is to edit the x coordinate manually, like this

 ggplot(data=d, aes(x=x, y=y)) +
      geom_point(aes(fill=color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray') +
      geom_point(data=df1, aes(x=as.numeric(x)-dw/4, y=y), alpha=.9, size=4 , color='blue') +            ## first set of points
      geom_line( data=df1, aes(x=as.numeric(x)-dw/4, y=y , group=color.var     ), color='blue', size=1) +    ## first line
      geom_label(data=df1, aes(x=as.numeric(x)-dw/4, y=y , label=round(y,1)), color='blue', vjust=-.25)+ ## first set of labels
      facet_wrap(~facet.var) +
      scale_fill_manual(values=c( 'lightblue','gray'))+
      theme(axis.title = element_blank() +
      theme(legend.position="top")

An adjustment of 1/4 of the dodge.width seems to work.  This works fine, but it seems like there should be a better way, especially since I will eventually want to do this with 4-5 sets of highlighted points/lines, which may all be all be the same color.var, like the blue 'color1' factor above.  Repeating this 4-5 times would be cumbersome. I will also eventually want to do this will 5-10 different figures. I suppose dodge.width*1/4 will always work, and copying and pasting might do the trick, but would like to know if there is a better way.

Body:
Here is a solution based on @aosmith's comment.  Basically, just need to add this code before using ggplot:

library(dplyr) ## needed for group_by()
library(tidyr) ## needed for complete()
df1 = df1 %>% group_by(facet.var, x) %>% complete(color.var)

That adds extra rows to the data so that all the levels of color.var are present. Then the code given in the question, along with a couple of small edits that fix the legend, can be used:

ggplot() +
  geom_point(data=d  , aes(x=x, y=y, fill =color.var), position=position_jitterdodge(dodge.width=dw), size=3, alpha=1, shape=21, color='darkgray', show.legend=T) +
  geom_point(data=df1, aes(x=x, y=y, color=color.var                                   ), position=position_dodge(width=.75), size=4, show.legend=T   ) +
  geom_line( data=df1, aes(x=x, y=y, color=color.var, group=color.var                  ), position=position_dodge(width=.75), size=1, show.legend=F   ) +
  geom_label(data=df1, aes(x=x, y=y, color=color.var, group=color.var, label=round(y,1)), position=position_dodge(width=.75), vjust=-.5, show.legend=F) +
  facet_wrap(~facet.var) +
  scale_fill_manual( values=c( 'lightblue','gray'), name='Background dots', guide=guide_legend(override.aes = list(color=c('lightblue', 'gray')))) +
  scale_color_manual(values=c( 'blue', 'gray40')  , name='Highlighted dots') +
  theme(axis.title = element_blank())+
  theme(legend.position="top")+
  scale_x_discrete(drop=F)


问:
issue due to getAdapterPosition
I have an array which contains values like {seat 1,seat 1,seat 1,seat 2, seat 2, seat 3, seat 4,seat 4,seat 4}. ie Left side of image
I need to group them according to its seat values ie. Right side of image.

For given environment seat list array will be: {"1", "-1", "-1", "2", "-1", "3", "4", "-1", "-1"}
currently i am using recyclerview and checking this with below condition:

```<code>if(seat_list.get(holder.getAdapterPosition()).equals("-1"))
    {
        Log.d("aaa", "if :" + seat_list.get(holder.getAdapterPosition()) );
    }
    else
    {
        Log.d("aaa", "else :" + seat_list.get(holder.getAdapterPosition()) );
        holder.ll_header.setVisibility(View.VISIBLE);
        holder.tv_seat_num.setText(seat_list.get(holder.getAdapterPosition()));
    }
</code>```

With above code list is getting destroyed on scrolling the recyclerview.
i already sorted but i want to give common header or heading to all orders with same seat

答: You can sort using Collections.sort method </p>

Title: issue due to getAdapterPosition

Body:
I have an array which contains values like {seat 1,seat 1,seat 1,seat 2, seat 2, seat 3, seat 4,seat 4,seat 4}. ie Left side of image
I need to group them according to its seat values ie. Right side of image.

For given environment seat list array will be: {"1", "-1", "-1", "2", "-1", "3", "4", "-1", "-1"}
currently i am using recyclerview and checking this with below condition:

if(seat_list.get(holder.getAdapterPosition()).equals("-1"))
    {
        Log.d("aaa", "if :" + seat_list.get(holder.getAdapterPosition()) );
    }
    else
    {
        Log.d("aaa", "else :" + seat_list.get(holder.getAdapterPosition()) );
        holder.ll_header.setVisibility(View.VISIBLE);
        holder.tv_seat_num.setText(seat_list.get(holder.getAdapterPosition()));
    }

With above code list is getting destroyed on scrolling the recyclerview.
i already sorted but i want to give common header or heading to all orders with same seat


问:
How to add tracing/debug output to stored procedures in Sql Server (2008)
What is the closest to being able to add log4net style debug information to a set of stored procedures? Some of procedures delegate work to other procedures and I want trace information from both.

I've sprinkled print and select statements through while developing them, and ideally would like to be able to run the proc in different modes depending on whether it's normal operation of troubleshooting and get more or less output.

In this particular case the primary stored proc will be run repeatedly from an agent job, but may be run from management studio when troubleshooting.

The procs already use an error log table and email facilities to catch raised errors. The kind of thing I'm looking to be able to track down is where an input data issue means the output data is wrong but the procs don't fail completely, and it would be useful to see exactly what was done at each step.

What approaches do you know of for producing meaningful and ideally filterable output?

One per answer so we can see the final rankings ;-)

Out of the box answers welcome, such as "don't - step through with management studio when you need to"

答:
Piles of print statements

eg

```<code>print 'Doing something...'
INSERT INTO foo(a) VALUES(1)
print @@ROWCOUNT
</code>```

This answer just for balance, seeing as it's quiet round here.

Body:
Piles of print statements

eg

print 'Doing something...'
INSERT INTO foo(a) VALUES(1)
print @@ROWCOUNT

This answer just for balance, seeing as it's quiet round here.


问:
Batch Delete Files and Keep Latest One from Subdirectories
I'd like to search for a specific filename [*dwg] within the "Service" folder and delete all files but the newest one:

G:\Backup\Owner\Project1\Service

G:\Backup\Owner\Project2\Service

G:\Backup\Owner\Project3\Service

This is what I compiled so far from a various searches but haven't been able to get it to search within the subdirectories. Any help or tip pointing me to the right path will be truly appreciated!

```<code>@echo off &setlocal
set folder=G:\Backup\Owner
pushd "%folder%"
for /f "skip=1 tokens=*" %%i in ('dir /s /a:-d-s /o:-d *.DWG') do @del "%%i"
popd
pause
</code>```

答:
First and most important issue:

Change @del to ECHO del

This will simply report the deletions proposed, not actually perform the deletion.

Note: @ before a command simply suppresses the command-logging. Once @echo off has been executed, it is redundant.

Now to tackle the (I suppose) leave-the-latest-1-per-directory issue.

```<code>dir /s /B /a:-d /o:-d *.DWG
</code>```

produces a directory-listing with no directory-names (/a-d) in reverse-date order (/o-d) of filename only (/b) recursing into subdirectories (/s). The colon in options is optional, the case is irrelevant. The filemask *.dwgmeans "all names ending in.dwg`" (again, case is irrelevant)

This would yield a listing like

```<code>d:\dirname\subdir\latest.dwg
d:\dirname\subdir\2ndlatest.dwg
d:\dirname\subdir\3rdlatest.dwg
d:\dirname\subdir2\latest.dwg
d:\dirname\subdir2\2ndlatest.dwg
d:\dirname\subdir2\3rdlatest.dwg
</code>```

And the project appears to be to leave only the first of these within any subdirectory, so we need a switch to tell us that the subdirectory has changed.

%%~pi provides the pathname of %%i, so we can detect a change there.

We can set a flag easily by setting a variable to well, 1 and 0 or Y and N or whatever - two different values.

The difficulty we will encounter is interpreting flags because of the delayed expansion issue (Search SO using the facility in the top bar for many items about this)

I bypass the delayedexpansion problem by setting flag-variables either to something or to nothing since that way, they can be interpreted by if defined, which operates on the run-time value of the variable, not the initial value.

Hence,

@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
pushd "%sourcedir%"
set "lastdir="
for /f "tokens=*" %%i in ('dir /s /B /a:-d /o:-d *.DWG') do (
 CALL SET "keepflag=%%lastdir:%%~pi=%%"
 if NOT defined keepflag ECHO del "%%i"
 set "lastdir=%%~pi"
)
popd
GOTO :EOF
```

You would need to change the setting of sourcedir to suit your circumstances.

lastdir is first set to nothing and then the for loop assigns each name found in turn to %%i.

The call set instruction bypasses delayed expansion and executes SET "keepflag=%lastdir:%%~pi=%" where %%~pi has been replaced by the path of %%i. This sets keepflag to the result of [the last directory processed replace the path of the filename by nothing], which will be a total of nothing if the directory-names match and something if not.

So, if keepflag contains nothing then the directoryname did not change, so we need to delete the file (or ECHO the delete command for safety during testing). If keepflag is set to something then this is the first file in a new directory, so we keep it by not executing the del.

Then we simply set lastdir to the pathname from the file %%i. That way, another filename in the same directory will set keepfile to nothing but a change-of-directory will set keepfile to something.

Body:
I'd like to search for a specific filename [*dwg] within the "Service" folder and delete all files but the newest one:

G:\Backup\Owner\Project1\Service

G:\Backup\Owner\Project2\Service

G:\Backup\Owner\Project3\Service

This is what I compiled so far from a various searches but haven't been able to get it to search within the subdirectories. Any help or tip pointing me to the right path will be truly appreciated!

@echo off &setlocal
set folder=G:\Backup\Owner
pushd "%folder%"
for /f "skip=1 tokens=*" %%i in ('dir /s /a:-d-s /o:-d *.DWG') do @del "%%i"
popd
pause

Body:
First and most important issue:

Change @del to ECHO del

This will simply report the deletions proposed, not actually perform the deletion.

Note: @ before a command simply suppresses the command-logging. Once @echo off has been executed, it is redundant.

Now to tackle the (I suppose) leave-the-latest-1-per-directory issue.

dir /s /B /a:-d /o:-d *.DWG

produces a directory-listing with no directory-names (/a-d) in reverse-date order (/o-d) of filename only (/b) recursing into subdirectories (/s). The colon in options is optional, the case is irrelevant. The filemask *.dwgmeans "all names ending in.dwg`" (again, case is irrelevant)

This would yield a listing like

d:\dirname\subdir\latest.dwg
d:\dirname\subdir\2ndlatest.dwg
d:\dirname\subdir\3rdlatest.dwg
d:\dirname\subdir2\latest.dwg
d:\dirname\subdir2\2ndlatest.dwg
d:\dirname\subdir2\3rdlatest.dwg

And the project appears to be to leave only the first of these within any subdirectory, so we need a switch to tell us that the subdirectory has changed.

%%~pi provides the pathname of %%i, so we can detect a change there.

We can set a flag easily by setting a variable to well, 1 and 0 or Y and N or whatever - two different values.

The difficulty we will encounter is interpreting flags because of the delayed expansion issue (Search SO using the facility in the top bar for many items about this)

I bypass the delayedexpansion problem by setting flag-variables either to something or to nothing since that way, they can be interpreted by if defined, which operates on the run-time value of the variable, not the initial value.

Hence,

@ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
pushd "%sourcedir%"
set "lastdir="
for /f "tokens=*" %%i in ('dir /s /B /a:-d /o:-d *.DWG') do (
 CALL SET "keepflag=%%lastdir:%%~pi=%%"
 if NOT defined keepflag ECHO del "%%i"
 set "lastdir=%%~pi"
)
popd
GOTO :EOF

You would need to change the setting of sourcedir to suit your circumstances.

lastdir is first set to nothing and then the for loop assigns each name found in turn to %%i.

The call set instruction bypasses delayed expansion and executes SET "keepflag=%lastdir:%%~pi=%" where %%~pi has been replaced by the path of %%i. This sets keepflag to the result of [the last directory processed replace the path of the filename by nothing], which will be a total of nothing if the directory-names match and something if not.

So, if keepflag contains nothing then the directoryname did not change, so we need to delete the file (or ECHO the delete command for safety during testing). If keepflag is set to something then this is the first file in a new directory, so we keep it by not executing the del.

Then we simply set lastdir to the pathname from the file %%i. That way, another filename in the same directory will set keepfile to nothing but a change-of-directory will set keepfile to something.