问:
JavaScript - Toggle function
Im trying to hide/show a JS function I have defined in a chrome extension.

What I have so far:
The span classes I am trying to hide are label:

```<code>dspan.className = "cExtension";

//Create toggle button:

function createToggleButton(){
    var toggleButton = document.createElement("button");
    toggleButton.innerHTML = "Toggle Overlay";
    toggleButton.id = "Toggle"
    var header = document.getElementById("header");
    header.appendChild(toggleButton);
    toggleExtension();
}

// find all spans and toggle display:

function toggleExtension(){
    var spans = document.getElementsByTagName('span');
    var toggle = function() {
        for (var i = 0, l = spans.length; i < l; i++) {
            if (spans[i].getAttribute('class') == 'cExtension')
                if (spans[i].style.display == 'none') spans[i].style.display = '';
                else spans[i].style.display = 'none';
        }
    }
    document.getElementById('Toggle').onclick = toggle;
}
</code>```

The button shows on the header, however it is unclickable. If I change document.getElementById('Toggle').onclick = toggle; to document.getElementById('Toggle').onclick = alert{"Hello"); the alert is triggered on page load on not onclick. I am trying to get this done in pure JS. Where am I going wrong?

答:
if visible is set remove it, otherwise add it

```<code>div.classList.toggle("visible");
</code>```

add/remove visible, depending on test conditional, i less than 10

```<code>div.classList.toggle("visible", i < 10 );
</code>```

Make sure browser support: http://caniuse.com/#feat=classlist

Title: JavaScript - Toggle function

Body:
Im trying to hide/show a JS function I have defined in a chrome extension.

What I have so far:
The span classes I am trying to hide are label:

dspan.className = "cExtension";

//Create toggle button:

function createToggleButton(){
    var toggleButton = document.createElement("button");
    toggleButton.innerHTML = "Toggle Overlay";
    toggleButton.id = "Toggle"
    var header = document.getElementById("header");
    header.appendChild(toggleButton);
    toggleExtension();
}

// find all spans and toggle display:

function toggleExtension(){
    var spans = document.getElementsByTagName('span');
    var toggle = function() {
        for (var i = 0, l = spans.length; i < l; i++) {
            if (spans[i].getAttribute('class') == 'cExtension')
                if (spans[i].style.display == 'none') spans[i].style.display = '';
                else spans[i].style.display = 'none';
        }
    }
    document.getElementById('Toggle').onclick = toggle;
}

The button shows on the header, however it is unclickable. If I change document.getElementById('Toggle').onclick = toggle; to document.getElementById('Toggle').onclick = alert{"Hello"); the alert is triggered on page load on not onclick. I am trying to get this done in pure JS. Where am I going wrong?

Body:
if visible is set remove it, otherwise add it

div.classList.toggle("visible");

add/remove visible, depending on test conditional, i less than 10

div.classList.toggle("visible", i < 10 );

Make sure browser support: http://caniuse.com/#feat=classlist


来源: stackexchange

问:
why use Google V8
I don't get it. I'm a C/C++ programmer, what's the possible use of V8 for me? There are few examples and tutorials out there, and they all lack substance - I don't want to use another library to just add a couple of numbers or print something in a console window.
My question is: is there a real use for this technology, and if yes, then would be the scenario?
Also, can I do any part of GUI this way?

Help is appreciated.

答:
"V8 is Google's open source JavaScript engine"

So the whole point is ability to write code in JavaScript, and run it quite fast (for an interpreted dynamic language). Google Chrome, which is written in C++, uses it for internal scripting — not only for regular web page scripting, but also for extension code. Let's consider this as a 'real use'.

So, if your app needs scripting, V8 may be good for you (JS is not a perfect language, but stil quite decent). As for GUI, you'll need to bind your GUI components with JS first, there's no built-in UI components (as Tk in TCL).

ContentLicense: CC BY-SA 2.5

Title: why use Google V8


问:
What is the alternative for jsonp format in MVC core?
I need to return result in jsonp format while I'm using asp.net MVC Core.
In asp.net MVC we can use MVC.jsonp dll an it's work fine but what is the alternative in MVC Core because I can't find any.

```<code>  public JsonpResult FunctionalitesTblList()
    {
        var settings = new JsonSerializerSettings();
        return Jsonp(Rows, settings);
    }
</code>```

答:
There was no built in ability to handle JSONP with MVC, so you were always using a third-party addition. Apparently, that library is incompatible with .NET Core. Therefore, your option is to find a similar library that is compatible or choose some other approach.

@CuongLe is correct that CORS is a better approach overall, so you should definitely investigate that. However, if you insist on JSONP, it's so simple to implement manually, you don't really need a library.

Simply, all JSONP is a is JSON passed into a "callback" function, specified by the client. In other words, if the callack was specified as "mycallback", the response should just look like:

```<code>mycallback({ "foo": "bar" });
</code>```

As a result, your code simply becomes:

```<code>string json = null;
using (var ms = new MemoryStream())
{
    var serializer = new DataContractJsonSerializer(typeof(Foo));
    serializer.WriteObject(ms, foo);
    json = Encoding.UTF8.GetString(ms.ToArray());
}
var jsonp = String.Format("{0}({1});", callback, json);
Response.ContentType = "application/javascript";
return Content(jsonp);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to return result in jsonp format while I'm using asp.net MVC Core.
In asp.net MVC we can use MVC.jsonp dll an it's work fine but what is the alternative in MVC Core because I can't find any.

  public JsonpResult FunctionalitesTblList()
    {
        var settings = new JsonSerializerSettings();
        return Jsonp(Rows, settings);
    }

Body:
There was no built in ability to handle JSONP with MVC, so you were always using a third-party addition. Apparently, that library is incompatible with .NET Core. Therefore, your option is to find a similar library that is compatible or choose some other approach.

@CuongLe is correct that CORS is a better approach overall, so you should definitely investigate that. However, if you insist on JSONP, it's so simple to implement manually, you don't really need a library.

Simply, all JSONP is a is JSON passed into a "callback" function, specified by the client. In other words, if the callack was specified as "mycallback", the response should just look like:

mycallback({ "foo": "bar" });

As a result, your code simply becomes:

string json = null;
using (var ms = new MemoryStream())
{
    var serializer = new DataContractJsonSerializer(typeof(Foo));
    serializer.WriteObject(ms, foo);
    json = Encoding.UTF8.GetString(ms.ToArray());
}
var jsonp = String.Format("{0}({1});", callback, json);
Response.ContentType = "application/javascript";
return Content(jsonp);


问:
Creating SSIS package in VS2013 for SQL Server 2012?
Our IT department bought SQL Server 2012 Enterprise and VS 2013 Pro many years ago.

I realize that SQL Server 2012 Agent will not execute SSIS packages created in VS2013. So what are my options, if any?

Is there any way I can create SSIS packages in VS2013 that will run in SQL Server 2012?

Thanks.

答:
The latest version of SSDT is free, and supports SSIS versions 2012 and later.

https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt


问:
Look up variable for a calculation
I've got a table, data', which contains sample names and measurement sizes. I need to convert size to CAG using the formula ((CAG - flank)/3)+correction. The trouble is each sample has a different 'flank' and 'correction', as defined in 'settings'. I then need to filter out rows where the CAG is less than 'start' or greater than 'end'. Start and end are defined in 'settings' and also vary for each sample.
I'd be really grateful for help adapting the calculation to index the appropriate flank and correction for each sample</p>

```<code>#Example dataset
data <- data.frame(sample = c('A01', 'A01', 'A02', 'A02', 'A03', 'A04', 'A04'),
               size = c(200, 280, 315, 430, 510, 560, 610))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   flank = c(108, 108, 60, 60)
                   correction = (2, 2, 1, 1)
                   start = (10, 10, 13, 13)
                   end = (2000, 2000, 6000, 6000)
                   control = c('A01', 'A01', 'A03', 'A03'))

#Convert size unit from bp to CAG in new column
data$CAG <- ((data$size - flank)/3)+correction

#Exclude peaks outside the window
filter <- subset(data, CAG >= start & CAG <= end)
</code>```

答:
You can merge both data frames so each sample will have its corresponding flank and correction. Then you do your calculations. </p>

```<code>settings$sample <- settings$samples   # You need an id variable with a common name.
data_merged <- merge(data, settings, by = sample)

