text:
Q: Nesting two observeEvents duplicates the reactive event This question is related to another one I somewhat solved a few days ago.
My intention:

*

*To upload a csv with several columns.

*Plot each column in a line and points plot.

*Allow the user to select two different points from the plot, called first/last. The program always get the last two points clicked, order them to find first/last (first<=last).

Since the columns may differ from one dataset to another I have to create dynamically the structure of the app, and the problem is that I nest a observeEvent for the click in each plot inside a observeEvent (when the user changes the input dataset). The problem is that the observeEvent for the click depends on the dataset loaded (different columns).
What I do in the app is to create a pool with all the clicks in all the plots and extract the lastest two ones from each plot when needed, and I use this information to modify the plot with colors green and red.
To create two sample datasets:
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)
test1<-inputdata[c("normal","gamma")]
row.names(test1)<-inputdata$weekna
test2<-inputdata[c("normal","logistic")]
row.names(test2)<-inputdata$weekna
write.csv(test1, file="test1.csv")
write.csv(test2, file="test2.csv")

The app:
library(ggplot2)
library(shiny)
library(shinydashboard)

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)
  data<-i.data
  results <- do.call("rbind", by(data, data[i.column], tail.order, i.n=2, i.order=i.order))
  return(results)
}

ui <- fluidPage(
  fluidRow(
    column(4,fileInput('file', "Load file")),
    column(8,uiOutput("maintab"))
  )
)

server <- function(input, output) {

  values <- reactiveValues(origdata = NULL, plotdata = NULL, clickdata=NULL, dummy = TRUE)

  read_data <- reactive({
    infile <- input$file
    inpath <- infile$datapath
    inname <- infile$name
    if(is.null(infile)) readdata<-NULL else readdata<-read.csv(inpath, row.names=1)
    readdata
  })

  observeEvent(input$file, {
    datfile <- read_data()
    seasons<-names(datfile)
    plotdata<-cbind(data.frame(weekno=1:NROW(datfile),weekna=rownames(datfile), stringsAsFactors = F), datfile)
    origdata<-plotdata
    for (s in seasons) eval(parse(text=paste0("plotdata$'",as.character(s),"_color'<-'1'")))
    values$origdata <- origdata
    values$plotdata <- plotdata
    values$clickdata <- data.frame()
    rm("origdata", "plotdata")
    lapply(seasons, function(s){output[[paste0("plot_",as.character(s))]] <- renderPlot({
      ggplot(values$plotdata, aes_(x=as.name("weekno"), y=as.name(s))) +
        geom_point(aes_(as.name("weekno"), as.name(s), colour=as.name(paste0(s,"_color")), size=as.name(paste0(s,"_color")))) +
        scale_color_manual(values = c("1" = "grey", "2" = "red", "3" = "green")) +
        scale_size_manual(values = c("1" = 4, "2" = 6, "3" = 6)) +
        geom_line(aes_(x=as.name("weekno"), y=as.name(s)), color="#000000") +
        ggthemes::theme_few() +
        guides(color=FALSE, size=FALSE)
    })})
    lapply(seasons,function(s){
      observeEvent(input[[paste0("plot_",as.character(s),"_click")]], {
        np <- nearPoints(values$origdata, input[[paste0("plot_",as.character(s),"_click")]], maxpoints=1 , threshold = 10000)
        values$clickdata<-rbind(values$clickdata,cbind(data.frame(variable=as.character(s), stringsAsFactors = F), np))
        if (NROW(values$clickdata)>0){
          p0<-extract.two(values$clickdata,"weekno","variable")
          p1<-subset(p0, variable==as.character(s) & id.tail==1)
          p2<-subset(p0, variable==as.character(s) & id.tail==2)
          if (NROW(p1)>0) {
            values$plotdata[values$plotdata[,paste0(as.character(s),"_color")]=="2", paste0(as.character(s),"_color")]<-"1"
            values$plotdata[values$origdata$weekno==p1$weekno,paste0(as.character(s),"_color")]<-"2"
          }
          if (NROW(p2)>0){
            values$plotdata[values$plotdata[,paste0(as.character(s),"_color")]=="3",paste0(as.character(s),"_color")]<-"1"
            values$plotdata[values$origdata$weekno==p2$weekno,paste0(as.character(s),"_color")]<-"3"
          }
        }
      })
    })
  })

  output$maintab <- renderUI({
    datfile <- read_data()
    seasons<-names(datfile)
    do.call(tabsetPanel,
            c(
              lapply(seasons,function(s){
                call("tabPanel",s,call("plotOutput", outputId=paste0("plot_",as.character(s)),
                                       click = paste0("plot_",as.character(s),"_click")))
              }),
              list(
                tabPanel("First & last",tableOutput("results")),
                tabPanel("Clicks",tableOutput("resultsfull"))
              )
            )
    )
  })

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

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

}

shinyApp(ui, server)

To reproduce the bug:
Open test1.csv, a observeEvent for each column is created ("_click").
Open test2.csv, a observeEvent for each column is created ("_click").
Since test1.csv and test2.csv first column is called "normal" then the observeEvent$normal_click is created two times, so when I click the plot it writes two times the point clicked to the "clicks pool" (because there are two observeEvent related to that "normal_click".
When I extract the lastest two points from the "clicks pool", it retrieves the same point two times (the point I clicked and was stored two times because there was two observeEvents_click to the same plot).
I know to to circumvent the problem by uncommenting:
#data<-unique(i.data, fromLast=T)

This way it removes duplicates, but also denies the chance of telling the app to use the same point for first and last (first can be equal to last). And also this solution is not elegant since the structural problem is still there.
Any hints on how to fix this?

A: I found another post talking about another problem that did lead me to the solution.
I have created a list of observeEvent that have been created not to allow duplicate the same observeEvent (called idscreated).
library(ggplot2)
library(shiny)
library(shinydashboard)

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<-i.data
  results <- do.call("rbind", by(data, data[i.column], tail.order, i.n=2, i.order=i.order))
  return(results)
}

ui <- fluidPage(
  fluidRow(
    column(4,fileInput('file', "Load file")),
    column(8,uiOutput("maintab"))
  )
)

server <- function(input, output) {

  values <- reactiveValues(origdata = NULL, plotdata = NULL, clickdata=NULL, idscreated = character())

  read_data <- reactive({
    infile <- input$file
    inpath <- infile$datapath
    inname <- infile$name
    if(is.null(infile)) readdata<-NULL else readdata<-read.csv(inpath, row.names=1)
    readdata
  })

  observeEvent(read_data(), {
    datfile <- read_data()
    seasons<-names(datfile)
    plotdata<-cbind(data.frame(weekno=1:NROW(datfile),weekna=rownames(datfile), stringsAsFactors = F), datfile)
    origdata<-plotdata
    for (s in seasons) eval(parse(text=paste0("plotdata$'",as.character(s),"_color'<-'1'")))
    values$origdata <- origdata
    values$plotdata <- plotdata
    values$clickdata <- data.frame()
    rm("origdata", "plotdata")
    lapply(seasons, function(s){output[[paste0("plot_",as.character(s))]] <- renderPlot({
      ggplot(values$plotdata, aes_(x=as.name("weekno"), y=as.name(s))) +
        geom_point(aes_(as.name("weekno"), as.name(s), colour=as.name(paste0(s,"_color")), size=as.name(paste0(s,"_color")))) +
        scale_color_manual(values = c("1" = "grey", "2" = "red", "3" = "green", "4" = "purple")) +
        scale_size_manual(values = c("1" = 4, "2" = 6, "3" = 6, "4" = 8)) +
        geom_line(aes_(x=as.name("weekno"), y=as.name(s)), color="#000000") +
        ggthemes::theme_few() +
        guides(color=FALSE, size=FALSE)
    })})
    lapply(seasons,function(s){
      nameid<-paste0("plot_",as.character(s),"_click")
      if (!(nameid %in% values$idscreated)){
        values$idscreated<-c(values$idscreated,nameid)
      observeEvent(input[[nameid]], {
        np <- nearPoints(values$origdata, input[[nameid]], maxpoints=1 , threshold = 10000)
        values$clickdata<-rbind(values$clickdata,cbind(data.frame(variable=as.character(s), stringsAsFactors = F), np))
        if (NROW(values$clickdata)>0){
          p0<-extract.two(values$clickdata,"weekno","variable")
          p1<-subset(p0, variable==as.character(s) & id.tail==1)
          p2<-subset(p0, variable==as.character(s) & id.tail==2)
          if (NROW(p1)>0) {
            values$plotdata[values$plotdata[,paste0(as.character(s),"_color")]!="3", paste0(as.character(s),"_color")]<-"1"
            values$plotdata[values$origdata$weekno==p1$weekno,paste0(as.character(s),"_color")]<-"2"
          }
          if (NROW(p2)>0){
            values$plotdata[values$plotdata[,paste0(as.character(s),"_color")]!="2", paste0(as.character(s),"_color")]<-"1"
            values$plotdata[values$origdata$weekno==p2$weekno,paste0(as.character(s),"_color")]<-"3"
          }
          if (NROW(p1)>0 & NROW(p2)>0){
            if (p1$weekno==p2$weekno){
              values$plotdata[, paste0(as.character(s),"_color")]<-"1"
              values$plotdata[values$origdata$weekno==p1$weekno,paste0(as.character(s),"_color")]<-"4"
            }
          }

        }
      })
      }

    })
  })

  output$maintab <- renderUI({
    datfile <- read_data()
    seasons<-names(datfile)
    do.call(tabsetPanel,
            c(
              lapply(seasons,function(s){
                call("tabPanel",s,call("plotOutput", outputId=paste0("plot_",as.character(s)),
                                       click = paste0("plot_",as.character(s),"_click")))
              }),
              list(
                tabPanel("First & last",tableOutput("results")),
                tabPanel("Clicks",tableOutput("resultsfull"))
              )
            )
    )
  })

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

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

}

shinyApp(ui, server)


text:
Q: How do I assign argument properties to self? Aim
I am aiming to emulate the Mongoose model "class" using an in-memory store. Here is an example of what that might look like:
var Book = require("./book");
var book = new Book({
  title: "Hello"
});

Now, when I pass book to, for example, console.log the following output is returned:
console.log(book); // returns { title: "Hello" }

Problem
I made a function called MyBook that emulates the Mongoose model "class":
function MyBook(doc) {
  this.doc = doc;
}
var book = new MyBook({title: "Hello"});

But when I pass book to console.log, the output is different:
console.log(book); // returns { doc: { title: "Hello" } }

This makes sense to me. I am assigning to doc so it makes sense that I have a property doc. This is not what I want, though. What I want is an output like the one Mongoose returns. I assign to doc because, when I assign to this:
function MyBook(doc) {
  this = doc;
}

I get this error:
ReferenceError: Invalid left-hand side in assignment

Again, this makes sense to me. But the question remains: How do I (dynamically) assign properties of the given argument to the current object?

A: You can iterate over all the properties of doc with a for...in loop:
function MyBook(doc) {
  for (var property in doc) {
    if (doc.hasOwnProperty(property)) {
      this[property] = doc[property];
    }
  }
}