data_merged$CAG <-  ((data_merged$size - data_merged$flank)/3) + data_merged$correction
</code>```

Title: Look up variable for a calculation

Body:
I've got a table, data', which contains sample names and measurement sizes. I need to convert size to CAG using the formula ((CAG - flank)/3)+correction. The trouble is each sample has a different 'flank' and 'correction', as defined in 'settings'. I then need to filter out rows where the CAG is less than 'start' or greater than 'end'. Start and end are defined in 'settings' and also vary for each sample.
I'd be really grateful for help adapting the calculation to index the appropriate flank and correction for each sample

#Example dataset
data <- data.frame(sample = c('A01', 'A01', 'A02', 'A02', 'A03', 'A04', 'A04'),
               size = c(200, 280, 315, 430, 510, 560, 610))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   flank = c(108, 108, 60, 60)
                   correction = (2, 2, 1, 1)
                   start = (10, 10, 13, 13)
                   end = (2000, 2000, 6000, 6000)
                   control = c('A01', 'A01', 'A03', 'A03'))

#Convert size unit from bp to CAG in new column
data$CAG <- ((data$size - flank)/3)+correction

#Exclude peaks outside the window
filter <- subset(data, CAG >= start & CAG <= end)

Body:
You can merge both data frames so each sample will have its corresponding flank and correction. Then you do your calculations.

settings$sample <- settings$samples   # You need an id variable with a common name.
data_merged <- merge(data, settings, by = sample)

data_merged$CAG <-  ((data_merged$size - data_merged$flank)/3) + data_merged$correction


问:
Rolling 7 days in BigQuery
I've recently migrated my code from Legacy SQL and need a replacement for TABLE_DATE_RANGE, how can this be achieved using standard SQL? My data is GA tables imported into BigQuery in the YYYYMMDD format.

I have read through the migration documentation but I don't understand how I can apply a dynamic date range (for example last 7 days) using _TABLE_SUFFIX. I understand how I could use this to pull date for a particular month, but not for a rolling range. Is this possible?

答:
I found the answer to my question on this post:
BigQuery StandardSQL: Last 7 Days using _TABLE_SUFFIX

I added in:

```<code>WHERE
  PARSE_DATE('%y%m%d', _TABLE_SUFFIX) BETWEEN
  DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY) AND
  DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)
</code>```

And updated my wildcard to .ga_sessions_20* instead of .ga_sessions_*

Thanks everyone for your help.

Title: Rolling 7 days in BigQuery

Body:
I found the answer to my question on this post:
BigQuery StandardSQL: Last 7 Days using _TABLE_SUFFIX

I added in:

WHERE
  PARSE_DATE('%y%m%d', _TABLE_SUFFIX) BETWEEN
  DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY) AND
  DATE_SUB(CURRENT_DATE(), INTERVAL 1 DAY)

And updated my wildcard to .ga_sessions_20* instead of .ga_sessions_*

Thanks everyone for your help.


问:
Coroutine doesn't work in Unity
I need to make a screenshot in Unity. I did it the next way:

```<code>public void Capture(){
    StartCoroutine(CaptureScreenshot());
}

private IEnumerator CaptureScreenshot(){
    GameObject canvas = GameObject.Find("Canvas");
    canvas.SetActive(false); // hide all buttons
    yield return new WaitForEndOfFrame();

    string timestamp = DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt");
    Application.CaptureScreenshot("screenshot" + timestamp + ".png");
    Debug.Log("Screenshot was captured.");
    yield return new WaitForEndOfFrame();

    canvas.SetActive(true); // restore all buttons
    yield return null;
}
</code>```

When I invoke Capture(), canvas hides but neither screenshot takes nor text logs.

What is wrong with this code? Thanks for response.

答:
You could also do this.

```<code>foreach(Transform t in GameObject.Find("Canvas").transform)
{
 if(transform.gameObject.name != t.gameObject.name)
 t.gameObject.SetActive(false);
}
</code>```

Be sure to re-enable them with

```<code>foreach(Transform t in GameObject.Find("Canvas").transform)
    {

     t.gameObject.SetActive(true);
    }
</code>```

Title: Coroutine doesn't work in Unity

Body:
I need to make a screenshot in Unity. I did it the next way:

public void Capture(){
    StartCoroutine(CaptureScreenshot());
}

private IEnumerator CaptureScreenshot(){
    GameObject canvas = GameObject.Find("Canvas");
    canvas.SetActive(false); // hide all buttons
    yield return new WaitForEndOfFrame();

    string timestamp = DateTime.Now.ToString("dd_MMMM_hh_mm_ss_tt");
    Application.CaptureScreenshot("screenshot" + timestamp + ".png");
    Debug.Log("Screenshot was captured.");
    yield return new WaitForEndOfFrame();

    canvas.SetActive(true); // restore all buttons
    yield return null;
}

When I invoke Capture(), canvas hides but neither screenshot takes nor text logs.

What is wrong with this code? Thanks for response.

Body:
You could also do this.

foreach(Transform t in GameObject.Find("Canvas").transform)
{
 if(transform.gameObject.name != t.gameObject.name)
 t.gameObject.SetActive(false);
}

Be sure to re-enable them with

foreach(Transform t in GameObject.Find("Canvas").transform)
    {

     t.gameObject.SetActive(true);
    }


问:
how to recover BufferedReader object from ByeArrayOutputStream
I have written a code to stub the System.out.println and passing the object of BuffredReader into it.
My question is how to recover the BufferedReader object?

```<code>import java.io.*;

class Test {

  public static void main(String args[]) throws IOException {
    // stubbing the default print statement
    ByteArrayOutputStream outcontent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outcontent);

      //createing a BufferedReader obj and passing to print
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.println(br);

      //trying to get the value from the outcontent and
      // but i need to serialise this to BufferedReader
      System.err.println(outContent.toString());

    }
  }
</code>```

I have tried to use this answer but i am getting the error java.io.StreamCorruptedException: invalid stream header: 6A617661

答:
Since you already have a ByteArrayOutputStream, you should try something like this:

```<code>BufferedReader reader = new BuffererdBeader( new InputStreamReader(
                            new ByteArrayInputStream( outcontent.toByteArray() ) ) );
</code>```

Body:
I have written a code to stub the System.out.println and passing the object of BuffredReader into it.
My question is how to recover the BufferedReader object?

import java.io.*;

class Test {

  public static void main(String args[]) throws IOException {
    // stubbing the default print statement
    ByteArrayOutputStream outcontent = new ByteArrayOutputStream();
    System.setOut(new PrintStream(outcontent);

      //createing a BufferedReader obj and passing to print
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.println(br);

      //trying to get the value from the outcontent and
      // but i need to serialise this to BufferedReader
      System.err.println(outContent.toString());

    }
  }

I have tried to use this answer but i am getting the error java.io.StreamCorruptedException: invalid stream header: 6A617661

Body:
Since you already have a ByteArrayOutputStream, you should try something like this:

BufferedReader reader = new BuffererdBeader( new InputStreamReader(
                            new ByteArrayInputStream( outcontent.toByteArray() ) ) );


问:
repeated measures bootstrap stats, grouped by multiple factors
I have a data frame that looks like this, but obviously with many more rows etc:

```<code>df <- data.frame(id=c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2),
                 cond=c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
                 comm=c('X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y','X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'),
                 measure=c(0.8, 1.1, 0.7, 1.2, 0.9, 2.3, 0.6, 1.1, 0.7, 1.3, 0.6, 1.5, 1.0, 2.1, 0.7, 1.2))
</code>```

So we have 2 factors (each with 2 levels, thus 4 combinations) and one continuous measure. We also have a repeated measures design in that we have multiple measure's within each cell that correspond to the same id.

I've attempted to first solve the groupby issue, then the bootstrap issue, then combine the two, but am pretty much stuck...

Stats, grouped by the 2 factors

I can get multiple summary stats for each of the 4 cells by:

```<code>summary_stats <- aggregate(df$measure,
                           by = list(df$cond, df$comm),
                           function(x) c(mean = mean(x), median = median(x), sd = sd(x)))
print(summary_stats)
</code>```

resulting in

```<code>  Group.1 Group.2     x.mean   x.median       x.sd
1       A       X 0.85000000 0.85000000 0.12909944
2       B       X 0.65000000 0.65000000 0.05773503
3       A       Y 1.70000000 1.70000000 0.58878406
4       B       Y 1.25000000 1.20000000 0.17320508
</code>```

This is great as we are getting multiple stats for each of the 4 cells.

But what I'd really like is the 95% bootstrap CI's, for each stat, for each of the 4 cells. I don't mind if I have to run a final solution once for statistic (e.g. mean, median, etc), but bonus points for doing it all in one go.

Bootstrap for repeated measures

Can't quite make this work, but what I want is 95% bootstrap CI's, done in a way which is appropriate for this repeated measures design. Unless I'm mistaken then I want to select bootstrap samples on the basis of id (not on the basis of rows of the dataframe), then calculate a summary measure (e.g. mean) for each of the 4 cells.

```<code>library(boot)
myfunc <- function(data, indices) {
   # select bootstrap sample to index into `id`
   d <- data[data$id==indicies,]
   return(c(mean=mean(d), median=median(d), sd = sd(d)))
}

bresults <- boot(data = CO2$uptake, statistic = myfunc, R = 1000)
</code>```

Q1: I'm getting errors in selecting the bootstrap sample by id, i.e. the line d <- data[ data$id==indicies, ]

Combining bootstrap and the groupby 2 factors

Q2: I have no intuition of how to gel the two approaches together to achieve the final desired result. My only idea is to put the aggregate call in myfunc, to repeatedly calculate cell stats under each bootstrap replicate, but I'm out of my comfort zone with R here.

答:
For a bootstrap with a cluster variable, here's a solution without additional packages. I didn't use the boot package though.

Part 1: Bootstrap

This function draws a random sample from a set of clustered observations.

```<code>.clusterSample <- function(x, id){

  boot.id <- sample(unique(id), replace=T)
  out <- lapply(boot.id, function(i) x[id%in%i,])

  return( do.call("rbind",out) )

}
</code>```

Part 2: Boostrap estimates and CIs

The next function draws multiple samples and applies the same aggregate statement to each of them. The bootstrap estimates and CIs are then obtained by mean and quantile.

```<code>clusterBoot <- function(data, formula, cluster, R=1000, alpha=.05, FUN){

  # cluster variable
  cls <- model.matrix(cluster,data)[,2]

  template <- aggregate(formula, .clusterSample(data,cls), FUN)
  var <- which( names(template)==all.vars(formula)[1] )
  grp <- template[,-var,drop=F]
  val <- template[,var]

  x <- vapply( 1:R, FUN=function(r) aggregate(formula, .clusterSample(data,cls), FUN)[,var],
               FUN.VALUE=val )

  if(is.vector(x)) dim(x) <- c(1,1,length(x))
  if(is.matrix(x)) dim(x) <- c(nrow(x),1,ncol(x))

  # bootstrap estimates
  est <- apply( x, 1:2, mean )
  lo <- apply( x, 1:2, function(i) quantile(i,alpha/2) )
  up <- apply( x, 1:2, function(i) quantile(i,1-alpha/2) )
  colnames(lo) <- paste0(colnames(lo), ".lo")
  colnames(up) <- paste0(colnames(up), ".up")

  return( cbind(grp,est,lo,up) )

}
</code>```

Note the use of vapply. I use it because I prefer working with arrays over lists. Note also that I used the formula interface to aggregate, which I also like better.

Part 3: Examples

It can be used with any kind of stats, basically, even without grouping variables. Some examples include:

```<code>myStats <- function(x) c(mean = mean(x), median = median(x), sd = sd(x))

clusterBoot(data=df, formula=measure~cond+comm, cluster=~id, R=10, FUN=myStats)
#   cond comm mean median         sd mean.lo median.lo      sd.lo mean.up median.up      sd.up
# 1    A    X 0.85  0.850 0.11651125    0.85      0.85 0.05773503    0.85      0.85 0.17320508
# 2    B    X 0.65  0.650 0.05773503    0.65      0.65 0.05773503    0.65      0.65 0.05773503
# 3    A    Y 1.70  1.700 0.59461417    1.70      1.70 0.46188022    1.70      1.70 0.69282032
# 4    B    Y 1.24  1.215 0.13856406    1.15      1.15 0.05773503    1.35      1.35 0.17320508

clusterBoot(data=df, formula=measure~cond+comm, cluster=~id, R=10, FUN=mean)
#   cond comm  est  .lo  .up
# 1    A    X 0.85 0.85 0.85
# 2    B    X 0.65 0.65 0.65
# 3    A    Y 1.70 1.70 1.70
# 4    B    Y 1.25 1.15 1.35

clusterBoot(data=df, formula=measure~1, cluster=~id, R=10, FUN=mean)
#      est    .lo    .up
# 1 1.1125 1.0875 1.1375
</code>```

Body:
I have a data frame that looks like this, but obviously with many more rows etc:

df <- data.frame(id=c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2),
                 cond=c('A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B', 'A', 'A', 'B', 'B'),
                 comm=c('X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y','X', 'Y', 'X', 'Y', 'X', 'Y', 'X', 'Y'),
                 measure=c(0.8, 1.1, 0.7, 1.2, 0.9, 2.3, 0.6, 1.1, 0.7, 1.3, 0.6, 1.5, 1.0, 2.1, 0.7, 1.2))

So we have 2 factors (each with 2 levels, thus 4 combinations) and one continuous measure. We also have a repeated measures design in that we have multiple measure's within each cell that correspond to the same id.

I've attempted to first solve the groupby issue, then the bootstrap issue, then combine the two, but am pretty much stuck...

Stats, grouped by the 2 factors

I can get multiple summary stats for each of the 4 cells by:

summary_stats <- aggregate(df$measure,
                           by = list(df$cond, df$comm),
                           function(x) c(mean = mean(x), median = median(x), sd = sd(x)))
print(summary_stats)

resulting in

  Group.1 Group.2     x.mean   x.median       x.sd
1       A       X 0.85000000 0.85000000 0.12909944
2       B       X 0.65000000 0.65000000 0.05773503
3       A       Y 1.70000000 1.70000000 0.58878406
4       B       Y 1.25000000 1.20000000 0.17320508

This is great as we are getting multiple stats for each of the 4 cells.

But what I'd really like is the 95% bootstrap CI's, for each stat, for each of the 4 cells. I don't mind if I have to run a final solution once for statistic (e.g. mean, median, etc), but bonus points for doing it all in one go.

Bootstrap for repeated measures

Can't quite make this work, but what I want is 95% bootstrap CI's, done in a way which is appropriate for this repeated measures design. Unless I'm mistaken then I want to select bootstrap samples on the basis of id (not on the basis of rows of the dataframe), then calculate a summary measure (e.g. mean) for each of the 4 cells.

library(boot)
myfunc <- function(data, indices) {
   # select bootstrap sample to index into `id`
   d <- data[data$id==indicies,]
   return(c(mean=mean(d), median=median(d), sd = sd(d)))
}

bresults <- boot(data = CO2$uptake, statistic = myfunc, R = 1000)

Q1: I'm getting errors in selecting the bootstrap sample by id, i.e. the line d <- data[ data$id==indicies, ]

Combining bootstrap and the groupby 2 factors

Q2: I have no intuition of how to gel the two approaches together to achieve the final desired result. My only idea is to put the aggregate call in myfunc, to repeatedly calculate cell stats under each bootstrap replicate, but I'm out of my comfort zone with R here.

Body:
For a bootstrap with a cluster variable, here's a solution without additional packages. I didn't use the boot package though.

Part 1: Bootstrap

This function draws a random sample from a set of clustered observations.

.clusterSample <- function(x, id){

  boot.id <- sample(unique(id), replace=T)
  out <- lapply(boot.id, function(i) x[id%in%i,])

  return( do.call("rbind",out) )

}

Part 2: Boostrap estimates and CIs

The next function draws multiple samples and applies the same aggregate statement to each of them. The bootstrap estimates and CIs are then obtained by mean and quantile.

clusterBoot <- function(data, formula, cluster, R=1000, alpha=.05, FUN){

  # cluster variable
  cls <- model.matrix(cluster,data)[,2]

  template <- aggregate(formula, .clusterSample(data,cls), FUN)
  var <- which( names(template)==all.vars(formula)[1] )
  grp <- template[,-var,drop=F]
  val <- template[,var]

  x <- vapply( 1:R, FUN=function(r) aggregate(formula, .clusterSample(data,cls), FUN)[,var],
               FUN.VALUE=val )

  if(is.vector(x)) dim(x) <- c(1,1,length(x))
  if(is.matrix(x)) dim(x) <- c(nrow(x),1,ncol(x))

  # bootstrap estimates
  est <- apply( x, 1:2, mean )
  lo <- apply( x, 1:2, function(i) quantile(i,alpha/2) )
  up <- apply( x, 1:2, function(i) quantile(i,1-alpha/2) )
  colnames(lo) <- paste0(colnames(lo), ".lo")
  colnames(up) <- paste0(colnames(up), ".up")

  return( cbind(grp,est,lo,up) )

}

Note the use of vapply. I use it because I prefer working with arrays over lists. Note also that I used the formula interface to aggregate, which I also like better.

Part 3: Examples

It can be used with any kind of stats, basically, even without grouping variables. Some examples include:

myStats <- function(x) c(mean = mean(x), median = median(x), sd = sd(x))

clusterBoot(data=df, formula=measure~cond+comm, cluster=~id, R=10, FUN=myStats)
#   cond comm mean median         sd mean.lo median.lo      sd.lo mean.up median.up      sd.up
# 1    A    X 0.85  0.850 0.11651125    0.85      0.85 0.05773503    0.85      0.85 0.17320508
# 2    B    X 0.65  0.650 0.05773503    0.65      0.65 0.05773503    0.65      0.65 0.05773503
# 3    A    Y 1.70  1.700 0.59461417    1.70      1.70 0.46188022    1.70      1.70 0.69282032
# 4    B    Y 1.24  1.215 0.13856406    1.15      1.15 0.05773503    1.35      1.35 0.17320508

clusterBoot(data=df, formula=measure~cond+comm, cluster=~id, R=10, FUN=mean)
#   cond comm  est  .lo  .up
# 1    A    X 0.85 0.85 0.85
# 2    B    X 0.65 0.65 0.65
# 3    A    Y 1.70 1.70 1.70
# 4    B    Y 1.25 1.15 1.35

clusterBoot(data=df, formula=measure~1, cluster=~id, R=10, FUN=mean)
#      est    .lo    .up
# 1 1.1125 1.0875 1.1375


问:
Make Dropdown menu Disappear
I have a code from W3schools, in which we get dropdown menu after clicked on a button.

Dropdown menu don't disappear when we click anywhere else.
I have surfed a bit but it seems confusing as am new to js.

It would be much helpful if anyone could suggest how do we make it disappear?

Code Link

答:
Use this:

document.getElementById("myBtn").onblur = function(){
document.getElementById("myDropdown").classList.remove('show')
};```