var book = new MyBook({title: "Hello"});

Soon you'll be able to just do Object.assign(this, doc).

A: You can use extend function from util module to merge the passed arguments with the self this object
var extend = require('util')._extend
;

var MyBook = function(options) {
    extend(this, options);
};

A: You could use JavaScripts arguments object. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/arguments
function MyBook() {
    this.title = arguments[0];
    this.other = arguments[1]
}
var book = new MyBook("Hello", "Other");
console.log(book); // returns - MyBook {title: "Hello", other: "Other"}

Though doing it this way you need to set up the properties you want on MyBook originally. This doesnt really match the "dynamic" element you were looking for but does match your aim, the idea of a "class"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to disable CORS within a Zuul / Spring Boot microservice setup? (route CORS OPTIONS preflights) In our setup Zuul should act as router for our Microservices. This means that also CORS OPTIONS request should be routed to our Microservices (noone else knows about the correct CORS settings...).
How to setup Spring-Boot/Spring-MVC/Zuul that it routes the CORS to the microservices?
There are many Answers around how to enable and how to configure cors. But they aim on how to enable CORS or "allow every domain". There is no answer how to disable the CORS handling on a Spring-Boot with Zuul setup.

A: The Problem is that Spring-Boot in its autoconfiguration hijacks the CORS OPTIONS requests and isn't forwarding it to the zuul part. To disable the CORS Filter just put this into your application properties or yml.
spring.mvc.dispatch-options-request=true

Now the CORS Requests are forwarded to your microservices.


text:
Q: HDMI TV not showing as audio output in System Preferences I have linked a cable from my MacBook Air to my TV via HDMI but cannot get volume on the TV. I have gone into preferences-sound but their is no facility to change 'internal speakers'. How can I do this?

A: If you are using a Mini Displayport to HDMI adapter this should help you.  If you are using Mini-DVI to HDMI adapter then you will have to get audio from your headphone port via an external cable because DVI is strictly video.


text:
Q: On what sets can $\mathfrak{S}_n$ act transitively? I would like to know $\mathfrak{S}_n$ could act faithfully transitively on sets with $m$ elements, with $m > n$.
I know that it is not possible if $m = n+1$ except for $n = 5$.
Any ideas ?

A: There are many sets of more than $n$ elements on which $\mathfrak S_n$ acts transitively. The largest possible example is that of the $n!$ total orderings of the set of $n$ elements (the one used to define $\mathfrak S_n$). One can deduce numerous smaller examples from this one.

A: There is a complete classification of sets equipped with a transitive $G$-action. Namely:

If $G$ acts on a set $X$ (on the left) transitively, then there is a subgroup $H \le G$ and a $G$-equivariant bijection between the set $[G : H]$ of (left) cosets of $H$ (with the evident (left) $G$-action) and $X$.

In fact, this is just a different way of stating the orbit–stabiliser theorem. Thus, $G$ can act transitively on a set of $n$ elements if and only if $G$ has a subgroup of index $n$.

A: This question is equivalent to asking what the conjugacy classes of subgroups of $S_{n}$ are, since each transitive permutation representation of any finite group is permutation equivalent to the action on the cosets of one of its subgroups, and conjugate subgroups lead to equivalent permutation representations. Since every finite group embeds in some symmetric group, this would soon become an enormous task without further information.
For larger $n,$ I think that the next smallest degree of a faithful permutation representation of $S_{n}$ ( after $n$) is $\frac{n(n-1)}{2},$  which comes from  the action on unordered pairs from $\{1,2, \ldots n \}.$ There are small exceptions to this though.

A: Here is a way to understand the faithful, transitive actions of $S_n$. We concentrate on small $|X|$. Clearly $\binom{n}{1} \leq X$, and we describe the $X$ that are "near" to $\binom{n}{k}$.
For $n$ sufficiently large compared to $k$, the answer is very simple: $S_n$ is (basically) acting on the subsets of size $k$ of $\{1,2,\ldots,n\}$. For small $k$ we can list the exceptions.

Claim (large $n$): For each $k$ there is some $N$ such that for $n>N$ the only faithful transitive actions of $S_n$ on $X$ with $\binom{n}{k} \leq |X| < \binom{n}{k+1}$ have a stabilizer $H$ satisfying $$\underbrace{S_1 \times \cdots \times S_1}_{k\text{ factors}} \times A_{n-k} \leq H \leq S_k \times S_{n-k},$$ where the left hand and right hand groups are the natural subgroups of $S_n$ acting on the sets $\{1\},\{2\}, \ldots, \{k\}, \{k+1, \ldots, n\}$ and $\{1,2,\ldots,k\}, \{k+1,\ldots,n\}$. This means that $$\binom{n}{k} \leq |X| \leq 2k! \binom{n}{k}=2n(n-1)\cdots(n-k+1).$$

Depending on what kind of relationship you want $|X|$ and $n$ to have, we can make the claim more specific. For instance, if you want $|X|$ to grow linearly with $n$, then for large enough $n$, you'll want $|X| < \binom{n}{2}$.

Claim ($k=1$):  If $S_n$ has a faithful, transitive action on a set $X$ with $|X| < \binom{n}{2}$, then the stabilizer $H$ of a point is conjugate to exactly one of:

*

*the natural $S_1 \times S_{n-1}$ with $|X|= \phantom{2}\binom{n}{1}$, or

*the natural $S_1 \times A_{n-1}$ with $|X|= 2\binom{n}{1}$

  unless $H$ exists in an exceptional way:

*

*$n=5$, $|X|=6$, $H$ is the natural affine $\operatorname{AGL}(1,5) = F_{20}$

*$n=6$, $|X|=6$, $H$ is the natural almost simple $\operatorname{PGL}(2,5)$,
  outer conjugate to $(H,|X|)=(S_1\times S_5,\binom{n}{1})$

*$n=6$, $|X|=10$, $H$ is the natural wreath $S_3 \wr S_2$

*$n=6$, $|X|=12$, $H$ is the natural almost simple $\operatorname{PSL}(2,5)$,
  outer conjugate to $(H,|X|)=(S_1 \times A_5,2\binom{n}{1})$

  or $n$ is so small, that some rows need to be ignored:

*

*$n\leq 3$, in which case no such $X$ exists, since $\binom{n}{2} \leq \binom{n}{1}$

*$n=4$, in which case the second row is too big, since $\binom{n}{2} \leq 2\binom{n}{1}$

This says that actions of linear size are basically the natural action on $n$ points. We can also handle quadratic easily enough. Again for $n$ large enough, you'll want $|X| < \binom{n}{3}$.

Claim ($k=2$): If $S_n$ has a faithful, transitive action on a set $X$ with $|X|< \binom{n}{3}$, then the stabilizer $H$ of a point is conjugate to exactly one of:

*

*the natural $S_1 \times S_{n-1}$ with $|X|= \phantom{2}\binom{n}{1}$,

*the natural $S_1 \times A_{n-1}$ with $|X|= 2\binom{n}{1}$,

*the natural $S_2 \times S_{n-2}$ with $|X|= \phantom{2}\binom{n}{2}$,

*the natural $S_2 \times A_{n-2}$ with $|X|= 2\binom{n}{2}$,

*the natural $A_2 \times S_{n-2}$ with $|X|= 2\binom{n}{2}$,

*the natural $2(A_2 \times A_{n-2})$ with $|X|= 2\binom{n}{2}$,

*the natural $A_2 \times A_{n-2}$ with $|X|= 4\binom{n}{2}$,

  unless $H$ is a new group:

*

*$n=5$, $|X|=6$, $H$ is the natural affine $\operatorname{AGL}(1,5) = F_{20}$

*$n=6$, $|X|=6$, $H$ is the natural almost simple $\operatorname{PGL}(2,5)$,
  outer conjugate to $(H,|X|)=(S_1\times S_5,\binom{n}{1})$

*$n=6$, $|X|=10$, $H$ is the natural wreath $S_3 \wr S_2$

*$n=6$, $|X|=12$, $H$ is the natural almost simple $\operatorname{PSL}(2,5)$,
  outer conjugate to $(H,|X|)=(S_1 \times A_5,2\binom{n}{1})$

*$n=6$, $|X|=15$, $H$ is an outer conjugate of $(H,|X|) = (S_2 \times S_4,\binom{n}{2})$

*$n=7$, $|X|=30$, $H$ is the natural almost simple $\operatorname{PSL}(3,2)$

*$n=8$, $|X|=30$, $H$ is the natural affine $\operatorname{ASL}(3,2)$

*$n=8$, $|X|=35$, $H$ is the natural wreath $S_4 \wr S_2$

  or $H$ does not exist / should be ignored:

*

*$n\leq 3$, in which case no such $X$ exists, since $\binom{n}{3} \leq \binom{n}{1}$

*$n=4,5$, in which case the fourth through the seventh row are too big, since $\binom{n}{3} \leq \binom{n}{2}$

*$n=6,7,8$, in which case the fifth through seventh row are too big, since $\binom{n}{3} \leq 2\binom{n}{2}$

*$n=9,10$, in which case the seventh row is too big, since $\binom{n}{3} \leq 4\binom{n}{2}$

This says the actions of quadratic size are basically the natural actions on pairs of points. The exceptions are either due to stabilizers not existing / having the right index for tiny $n$ (for example, $A_n$ has order $n!/2$ unless $n=0,1$), or honest to goodness other families from the O'Nan Scott classification: acting on block systems to give wreath product stabilizers, affine subgroups acting naturally on $p^n$ points, almost simple groups (either acting in in their "natural" way, or in other primitive ways), etc.
We could even continue to cubic:

Claim $(k=3)$: For $|X| < \binom{n}{4}$, the only new things happening are $$S_1 \times S_1 \times S_1 \times A_{n-3} \leq H \leq S_3 \times S_{n-3}$$ in general (that is $i\binom{n}{3}$ for $i=1,2,2,2,3,4,6,6,6,12$ up to conjugacy). The new exceptions are:

*

*$n=4$, $|X|=6$, an exceptional $H=C_4$

*$n=10$, $|X|=126$, the natural wreath $S_5 \wr S_2$

*$n=12$, $|X|=462$, the natural wreath $S_6 \wr S_2$

  The orders with problematic rows that may need to be ignored stop at $n=52$.

This says the actions of cubic size are basically the natural action on triples of points.
Caveat: Personally, I'm only interested in small $n$. For small $n$ there are very few exceptions, so these claims seem very useful. Also the proofs are tedious but easy. For general $n$, I get very weird inequalities that are basically ridiculous (find $n$ such that $n > n!$) but they have enough complication that I'm not sure how to prove them. I would not be surprised if some of them are still open. Some of the exceptional cases were only checked by order and multiplicity, so for $n < 52$ there could be an error where on of the general rows does not exist ($A_1$ vs $S_1$ type thing), while some other $H$ does exist. One could check this more carefully, but I think my lists give the right feel.