"onBlur" is the Event for losing the focus

Title: Make Dropdown menu Disappear

Body:
Use this:

document.getElementById("myBtn").onblur = function(){
document.getElementById("myDropdown").classList.remove('show')
};

"onBlur" is the Event for losing the focus


问:
Is there a Java parser for BER-TLV?
I'm new to Java, so I would like to use the standard solution for, I think, the standard task. The length of tags and values are not known.</p>

答:
You can use this BER-TLV parser: source code on git.

Examples:

How to parse

```<code>byte[] bytes = HexUtil.parseHex("50045649534157131000023100000033D44122011003400000481F");
BerTlvParser parser = new BerTlvParser(LOG);
BerTlvs tlvs = parser.parse(bytes, 0, bytes.length);
</code>```

How to build

```<code>byte[] bytes =  new BerTlvBuilder()
                .addHex(new BerTag(0x50), "56495341")
                .addHex(new BerTag(0x57), "1000023100000033D44122011003400000481F")
                .buildArray();
</code>```

Maven dependency

```<code><dependency>
  <groupId>com.payneteasy</groupId>
  <artifactId>ber-tlv</artifactId>
  <version>1.0-10</version>
</dependency>
</code>```

Title: Is there a Java parser for BER-TLV?

Body:
You can use this BER-TLV parser: source code on git.

Examples:

How to parse

byte[] bytes = HexUtil.parseHex("50045649534157131000023100000033D44122011003400000481F");
BerTlvParser parser = new BerTlvParser(LOG);
BerTlvs tlvs = parser.parse(bytes, 0, bytes.length);

How to build

byte[] bytes =  new BerTlvBuilder()
                .addHex(new BerTag(0x50), "56495341")
                .addHex(new BerTag(0x57), "1000023100000033D44122011003400000481F")
                .buildArray();

Maven dependency

<dependency>
  <groupId>com.payneteasy</groupId>
  <artifactId>ber-tlv</artifactId>
  <version>1.0-10</version>
</dependency>

ContentLicense: CC BY-SA 4.0


问:
Choosing a data structure
Different Data structures are used according to requirement but how would I know which data structure should I use? I just want to know how to choose an appropriate data structure ? Thanks</p>

答:
This flowchart is for the STL in C++, but you could implement any of the data structures supported by the STL containers in C.

List is a linked list

Vector is a dynamic array

Deque is something like a list of dynamic arrays -- sort of splits the difference.

Queue and Priority queue are like they say (usually queue is implemented in terms of deque, priority queue is usually implemented in terms of a heap inside a vector or deque)

Set/Map/Multiset/Multimap are all implemented using some form of balanced binary tree.

Update 2016: Apparently the image I used to link to here has been link-rotted, but you can see several equivalent images over at this question: In which scenario do I use a particular STL container?

Title: Choosing a data structure


问:
Internet Explorer 11 detection
I know IE 11 has different user agent string than all other IE

```<code> Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko
</code>```

I have tried to detect IE 11 with answer specified for this question'

Jquery fail to detect IE 11

Thats !!navigator.userAgent.match(/Trident\/7\./)

But I am getting error
Object not found and needs to be re-evaluated.

Then I openede developer console in IE11 and tried to access some predefined javascript objects, I am still getting same error.

I have tried

navigator.userAgent

window.navigator

console.log('test');

Anyone have any idea about it ?

答:
This link was helpful . It contains the javascript code to detect all versions of IE up to IE11.  I tested the script with IE11 emulator. To find the IE11 emulator, right-click on the web browser click "Inspect element". At the bottom-left of the page, scroll down the navigation bar and click the desktop icon. The "User Agent String" dropdown box contains options to emulate IE6-11.

It works. I just used it some minutes before writing this answer. Cannot post snapshots - not enough reputation.

This is the code - follow the link to view it again:

// Get IE or Edge browser version
var version = detectIE();

if (version === false) {
  document.getElementById('result').innerHTML = '<s>IE/Edge</s>';
} else if (version >= 12) {
  document.getElementById('result').innerHTML = 'Edge ' + version;
} else {
  document.getElementById('result').innerHTML = 'IE ' + version;
}

// add details to debug result
document.getElementById('details').innerHTML = window.navigator.userAgent;

/**
 * detect IE
 * returns version of IE or false, if browser is not Internet Explorer
 */
function detectIE() {
  var ua = window.navigator.userAgent;

  // Test values; Uncomment to check result …

  // IE 10
  // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

  // IE 11
  // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

  // Edge 12 (Spartan)
  // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

  // Edge 13
  // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

  var msie = ua.indexOf('MSIE ');
  if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  }

  var trident = ua.indexOf('Trident/');
  if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  }

  var edge = ua.indexOf('Edge/');
  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  }

  // other browser
  return false;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url(https://fonts.googleapis.com/css?family=Fira+Mono|Fira+Sans:300);
body {
  color: black;
  background-color: white;
  font-family: "Fira Sans", sans-serif;
  font-weight: 300;
  margin: 0;
  padding: 3rem;
}

h1 {
  color: darkgrey;
  text-align: center;
  font-weight: 300;
  font-size: 1.5rem;
  line-height: 2rem;
}

h2 {
  text-align: center;
  font-weight: 300;
  font-size: 4rem;
}

p {
  color: darkgrey;
  text-align: center;
  font-family: "Fira Mono", monospace;
  font-size: 1rem;
  line-height: 1.5rem;
}</code>```

Detect IE/Edge version with JavaScript.
 Updated to recognize Internet Explorer 12+ aka Edge.

detecting…

n/a
```

Title: Internet Explorer 11 detection

Body:
I know IE 11 has different user agent string than all other IE

 Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv 11.0) like Gecko

I have tried to detect IE 11 with answer specified for this question'

Jquery fail to detect IE 11

Thats !!navigator.userAgent.match(/Trident\/7\./)

But I am getting error
Object not found and needs to be re-evaluated.

Then I openede developer console in IE11 and tried to access some predefined javascript objects, I am still getting same error.

I have tried

navigator.userAgent

window.navigator

console.log('test');

Anyone have any idea about it ?

Body:
This link was helpful . It contains the javascript code to detect all versions of IE up to IE11.  I tested the script with IE11 emulator. To find the IE11 emulator, right-click on the web browser click "Inspect element". At the bottom-left of the page, scroll down the navigation bar and click the desktop icon. The "User Agent String" dropdown box contains options to emulate IE6-11.

It works. I just used it some minutes before writing this answer. Cannot post snapshots - not enough reputation.

This is the code - follow the link to view it again:

// Get IE or Edge browser version
var version = detectIE();

if (version === false) {
  document.getElementById('result').innerHTML = '<s>IE/Edge</s>';
} else if (version >= 12) {
  document.getElementById('result').innerHTML = 'Edge ' + version;
} else {
  document.getElementById('result').innerHTML = 'IE ' + version;
}

// add details to debug result
document.getElementById('details').innerHTML = window.navigator.userAgent;

/**
 * detect IE
 * returns version of IE or false, if browser is not Internet Explorer
 */
function detectIE() {
  var ua = window.navigator.userAgent;

  // Test values; Uncomment to check result …

  // IE 10
  // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';

  // IE 11
  // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';

  // Edge 12 (Spartan)
  // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';

  // Edge 13
  // ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';

  var msie = ua.indexOf('MSIE ');
  if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  }

  var trident = ua.indexOf('Trident/');
  if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  }

  var edge = ua.indexOf('Edge/');
  if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  }

  // other browser
  return false;
}

@import url(https://fonts.googleapis.com/css?family=Fira+Mono|Fira+Sans:300);
body {
  color: black;
  background-color: white;
  font-family: "Fira Sans", sans-serif;
  font-weight: 300;
  margin: 0;
  padding: 3rem;
}

h1 {
  color: darkgrey;
  text-align: center;
  font-weight: 300;
  font-size: 1.5rem;
  line-height: 2rem;
}

h2 {
  text-align: center;
  font-weight: 300;
  font-size: 4rem;
}

p {
  color: darkgrey;
  text-align: center;
  font-family: "Fira Mono", monospace;
  font-size: 1rem;
  line-height: 1.5rem;
}

<h1>Detect IE/Edge version with JavaScript.<br> Updated to recognize Internet Explorer 12+ aka Edge.</h1>
<h2 id="result">detecting…</h2>
<p id="details">n/a</p>


问:
the timing of String Literal loaded into StringTable in Java HotSpot vm
The Question came out when i was learning java.lang.String Java API.

I found an article in Chinese.
Java 中new String("字面量") 中 "字面量" 是何时进入字符串常量池的?

it said,CONSTANT_String is lazy resolve in HotSpot VM, so String Literal is loaded into StringTable util it is used.

And i found some relavant saying.

jvms Chapter 5.4. Linking says

For example, a Java Virtual Machine implementation may choose to resolve each symbolic reference in a class or interface individually when it is used ("lazy" or "late" resolution), or to resolve them all at once when the class is being verified ("eager" or "static" resolution).

I found some openjdk code about ldc

```<code>IRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* thread, bool wide))
  // access constant pool
  constantPoolOop pool = method(thread)->constants();
  int index = wide ? get_index_u2(thread, Bytecodes::_ldc_w) :get_index_u1(thread, Bytecodes::_ldc);
  constantTag tag = pool->tag_at(index);

  if (tag.is_unresolved_klass() || tag.is_klass()) {
    klassOop klass = pool->klass_at(index, CHECK);
    oop java_class = klass->java_mirror();
    thread->set_vm_result(java_class);
  } else {
#ifdef ASSERT
    // If we entered this runtime routine, we believed the tag contained
    // an unresolved string, an unresolved class or a resolved class.
    // However, another thread could have resolved the unresolved string
    // or class by the time we go there.
    assert(tag.is_unresolved_string()|| tag.is_string(), "expected string");
#endif
    oop s_oop = pool->string_at(index, CHECK);
    thread->set_vm_result(s_oop);
  }
IRT_END
</code>```

and code about pool->string_at(index, CHECK)

```<code>oop constantPoolOopDesc::string_at_impl(constantPoolHandle this_oop, int which, TRAPS) {
  oop str = NULL;
  CPSlot entry = this_oop->slot_at(which);
  if (entry.is_metadata()) {
    ObjectLocker ol(this_oop, THREAD);
    if (this_oop->tag_at(which).is_unresolved_string()) {
      // Intern string
      Symbol* sym = this_oop->unresolved_string_at(which);
      str = StringTable::intern(sym, CHECK_(constantPoolOop(NULL)));
      this_oop->string_at_put(which, str);
   } else {
      // Another thread beat us and interned string, read string from constant pool
     str = this_oop->resolved_string_at(which);
    }
  } else {
    str = entry.get_oop();
  }
  assert(java_lang_String::is_instance(str), "must be string");
  return str;
}
</code>```

But

those code only could prove String Literal maybe loaded into StringTable util ldc, but can not prove lazy resolve in HotSpot VM.

Could someone explicate it explicitly.

FYI, i know little c but not c++.

Thanks.!

答:
There is a corner case which allows to check within a Java application whether a string existed in the pool prior to the test, but it can be done only once per string. Together with string literals of the same content, the lazy loading can be detected:

```<code>public class Test {
    public static void main(String[] args) {
        test('h', 'e', 'l', 'l', 'o');
        test('m', 'a', 'i', 'n');
    }
    static void test(char... arg) {
        String s1 = new String(arg), s2 = s1.intern();
        System.out.println('"'+s1+'"'
            +(s1!=s2? " existed": " did not exist")+" in the pool before");
        System.out.println("is the same as \"hello\": "+(s2=="hello"));
        System.out.println("is the same as \"main\": "+(s2=="main"));
        System.out.println();
    }
}
</code>```

The test first creates a new string instance which does not exist in the pool. Then it calls intern() on it and compares the references. There are three possible scenarios:

If a string of the same contents exists in the pool, that string will be returned which must be a different object than our string not being in the pool.

Our string is added to the pool and returned. In this case, the two references are identical.

A new string with the same contents will be created and added to the pool. Then, the returned reference will be different.

We can’t distinguish between 1 and 3, so if a JVM generally adds new strings to the pool in intern(), we are out of luck. But if it adds the instance we’re calling intern() on, we can identify scenario 2 and know for sure that the string wasn’t in the pool, but has been added as a side effect of our test.

On my machine, it prints:

"hello" did not exist before
is the same as "hello": true
is the same as "main": false

"main" existed before
is the same as "hello": false
is the same as "main": true
```

Also on Ideone

showing that "hello" did not exist when entering the test method the first time, despite there is a string literal "hello" in the code later-on. So this proves that the string literal is resolved lazily. Since we already added a hello string manually, the string literal with the same contents will resolve to the same instance.

In contrast, the "main" string already exists in the pool, which is easy to explain. The Java launcher searches for the main method to execute, hence, adds that string to the pool as a side effect.

If we swap the order of the tests to test('m', 'a', 'i', 'n'); test('h', 'e', 'l', 'l', 'o'); the "hello" string literal will be used in the first test invocation and remains in the pool, so when we test it in the second invocation the string will already exist.

Body:
The Question came out when i was learning java.lang.String Java API.

I found an article in Chinese.
Java 中new String("字面量") 中 "字面量" 是何时进入字符串常量池的?

it said,CONSTANT_String is lazy resolve in HotSpot VM, so String Literal is loaded into StringTable util it is used.

And i found some relavant saying.

jvms Chapter 5.4. Linking says

For example, a Java Virtual Machine implementation may choose to resolve each symbolic reference in a class or interface individually when it is used ("lazy" or "late" resolution), or to resolve them all at once when the class is being verified ("eager" or "static" resolution).

I found some openjdk code about ldc

IRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* thread, bool wide))
  // access constant pool
  constantPoolOop pool = method(thread)->constants();
  int index = wide ? get_index_u2(thread, Bytecodes::_ldc_w) :get_index_u1(thread, Bytecodes::_ldc);
  constantTag tag = pool->tag_at(index);

  if (tag.is_unresolved_klass() || tag.is_klass()) {
    klassOop klass = pool->klass_at(index, CHECK);
    oop java_class = klass->java_mirror();
    thread->set_vm_result(java_class);
  } else {
#ifdef ASSERT
    // If we entered this runtime routine, we believed the tag contained
    // an unresolved string, an unresolved class or a resolved class.
    // However, another thread could have resolved the unresolved string
    // or class by the time we go there.
    assert(tag.is_unresolved_string()|| tag.is_string(), "expected string");
#endif
    oop s_oop = pool->string_at(index, CHECK);
    thread->set_vm_result(s_oop);
  }
IRT_END

and code about pool->string_at(index, CHECK)

oop constantPoolOopDesc::string_at_impl(constantPoolHandle this_oop, int which, TRAPS) {
  oop str = NULL;
  CPSlot entry = this_oop->slot_at(which);
  if (entry.is_metadata()) {
    ObjectLocker ol(this_oop, THREAD);
    if (this_oop->tag_at(which).is_unresolved_string()) {
      // Intern string
      Symbol* sym = this_oop->unresolved_string_at(which);
      str = StringTable::intern(sym, CHECK_(constantPoolOop(NULL)));
      this_oop->string_at_put(which, str);
   } else {
      // Another thread beat us and interned string, read string from constant pool
     str = this_oop->resolved_string_at(which);
    }
  } else {
    str = entry.get_oop();
  }
  assert(java_lang_String::is_instance(str), "must be string");
  return str;
}

But

those code only could prove String Literal maybe loaded into StringTable util ldc, but can not prove lazy resolve in HotSpot VM.

Could someone explicate it explicitly.

FYI, i know little c but not c++.

Thanks.!

Body:
There is a corner case which allows to check within a Java application whether a string existed in the pool prior to the test, but it can be done only once per string. Together with string literals of the same content, the lazy loading can be detected:

public class Test {
    public static void main(String[] args) {
        test('h', 'e', 'l', 'l', 'o');
        test('m', 'a', 'i', 'n');
    }
    static void test(char... arg) {
        String s1 = new String(arg), s2 = s1.intern();
        System.out.println('"'+s1+'"'
            +(s1!=s2? " existed": " did not exist")+" in the pool before");
        System.out.println("is the same as \"hello\": "+(s2=="hello"));
        System.out.println("is the same as \"main\": "+(s2=="main"));
        System.out.println();
    }
}

The test first creates a new string instance which does not exist in the pool. Then it calls intern() on it and compares the references. There are three possible scenarios:

If a string of the same contents exists in the pool, that string will be returned which must be a different object than our string not being in the pool.

Our string is added to the pool and returned. In this case, the two references are identical.

A new string with the same contents will be created and added to the pool. Then, the returned reference will be different.

We can’t distinguish between 1 and 3, so if a JVM generally adds new strings to the pool in intern(), we are out of luck. But if it adds the instance we’re calling intern() on, we can identify scenario 2 and know for sure that the string wasn’t in the pool, but has been added as a side effect of our test.

On my machine, it prints:

"hello" did not exist before
is the same as "hello": true
is the same as "main": false

"main" existed before
is the same as "hello": false
is the same as "main": true

Also on Ideone

showing that "hello" did not exist when entering the test method the first time, despite there is a string literal "hello" in the code later-on. So this proves that the string literal is resolved lazily. Since we already added a hello string manually, the string literal with the same contents will resolve to the same instance.

In contrast, the "main" string already exists in the pool, which is easy to explain. The Java launcher searches for the main method to execute, hence, adds that string to the pool as a side effect.

If we swap the order of the tests to test('m', 'a', 'i', 'n'); test('h', 'e', 'l', 'l', 'o'); the "hello" string literal will be used in the first test invocation and remains in the pool, so when we test it in the second invocation the string will already exist.


问:
How do I set a callback function parameter like 'data' in the "jQuery.ajax({ success : function(data)"?
I am wondering how to set the first parameter of a callback function to what I want, the same way jquery does in the success callback or the complete callback

I want to do this:

```<code>$.ajax({
  success: function(data) {
    alert(data)
  }
});
</code>```

from what I understand this is as close as I can get to what I want

```<code>function test(text) {
  this.text = text
  this.success = function(this.text) { }
}

var a = new test('King Kong')
a.success = function(k){
  alert(k)
}
</code>```

and I want the alert to say "King Kong"

答:
Here's an example of accepting a callback in your constructor function and then calling it later in response to some trigger. In the below, the trigger is someone calling the trigger function, but it can be anything you want:

```<code>function Test(text, callback) {

  this.text = text;
  this.success = callback;
}

Test.prototype.trigger = function() {
    // Call the success callback, passing in the text
    this.success(this.text);
};

var a = new Test('King Kong', function(k) {
    alert(k);
});

a.trigger();
</code>```

(I've made Test initially-capped there. That's the convention for constructor functions, which you are of course free to ignore.)

The key, fundamental thing to understand is that functions are just objects like anything else. You can pass references to them around, etc. To call a function, you just access whatever variable you have the function reference stored in and add parentheses (optionally with the function's arguments in the parentheses).

Consequently, all of the following call the foo function and trigger the alert:

```<code>function foo(msg) {
    alert(msg);
}

var f = foo;   // No parens, just getting the function reference, not calling it
f("Hi there"); // Now we're calling it
var a = {};
a.nifty = f;
a.nifty("Hi again");

function bar(func) {
    func("Hello for the third time");
}
bar(foo);     // Passing a reference to `foo` into the `bar` function, which will call it
</code>```

Advanced: Now, one thing that jQuery does is that it calls the callback with the this value set to something specific (usually the DOM element related to the call). That will happen any time you call a function via an object property:

```<code>var a = {name: "Fred"};
a.func = function() {
    alert(this.name);
};
a.func(); // alerts "Fred"
</code>```

...but that's not the only way you can do it; there's also the call and apply functions on the function object itself:

```<code>var a = {name: "Fred"};
function func() {
    alert(this.name);
}
func.call(a); // alerts "Fred"
</code>```

There, the function isn't assigned to any of a's properties, but we've called the function using call, which accepts the value for this as its first argument. Call also passes on any further arguments to the function you're calling:

```<code>function func(msg1, msg2) {
   alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.call(a, "one", "two"); // alerts "Fred says one and two"
</code>```

apply does exactly the same thing, but it accepts the arguments to pass on to the underlying function as an array instead of as discrete arguments:

```<code>function func(msg1, msg2) {
   alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.apply(a, ["one", "two"]); // alerts "Fred says one and two"
//            ^------------^----- note these args are now an array
</code>```

More reading: Mythical Methods

Body:
I am wondering how to set the first parameter of a callback function to what I want, the same way jquery does in the success callback or the complete callback

I want to do this:

$.ajax({
  success: function(data) {
    alert(data)
  }
});

from what I understand this is as close as I can get to what I want

function test(text) {
  this.text = text
  this.success = function(this.text) { }
}

var a = new test('King Kong')
a.success = function(k){
  alert(k)
}

and I want the alert to say "King Kong"

Body:
Here's an example of accepting a callback in your constructor function and then calling it later in response to some trigger. In the below, the trigger is someone calling the trigger function, but it can be anything you want:

function Test(text, callback) {

  this.text = text;
  this.success = callback;
}

Test.prototype.trigger = function() {
    // Call the success callback, passing in the text
    this.success(this.text);
};

var a = new Test('King Kong', function(k) {
    alert(k);
});

a.trigger();

(I've made Test initially-capped there. That's the convention for constructor functions, which you are of course free to ignore.)

The key, fundamental thing to understand is that functions are just objects like anything else. You can pass references to them around, etc. To call a function, you just access whatever variable you have the function reference stored in and add parentheses (optionally with the function's arguments in the parentheses).

Consequently, all of the following call the foo function and trigger the alert:

function foo(msg) {
    alert(msg);
}

var f = foo;   // No parens, just getting the function reference, not calling it
f("Hi there"); // Now we're calling it
var a = {};
a.nifty = f;
a.nifty("Hi again");

function bar(func) {
    func("Hello for the third time");
}
bar(foo);     // Passing a reference to `foo` into the `bar` function, which will call it

Advanced: Now, one thing that jQuery does is that it calls the callback with the this value set to something specific (usually the DOM element related to the call). That will happen any time you call a function via an object property:

var a = {name: "Fred"};
a.func = function() {
    alert(this.name);
};
a.func(); // alerts "Fred"

...but that's not the only way you can do it; there's also the call and apply functions on the function object itself:

var a = {name: "Fred"};
function func() {
    alert(this.name);
}
func.call(a); // alerts "Fred"

There, the function isn't assigned to any of a's properties, but we've called the function using call, which accepts the value for this as its first argument. Call also passes on any further arguments to the function you're calling:

function func(msg1, msg2) {
   alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.call(a, "one", "two"); // alerts "Fred says one and two"

apply does exactly the same thing, but it accepts the arguments to pass on to the underlying function as an array instead of as discrete arguments:

function func(msg1, msg2) {
   alert(this.name + " says " + msg1 + " and " + msg2);
}
var a = {name: "Fred"};
func.apply(a, ["one", "two"]); // alerts "Fred says one and two"
//            ^------------^----- note these args are now an array

More reading: Mythical Methods


答:
EDITED for OPs comments

Make the column name for sample in data and settings the same. Then you can do:

```<code>library(dplyr)
full_join(data,settings,c=("sample")) %>%
    mutate(CAG = ((size-flank)/3)+correction) %>%
    rowwise() %>%
    filter(between(CAG,start,end)) %>%
    ungroup()
</code>```

This will create a new column CAG of your output and keep only CAG values that are >= start and <= end.

```<code>  sample size flank correction start  end control       CAG
1    A01  200   108          2    10 2000     A01  32.66667
2    A01  280   108          2    10 2000     A01  59.33333
3    A02  315   108          2    10 2000     A01  71.00000
4    A02  430   108          2    10 2000     A01 109.33333
5    A03  510    60          1    13 6000     A03 151.00000
6    A04  560    60          1    13 6000     A03 167.66667
7    A04  610    60          1    13 6000     A03 184.33333
</code>```

Title: Look up variable for a calculation

Body:
I've got a table, data', which contains sample names and measurement sizes. I need to convert size to CAG using the formula ((CAG - flank)/3)+correction. The trouble is each sample has a different 'flank' and 'correction', as defined in 'settings'. I then need to filter out rows where the CAG is less than 'start' or greater than 'end'. Start and end are defined in 'settings' and also vary for each sample.
I'd be really grateful for help adapting the calculation to index the appropriate flank and correction for each sample

#Example dataset
data <- data.frame(sample = c('A01', 'A01', 'A02', 'A02', 'A03', 'A04', 'A04'),
               size = c(200, 280, 315, 430, 510, 560, 610))

#Define controls for each sample
settings <- data.frame(samples = c('A01', 'A02', 'A03', 'A04'),
                   flank = c(108, 108, 60, 60)
                   correction = (2, 2, 1, 1)
                   start = (10, 10, 13, 13)
                   end = (2000, 2000, 6000, 6000)
                   control = c('A01', 'A01', 'A03', 'A03'))

#Convert size unit from bp to CAG in new column
data$CAG <- ((data$size - flank)/3)+correction

#Exclude peaks outside the window
filter <- subset(data, CAG >= start & CAG <= end)

Body:
EDITED for OPs comments

Make the column name for sample in data and settings the same. Then you can do:

library(dplyr)
full_join(data,settings,c=("sample")) %>%
    mutate(CAG = ((size-flank)/3)+correction) %>%
    rowwise() %>%
    filter(between(CAG,start,end)) %>%
    ungroup()

This will create a new column CAG of your output and keep only CAG values that are >= start and <= end.

  sample size flank correction start  end control       CAG
1    A01  200   108          2    10 2000     A01  32.66667
2    A01  280   108          2    10 2000     A01  59.33333
3    A02  315   108          2    10 2000     A01  71.00000
4    A02  430   108          2    10 2000     A01 109.33333
5    A03  510    60          1    13 6000     A03 151.00000
6    A04  560    60          1    13 6000     A03 167.66667
7    A04  610    60          1    13 6000     A03 184.33333


问:
File not Found Codeigniter in production
So I've put my website online and only my landing page (Home_controller) is working fine but any other page is not working.

http://www.my-websiteabc.net/ works fine but not http://www.my-websiteabc.net/About_cookies

http://www.my-websiteabc.net/Home_controller and http://www.my-websiteabc.net/home_controller don't work either.

I've spent all day reading different suggestions and workarounds but can't get it to work.

What I've tried so far:

1.My Controllers filenames and Classes have a first Uppercase character. For instance:

About_cookies.php

class About_cookies extends CI_Controller

View: cookies.php

2.My folder structure is:

```<code>/.
   /my-websiteabc
   /my-websiteabc/application
   /my-websiteabc/js
   /my-websiteabc/css
   /my-websiteabc/system
</code>```

3.I have .htaccess in the root folder contains:

```<code><IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>
</code>```

4.I also tried with/without this .htaccess in the application folder:

```<code><IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
</code>```

5.My routes.php :

```<code>$route['default_controller'] = 'Home_controller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

6.And config.php:

```<code>$config['base_url'] = 'http://www.my-websiteabc.net/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
</code>```

I get File not found. when trying anything else than http://www.my-websiteabc.net/ but on this page all the images and CSS are correct so I guess my path is correct.

Using CI 3.1.5 and PHP 7.1.6

Update 05/07:

Controller definition (About_cookies.php):

```<code><?php
class About_cookies extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $ci =& get_instance();
        if ($ci->session->userdata('site_lang')) {
            $siteLang = $ci->session->userdata('site_lang');
        } else {
            $siteLang = 'english';
            $this->session->set_userdata('site_lang', $siteLang);
        }
        $ci->lang->load('home',$siteLang);
    }

    public function index(){
        $data['main_content'] = 'cookies';
        $this->load->view('templates/default',$data);
    }
}
</code>```

The URL my browser is trying to access:
http://www.my-websiteabc.net/About_cookies

My view: cookies.php

答:
Try using this .htaccess definition:

```<code><IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

<FilesMatch "\.(html|htm|js|css|php)$">
    FileETag None
    Header unset ETag
    Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</FilesMatch>

SetEnv CI_ENV development
</code>```

To make it clear, it has three parts:

The first one is the one you need, will convert mysite.domain/controller URIs into mysite.domain/index.php/controller automatically and transparently.

The second part just disables caching for some files. In this case, files with html, htm, js, css, php extensions won't be cached. This isn't part of your problem, but I think it could be useful to you in some cases (you probably want to remove the php extension in order for the CodeIgniter internal cache to work).

The third one sets the environment for CodeIgniter. It can be development or production.

Note that this .htaccess file should be to the side of index.php (the one at the root of the whole CodeIgniter folder tree), not inside any folder.

Body:
So I've put my website online and only my landing page (Home_controller) is working fine but any other page is not working.

http://www.my-websiteabc.net/ works fine but not http://www.my-websiteabc.net/About_cookies

http://www.my-websiteabc.net/Home_controller and http://www.my-websiteabc.net/home_controller don't work either.

I've spent all day reading different suggestions and workarounds but can't get it to work.

What I've tried so far:

1.My Controllers filenames and Classes have a first Uppercase character. For instance:

About_cookies.php

class About_cookies extends CI_Controller

View: cookies.php

2.My folder structure is:

/.
   /my-websiteabc
   /my-websiteabc/application
   /my-websiteabc/js
   /my-websiteabc/css
   /my-websiteabc/system

3.I have .htaccess in the root folder contains:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
</IfModule>

4.I also tried with/without this .htaccess in the application folder:

<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>

5.My routes.php :

$route['default_controller'] = 'Home_controller';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

6.And config.php:

$config['base_url'] = 'http://www.my-websiteabc.net/';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

I get File not found. when trying anything else than http://www.my-websiteabc.net/ but on this page all the images and CSS are correct so I guess my path is correct.

Using CI 3.1.5 and PHP 7.1.6

Update 05/07:

Controller definition (About_cookies.php):

<?php
class About_cookies extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $ci =& get_instance();
        if ($ci->session->userdata('site_lang')) {
            $siteLang = $ci->session->userdata('site_lang');
        } else {
            $siteLang = 'english';
            $this->session->set_userdata('site_lang', $siteLang);
        }
        $ci->lang->load('home',$siteLang);
    }

    public function index(){
        $data['main_content'] = 'cookies';
        $this->load->view('templates/default',$data);
    }
}

The URL my browser is trying to access:
http://www.my-websiteabc.net/About_cookies

My view: cookies.php

Body:
Try using this .htaccess definition:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

<FilesMatch "\.(html|htm|js|css|php)$">
    FileETag None
    Header unset ETag
    Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
    Header set Pragma "no-cache"
    Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</FilesMatch>

SetEnv CI_ENV development

To make it clear, it has three parts:

The first one is the one you need, will convert mysite.domain/controller URIs into mysite.domain/index.php/controller automatically and transparently.

The second part just disables caching for some files. In this case, files with html, htm, js, css, php extensions won't be cached. This isn't part of your problem, but I think it could be useful to you in some cases (you probably want to remove the php extension in order for the CodeIgniter internal cache to work).

The third one sets the environment for CodeIgniter. It can be development or production.

Note that this .htaccess file should be to the side of index.php (the one at the root of the whole CodeIgniter folder tree), not inside any folder.


问:
insert attributes dynamically in html elements in angular
I have to insert a set of attributes to my a component I want to re use...
now different attributes will come as string to me...
say for example I want to insert an element in my component

```<code><input type="text" maxlength="10" placeholder="enter your name"/>
</code>```

then i will get all the attributes as a single string

```<code>attr = 'type="text" maxlength="10" placeholder="enter your name"'
</code>```

in the controller for my component...
and i have to insert that to my conponent  in the html...

i have tried

```<code><input {{attr}}/>
</code>```

and

```<code><input {{jQuery.parseHtml(attr)}}
</code>```

etc..

but it is not working... also, could not find any solutions...
please share any solutions or some links/references helpful for me...

答: You can use @Input properties to pass data to a nested reusable component. However, AFAIK there isn't an easy way to pass a string of html attributes and apply them automatically. You'd either need to pass them on individual input properties or write code to process the string yourself and map them into attributes for binding.</p>

Body:
I have to insert a set of attributes to my a component I want to re use...
now different attributes will come as string to me...
say for example I want to insert an element in my component

<input type="text" maxlength="10" placeholder="enter your name"/>

then i will get all the attributes as a single string

attr = 'type="text" maxlength="10" placeholder="enter your name"'

in the controller for my component...
and i have to insert that to my conponent  in the html...

i have tried

<input {{attr}}/>

and

<input {{jQuery.parseHtml(attr)}}

etc..

but it is not working... also, could not find any solutions...
please share any solutions or some links/references helpful for me...


问:
How to get all the products? MySQL, PHP
How to get all the products? With the return, I get only one row...
I would like to type a loop to get all the values of the MySQL table "listaprodotti"?

```<code>     public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($username, $id_prodotto, $nome_prodotto, $categoria, $quantita);
    $stmt->fetch();
    $prodotti = array();

    $prodotti['username'] = $username;
    $prodotti['id_prodotto'] = $id_prodotto;
    $prodotti['nome_prodotto'] = $nome_prodotto;
    $prodotti['categoria'] = $categoria;
    $prodotti['quantita'] = $quantita;

    return $prodotti;

   }

   }
</code>```

That's what I get

```<code>     "prodotti":
   {"username":"anto","id_prodotto":57,"nome_prodotto":"xxx",
       "categoria":"xxx","quantita":"2"}}
</code>```

All this must be called with Swift 3 as an NSDictionary.

UPDATE

How do I get the values as an NSDictionary in Swift 3 ?

PHP CODE

```<code>  public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $i=0;
    $prodotti = array();
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $prodotti[$i]['username'] = $row['username'];
        $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
        $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
        $prodotti[$i]['categoria'] = $row['categoria'];
        $prodotti[$i]['quantita'] = $row['quantita'];
        $i++;
    }
     return $prodotti;
    }

    }
</code>```

SWIFT CODE

```<code>   import Alamofire
   import UIKit
    import AVFoundation

   class LoginController1: UIViewController {

//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://.............../login.php"

//the defaultvalues to store user data
let defaultValues = UserDefaults.standard

//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!

//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {

    //getting the username and password
    let parameters: Parameters=[
        "username":username.text!,
        "password":password.text!
    ]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary

                    //getting user values
                    let userId = user.value(forKey: "id") as! Int
                    let userName = user.value(forKey: "username") as! String
                    let userEmail = user.value(forKey: "email") as! String
                    let userNome = user.value(forKey: "nome") as! String
                    let userCognome = user.value(forKey: "cognome") as! String
                    let userTelefono = user.value(forKey: "telefono") as! String

                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")
                    self.defaultValues.set(userName, forKey: "username")
                    self.defaultValues.set(userEmail, forKey: "useremail")
                    self.defaultValues.set(userNome, forKey: "usernome")
                    self.defaultValues.set(userCognome, forKey: "usercognome")
                    self.defaultValues.set(userTelefono, forKey: "usertelefono")

                    ///prende i valori dei prodotti dalla cella legata a quel username
                    let prodotti = jsonData.value(forKey: "row") as! NSDictionary

                    let prodottiNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
                    let prodottiCategoria = prodotti.value(forKey: "categoria") as! String
                    let prodottiQuantita = prodotti.value(forKey: "quantita") as! String

                    //saving i valori di questo username

                    self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
                    self.defaultValues.set(prodottiCategoria, forKey: "categoria")
                    self.defaultValues.set(prodottiQuantita, forKey: "quantita")

                    //Go to the HomeViewController if the login is sucessful
                    let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
                    self.navigationController?.pushViewController(ProfiloController, animated: true)

                    self.dismiss(animated: false, completion: nil)

                    }else{
                                            //error message in case of invalid credential
                    let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                    }
            }
                }
}

override func viewDidLoad() {
    super.viewDidLoad()
    if defaultValues.string(forKey: "username") != nil{
        let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
        self.navigationController?.pushViewController(ProfiloController, animated: true)

    }
}

    var player: AVPlayer?
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
    view.addGestureRecognizer(tap)
    let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
    player = AVPlayer(url: URL(fileURLWithPath: path!))
    player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.insertSublayer(playerLayer, at: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
    player!.seek(to: kCMTimeZero)
    player!.play()

}

func playerItemDidReachEnd() {
    player!.seek(to: kCMTimeZero)
}

func dismissKeyboard(tap: UITapGestureRecognizer) {
    print("Keyboard Dismiss Again")
    view.endEditing(true)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
 }

  }
</code>```

答:
You can call your result in a loop, otherwise it just takes the first row:</p>

```<code>$result = $stmt->get_result();
$i=0;
while($row = $result->fetch_array(MYSQLI_ASSOC)){
    $prodotti[$i]['username'] = $row['username'];
    $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
    $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
    $prodotti[$i]['categoria'] = $row['categoria'];
    $prodotti[$i]['quantita'] = $row['quantita'];
    $i++;
}
</code>```

Title: How to get all the products? MySQL, PHP

Body:
How to get all the products? With the return, I get only one row...
I would like to type a loop to get all the values of the MySQL table "listaprodotti"?

     public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->bind_result($username, $id_prodotto, $nome_prodotto, $categoria, $quantita);
    $stmt->fetch();
    $prodotti = array();

    $prodotti['username'] = $username;
    $prodotti['id_prodotto'] = $id_prodotto;
    $prodotti['nome_prodotto'] = $nome_prodotto;
    $prodotti['categoria'] = $categoria;
    $prodotti['quantita'] = $quantita;

    return $prodotti;

   }

   }