text:
Q: How to detect if any keyboard key other than a specific keyboard key has been pressed in C++? I have the following code which works fine.
int x = 0;
int main()
{
    while(true) {
        if (GetKeyState('A') & 0x8000 && x == 0) {
            Sleep(500);
            x = 1;
        }
        else if (GetKeyState('B') & 0x8000 && x == 1) {
            Sleep(500);
            x = 2;
        }
        else if (GetKeyState('C') & 0x8000 && x == 2) {
            Sleep(500);
            x = 0;
            //Do Something
        }
    }
}

In order to execute the //Do Something part of the code, the user must first press A, then B and then C in that order. However the user can press any key in between and it will still work. So in addition to "A+B+C" the following will also work.

*

*A+C+B+C

*A+Q+B+C

*A+F11+B+8+LSHIFT+Spacebar+Tab+C
I want only the A+B+C combination to work. Not any of the above.
The code I am trying to implement is somewhat like this
int x = 0;
int main()
{
    while(true) {

        if (GetKeyState('A') & 0x8000 && x == 0) {
            Sleep(500);
            x = 1;
        }
        else if (GetKeyState('B') & 0x8000 && x == 1) {
            Sleep(500);
            x = 2;
        }
        else if (GetKeyState(/*Any keyboard input other than 'B' or 'A'*/) & 0x8000 && x == 1) {
            Sleep(500);
            x = 0;
        }
        else if (GetKeyState('C') & 0x8000 && x == 2) {
            Sleep(500);
            x = 0;
            //Do Something
        }
        else if (GetKeyState(/*Any keyboard input other than 'C' or 'B'*/) & 0x8000 && x == 2) {
            Sleep(500);
            x = 0;
        }
    }
}

So you see I understand the logic required. I just don't know the correct code required to replace the commented part of my code. Please note that the reason I have entered two keys in the comments is because the user might accidentally press a key twice or thrice for which he/she needs to be excused and code needs to still work.
I think I have tried my best to make this question as understandable as possible. If not feel free to suggest edits.

A: On Windows, for simplicity, you could use _kbhit() unless there is a specific reason you want to use GetKeyState
#include <iostream>
#include <conio.h>

int main()
{
    int x = 0;
    while (true)
    {
        if (!_kbhit())
            continue;

        switch (_getch())
        {
        case 'A':
            x == 0 ? ++x : x = 0;
            break;
        case 'B':
            x == 1 ? ++x : x = 0;
            break;
        case 'C':
            x == 2 ? ++x : x = 0;
            break;
        default:
            x = 0;
        }

        if (x == 0)
            std::cout << "Oops!" << std::endl;
        else if (x == 3)
        {
            std::cout << "Bingo!" << std::endl;
            break;
        }
    }
}


text:
Q: Migrating RCP application from Eclipse Indigo to Luna I'm actually trying to migrate an Eclipse RCP application from Eclipse Indigo to Luna. I follow the following article to perform the migration
https://www.eclipse.org/community/eclipse_newsletter/2013/february/article3.php
I have choosen to use the "Compatibility Layer", and I have added the needed plugins.
I still have a problem, on my MANIFEST.MF, the specfic plugins of Nebula is marked as red.

Do ou have any idea how to solve this problem ?
Thank you a lot


text:
Q: paragraph Select() doesn't work in javascript Here is my html code

Copy this key

4567887654345678

<button>Open dialog</button>

The div appears as a dialog on button click, and I would like to have the  "key" text selected when the dialog opens
Here is the javascript for the same, but the
 doesn't appear to be selected
$(function() {
    $( "button" ).click(function() {
      $("#dialog" ).dialog();
        $( "#dialog" ).show( "slow" );
        $("#key").select();
  });
    });

How can I make the
 be pre-selected ?

A: Change the key paragraph to an editable element, such as a textarea:
<textarea id="key">4567887654345678</textarea>

JSFiddle
It appears you need an editable text field to select text in.

A: I think you should use jQuery dialog open event:
$( "#dialog" ).dialog({
    open: function( event, ui ) {
        $("#key").select();
    }
});

JSFiddle


text:
Q: Proving a equality regarding a piece-wise linear function built from $x^2$ My question is strictly related to this question.
Frechet Differentiability versus Strict Differentiability
The author said it can be proved that $f(x) - f(y) \le 3x(x - y)$ for all $x > y > 0$. After several attempts, I have not found how this could be proved.
I did find out how the author built his function though. The piece-wise linear function $f$ was built from $x^2$ by using the points on the graph at $x = 2^j$ and $x = -2^j$, $j \in \mathbb{Z}$ and connect them all together by the increasing order of $j$.
Even with this discovery, I can not prove the prementioned inequality. I have gone through the properties of a convex function to, but this also came to no avail.
Please give me a hint regarding this problem. Thank you.

A: Note that $f$ is a convex increasing function in $(0,+\infty)$  and therefore for $y>0$,
$$x\to \frac{f(x)-f(y)}{x-y}$$
is increasing in $(y,+\infty)$.
Let $i\in\mathbb{N}$ such that $2^{i-1}< x\leq 2^{i}$ then
$$\frac{f(x)-f(y)}{x-y}\leq \frac{f(2^{i})-f(2^{i-1})}{2^{i}-2^{i-1}}=
\frac{4^{i}-4^{i-1}}{2^{i}-2^{i-1}}=(4-1)\cdot 2^{i-1}<3x.$$
Note that if $2^{i-1}\leq y< x\leq 2^{i}$ the first inequality is actually an equality.


text:
Q: Convert a colormap image into data values according to a legend I have this image

that I want to turn into data using this gradient

black being 0, white being 1, and all the colors in between accordingly, so I could later use ListPlot3D to make a height map.
I tried using ImageData, to work something out using RGB values of each color point, but in the end the purple was higher than the blue, so that didn't workout.

A: Import data, take only one column from the legend, and extract ImageData from the legend:
img = Import["https://i.stack.imgur.com/1JxTr.png"];
leg = ImageTake[Import["https://i.stack.imgur.com/MRqiH.png"], All, {1, 1}];
legdata = ImageData[leg, DataReversed -> True][[All, 1, 1 ;; 3]];

Connect the RGB values to a number in $[0,1]$:
rules = Rule @@@ Transpose[{legdata, Subdivide[Length@legdata - 1]}];

Extract ImageData info from the image:
imgpoints = ImageData[img][[All, All, 1 ;; 3]];

Employ Nearest to find the best approximation of the color in img using colors available from leg:
pts = Table[
    Nearest[legdata, imgpoints[[i, j]]][[1]], {i, 1,
     Length@imgpoints}, {j, 1, Length@imgpoints[[i]]}] /. rules;

Draw points:
ListPlot3D[pts, ColorFunction -> "Rainbow", BoxRatios -> {1, 1, 1}]


text:
Q: How to get a certain column in SQLserver to combo box? Here is my big dilemma in programming in VB.
I want to make an 'Admission' form and display a certain context?? in the DataGridView with a foreign key.
I've made a table
CREATE TABLE Admission
    (
     AdmissionID NUMERIC IDENTITY(1, 1) NOT NULL CONSTRAINT pk_Admission PRIMARY KEY
    ,paID NUMERIC FOREIGN KEY REFERENCES pInformation ( paId )
    ,DateAdmit DATE NOT NULL
    ,doctorID NUMERIC FOREIGN KEY REFERENCES Doctor ( doctorid )
    ,roomId VARCHAR(6) FOREIGN KEY REFERENCES room ( roomid )
    ,Status VARCHAR(250) NOT NULL
    ,Remarks VARCHAR(250) NOT NULL
    ,DateDischarged DATE NOT NULL
    )

And I want to display that in DataGridview. So I've done it. I've made a 3 combo box for the three foreign keys, so that the combo box will display inserted data in the table. Like this, I have a table with a paID primary key. I want that the user will see all the paID in the combobox1.

A: _I dont know what version of visual studio you are using but at least in earlier versions there was properties like Data Source And Display member in combobox. With display member you could select which column form Data Source table is shown in combobox.


text:
Q: Estimote beacons detector service in background I am trying to make a service on Android that would find Estimote beacons and push notifications to the user. I have downloaded sample code, and created new myService Activity using that code. Code is running, and I can see in LogCat that Android is scanning for beacons. Unfortunately no beacons are found. What is wrong with my code?
Or maybe I'm doing this in wrong way?
package com.osos.service;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.BeaconManager.MonitoringListener;
import com.estimote.sdk.BeaconManager.RangingListener;
import com.estimote.sdk.Region;
import com.estimote.sdk.utils.L;

import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MyService extends Service{
      private static final int NOTIFICATION_ID = 123;
    private BeaconManager beaconManager;
    Beacon beacon;
    private NotificationManager myNotificationManager;
     private NotificationManager notificationManager;
    private static final String TAG = "MyService";
private static final Region ALL_ESTIMOTE_BEACONS_REGION = new Region("rid", null, null, null);
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onCreate() {

        beaconManager = new BeaconManager(this);
        beaconManager.setBackgroundScanPeriod(TimeUnit.SECONDS.toMillis(1), 0);
//      beaconManager.setRangingListener(new RangingListener() {
//
//          @Override
//          public void onBeaconsDiscovered(Region arg0, List<Beacon> beacons_list) {
//              // TODO Auto-generated method stub
//
//          }
//      });
        Toast.makeText(this, "Jus paleidote OSOS serviza", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
          L.enableDebugLogging(true);
          Log.d(TAG, "onStartCOmmand");
            try{
                connectToService();
            }catch(Exception e){
                System.out.println("### problem ####");
                System.out.println(e);
            }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCOmmand");

         beaconManager.setMonitoringListener(new MonitoringListener() {
              @Override
              public void onEnteredRegion(Region region, List<Beacon> beacons) {
                  switch(beacon.getMinor()){
                  case 11111: displayNotificationOne(1,"This is OSOS");
                  break;
                  default:        displayNotificationOne(1,"This is Sparta");

              }
              }
              @Override
              public void onExitedRegion(Region region) {
                  displayNotificationOne(2,"Exited OSOS");
              }
            });

        return  startId;

    }

    protected void displayNotificationOne(int i, String msg) {
        Log.d(TAG, "Display notif");
        // Invoking the default notification service
        Notification.Builder mBuilder = new Notification.Builder(this);

        mBuilder.setContentTitle("Simplify");
        mBuilder.setContentText("Jus turite nauju uzduociu");
        mBuilder.setTicker("Simplify: Jus turite nauju uzduociu");
        mBuilder.setSmallIcon(R.drawable.arrow_up_float).setAutoCancel(true).build();

        long[] vibrate = {0,200,500 };
        mBuilder.setVibrate(vibrate);
        //mBuilder.setSound(Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.groan));

        // Increase notification number every time a new notification arrives

        mBuilder.setAutoCancel(true);
        // Creates an explicit intent for an Activity in your app
//      Intent resultIntent = new Intent(this, Welcome.class);

        // This ensures that navigating backward from the Activity leads out of
        // the app to Home page
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        // Adds the back stack for the Intent
//      stackBuilder.addParentStack(StartedReviewsActivity.class);

        // Adds the Intent that starts the Activity to the top of the stack
//      stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                PendingIntent.FLAG_ONE_SHOT // can only be used once
                );
        // start the activity when the user clicks the notification text
        mBuilder.setContentIntent(resultPendingIntent);

        myNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // pass the Notification object to the system
        myNotificationManager.notify(1, mBuilder.build());
    }

     private void connectToService() {
           Log.e(TAG, "Connect to service");
//          getActionBar().setSubtitle("Scanning...");
//          adapter.replaceWith(Collections.<Beacon>emptyList());
            beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
              @Override
              public void onServiceReady() {
                try {
                  beaconManager.startRanging(ALL_ESTIMOTE_BEACONS_REGION);
                } catch (RemoteException e) {

                  Log.e(TAG, "Cannot start ranging", e);
                }
              }
            });
          }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        beaconManager.disconnect();
    }
}

A: Yes that is because you did not change the UUID, MAJOR and MINOR number of the beacon. Download the estimote sdk app on your phone and then you can get all three numbers replace them with the one you already have. It will start working.


text:
Q: Infinite scroll with jquery in webGrid on Partial Page I am trying to get an infinite scroll working in my Webgrid control. I have my Webgrid in a partial page. I have managed to get it "scrolling" , but the issue is my Webgrid header is repeating due to the fact that the grid is in a partial page so the whole thing gets rendered again. Anyone else have a similar issue or any ideas how to sort this out ?
Here is my view code:

var page = 0;
var _inCallback = false;

function loadAccounts() {
    if (page > -1 && !_inCallback) {
        _inCallback = true;
        page++;
        var loadingImagesrc = '@Url.Content("../../Images/loading.gif")';
        var infiniteScrollAction = '@Url.Action("AccountInfiniteScroll/", "Client")';
        $('div#loading').html('

');
        $.get(infiniteScrollAction + page, function (data) {
            if (data != '') {
                $("#accountsList").append(data);
            }
            else {
                page = -1;
            }

            _inCallback = false;
            $('div#loading').empty();
        });
    }
}

var dcList = true;

$(window).scroll(function () {
    if ($(window).scrollTop() == $(document).height() - $(window).height()) {

        loadAccounts();
    }
});
</script>

     @Html.Action(Controllers.ClientController.AccountInfiniteScroll, new { id =         Model.ClientId })

Here is my Controller code:
        const int recordsPerPage = 30;
    public const string AccountInfiniteScroll = "AccountInfiniteScroll";
    [ActionName(AccountInfiniteScroll)]
    public ActionResult Result(int id = 1)
    {
        return PartialView("_AccountsList", GetAccountsForInfiniteScroll(id));
    }

    ///
    /// Gets the accounts for infinite scroll.
    ///
    /// <param name="page">The page.</param>
    /// <returns></returns>
    private List<Account> GetAccountsForInfiniteScroll(int page = 1)
    {
        var skipRecords = page * recordsPerPage;

        var listOfProducts = Context.Accounts.Where(x => x.Accountid != null);

        return listOfProducts.
            OrderBy(x => x.Accountid).
            Skip(skipRecords).
            Take(recordsPerPage).ToList();
    }

And here is my partial page with my Webgrid:
@model IEnumerable<Models.Account>
@{
ViewBag.Title = "Home Page";
}

@{       var grid = new WebGrid(source: Model,  rowsPerPage: 30);
}

@grid.GetHtml(
tableStyle: "grid-view",
headerStyle: "headerStyle",
alternatingRowStyle: "alternate",
selectedRowStyle: "selected",
rowStyle: "normal",displayHeader :true,

columns: grid.Columns(
grid.Column(header: "Account Number", columnName: "AccountId", format: (item) => Html.ActionLink(
                     (string)@item.AccountIdentifier, "Details", "Account", new { id =     @item.AccountId }, null)),

grid.Column(header:"Account Type",columnName:"AccountType"),
grid.Column("Currency"),
grid.Column(header:"Start Date",columnName:"StartDate",format: (item) => string.Format("{0:dd-MMM-yyyy}", @item.StartDate)),
grid.Column(header:"Close Date",columnName:"CloseDate",format: (item) => string.Format("{0:dd-MMM-yyyy}", @item.CloseDate))
)
 )

A: Have you tried putting a display header flag in a viewbag in the controller and passing it back to your partial view?  If the flag says yes, display the header, otherwise don't.


text:
Q: Can't connect to port 25 from all computers I installed hMailServer on Windows Server 2003 and somehow I can't connect to SMTP 25 port from all computers. When I run the following command, it connects successfully on some clients, but on others it doesn't.

telnet myhost.com 25

I have added an exception to the Windows Firewall for 25 port, but this does not seem to help.

A: If people want to send mail on port 25, they should be connecting to their mail server, not yours. Port 25 is still occasionally used for internal mail submission, though it really shouldn't be. But it's primarily for one mail server to contact another for inter-domain mail relaying.
Why are ordinary users trying to connect to connect to your mail server on port 25? Port 587 is for remote mail submission.

A: You've given little detail, so any answer is just a stab in the dark. That said, here's mine:
If it's not blocked by a firewall ACL, it's probably blocked by anti-malware. McAfee labels this "Prevent Mass Mailing Worms from Sending Mail" in the Access Protection section. Chances are, other AVs have a similar configurable setting.

A: I figured out. It's because on pc's where it doesn't connect, ISP blocks 25 port


text:
Q: Adding superscript to graph in R with no preceding character I'm trying to add a text in the form of ab to a graph instead of ab.
This works fine:
> xlab = expression(paste("a"^"b"))

If I reverse them I get:
Error: unexpected '^' in "xlab = expression(paste(^"

What would be the correct way to implement it?

A: Try phantom()
plot(0, xlab = ~ phantom() ^ a * b)


text:
Q: Is there any map structure with key sorted by value? The TreeMap structure is a classic map structure with keys sorted by their natural order. For example, with the following codes:
Map<String, Integer> map = new TreeMap<>();
map.put("apple", 100);
map.put("orange", 10);
map.put("banana", 5);

If I want to print the map, like:
System.out.println(map);

Then the console will output (with natural order of the key):
{apple=100, banana=5, orange=10}
My question is: is there any Map structure available (UnknownMap) that could automatically sort the key by the value? If we have such structure, if we revise the codes to:
Map<String, Integer> map = new UnknownMap<>();
map.put("apple", 100);
map.put("orange", 10);
map.put("banana", 5);
System.out.println(map);

The console will output:
{banana=5, orange=10, apple=100}
Note: this question is not asking how to sort a map. Instead, this is to ask a specific sorted map implementation that efficiently do the sorting by value with any changes to the map, such as put, remove, etc.

A: Maintaining a sorted map by value is very not trivial, and would definitely require to adjust existing data structures. The entries, keys and values fields, that are required by the Map interface, are expected to be consistent with their order, and this is not trivial to get all of them sorted by value, and at least would require to override these fields in existing classes. Take for example the TreeMap class. The keys are stored in a tree data-structure, and the order of all three fields is according to the keys inserted to the tree. Also you cannot override the `Comparator of the tree to ignore the key itself, because some fundamental map properties of this class depends on that the tree compare between keys and not values.
This is as opposed to just sorting the map entries when it requires which is much simpler task. If you need to frequently use the sorted map entries, and the map tends to be modified between such usages, than it worth maintaining such data structure, otherwise you should just sort the entries and store them separately for future use.
In you you have decided to maintain the sorted map by value, you will probably need to implement it yourself. Try using the answers from this post


text:
Q: Asynctask and progressbar timing After pressing ok in dialogbox, I should get data from some place else. so I used Asynctask class. The implementation is below. But after pressing first Ok I wont get any progress bar. I only get it after the second ok is pressed(basically, when all lines inside the button onClick method is executed...
What should I do to get the progress bar right after pressing first ok?
confirmPath= (Button) findViewById(R.id.confirmPath);
            confirmPath.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                        construction
                        AlertDialog.Builder builder = new AlertDialog.Builder(Destination.this);
                        builder.setMessage("Press 'Ok' ")
                               .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {

                                       LoadData task = new LoadData();
                                       task.execute();

                                                                                AlertDialog alertDialog = new AlertDialog.Builder(Destination.this).create();
                                    alertDialog.setTitle("Attention!");
                                    alertDialog.setMessage(" Pay attention");
                                     alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                           public void onClick(DialogInterface dialog, int which) {
                                           }
                                        });

                                        alertDialog.show();

                                   }
                               })
                               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {
                                       // do nothing
                                   }
                               });
                       builder.create();
                       builder.show();

And this is the AsynkTask class:
public class LoadData extends AsyncTask<Void, Void, Void> {
        ProgressDialog progressDialog;
        //declare other objects as per your need
        @Override
        protected void onPreExecute()
        {
            progressDialog= ProgressDialog.show(Destination.this, "Progress Dialog Title Text","Please wait", true);

            //do initialization of required objects objects here
        };
        @Override
        protected Void doInBackground(Void... params)
        {

               ReadFromFile readFromFile= new ReadFromFile();
               readFromFile.ReadAllData("Data");
               //some other tasks to do

            return null;
        }
        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
        };
     }

A: Put this code outside AlertDialogBuilder:
LoadData task = new LoadData();
task.execute();

New code should look like:
 @Override
            public void onClick(View arg0) {

                                       LoadData task = new LoadData();
                                       task.execute();

                        construction
                        AlertDialog.Builder builder = new AlertDialog.Builder(Destination.this);
                        builder.setMessage("Press 'Ok' ")
                               .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {

                                                                                AlertDialog alertDialog = new AlertDialog.Builder(Destination.this).create();
                                    alertDialog.setTitle("Attention!");
                                    alertDialog.setMessage(" Pay attention");
                                     alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                                           public void onClick(DialogInterface dialog, int which) {
                                           }
                                        });

                                        alertDialog.show();

                                   }
                               })
                               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {
                                       // do nothing
                                   }
                               });
                       builder.create();
                       builder.show();

A: use this code
    private class NetworkDelegate extends AsyncTask<String, Void, String> {

    private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

    protected String doInBackground(String... pass) {

        try {

            //userid is getting from webservice

        return userid;

        } catch (Exception e) {

            System.out.println(e);
        }

    }

    protected void onPostExecute(String result) {

        Dialog.dismiss();

        if (result == null) {
            tv.setText("Enter Your Password Correctly");
            pwet.setFocusable(true);

        } else {

        }

    }

    protected void onPreExecute() {

        Dialog.setMessage("Loading...");
        Dialog.show();

    }

}

A: I should have put the second alertdialog also in asynctask onPostExecute method. then I have the progressbar before obviously


text:
Q: Passing data to fragment via Bundle OR a public method defined inside fragment Can anyone tell what will be the difference between following approaches for sharing data to fragment.

*

*Using Bundle.
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);

*Using a public method defined inside fragment.
MyFragment fragment = new MyFragment();
fragment.setData("param");

public void setData(String param1) {
        this.param1 = param1;
    }

A: The Bundle is built in and supported by the framework.  If the Fragment is automatically torn down and re-created by the framework due to lifecycle you will still get the Bundle back.
In the second case, the private data member param1 won't be automatically re-created by the framework if the Fragment is torn down and re-created.  It's the same reason you don't use overloaded constructors with Fragment.

A: Use a Bundle if you want to provide data to a fragment, but want to decide inside the fragment when to use this data.
Use a method call if you want to pass data to an already active fragment and expect instant reaction from the fragment.

A: Also you need to have an instance of the  class from which you want to access the data.
This may leads to memory leaks
If you use public methods frequently instead of bundle ,
Via bundle you can share data without any reference via android message mechanism


text:
Q: Java stringbuffer method I am learning Java in this summer st college in US. I am new to Stringmethod.
I try to understand how to use Stringbuffer() method.
I tried to make  ssl=statusBuffer in Else if section, but it causes error; how should I fix appropriate way?
Thank you so much.
public class test {
    public static void main(String[] args){
        String s= "123-45-6789";
        String ssl;
        int slength = (s.length());

        if(slength ==11)
        {
            ssl = s;
        }
        else if(slength =9){
            StringBuffer statusBuffer = new StringBuffer(s);
            statusBuffer.insert(3,"-");
            statusBuffer.insert(6,"-");

            ssl=statusBuffer; //------ This part is causing error**
        }
        System.out.println(ssl);
    }
}

A: ssl is a String. statusBuffer is a StringBuffer.
You need
    ssl = statusBuffer.toString();

A: StringBuffer is not a string. You have to call statusBuffer.toString() to actually get the String from your StringBuffer.
In Java, Strings cannot be modified. If you create a String, it is always that String. If you modify a String, a new string is created. A StringBuffer is basically a modifiable String, which can be used for performance reasons when assembling big texts. They are also Thread safe. For more information, see the javadocs


text:
Q: Best way to arrange a HairDresser database based in their skills I need some help in a smart way to organize a database for a hairdresser shop.
So far, I understand that I need a table for the hairdressers containing usual data such as id, name, etc.
I also think I need a table for the procedures the hairdressers can perform. This table would contain the procedure id, description, time required, cost, price and so on.
But I don't see a good way to link those two tables. For example: Professional A can do procedures #1 and #3, but not #2.
How to include this info in the database?
I thought of two possible ways:

*

*Make the procedures be columns in the Professionals table, and assign true in the column in case a professional can perform that procedure;

*Make the professionals be columns in the Procedures table, assigning true if the procedure can be performed by that professional.
Neither possibilities seem to be quite the best way to achieve what I want, specially if the number of professionals/procedures get large.
Since I have very few experience in this, I count on your help giving me some insights in this matter.

A: I think you can have a separate new table to handle and map this information. Let's say you have created a table professional_procedures, then you can store the professionalID and the corresponding procedureID in it. Basically having a third table that references both the original tables.
This is a m:n relation and it will be good to have a separate table that contains foreign keys to both the other tables.
Professional (Hairdresser) <===> Professional_Procedures <===> Procedures
CREATE TABLE Professional_Procedures (
    ProfessionalID int not null,
    ProcedureID int not null,
    constraint PK_PersonRoles PRIMARY KEY (ProfessionalID ,ProcedureID ),
    constraint FK_PersonRoles_Persons FOREIGN KEY (ProfessionalID ) references Professional(ID),
    constraint FK_PersonRoles_Roles FOREIGN KEY (ProcedureID ) references Procedures(ID)
)

This should get you the complete mapping of procedure details for a particular professional.
So to explain this, let's say Professional_Procedures table has below data:
ProfessionID ProcedureID
     1           P1
     2           P3
     1           P4

This means, Professional (with ID 1) can perform Procedures P1 and P4 however profession (with ID 2) can perform procedure P3 only.
Hope I got your query right.


text:
Q: Задача с областью видимости JS function t(){
}

let counter = t;

console.log(counter()); //1
console.log(counter()); //2
console.log(counter()); //3
console.log(counter()); //4
console.log(counter()); //5

Задача: Описать финкцию t , что бы при каждом вызове console.log() выводилось соответствующее значение после коментария. Для первого вызова - 1 , для 5ого -  5. Без использования глобальных переменных!! Весь код должен лежать в функции.
Мне кажется, всё дело в области видимости. Но я в этом не уверен и не знаю с чего мне начать. Укажите пожалуйста направление для мыслей! Спасибо

A: Ну раз уж ответ с тем, что нужно, запостили, запощу и ответ с тем, что НЕ нужно, зато полностью соответствует условию из вопроса:

function t() {
  var x = 1;
  counter = () => ++x;
  return x;
}

let counter = t;

console.log(counter()); //1
console.log(counter()); //2
console.log(counter()); //3
console.log(counter()); //4
console.log(counter()); //5

A: Справедливости ради, стоит заметить что задачу можно решить и одной функцией.

function t() {
   if (typeof t._counter !== 'number') {
      t._counter = 0
   }

   return ++t._counter
}

const counter = t

console.log(counter())  // 1
console.log(counter())  // 2
console.log(counter())  // 3
console.log(counter())  // 4
console.log(counter())  // 5

A: Простой пример замыкания. И да, вместо t, должно быть t() по логике условия.

function t() {
  var i = 0;
  return function() {
    return ++i;
  };
}

var counter = t();

console.log(counter()); //1
console.log(counter()); //2
console.log(counter()); //3
console.log(counter()); //4
console.log(counter()); //5

A: Варианта с генератором еще нету?

const g = (function* (i){
    while(true) yield i++;
})(1);

function t(){
    return g.next().value;
}

let counter = t;

console.log(counter()); //1
console.log(counter()); //2
console.log(counter()); //3
console.log(counter()); //4
console.log(counter()); //5


text:
Q: ErrorException When Registering with Laravel 8 Jetstream I started a project on Laravel 7 just before the launch of Laravel 8, I am still learning this framework, so I updated to that version using this steps, and I am aware of this new scaffolding library call Jetstream that I installed with these steps:

*

*composer require laravel/jetstream

*php artisan jetstream:install livewire --teams

*npm install && npm run dev

*php artisan migrate
After working on my views and models I am proceeding to implement sessions functionalities, but when I tried to register with the project at localhost:8000/register, and having my data validated I get this error

Trying to get property 'id' of non-object (View: \path-to\my-project\resources\views\navigation-dropdown.blade.php) (View: \path-to\my-project\resources\views\navigation-dropdown.blade.php) (View: \path-to\my-project\resources\views\navigation-dropdown.blade.php)
http://localhost:8000/dashboard

This is the section of view that is throwing the exception
navigation-dropdown.blade.php line 169 this is the vanilla file
                    <!-- Team Settings -->
                <x-jet-responsive-nav-link href="{{ route('teams.show', Auth::user()->currentTeam->id) }}" :active="request()->routeIs('teams.show')">
                    {{ __('Team Settings') }}
                </x-jet-responsive-nav-link>

The data introduced in the register form gets stored in the database, but the error happens
I checked this other question Laravel Jetstream + Livewire + Teams FeatureTest problems when authenticate but it seems that answer apply to a different context since it is dealing with tests, no the vanilla register functions.
This is my current composer.json
{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3.0",
        "fideloper/proxy": "^4.2",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.0",
        "laravel/jetstream": "^1.0",
        "laravel/sanctum": "^2.6",
        "laravel/tinker": "^2.0",
        "livewire/livewire": "^2.0"
    },
    "require-dev": {
        "facade/ignition": "^2.3.6",
        "fzaninotto/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^8.5"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

I tried installing to test a fresh Laravel project with Jetstream, and this worked as it should, that let me confused as to what happened with my current project.

A: In the end, what worked for me was create a new fresh project with jetstream, then in my original project deleted the vendor and node_modules folder then copying the files of the new fresh project unto my original project and now it works as expected
Answer added on behalf of OP.

A: The user was not created with a team assigned, see users table and column current_team_id is null.
The navigation-menu.blade.php checks only for TeamFeatures but not if a team is really assigned.
            @if (Laravel\Jetstream\Jetstream::hasTeamFeatures())
            @if (Laravel\Jetstream\Jetstream::hasTeamFeatures() && Auth::user()->current_team_id)

For details here is the issue trying to get property of non-object


text:
Q: Store PHP array to csv in Column wise $handle = fopen("googleshopping.csv", "r");
    if ($handle)
    {
        while (($buffer = fgets($handle)) !== false)
        {
          $a=str_replace( array('[',']','(',')','"',"'") , ''  , $buffer );
            $array=explode(",",$a);
            echo'<pre>';
             print_r($array);

        }

fclose($handle);

A: According to your comment:
You want to do this:
$y = 3; // number of nodes in each column or row. Change if needed.
$arr = array(); //the original one
$newArr = array();
$manipulationArr = array(); //this is an array to manipulate and use to get what you want in the $newArr
$x = 0;
foreach($arr as $e) {
 $manipulationArr[] = $e;
 $x = $x + 1;
 if ($x == $y) {
   $newArr[] = $manipulationArr;
   $manipulationArr = array();
   $x = 0;
 }
}
unset($e);

This turns:
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

into:
$newArr = array(
  array(1,2,3),
  array(4,5,6),
  array(7,8,9)
);

Though, that is row wise.
For the actual Column wise you need to do the row wise and then do this:
$newArr = array(); //row wise one
$columnWise = array();
$manipulation1 = array();
$manipulation2 = array(); // as many manipulation arrays as the value of $y
$manipulation3 = array();
$x = 0;
foreach ($newArr as $e) {
  $manipulation1[] = $e[0];
  $manipulation2[] = $e[1]; // the pattern continues based on the number of $manipulation arrays
  $manipulation3[] = $e[2];
}

$columnWise[] = $manipulation1;
$columnWise[] = $manipulation2;
$columnWise[] = $manipulation3;

//pattern continues based on the number of $manipulation arrays

This means:
array(1, 2, 3, 4, 5, 6, 7, 8, 9) turns into:
array(
  array(1, 4, 7),
  array(2, 5, 8),
  array(3, 6, 9)
)


text:
Q: How to make an app minimize itself after some time? Is there an argument to specify for an app to minimize itself after being launched after a certain delay in Windows?
I made a .bat file to be able to launch multiple apps with one launcher, I provided the /min argument for some of them so they start minimized, but I can't seem to find an argument to specify a delay after what time they should minimize themselves (in seconds).

A: Use:
Powershell -WindowStyle style [name_script_file] ;exit
You can also use aliases -NoP and W:
Powershell -NoP -W style [name_script_file] ;exit
-NoP -WindowStyle
-WindowStyle
    Sets the window style to Normal, Minimized, Maximized or Hidden.
@echo off

rem :: do some tasks...
       "%__APPDIR__%Ping.exe" 1.1.1.1 -n 1 | Find "TTL"

rem :: apply timeout/delay execution...
       "%__APPDIR__%TimeOut.exe" -t 2

rem :: use PowerShell to change your Windows -WindowStyle to Minimized
       "%__APPDIR__%\WindowsPowerShell\v1.0\PowerShell.exe" -NoP -W Minimized ;exit

rem :: do some more tasks...
       "%__APPDIR__%Ping.exe" 1.1.1.1 -n 1 | Find "TTL"

rem :: apply more (if needs) TimeOut/delay execution...
       "%__APPDIR__%Timeout.exe" -t 2

rem :: use PowerShell to change back your windows -WindowStyle to Normal
       "%__APPDIR__%\WindowsPowerShell\v1.0\PowerShell.exe" -NoP -W Normal ;exit

You can use the timhetzel answer

A: You can use PowerShell to control your opened desktop windows.
Use the VexasoftCmdlet Set-WindowState to control the state (min, max etc.) of your window. It must be used in conjunction with the Get-Window cmdlet.
For example, with this piece of code you can minimize your opened PS window:
Get-Window powershell | Set-WindowState -Minimize

You can use the Start-Sleep Cmdlet to pause your script for example for 15 seconds
Start-Sleep -s 15


text:
Q: How do I stop accessing class variables and instead access an instance variable? given the following code:
class GridSpace:
    space = "e"

class GridRow:
    space1 = GridSpace()
    space2 = GridSpace()
    space3 = GridSpace()
    space4 = GridSpace()
    space5 = GridSpace()
    space6 = GridSpace()
    space7 = GridSpace()
    space8 = GridSpace()
    space9 = GridSpace()
    space10 = GridSpace()
    spaceList = [space1, space2, space3, space4, space5, space6, space7, space8, space9, space10]

class Grid:
    gridRow1 = GridRow()
    gridRow2 = GridRow()
    gridRow3 = GridRow()
    gridRow4 = GridRow()
    gridRow5 = GridRow()
    gridRow6 = GridRow()
    gridRow7 = GridRow()
    gridRow8 = GridRow()
    gridRow9 = GridRow()
    gridRow10 = GridRow()
    rowList = [gridRow1, gridRow2, gridRow3, gridRow4, gridRow5, gridRow6, gridRow7, gridRow8, gridRow9, gridRow10]

grid = Grid()

grid.rowList[0].spaceList[0].space = "s"

for x in grid.rowList:
    rowWord = ""
    for y in x.spaceList:
        rowWord = rowWord + y.space + " "
    print(rowWord)

I want to output a 10x10 grid of the e character, except the top left character which is supposed to be an s character. What instead happens is I am changing the class variable for the first element of every row list, instead of the instance variable of the first element of only the first row list. How do I make it change only the very first character into an s, and leave the other 99 characters an e?

A: If you want the variables to be instance variables you have to define them so (e.g. in __init__ function by using self parameter):
class GridSpace:
    def __init__(self):
        self.space = "e"

class GridRow:
    def __init__(self):
        self.spaceList = [GridSpace() for i in range(10)]

class Grid:
    def __init__(self):
        self.rowList = [GridRow() for i in range(10)]

PS: I used list comprehension to make the code simpler.

A: This happens because the following statement is True
grid = Grid()
print(Grid.rowList[0].spaceList[0] is Grid.rowList[1].spaceList[0]) # outputs True

Here you can see that the First row's spaceList[0] is the exact same as the second row's spaceList[0] (they are referring to the same object and when one is changed the other is as well).
As you have already somehow guessed, you need to turn these into instance variables. But you'll have to do this 2 level deeps, meaning you'll have to apply this to both GridSpace and GridRow
class GridSpace:
    def __init__(self):
        self.space = "e" # Now "e" is unique to every column

As well as
class GridRow:
    def __init__(self):
        self.spaceList = [GridSpace() for _ in range(10)]

Now the statement print(Grid.rowList[0].spaceList[0] is Grid.rowList[1].spaceList[0]) is indeed False and your code runs fine
s e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e


text:
Q: EclEmma 2.3.2 support for Eclipse Mars 4.5 Has anyone had success getting EclEmma 2.3.2 installed in Eclipse Mars 4.5?  I used the Eclipse Marketplace to install EclEmma, however, upon Eclipse restarting the EclEmma Coverage was not available via Run launch mode, toolbar, nor the Run menu as stated on the EclEmma installation page.

A: I've sometimes had problems with the marketplace.  In those cases, I use the update site.
Follow directions for the Option 2. Update Site

*

*From your Eclipse menu select Help → Install New Software...

*In the Install dialog enter http://update.eclemma.org/ at the Work with field.

*Check the latest EclEmma version and press Next

*Follow the steps in the installation wizard.


text:
Q: iPad equivalent of onmousemove? I'm trying to get a website to work on my iPad but the only thing that isn't working is the onmousemove method. I would like onmousemove to be triggered when the user pans their finger across the screen.

A: The equivalent of a mousemove event in a touch-enabled device is the touchmove event.
So you might bind the event like this:
var addEvent = (function () {
    var tester, allHandlers, attachGenerator, addFunc, removeFunc;

    tester = document.createElement("div");
    allHandlers = [];

    attachGenerator = function (el, cb) {
        var ret;
        ret = function (e) {
            e = e || window.event;
            cb.call(el, e);
        };
        return ret;
    };

    if (tester.addEventListener) {
        addFunc = function (element, eventName, callback) {
            allHandlers.push({
                element: element,
                eventName: eventName,
                callback: callback
            });
            element.addEventListener(eventName, callback, false);
        };
        removeFunc = function (element, eventName, callback) {
            element.removeEventListener(eventName, callback);
        };
    } else if (tester.attachEvent) {
        addFunc = function (element, eventName, callback) {
            var finalCallback;
            finalCallback = attachGenerator(element, callback);
            allHandlers.push({
                element: element,
                eventName: eventName,
                callback: finalCallback
            });
            element.attachEvent("on" + eventName, finalCallback);
        };
        removeFunc = function (element, eventName, callback) {
            element.detachEvent("on" + eventName, callback);
        };
    }

    addFunc(window, "unload", function () {
        var i, j, cur;
        // Don't remove this unload handler
        for (i = 1, j = allHandlers.length; i < j; i++) {
            cur = allHandlers[i];
            removeFunc(cur.element, cur.eventName, cur.callback);
        }
    });

    return addFunc;
}());

function loadHandler() {
    addEvent(document, "touchmove", touchmoveHandler);
}

function touchmoveHandler() {
    // this callback should fire for every pixel (or whatever unit they may use) the touch moves
}

addEvent(window, "load", loadHandler);

(the addEvent function is just a general event binding function to help work in old IE...probably unnecessary if you're binding to touch events)
Note that my original generic addEvent function isn't perfect: http://www.quirksmode.org/blog/archives/2005/08/addevent_consid.html , but I modified what I used to use better support the availability of this inside the handler when attachEvent has to be used, and also to remove all handlers when the window's unload event occurs.
References:

*

*https://developer.mozilla.org/en-US/docs/Web/Reference/Events/touchmove

*https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Touch_events


text:
Q: Are the reversed digits of $\pi$ equidistributed modulo 1? Let $r_n$ be the real number obtained by truncating the decimal expansion of $\pi$ at $n$ total digits, removing the decimal point, reversing the digits, then prepending a new decimal point. For example, $r_3$ is computed as follows: $$\pi \approx 3.14 \to 314 \to 413 \to .413.$$
Here are the first few values of $r_n$:
\begin{align*}
    r_1 &= .3 \\
    r_2 &= .13 \\
    r_3 &= .413 \\
    r_4 &= .1413 \\
    r_5 &= .51413.
\end{align*}
Is $\{r_n\}$ equidistributed on the unit interval $[0, 1]$? That is, is it true that $$\lim_n \frac{|\{r_1, \dots, r_n\} \cap [a, b]|}{n} = b - a$$ for all $0 \leq a \leq b \leq 1$?


text:
Q: Get existing and inserted IDs in upsert operation (db.Clauses clause.OnConflict) I have a scenario where I need to insert into a table some array of data, In which case if the combination of name and version already exists (composite unique constrain), I need to get those IDs, else get inserted IDs, if both case exist get inserted and existing ids
Models and code I tried are given below:
Model Dependency
type Dependency struct {
    gorm.Model
    ID      string `gorm:"primaryKey; not null"`
    Name    string `gorm:"not null; UniqueIndex:idx_name_version"`
    Version string `gorm:"not null; UniqueIndex:idx_name_version"`
}

go code with gorm query to insert dependencies
var saveDependencyData []models.Dependency

// Dependecies are read form api input
// [
//   {
//       "name": "node",
//       "version": "16.0.0"
//   },
//   {
//       "name": "node",
//       "version": "18.0.0"
//   }
// ]

for _, dep := range Dependecies {
    saveDependencyData = append(saveDependencyData, models.Dependency{
        ID:      nanoid.New(),
        Name:    dep.Name,
        Version: dep.Version,
    })
}

res :=  db.Clauses(clause.OnConflict{
            Columns:   []clause.Column{{Name: "name"}, {Name: "version"}},
            DoUpdates: clause.AssignmentColumns([]string{"name"}),
        }).Create(saveDependencyData)

gorm query output
INSERT INTO "dependencies" ("id","created_at","updated_at","deleted_at","name","version") VALUES ('QanL-nfNFrOGdxG2iXdoQ','2022-10-06 19:21:13.079','2022-10-06 19:21:13.079',NULL,'react','16.0.0'),('Yw1YyQ-aBqrQtwZ72GNtB','2022-10-06 19:21:13.079','2022-10-06 19:21:13.079',NULL,'react','18.0.0') ON CONFLICT ("name","version") DO UPDATE SET "name"="excluded"."name" RETURNING "id"

This query returns the list of ids I needed, but could not find a way to retrieve that.

using Scan() gets all the datas in that table.

Either you can help with a way to retrieve the returning IDs form the above GORM db.Clauses(), Or any other optimized method to get those (inserted & existing) ids with a upsert query.

A: As indicated in the comments: Several functions of GORM expect a pointer as argument and will update the variable with information.
That's obviously the case for all functions whose main purpose is to retrieve information (First, Find, ..., cf. https://gorm.io/docs/query.html).
But it's also the case for functions that modify data like

*

*Create (https://gorm.io/docs/create.html),

*Update (https://gorm.io/docs/update.html#Returning-Data-From-Modified-Rows) or

*Delete (https://gorm.io/docs/delete.html#Returning-Data-From-Deleted-Rows)

So, the solution in this case is to pass Create(&saveDependencyData) instead of Create(saveDependencyData).
The up-to-date information corresponding to the database will then be available in the saveDependencyData after the call.


text:
Q: With Windows Azure, can I deploy a node.js server using Dropbox? There are several tutorials on Azure showing how to deploy a node.js server using git. Azure has a nifty feature where you can link a Dropbox folder to an Azure web site for very simple deployments. Works awesome for websites, but I was hoping it might work for node.js deployments as well.
It doesn't seem to work- the deployment process goes fine, but navigating to the URL of the node.js deployment produces this error:
The page cannot be displayed because an internal server error has occurred.

Anyone know if it's possible to  deploy a node.js server to Windows Azure via Dropbox?
Many thanks-
UPDATE-
Just ran through the deployment logs and found this line:
The package.json file is not present.
The node.js application will run with the default node.js version 0.6.20.

Perhaps that it explains my problem?

A: from the console and folder type "npm init" to generate package.json


text:
Q: Ubuntu vmware workstation guest doesn't connect anymore after windows host update from 8 to 10 I'm using VMWare Workstation 11 to power a Ubuntu 15.04 virtual machine. My Host operating system was Windows 8 and the NAT connection from Ubuntu to the Internet via my host system worked perfectly.
Now I had to upgrade my Windows from 8 to 8.1 and then to Windows 10. This took quite some time due to user profile migration problems but i finally fixed it. The VM files were not affected by this. When I'm now powering my Ubuntu guest it starts normally but it won't connect for some reason to the host vie the NAT adapter. When I click the icon in the icon bar on the top right it says "Ethernet Networks \n disconnected".
Has someone any idea if this could be caused by the Windows update or how I can fix this issue?

A: I could solve the problem by restoring the default settings in my VMWare Workstation Virtual Network Editor.
Solution found at: Source


text:
Q: Bug in editing questions when reviewing a queue When I view the following question in the review queue and click "Edit", it takes me to the top of the page, and does nothing.  However, when I open it up as a regular page, then clicking "Edit" gives the following error:

Another edit is awaiting approval for this post. Further edits cannot be submitted until the pending edit is reviewed.

Even if this edit goes through by the time you view this, this should be a replicatable bug.


text:
Q: Beach Path math question Anyone who has walked on the beach knows that walking speed is dependent upon how far away from the ocean one walks. If you walk on the wet sand you can walk much more quickly than if you walked on the dry sand. I have a question that discusses this principal.
On a Cartesian $xy$ plane limited by: Domain: {$x|0 \le x \le 1$} Range: {$y|0 \le y \le 1$} you start at the point ($0,0$) and you would like to travel on a defined path to ($1,1$) in the shortest amount of time. This sounds simple just take the path $y=x$ because it is the shortest path so it will take the shortest amount of time, but there is a catch. Your forward speed $\frac{dS}{dt}$ is equal to ($1−\frac{3}{4}y$). With this constraint in mind the path $y=x$ would not be the fastest path. What is the fastest path. I am open to questions about the problem itself if I have not been clear. Thank you.

A: For your particular problem, there might be a simple solution in terms of e.g. Snell's law, as Hagen suggests in the comments above. But let me tell you a bit about how to solve these kinds of problems generally.
The general technique for solving this kind of optimization problem is the Calculus of Variations. The basic idea is this: you are looking at all paths $y(x)$ from $y(0)=0$ to $y(1)=1$, and trying to find the one that minimizes the total travel time
$$T(\gamma)=\int_0^1 \frac{\sqrt{1+y'^2}}{1-\frac{3}{4} y}dx.$$
(We can assume that the path is a graph over $x$, since it is obviously a bad idea to double back.)
How do you do this? Well, suppose you have  a best path $y$. Now consider perturbing the path by moving every point along it by some offset vector $\delta y(x)$. Since the endpoints of the path are fixed, you must have $\delta y(0) = \delta y(1) = 0$. For every scalar $\epsilon$, the perturbed curve $y + \epsilon \delta y$ must take longer to travel than $y$, since $y$ is the best path. In other words, for every $\delta y$, $\epsilon=0$ is a critical point of the scalar function
$$F(\epsilon) = T(y+\epsilon\delta y)$$
so
$$\frac{d}{d\epsilon} T(y+\epsilon\delta y)\Bigg\vert_{\epsilon=0} = 0.$$
For now we can write $T$ more generally as $\int_0^1 g(y,y')\,dx$. Taking the above derivative we get
$$\int_0^1 \left(g_y \delta y + g_{y'} (\delta y)'\right)\,dx=0.$$
The trick now is that you can get rid of dependence on $(\delta \gamma)'$ by integrating by parts:
$$\int_0^1 \frac{d}{dx} \left(g_{y'}\delta y\right)\,dx = \int_0^1 \left(\frac{d}{dx}g_{y'}\right)\delta y\,dx + \int_0^1 g_{y'}(\delta y)'\,dx$$
and the left-hand is zero since $\delta\gamma(1) = \delta\gamma(0) = 0.$ Plugging in we get the equation
$$\int_0^1 \left(g_y - \frac{d}{dx}g_{y'}\right)\delta y\,dx = 0.$$
The key step is that the above has to hold for every perturbation $\delta y$. The only way the above is always zero, for any $\delta y$ including those perturbations that are zero except for arbitrarily small neighborhoods of any point on $[0,1]$, is if the stuff in parentheses, which doesn't depend on $\delta y$, is zero:
$$\frac{d}{dx} g_{y'} = g_y,$$
an ordinary differential equation called the Euler-Lagrange equations of your variational problem.
Now
$$\frac{d}{dx}\left(y' g_{y'}\right) = y''g_{y'} + y' \frac{d}{dx}g_{y'},$$
and plugging in the Euler-Lagrange equation we get
$$\frac{d}{dx}\left(y' g_{y'}\right) = y''g_{y'} + y' g_y = \frac{d}{dx}g.$$
Integrating both sides by $x$ gives us
$$y' g_{y'} = C + g$$
for some constant $C$. For our particular $g$,
$$\frac{y'^2}{\left(1-\frac{3}{4}y\right)\sqrt{1+y'^2}} = C + \frac{\sqrt{1+y'^2}}{1-\frac{3}{4} y}.$$
Clearing out the denominator, things simplify to
$$1 = -C\left(1-\frac{3}{4}y\right)\sqrt{1+y'^2}$$
or, since $y'\geq 0$,
$$y' = \sqrt{\frac{1}{C^2\left(1-\frac{3}{4}y\right)^2}-1}.$$
This is now a separable first-order ODE; solving it and using the initial conditions $y(0)=0$ gives you a one-parameter family of curves from $(0,0)$ to $(1,1)$, and you can find the shortest by differentiating $T(\gamma)$ as a function of $C$ and finding the optimal $C$.

A: Taking my cue from Hagen von Eitzen, and looking at Snell's law, you find that at every point of the curve, the sine of the angle between a tangent and the $y$ direction will be proportional to the speed, i.e. proportional to $1-\frac34y$. What you need is that proportionality factor, which I'll call $a$. To treat $x$ and $y$ direction independently, it makes sense to look at the tangens instead of the sine, since that is the ratio of $x$ movement per $y$ movement:
\begin{align*}
\frac{\mathrm dx}{\mathrm dS} = \sin\theta &= a\left(1-\frac34y\right) \\
\frac{\mathrm dx}{\mathrm dy} = \tan\theta &= \frac{\sin\theta}{\sqrt{1-\sin^2\theta}} \\
x(1) = \int_0^1\tan\theta\,\mathrm dy &= \frac{4\left(\sqrt{1-\frac1{16}a^2}-\sqrt{1-a^2}\right)}{3a}
\end{align*}
Now you want to choose $a$ such that this value becomes $1$. You will find that it does for
$$ a= \frac4{\sqrt{17}} $$
With that, you can describe your curve using any of the following equations:
\begin{align*}
x(\tilde y) &= \int_0^{\tilde y}\tan\theta\,\mathrm dy =
\frac{\sqrt{1 + 24\tilde y - 9\tilde y^2} - 1}{3} \\
y(x) &= \frac{4-\sqrt{16 - 6x - 9x^2}}{3} \\
0 &= x^2+\frac23x+y^2-\frac83y \\
\frac{17}{9} &= \left(x+\frac13\right)^2 + \left(y-\frac43\right)^2
\end{align*}
So your curve is a segment of a circle of radius $\frac{\sqrt{17}}3$ with center at $(-\frac13,\frac43)$ just as studiosus indicated.

If you prefer to express things in terms of your time $t$, I've been able to obtain a formula for that as well:
\begin{align*}
x(t) &= \frac{8\left(1+\sqrt{17}\right)\left(e^{\frac32t}-1\right)}
{3\left(8+\left(9+\sqrt{17}\right)e^{\frac32t}\right)} \\
y(t) &= \frac43\left(1-\frac{\left(17+\sqrt{17}\right)e^{\frac34t}}
{8+\left(9+\sqrt{17}\right)e^{\frac32t}}\right) \\
t_1 &= \frac23\log\frac{8\left(4+\sqrt{17}\right)}{-19+5\sqrt{17}}
\approx 2.463
\end{align*}
This time $t_1$ is the time at which the point $(1,1)$ is reached.

A: This is a very cute problem.  Here is a solution using hyperbolic geometry which explains the suggestion you got at Mathoverflow. Take the formula
$$
T(\gamma)=\int_0^1 \frac{\sqrt{1+(y')^2}}{1- \frac{3}{4}y}dx
$$
as in user7530s answer. Now, let's make the change of variables:
$$
u= \frac{3}{4}x, v= 1- \frac{3}{4}y.
$$
Note that this change of variables is a Euclidean similarity (it contracts all distances by the same amount). The integral becomes
$$
T(\gamma)= \frac{3}{4}\int_0^{3/4} \frac{\sqrt{1+(v')^2}}{v}du
$$
Declare $t=u$ (time parameter). Then this integral (I am ignoring the constant factor in front) is the hyperbolic arc-length of the curve $\gamma$ with respect to the Riemannian metric
$$
\frac{du^2 + dv^2}{v^2}
$$
on the upper half-plane $H=\{(u,v): v>0\}$.
Your goal is to minimize $T$ over all paths $\gamma$ connecting the two given points. It is well-known that minimizers of lengths are hyperbolic geodesics which are arcs of circles perpendicular to the $v$-axis. See for instance J.Anderson "Hyperbolic Geometry".
Converting back to $xy$-coordinates, we see that the minimizing path is arc of circle through the points $(1,1), (0,0)$ and with center $p$ on the line $y=\frac{4}{3}$. Elementary computation then gives you that $p=(-\frac{1}{3}, \frac{4}{3})$ and the radius of the circle is $\frac{\sqrt{17}}{3}$.


text:
Q: Dragscroll a div containing floated divs I am trying to drag-scroll a div containing floated elements. You can play with it here
The intent is that dragging the grey area should drag the pane. I have applied suggestions from similar "expand div to floated content" questions. This is my best effort - vertical overflow looks good but horizontal scroll does not.

*

*added a clear element to the end of the floated elements

*added "overflow: hidden;" to parent of floated elements

*tried floating the parent div but this didn't seem to fix it

Setting a fixed width works but the content is dynamic.
Code

Tall elements - ok

hi

ho

off

...

Wide elements - not ok

hi

ho

off

...

$('#wrapper, #scroller').dragscrollable({
    dragSelector: '#items',
    acceptPropagatedEvent: false
});

$('#wrapper2, #scroller2').dragscrollable({
    dragSelector: '#items2',
    acceptPropagatedEvent: false
});

    #wrapper {
    width: 220px;
    height: 200px;
    overflow: auto;
    border: 1px solid #ff0000;
    background-color: lightgray;
    cursor: all-scroll;
}

#scroller {
    height: 100%;
}

#wrapper2 {
    width: 220px;
    height: 200px;
    overflow: auto;
    border: 1px solid #ff0000;
    background-color: lightgray;
    cursor: all-scroll;
}

#scroller2 {
    height: 100%;
}

#items {
    overflow: hidden;
}

#items2 {
    height: 100%;
    /* width: 500px; this will fix it */
    overflow: hidden;
}

.item-tall {
    width: 30px;
    height: 500px;
    float: left;
    background-color: white;
    cursor: default;
}

.item-wide {
    height: 30px;
    min-width: 1000px;
    float: left;
    background-color: white;
    cursor: default;
}

.clear {
    clear: both;
}

.title {
    padding: 20px;
}

References

*

*Horizontal scroll in a parent div containing floated child divs

*Floating elements within a div, floats outside of div. Why?

A: So, What do you want?
Horizontal scroll bar should not appear in your second item?
For that don't assign width in the second wrapper.You have assigned width:220px;, in the second wrapper but only one child has width:300px ,i.e greater than parent width that's why the horizontal scroll bar is coming.
Don't use width for wrapper2....
#wrapper2 {

    height: 200px;
    overflow: auto;
    border: 1px solid #ff0000;
    background-color: lightgray;
    cursor: all-scroll;
}

I hope this works.


text:
Q: passing a class thread parameters im new here and i need some help for a project:
My project was to merge two pictures and each threads got the mission to merge its part.
this my code:
class Partie_Gauche {
public:
    IMAGE & pict1;
    IMAGE & pict2;
    double beta;
    double omega;
    Partie_Gauche(IMAGE & image_1, IMAGE & image_2, double ruine, double b)
        :pict1(image_1), pict2(image_2), beta(ruine), omega(b) {};
};

DWORD WINAPI Second_thread(LPVOID lpParam)
{

    Partie_Gauche *m_thread = (Partie_Gauche*)lpParam;
    DWORD idThread = GetCurrentThreadId(); //recupere l'identifiant du thread
    int zeta = m_thread->omega;
    for (int x = ((zeta * 1.0) / nbreThreads)*m_thread->pict1.width(); x < ((1.0 + zeta)*m_thread->pict1.width()) / nbreThreads; x++)
    {
        for (int y = 0; y < m_thread->pict1.height(); y++)
        {
            for (int c = 0; c < m_thread->pict1.spectrum(); c++)  // les plans de couleur(R, G, B)
            {
                // détermination du ceof de pondération en fonction de la coordonnée y du pixel
                double coef = m_thread->beta*(1 - double(y) / m_thread->pict1.height());

                // somme pondérée des pixels
                m_thread->pict1(x, y, 0, c) = (unsigned char)((1 - m_thread->beta)*m_thread->pict1(x, y, 0, c) + coef*m_thread->pict2(x, y, 0, c));
            }
        }
    }
    return 0;

}

finally I create my threads :
    'HANDLE tabThread[nbreThreads];
    Partie_Gauche* m_Thd[nbreThreads];

    for (int y(0); y > nbreThreads;y++)
        m_Thd[y] = new Partie_Gauche(imageA, imageB, 0.5, (double)y);

    for (int i = 0; i < nbreThreads; i++)
        tabThread[i] = CreateThread(NULL, 0, Second_thread, &m_Thd[i], NULL, NULL);

    WaitForMultipleObjects(nbreThreads, tabThread, true, INFINITE);  '

And then the compiler indicates me an exception of violating memory access.
I dont understand why. Thanks


text:
Q: Specifying JVM Options in docker-compose File Currently I am trying to pass JVM options to my docker-compose.yml file. And this JVM_OPTS part in 'environment:' doesn't seem to be working. Is there another way to pass JVM options to docker-compose.yml file?
And also my DockerFile image is FROM openjdk:8-jre-alpine.
And my docker-compose.yml file is like this.
version: '3.1'
services:
  service:
    image: registry.gitlab.com/project/service/${BRANCH}:${TAG}
    container_name: serviceApp
    env_file: docker-compose.env
    environment:
      - JVM_OPTS=-XX:NativeMemoryTracking=summary
                 -XX:+StartAttachListener
                 -XX:+UseSerialGC
                 -Xss512k
                 -Dcom.sun.management.jmxremote.rmi.port=8088
                 -Dcom.sun.management.jmxremote=true
                 -Dcom.sun.management.jmxremote.port=8088
                 -Dcom.sun.management.jmxremote.ssl=false
                 -Dcom.sun.management.jmxremote.authenticate=false
                 -Dcom.sun.management.jmxremote.local.only=false
                 -Djava.rmi.server.hostname=localhost
    ports:
      - 8088:8088
    networks:
      - services
    working_dir: /opt/app
    command: ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/service.jar""]

networks:
  services:
    external:
      name: services

And If you ask of these arguments, I am trying to connect VisualVM to a local docker container.

A: Switching the environment declaration from sequence style to value-map style allows to use the YAML multiline string operator '>'. It will merge all lines to a single line.
version: '3.1'
services:
  service:
    image: registry.gitlab.com/project/service/${BRANCH}:${TAG}
    container_name: serviceApp
    env_file: docker-compose.env
    environment:
      JVM_OPTS: >
        -XX:NativeMemoryTracking=summary
        -XX:+StartAttachListener
        -XX:+UseSerialGC
        -Xss512k
        -Dcom.sun.management.jmxremote.rmi.port=8088
        -Dcom.sun.management.jmxremote=true
        -Dcom.sun.management.jmxremote.port=8088
        -Dcom.sun.management.jmxremote.ssl=false
        -Dcom.sun.management.jmxremote.authenticate=false
        -Dcom.sun.management.jmxremote.local.only=false
        -Djava.rmi.server.hostname=localhost

    ports:
        - 8088:8088
    networks:
        - services
    working_dir: /opt/app
    command: ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/service.jar""]

networks:
  services:
    external:
    name: services


text:
Q: Is MSS value fixed in SYN packet? I wonder how MSS is set in SYN packet? Is it a fixed value in one operating system or the value could be changed in the same operating system? I know that the value is different in different operating systems. Also is the MSS value in SYN related to hardware configuration?
Thanks.

A: RFC 879 describes how MSS is used and specified.
In short, MSS is specified during TCP handshake via SYN packet. However, this value can later be changed by OS itself or by setting a protocol option.
You can set option TCP_MAXSEG via setsockopt.

A: Whilst the value of MSS in SYN and SYNACK packets are set by the initiator and responder side, respectively, a widely used practice known as MSS clamping can result in the MSS being altered by a network element on the path - this is often used to reduce the MSS of all connections going over some sort of tunnelled link. For example PPPoE is commonly used on residential broadband and requires an MTU of 1492 and corresponding IPv4 MSS of 1452 so whilst the SYN may leave your machine with an MSS of 1460 (assuming you're using Ethernet with an MTU of 1500) but once it passes the MSS clamping ISP router the MSS in SYN packet will subsequently be changed to 1452, and likewise for the incoming/responder's SYNACK packet so the connection proceeds with reduced MSS of 1452. This practice seems to be used instead of Path MTU Discovery which relies upon the use of ICMP Fragmentation Needed responses from the network as these can be lost on poorly configured networks and by certain load balancing techniques.


text:
Q: How to get 'test' branch into 'master' when 'test' is a branch of 'dev'? Looking at the network graph for a github project, I see 3 branches of interest; master, test, dev.
Looking at the github network graph further, I am led to believe that test is a branch of dev instead of a branch from master.
At some point, I will want to put the contents of test into master.
Will I need to delete master and create a new branch called master from test in order to "get" test into master? By the way, I would like to keep the master history so I can roll back to an earlier commit if needed. So, deleting sounds bad.

A: You should just merge test into master then.
$ git checkout master
$ git merge test

A statement like "test is a branch of dev instead of a branch of master" isn't really true wit Git. test might have branched off of commits from dev, but assuming that dev branched off of master at some point, then by the transitive property test branched off of master too.


text:
Q: Implementing a high level 'interface' class Say I have a few 'low-level' classes that implement interaction with different hardware devices or other software components.
I want to provide a high-level 'interface' class. This class would implement a handful of methods that use the lower-level classes to do couple of common tasks.
What is the best way to implement this? Subclassing and multiple inheritance? Or a new class that instantiates the other ones (ie. self._device1, self._device2 etc)?
EDIT
I'm sorry, this has been marked as a duplicate, however, I have searched around a lot and have not found a clear answer. Could somebody at least point me to a question of which this is a dupe?


text:
Q: In java, about access modifiers, what the word "world" means? I've seen here on stackoverflow a post where there was this simple and clear summary about access modifiers in java.
I understand all but just one thing is weird :what the word "World" stands for ? What does it mean?
I have delete the display of the schema summary because the render was weird :s
So please look at the link below >>>
Here is the link of the post:
In Java, difference between default, public, protected, and private
Thks in advance!

A: It means if I have a class like:
package com.example;

public class Foo {
    public int bar;
}

I can access it from "outside" in the most general meaning of the word, like:
package com.client;         // not in the same package of `Foo`

class Client {              // not a subclass of `Foo`
    Foo foo = new Foo();    // possible because `Foo` is world-visible
    public int foobar() {
        return foo.bar;     // possible because `bar` is world-visible
    }
}

A: "World" is the visibility description when using non-reflection references from outside the package, as in a library reference.

A: World means you can call that method, or access that field or class no matter where the code is written, no matter the packaging, subclass, and so forth.
It could even be "universe" if you prefer.


text:
Q: Session variables not saving I have MVC application which uses Forms authentication. For some reason any session variable that I declare are not saving whenever the user is not logged in. My application needs to support both authenticated and unauthenticated users. The applications works fine when ran locally. The issue only occurs on our remote server. We're using appfabric for session state. I'm trying trouble shoot the issue but I don't know where to start. Any advice would be welcomed!
Edit-when I change the value for httpCookies domain = "future.domain.com" to httpCookies domain="" it works fine. I was told by our admins that we need this setting to not change.

A: 11 years later but if is still usefull for anybody there, sometimes this happend if you have more than one project of mvc open, i dont know why but that usually happened to me, just close the projects that are not in use and try again, if this still does not work, just try to reset visual studio or your computer


text:
Q: How provide variants with Daggers in a multi-module project? I'm building a serverless multi-module application (not Android) in which I would like to provide different variants of a module to different target applications.
Unlike Android, in which Components and Modules often converge towards a single large application, I'm looking to serve variants of the same module to different applications.
For example, given three projects with following structure:

*

*Commons: Contains multiple modules that are unrelated but required by Applications A, B. Modules in this Commons project require inputs to be customized for A or B

*Application A: Uses CommonModule and adds business logic modules to serve an endpoint X

*Application B: Uses CommonModule and adds business logic modules to serve an endpoint Y
Given how multi-modules build out, Commons needs to be built first but requires some configs from A or B to create a variant.

I've gone through a lot of Stackoverflow questions and I haven't found a good structure to achieve what I'm looking for. I admit I'm new to dependency injection, I'd appreciate any advice that the community might have.