That's what I get

     "prodotti":
   {"username":"anto","id_prodotto":57,"nome_prodotto":"xxx",
       "categoria":"xxx","quantita":"2"}}

All this must be called with Swift 3 as an NSDictionary.

UPDATE

How do I get the values as an NSDictionary in Swift 3 ?

PHP CODE

  public function getProdottiByUsername($username)
{
    $stmt = $this->conn->prepare("SELECT username, id_prodotto, nome_prodotto, categoria, quantita  FROM listaprodotti WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();
    $i=0;
    $prodotti = array();
    while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $prodotti[$i]['username'] = $row['username'];
        $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
        $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
        $prodotti[$i]['categoria'] = $row['categoria'];
        $prodotti[$i]['quantita'] = $row['quantita'];
        $i++;
    }
     return $prodotti;
    }

    }

SWIFT CODE

   import Alamofire
   import UIKit
    import AVFoundation

   class LoginController1: UIViewController {

//The login script url make sure to write the ip instead of localhost
//you can get the ip using ifconfig command in terminal
let URL_USER_LOGIN = "http://.............../login.php"

//the defaultvalues to store user data
let defaultValues = UserDefaults.standard

//the connected views
//don't copy instead connect the views using assistant editor
@IBOutlet weak var labelMessage: UILabel!
@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!

//the button action function
@IBAction func buttonLogin(_ sender: UIButton) {

    //getting the username and password
    let parameters: Parameters=[
        "username":username.text!,
        "password":password.text!
    ]

    //making a post request
    Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)

            //getting the json value from the server
            if let result = response.result.value {
                let jsonData = result as! NSDictionary

                //if there is no error
                if(!(jsonData.value(forKey: "error") as! Bool)){

                    //getting the user from response
                    let user = jsonData.value(forKey: "user") as! NSDictionary

                    //getting user values
                    let userId = user.value(forKey: "id") as! Int
                    let userName = user.value(forKey: "username") as! String
                    let userEmail = user.value(forKey: "email") as! String
                    let userNome = user.value(forKey: "nome") as! String
                    let userCognome = user.value(forKey: "cognome") as! String
                    let userTelefono = user.value(forKey: "telefono") as! String

                    //saving user values to defaults
                    self.defaultValues.set(userId, forKey: "userid")
                    self.defaultValues.set(userName, forKey: "username")
                    self.defaultValues.set(userEmail, forKey: "useremail")
                    self.defaultValues.set(userNome, forKey: "usernome")
                    self.defaultValues.set(userCognome, forKey: "usercognome")
                    self.defaultValues.set(userTelefono, forKey: "usertelefono")

                    ///prende i valori dei prodotti dalla cella legata a quel username
                    let prodotti = jsonData.value(forKey: "row") as! NSDictionary

                    let prodottiNome_prodotto = prodotti.value(forKey: "nome_prodotto") as! String
                    let prodottiCategoria = prodotti.value(forKey: "categoria") as! String
                    let prodottiQuantita = prodotti.value(forKey: "quantita") as! String

                    //saving i valori di questo username

                    self.defaultValues.set(prodottiNome_prodotto, forKey: "nome_prodotto")
                    self.defaultValues.set(prodottiCategoria, forKey: "categoria")
                    self.defaultValues.set(prodottiQuantita, forKey: "quantita")

                    //Go to the HomeViewController if the login is sucessful
                    let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
                    self.navigationController?.pushViewController(ProfiloController, animated: true)

                    self.dismiss(animated: false, completion: nil)

                    }else{
                                            //error message in case of invalid credential
                    let alertController = UIAlertController(title: "Error", message: "Username e password sbagliati", preferredStyle: .alert)
                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                    }
            }
                }
}

override func viewDidLoad() {
    super.viewDidLoad()
    if defaultValues.string(forKey: "username") != nil{
        let ProfiloController = self.storyboard?.instantiateViewController(withIdentifier: "Profilo") as! ProfiloController
        self.navigationController?.pushViewController(ProfiloController, animated: true)

    }
}

    var player: AVPlayer?
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

    let tap = UITapGestureRecognizer(target: self, action: #selector(LoginController1.dismissKeyboard))
    view.addGestureRecognizer(tap)
    let path = Bundle.main.path(forResource: "introoiphone 7 plus", ofType: "mp4")
    player = AVPlayer(url: URL(fileURLWithPath: path!))
    player!.actionAtItemEnd = AVPlayerActionAtItemEnd.none;
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.view.frame
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    self.view.layer.insertSublayer(playerLayer, at: 0)
    NotificationCenter.default.addObserver(self, selector: #selector(LoginController1.playerItemDidReachEnd), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player!.currentItem)
    player!.seek(to: kCMTimeZero)
    player!.play()

}

func playerItemDidReachEnd() {
    player!.seek(to: kCMTimeZero)
}

func dismissKeyboard(tap: UITapGestureRecognizer) {
    print("Keyboard Dismiss Again")
    view.endEditing(true)
}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
 }

  }

Body:
You can call your result in a loop, otherwise it just takes the first row:

$result = $stmt->get_result();
$i=0;
while($row = $result->fetch_array(MYSQLI_ASSOC)){
    $prodotti[$i]['username'] = $row['username'];
    $prodotti[$i]['id_prodotto'] = $row['id_prodotto'];
    $prodotti[$i]['nome_prodotto'] = $row['nome_prodotto'];
    $prodotti[$i]['categoria'] = $row['categoria'];
    $prodotti[$i]['quantita'] = $row['quantita'];
    $i++;
}


问:
how to send json data from html page to node.js server
i want to send some json data from my client page to server page of node.js,
 here i have my server page :

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.post('/', function(req,res){
   res.send('recieved request');
   console.log(req.body);
});

app.listen(8081);
console.log('listening on 8081');```
</div>
</div>
</p>

<p>client page:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var name ='someName';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){
  console.log(this.responseText);
 }
};
xhttp.setRequestHeader({'Content-Type': 'application/json'});
xhttp.open('POST', 'http://localhost:8081', true);
xhttp.send(JSON.stringify({'name' : name}));</code>```

I got the result as a null json {}.

NOTE: I don't want to about submission of a form , i just want to send JSON data from html file to node.js file.

答:
The correct signature for a call to XMLHTTPRequest#setRequestHeader is setRequestHeader(header, value);

Change

```<code>xhttp.setRequestHeader({'Content-Type': 'application/json'});
</code>```

to

```<code>xhttp.setRequestHeader('Content-Type', 'application/json');
</code>```

Docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Body:
i want to send some json data from my client page to server page of node.js,
 here i have my server page :

var express = require('express');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.post('/', function(req,res){
   res.send('recieved request');
   console.log(req.body);
});

app.listen(8081);
console.log('listening on 8081');

client page:

var name ='someName';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){
  console.log(this.responseText);
 }
};
xhttp.setRequestHeader({'Content-Type': 'application/json'});
xhttp.open('POST', 'http://localhost:8081', true);
xhttp.send(JSON.stringify({'name' : name}));

I got the result as a null json {}.

NOTE: I don't want to about submission of a form , i just want to send JSON data from html file to node.js file.

Body:
The correct signature for a call to XMLHTTPRequest#setRequestHeader is setRequestHeader(header, value);

Change

xhttp.setRequestHeader({'Content-Type': 'application/json'});

to

xhttp.setRequestHeader('Content-Type', 'application/json');

Docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader