问:
One row per group with multiple column sorting
Would like to return one row per group, where the one is selected by multiple sort columns. Treading lightly here in the land of greatest-n-per-group to avoid a duplicate question.

SCHEMA:

```<code>CREATE TABLE logs (
  id INT NOT NULL,
  ip_address INT NOT NULL,
  status INT NOT NULL,
  PRIMARY KEY id
);
</code>```

DATA:

```<code>INSERT INTO logs (id, ip_address, status)
VALUES ('1', 19216800, 1),
       ('2', 19216801, 2),
       ('3', 19216800, 2),
       ('4', 19216803, 0),
       ('5', 19216804, 0),
       ('6', 19216803, 0),
       ('7', 19216804, 1);
</code>```

CURRENT QUERY:

```<code>SELECT *
  FROM logs
 ORDER BY ip_address, status=1 DESC, id DESC
</code>```

Note: sorting by status=1 effectively turns the status column into a boolean. The tie breaker after status=1 is id. This query currently returns the correct row for each ip_address first and then a bunch of other rows I don't want for that ip_address.

CURRENT OUTPUT:

```<code>1, 19216800, 1
3, 19216800, 2
2, 19216801, 2
6, 19216803, 0
4, 19216803, 0
7, 19216804, 1
5, 19216804, 0
</code>```

WANTED OUTPUT:

```<code>1, 19216800, 1
2, 19216801, 2
6, 19216803, 0
7, 19216804, 1
</code>```

Today my workaround is to filter in PHP with if ($lastIP == $row['ip_address']) continue;. But I would like to move this logic to MySQL.

答:
Since there are already hundreds of solutions for greatest-n-per-group problems in MySQL, I'm going to start answering these questions with CTE syntax with window functions, since that is now available in MySQL 8.0.3.</p>

```<code>WITH sorted AS (
    SELECT id, ip_address, status,
      ROW_NUMBER() OVER (PARTITION BY ip_address ORDER BY status) AS rn
    FROM logs
)
SELECT * FROM sorted WHERE rn = 1;
</code>```

Body:
Would like to return one row per group, where the one is selected by multiple sort columns. Treading lightly here in the land of greatest-n-per-group to avoid a duplicate question.

SCHEMA:

CREATE TABLE logs (
  id INT NOT NULL,
  ip_address INT NOT NULL,
  status INT NOT NULL,
  PRIMARY KEY id
);

DATA:

INSERT INTO logs (id, ip_address, status)
VALUES ('1', 19216800, 1),
       ('2', 19216801, 2),
       ('3', 19216800, 2),
       ('4', 19216803, 0),
       ('5', 19216804, 0),
       ('6', 19216803, 0),
       ('7', 19216804, 1);

CURRENT QUERY:

SELECT *
  FROM logs
 ORDER BY ip_address, status=1 DESC, id DESC

Note: sorting by status=1 effectively turns the status column into a boolean. The tie breaker after status=1 is id. This query currently returns the correct row for each ip_address first and then a bunch of other rows I don't want for that ip_address.

CURRENT OUTPUT:

1, 19216800, 1
3, 19216800, 2
2, 19216801, 2
6, 19216803, 0
4, 19216803, 0
7, 19216804, 1
5, 19216804, 0

WANTED OUTPUT:

1, 19216800, 1
2, 19216801, 2
6, 19216803, 0
7, 19216804, 1

Today my workaround is to filter in PHP with if ($lastIP == $row['ip_address']) continue;. But I would like to move this logic to MySQL.

Body:
Since there are already hundreds of solutions for greatest-n-per-group problems in MySQL, I'm going to start answering these questions with CTE syntax with window functions, since that is now available in MySQL 8.0.3.

WITH sorted AS (
    SELECT id, ip_address, status,
      ROW_NUMBER() OVER (PARTITION BY ip_address ORDER BY status) AS rn
    FROM logs
)
SELECT * FROM sorted WHERE rn = 1;


来源: stackexchange

问:
Gradle Copy task says no source
I have this Gradle script as deploy.gradle(Gradle 4.3.1):

```<code>defaultTasks 'echoProp'
import org.apache.tools.ant.filters.ReplaceTokens

task copyWar(type: Copy) {
    from "${source}"
    into "${target}"
    include '*.war'
}

task echoProp(dependsOn: copyWar) << {
    println "source dir: ${source}"
    println "target dir: ${target}"
    println "source = ${project.property('source')}"
    def currentJvm = org.gradle.internal.jvm.Jvm.current()
    println currentJvm
}
</code>```

This is the rough output:

```<code>                                        The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
    at deploy_13e4yjnom30svmprt2wccq4te.run(E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\71\deploy.gradle:10)
    (Run with --stacktrace to get the full stack trace of this deprecation warning.)
:copyWar NO-SOURCE
:echoProp
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
1.8.0_31 (Oracle Corporation 25.31-b07)

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
</code>```

This runs on a Windows Server 2012 R2 machine. I checked and there is a .war file in the defined source directory.

I can't figure out why it doesn't copy over the testApp.war file. I mean, the Source Directory are defined just fine by the other task, but why can't the copyWar task find these files?

Result of removing the << and running with the --info flag:

```<code>Initialized native services in: C:\Windows\System32\config\systemprofile\.gradle\native
The client will now receive all logging from the daemon (pid: 5580). The daemon log file: C:\Windows\System32\config\systemprofile\.gradle\daemon\4.3.1\daemon-5580.out.log
Starting 19th build in daemon [uptime: 1 hrs 14 mins 1.715 secs, performance: 98%, no major garbage collections]
Using 2 worker leases.
Creating new cache for fileHashes, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\fileHashes.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for plugin-use-metadata, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\plugin-use-metadata.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Creating new cache for client-status, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\client-status.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Starting Build
Settings evaluated using settings file.
Projects loaded. Root project using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Included projects: [root project '72']
Evaluating root project '72' using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using SubsetScriptTransformer.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using BuildScriptTransformer.
source dir: file tree
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
1.8.0_31 (Oracle Corporation 25.31-b07)
All projects evaluated.
No tasks specified. Using project default tasks 'echoProp'
Selected primary task 'echoProp' from project :
Tasks to be executed: [task ':copyWar', task ':echoProp']
Creating new cache for resourceHashesCache, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\resourceHashesCache.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for taskHistory, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\taskHistory\taskHistory.bin, access org.gradle.cache.internal.DefaultCacheAccess@1e64a7a6
Creating new cache for outputFiles, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\buildOutputCleanup\outputFiles.bin, access org.gradle.cache.internal.DefaultCacheAccess@4faa606d
:copyWar (Thread[Daemon worker Thread 15,5,main]) started.
:copyWar
Putting task artifact state for task ':copyWar' into context took 0.0 secs.
Skipping task ':copyWar' as it has no source files and no previous output files.
:copyWar NO-SOURCE
:copyWar (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.002 secs.
:echoProp (Thread[Daemon worker Thread 15,5,main]) started.
:echoProp
Skipping task ':echoProp' as it has no actions.
:echoProp UP-TO-DATE
:echoProp (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.004 secs.
</code>```

also, the source and target variables from my Gradle.properties:

```<code>source=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
</code>```

I'm completely new to Gradle, so I'm not sure what this all means.

答:
Your error is, that the Copy task has a property called source.

You give the toString() representation of this property (which is file tree) to the from method.

There of course no WAR files are found and thus the copy task has nothing to do.

Either rename your source property to something different, or use project.source to explicitly reference the source property of the project instead of the one from the task.

Besides that into "${target}" is identical to into target but is more performant. source and target are already strings, but you use them as placeholders which means the placeholder needs to be evaluated first which doesn't make too much sense.

ContentLicense: CC BY-SA 3.0

Title: Gradle Copy task says no source

Body:
I have this Gradle script as deploy.gradle(Gradle 4.3.1):

defaultTasks 'echoProp'
import org.apache.tools.ant.filters.ReplaceTokens

task copyWar(type: Copy) {
    from "${source}"
    into "${target}"
    include '*.war'
}

task echoProp(dependsOn: copyWar) << {
    println "source dir: ${source}"
    println "target dir: ${target}"
    println "source = ${project.property('source')}"
    def currentJvm = org.gradle.internal.jvm.Jvm.current()
    println currentJvm
}

This is the rough output:

                                        The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
    at deploy_13e4yjnom30svmprt2wccq4te.run(E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\71\deploy.gradle:10)
    (Run with --stacktrace to get the full stack trace of this deprecation warning.)
:copyWar NO-SOURCE
:echoProp
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/71
1.8.0_31 (Oracle Corporation 25.31-b07)

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

This runs on a Windows Server 2012 R2 machine. I checked and there is a .war file in the defined source directory.

I can't figure out why it doesn't copy over the testApp.war file. I mean, the Source Directory are defined just fine by the other task, but why can't the copyWar task find these files?

Result of removing the << and running with the --info flag:

Initialized native services in: C:\Windows\System32\config\systemprofile\.gradle\native
The client will now receive all logging from the daemon (pid: 5580). The daemon log file: C:\Windows\System32\config\systemprofile\.gradle\daemon\4.3.1\daemon-5580.out.log
Starting 19th build in daemon [uptime: 1 hrs 14 mins 1.715 secs, performance: 98%, no major garbage collections]
Using 2 worker leases.
Creating new cache for fileHashes, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\fileHashes.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for plugin-use-metadata, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\plugin-use-metadata.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Creating new cache for client-status, path C:\Windows\System32\config\systemprofile\.gradle\caches\4.3.1\plugin-resolution\client-status.bin, access org.gradle.cache.internal.DefaultCacheAccess@4092835c
Starting Build
Settings evaluated using settings file.
Projects loaded. Root project using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Included projects: [root project '72']
Evaluating root project '72' using build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle'.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using SubsetScriptTransformer.
Compiling build file 'E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\deploy.gradle' using BuildScriptTransformer.
source dir: file tree
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target dir: E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target
source = E:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
1.8.0_31 (Oracle Corporation 25.31-b07)
All projects evaluated.
No tasks specified. Using project default tasks 'echoProp'
Selected primary task 'echoProp' from project :
Tasks to be executed: [task ':copyWar', task ':echoProp']
Creating new cache for resourceHashesCache, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\fileHashes\resourceHashesCache.bin, access org.gradle.cache.internal.DefaultCacheAccess@6e59e113
Creating new cache for taskHistory, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\4.3.1\taskHistory\taskHistory.bin, access org.gradle.cache.internal.DefaultCacheAccess@1e64a7a6
Creating new cache for outputFiles, path E:\environments\GRADLE_TEST\TEST\TESTDEPLOY\source\72\.gradle\buildOutputCleanup\outputFiles.bin, access org.gradle.cache.internal.DefaultCacheAccess@4faa606d
:copyWar (Thread[Daemon worker Thread 15,5,main]) started.
:copyWar
Putting task artifact state for task ':copyWar' into context took 0.0 secs.
Skipping task ':copyWar' as it has no source files and no previous output files.
:copyWar NO-SOURCE
:copyWar (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.002 secs.
:echoProp (Thread[Daemon worker Thread 15,5,main]) started.
:echoProp
Skipping task ':echoProp' as it has no actions.
:echoProp UP-TO-DATE
:echoProp (Thread[Daemon worker Thread 15,5,main]) completed. Took 0.004 secs.

also, the source and target variables from my Gradle.properties:

source=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/source/72
target=E\:/environments/GRADLE_TEST/TEST/TESTDEPLOY/target

I'm completely new to Gradle, so I'm not sure what this all means.


问:
Compute the square root of 3 in C++
How can I compute the square root of 3 in C++ using the following relation?

Here is what I tried:

```<code>#include <iostream>
#include <cmath>

int main(void)
{
    double prevRes(1);
    double res(1 + 1./2);
    short i(2);

    while (abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;

        res = i + 1 / res;

        i = 3 - i;
    }

    std::cout << res << std::endl;

    return 0;
}
</code>```

The program runs forever.

答:
```<code>double sqrt_of_three(bool adds_two, int rec_depth, int max_rec_depth)
{
    int x;
    if (rec_depth < 2)
        x =  1;
    else
        x = adds_two ? 2 : 1;
    if (rec_depth < max_rec_depth)
        return x + 1/sqrt_of_three(!adds_two, ++rec_depth, max_rec_depth);
    return x;
}
</code>```

And this method can be called with an estimate for a threshold.

```<code>int main()
{
    std::cout << sqrt_of_three(true, 0, 10);
}
</code>```

This is an example how to recursively call a function that calculates the square root of 3. Now you can either manually set the maximum recursion depth by trial and error or you do something that you did with your first approach and check after each complete recursion if the value between two different maximum recursion depths is smaller than some threshold.

It's for sure not the most efficient way to find the square root of three because you have to do n*(n-1)/2 (where n is the recursion depth that satisfied the boundary that you set) recursions in total and depending on how close you want to converge to the real result this can be a lot.

Title: Compute the square root of 3 in C++

Body:
How can I compute the square root of 3 in C++ using the following relation?

Here is what I tried:

#include <iostream>
#include <cmath>

int main(void)
{
    double prevRes(1);
    double res(1 + 1./2);
    short i(2);

    while (abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;

        res = i + 1 / res;

        i = 3 - i;
    }

    std::cout << res << std::endl;

    return 0;
}

The program runs forever.

Body:
double sqrt_of_three(bool adds_two, int rec_depth, int max_rec_depth)
{
    int x;
    if (rec_depth < 2)
        x =  1;
    else
        x = adds_two ? 2 : 1;
    if (rec_depth < max_rec_depth)
        return x + 1/sqrt_of_three(!adds_two, ++rec_depth, max_rec_depth);
    return x;
}

And this method can be called with an estimate for a threshold.

int main()
{
    std::cout << sqrt_of_three(true, 0, 10);
}

This is an example how to recursively call a function that calculates the square root of 3. Now you can either manually set the maximum recursion depth by trial and error or you do something that you did with your first approach and check after each complete recursion if the value between two different maximum recursion depths is smaller than some threshold.

It's for sure not the most efficient way to find the square root of three because you have to do n*(n-1)/2 (where n is the recursion depth that satisfied the boundary that you set) recursions in total and depending on how close you want to converge to the real result this can be a lot.


问:
Why is using a for loop faster than apply, in computing the norm of all rows/columns of a matrix?
Consider the following

```<code>n <- 10^4
p <- 2
foo <- matrix(runif(p*n), n, p)
</code>```

I would like to compute the norm of each row of the matrix, i.e., to compute sqrt(crossprod(a_i)) where a_i is the i-th row of foo. I can do this with apply, or with a for loop:

```<code>for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
    }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}
</code>```

I thought the simpler apply code would be faster, however:

```<code>> microbenchmark(for_loop(foo), use_apply(foo), times = 1000)
Unit: milliseconds
           expr      min       lq     mean   median       uq      max neval
  for_loop(foo) 16.07111 18.87690 24.25369 20.78997 27.66441 179.8374  1000
 use_apply(foo) 24.77948 29.05891 35.98689 31.89625 40.30085 205.1632  1000
</code>```

note that times = 1000 can take quite a bit of time, if you don't have a fast machine you may want to use microbenchmark defaults. Why is apply slower than the for loop code? Is there some function from purrr which would be faster?

EDIT I couldn't believe that crossprod(x) would be so much slower than sum(x*x), so I wanted to check Emmanuel-Lin's results. I get very different timings:

```<code>my_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(sum((x[i,] *x[i,])))
    }
  foo
}

my_apply <- function(x){
  apply(x, 1, function(r) sqrt(sum(r*r)))
}

for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
  }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}
> microbenchmark(for_loop(foo), my_loop(foo), use_apply(foo), my_apply(foo))
Unit: milliseconds
           expr       min       lq     mean   median       uq       max neval
  for_loop(foo) 16.299758 17.77176 21.59988 19.04428 22.44558 131.33819   100
   my_loop(foo)  9.950813 12.02106 14.43540 12.66142 15.26865  45.42030   100
 use_apply(foo) 25.480019 27.95396 31.98351 29.85244 36.41599  60.88678   100
  my_apply(foo) 13.277354 14.98329 17.60356 15.98103 19.70325  34.07097   100
</code>```

ok, my_apply and my_loop are faster (I still can't believe it! What, is crossprod optimized for slowness? :-/) but not so faster as Emmanuel-lin found. It's probably related to some dimension congruence checks which crossprod performs.

答:
To complete @LyzandeR answer on RAM.

You can perform computation way faster by coding your self the multiplication:

Repalce crossprod by sum(r * r)

```<code>my_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(sum(x[i,] * x[i,]))
  }
  foo
}

my_sapply <- function(x){
  apply(x, 1, function(r) sqrt(sum(r * r)))
}

microbenchmark(for_loop(X),
               use_apply(X),
               my_loop(X),
               my_sapply(X),
               times = 100)
</code>```

And the results:

```<code>Unit: milliseconds
         expr       min        lq      mean    median        uq       max neval
  for_loop(X) 122.45210 145.67150 179.84469 177.63446 199.10468 460.73182   100
 use_apply(X) 141.99250 169.11596 198.82019 198.11953 223.50906 296.94566   100
   my_loop(X)  10.38776  11.61263  16.47609  14.24066  19.07957  58.50008   100
 my_sapply(X)  13.21431  15.32081  23.23124  18.39573  26.08099 222.57685   100
</code>```

So it is more than 10 times faster!

Also you can notice than your machine is way faster than mine :/

Body:
Consider the following

n <- 10^4
p <- 2
foo <- matrix(runif(p*n), n, p)

I would like to compute the norm of each row of the matrix, i.e., to compute sqrt(crossprod(a_i)) where a_i is the i-th row of foo. I can do this with apply, or with a for loop:

for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
    }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}

I thought the simpler apply code would be faster, however:

> microbenchmark(for_loop(foo), use_apply(foo), times = 1000)
Unit: milliseconds
           expr      min       lq     mean   median       uq      max neval
  for_loop(foo) 16.07111 18.87690 24.25369 20.78997 27.66441 179.8374  1000
 use_apply(foo) 24.77948 29.05891 35.98689 31.89625 40.30085 205.1632  1000

note that times = 1000 can take quite a bit of time, if you don't have a fast machine you may want to use microbenchmark defaults. Why is apply slower than the for loop code? Is there some function from purrr which would be faster?

EDIT I couldn't believe that crossprod(x) would be so much slower than sum(x*x), so I wanted to check Emmanuel-Lin's results. I get very different timings:

my_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(sum((x[i,] *x[i,])))
    }
  foo
}

my_apply <- function(x){
  apply(x, 1, function(r) sqrt(sum(r*r)))
}

for_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(crossprod(x[i,]))
  }
  foo
}

use_apply <- function(x){
  apply(x, 1, function(r) sqrt(crossprod(r)))
}
> microbenchmark(for_loop(foo), my_loop(foo), use_apply(foo), my_apply(foo))
Unit: milliseconds
           expr       min       lq     mean   median       uq       max neval
  for_loop(foo) 16.299758 17.77176 21.59988 19.04428 22.44558 131.33819   100
   my_loop(foo)  9.950813 12.02106 14.43540 12.66142 15.26865  45.42030   100
 use_apply(foo) 25.480019 27.95396 31.98351 29.85244 36.41599  60.88678   100
  my_apply(foo) 13.277354 14.98329 17.60356 15.98103 19.70325  34.07097   100

ok, my_apply and my_loop are faster (I still can't believe it! What, is crossprod optimized for slowness? :-/) but not so faster as Emmanuel-lin found. It's probably related to some dimension congruence checks which crossprod performs.

Body:
To complete @LyzandeR answer on RAM.

You can perform computation way faster by coding your self the multiplication:

Repalce crossprod by sum(r * r)

my_loop <- function(x){
  range <- seq_along(x[,1])
  foo <- range
  for (i in range){
    foo[i] <- sqrt(sum(x[i,] * x[i,]))
  }
  foo
}

my_sapply <- function(x){
  apply(x, 1, function(r) sqrt(sum(r * r)))
}

microbenchmark(for_loop(X),
               use_apply(X),
               my_loop(X),
               my_sapply(X),
               times = 100)

And the results:

Unit: milliseconds
         expr       min        lq      mean    median        uq       max neval
  for_loop(X) 122.45210 145.67150 179.84469 177.63446 199.10468 460.73182   100
 use_apply(X) 141.99250 169.11596 198.82019 198.11953 223.50906 296.94566   100
   my_loop(X)  10.38776  11.61263  16.47609  14.24066  19.07957  58.50008   100
 my_sapply(X)  13.21431  15.32081  23.23124  18.39573  26.08099 222.57685   100

So it is more than 10 times faster!

Also you can notice than your machine is way faster than mine :/


问:
Can Laravel using join table to get data?
Just some random thought, can laravel using join table rather than using eloquent relationship. Because most of answers that i read in here suggest to using relationship like belongstoMany, belongsto and other eloquent relationship. If can, it should be nice if u guys giving me some sample code about how to do that. Sorry for the silly question. Thank you</p>

答: The Laravel query builder supports almost all SQL sentences, you can see all available methods here https://laravel.com/docs/5.5/queries</p>


问:
When is the timestamp set in MySQL binlogs
I've had a search through previous questions but can't find an exact match to my question:

At what point during a query transaction is the binary log timestamp set and then written to the binary log?

Context: I have been working with a DB which is using master/slave replication. Quite often the slave will fall behind the master server and I am certain is it simply due to there being a lot of transactions in the binary log that share the same timestamp. When I say a lot I am talking about over 150 timestamps belonging to over 9000 entries in a 1 hour log (plus the rest that returned under 9000 entries). This was found using:

```<code>mysqlbinlog bin-log.0001 | grep 'TIMESTAMP' | uniq -c | awk '{if ($1>9000){print $0}} ' | sed -e 's/\/\*\!\*\/;//g' | gawk -F '=' '{cmd="date -d @"$2; cmd | getline d; print $1"="$2"\t("d")"; close(d)}'
</code>```

So I'm basically trying to workout if the number of transactions sharing a timestamp is a reflection of workload on the master server, and whether these numbers are unusual.

When graphing the Second_behind_master it shows linear growth and then a sudden drop off which seems to suggest the same thing.

MySQL version is 5.6.33.

答:
There are a number possible reasons for 'slave lag' which would be hard to answer in detail here. The binary log timestamp is written at the start of the transaction.

There is a useful post that walks through how to identify the cause of your symptoms here: https://www.percona.com/blog/2014/05/02/how-to-identify-and-cure-mysql-replication-slave-lag/ For example, it explains how the Seconds_Behind_Master parameter can be misleading, because it only measures the difference between the timestamps of the relay log most recently executed, versus the relay log entry most recently downloaded by the IO_THREAD.

You'll find many other resources on the site that might help you. This includes the Percona Toolkit, mentioned in the blog post which, like ALL Percona software is entirely free of charge, and open source.

Disclosure: I work for Percona.

Body:
I've had a search through previous questions but can't find an exact match to my question:

At what point during a query transaction is the binary log timestamp set and then written to the binary log?

Context: I have been working with a DB which is using master/slave replication. Quite often the slave will fall behind the master server and I am certain is it simply due to there being a lot of transactions in the binary log that share the same timestamp. When I say a lot I am talking about over 150 timestamps belonging to over 9000 entries in a 1 hour log (plus the rest that returned under 9000 entries). This was found using:

mysqlbinlog bin-log.0001 | grep 'TIMESTAMP' | uniq -c | awk '{if ($1>9000){print $0}} ' | sed -e 's/\/\*\!\*\/;//g' | gawk -F '=' '{cmd="date -d @"$2; cmd | getline d; print $1"="$2"\t("d")"; close(d)}'

So I'm basically trying to workout if the number of transactions sharing a timestamp is a reflection of workload on the master server, and whether these numbers are unusual.

When graphing the Second_behind_master it shows linear growth and then a sudden drop off which seems to suggest the same thing.

MySQL version is 5.6.33.


问:
Media query about screen size instead of resolution
Is there a workaround to use physical screen width in CSS media queries? Today, there are phones which exceed the resolution of desktop monitors. However, phones should still display the mobile layout and desktops the standard layout.

So I can't rely on pixel based queries like the example below. Instead, I need either a physical measurement, or one about the pixel density.

```<code>@media screen and (min-width: 700px) {

}
</code>```

Since I haven't found such measurements through my research, they might not exist. Anyway, how is this problem approached typically?

答:
Media queries like @media screen and (min-width: 700px) and window.innerWidth use css pixels. At first when mobile devices were really 320px, css pixels and real pixels were the same. Now new devices with 800px and the same size still report 320 css pixels.

And that is really good for designing backwards-compatible websites. Essentially @media screen and (max-width: 480px) can be translated to: Small, taking into account eyes to screen distance, and screen size (in meters not pixels).

So the css pixel acts as a reference measure more than anything else.

Real pixels, dpi, screen type and orientation can or will be available with media queries. But it could be an anti-pattern to use those.

Also don't forget viewport meta tag.

Body:
Is there a workaround to use physical screen width in CSS media queries? Today, there are phones which exceed the resolution of desktop monitors. However, phones should still display the mobile layout and desktops the standard layout.

So I can't rely on pixel based queries like the example below. Instead, I need either a physical measurement, or one about the pixel density.

@media screen and (min-width: 700px) {

}

Since I haven't found such measurements through my research, they might not exist. Anyway, how is this problem approached typically?


问:
How to pass parameters for method call in controller from gsp?
I am calling a method located in the controller from my gsp file. The method in question has a parameter that need be filled.

The following is currently how I have it and does not work.

```<code><g:each in="${msdsLinkList}" status="i" var="msdsLink">
  <div id="msdsBox${i}" class="msdsBox">
    <g:link class="word-button" action="exportAttachment(msdsLink${i})"></g:link>
  </div>
</g:each>
</code>```

How can I pass msdsLink${i} in to the exportAttachment method?

答:
Try

```<code><g:each in="${msdsLinkList}" status="i" var="msdsLink">
  <div id="msdsBox${i}" class="msdsBox">
    <g:link class="word-button" action="exportAttachment" id="${msdsLink.id}"></g:link>
  </div>
</g:each>
</code>```

In your controller, you can retrieve the passed in value as

```<code>params.id
</code>```

Body:
I am calling a method located in the controller from my gsp file. The method in question has a parameter that need be filled.

The following is currently how I have it and does not work.

<g:each in="${msdsLinkList}" status="i" var="msdsLink">

    <g:link class="word-button" action="exportAttachment(msdsLink${i})"></g:link>

</g:each>

How can I pass msdsLink${i} in to the exportAttachment method?

Body:
Try

<g:each in="${msdsLinkList}" status="i" var="msdsLink">
  <div id="msdsBox${i}" class="msdsBox">
    <g:link class="word-button" action="exportAttachment" id="${msdsLink.id}"></g:link>
  </div>
</g:each>

In your controller, you can retrieve the passed in value as

params.id


问:
Typescript: Overloading generic methods
How is the best wat to translate these Java method signatures to typescript:</p>

```<code>public <E> Expression<E> setProjection(Expression<E> e) {
   //return ...
}

public Expression<?> setProjection(Expression<?>... o) {
    for (Expression<?> e : o)
        this.setProjection(Projections.tuple(o));
    return //...
}
</code>```

答:
In TypeScript you can satisfy both with a single method signature (if I'm interpreting things right)...

```<code>public setProjection<E>(...e: Expression<E>[]): Expression<E> {
</code>```

You can call this with one expression, or many expressions. You can test the length of e if you want to know whether you were passed one, or more than one.

If you don't care about E, you can make it dynamic, using setProjection<any>.

Additional note: overloads in TypeScript all decorate a single method... this leads you to a single implementation... which leads you to not overloading as the signature works each way. The overload would have looked like:

```<code>public setProjection<E>(e: Expression<E>): Expression<E>;
public setProjection<E>(...e: Expression<E>[]): Expression<E>;
public setProjection<E>(...e: Expression<E>[]): Expression<E> {
</code>```

But it would be identical to the non-overloaded version.

I haven't covered the implementation details of the method as the question is on the overloading aspect.

Title: Typescript: Overloading generic methods

Body:
How is the best wat to translate these Java method signatures to typescript:

public <E> Expression<E> setProjection(Expression<E> e) {
   //return ...
}

public Expression<?> setProjection(Expression<?>... o) {
    for (Expression<?> e : o)
        this.setProjection(Projections.tuple(o));
    return //...
}

Body:
In TypeScript you can satisfy both with a single method signature (if I'm interpreting things right)...

public setProjection<E>(...e: Expression<E>[]): Expression<E> {

You can call this with one expression, or many expressions. You can test the length of e if you want to know whether you were passed one, or more than one.

If you don't care about E, you can make it dynamic, using setProjection<any>.

Additional note: overloads in TypeScript all decorate a single method... this leads you to a single implementation... which leads you to not overloading as the signature works each way. The overload would have looked like:

public setProjection<E>(e: Expression<E>): Expression<E>;
public setProjection<E>(...e: Expression<E>[]): Expression<E>;
public setProjection<E>(...e: Expression<E>[]): Expression<E> {

But it would be identical to the non-overloaded version.

I haven't covered the implementation details of the method as the question is on the overloading aspect.


问:
Autocomplete on Combobox onkeypress event eats up the Enter key
I have a ComboBox with AutoCompleteMode = suggest and handle the KeyPress event like so:

```<code>private void searchBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Return)
    {
        // do stuff
    }
}
</code>```

However, it does not catch the Enter key. It catches everything else since the autocomplete dropdown works perfectly.

I also tried the suggestion offered here : http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/2db0b540-756a-4a4f-9371-adbb92409806, set the form's KeyPreview property to true and put a breakpoint in the form's KeyPress event handler:

```<code>private void Form_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = false;
}
</code>```

However, even the form's handler was not catching the enter key!

Any suggestions?

(If I disable the autocomplete, it catches the Enter key)

答:
Difference between KeyDown and KeyPress

In your case the best you may do is use KeyDown event.

```<code>void SearchBox_KeyDown(object sender, KeyEventArgs e)
{
   if(e.KeyCode == Keys.Enter)
    {
        // Do stuff
    }
}
</code>```

Another interesting thing about KeyPress event is: it even catches Enter key with autocompete on if the combobox has no items! :-)

ContentLicense: CC BY-SA 2.5

Body:
I have a ComboBox with AutoCompleteMode = suggest and handle the KeyPress event like so:

private void searchBox_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Return)
    {
        // do stuff
    }
}

However, it does not catch the Enter key. It catches everything else since the autocomplete dropdown works perfectly.

I also tried the suggestion offered here : http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/2db0b540-756a-4a4f-9371-adbb92409806, set the form's KeyPreview property to true and put a breakpoint in the form's KeyPress event handler:

private void Form_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = false;
}

However, even the form's handler was not catching the enter key!

Any suggestions?

(If I disable the autocomplete, it catches the Enter key)

Body:
Difference between KeyDown and KeyPress

In your case the best you may do is use KeyDown event.

void SearchBox_KeyDown(object sender, KeyEventArgs e)
{
   if(e.KeyCode == Keys.Enter)
    {
        // Do stuff
    }
}

Another interesting thing about KeyPress event is: it even catches Enter key with autocompete on if the combobox has no items! :-)


问:
Angular application styling
I am building an application with Angular and bootstrap in the front-end, basically I have a Landing page, login and dashboard after logged.

The question is about how to handle the style sheets between the application. The land page and the dashboard have styles completely distinct. The Landing page looks like this and the dashboard looks like this image.

I've made different css files to handle each part of the application and now I am trying to join in the Angular app, but if I add those css files in the styles array in angular-cli.json, the angular will add both in the index and I will have some class conflict and the file from the dashboard on the landing and vice versa.

I'll appreciate any help to handle this situation.

答:
Normally your components will be like

```<code>@Component({
  selector: 'app-component-uno',
  templateUrl: './app-component-uno.html',
  styleUrls:['./app-component-uno.css'] //<--this
}.....)
</code>```

The css is belong to the component.there are no conflict. The only way that you hace a conflict is if you use encapsulation: ViewEncapsulation.None,

Title: Angular application styling

Body:
Normally your components will be like

@Component({
  selector: 'app-component-uno',
  templateUrl: './app-component-uno.html',
  styleUrls:['./app-component-uno.css'] //<--this
}.....)

The css is belong to the component.there are no conflict. The only way that you hace a conflict is if you use encapsulation: ViewEncapsulation.None,


答:
The formula seems a bit wrong if I compare it to wikipedia. Note the 1 + is repeated at the start.

Next we can use a recursive function to perform the calculation and provide a number of iterations. Note that we can use a large return value to terminate the recursion (or even zero, but that would require more iterations as it is technically making the wrong assumption).

Finally we keep trying more iterations until the error is small enough.

```<code>#include <iostream>
#include <limits>
#include <cmath>

double f(int depth, bool odd = true)
{
    if(depth == 0)
        return std::numeric_limits<double>::max();
    return (odd ? 1 : 2) + 1. / f(--depth, !odd);
}

double sqrt3(int depth = 10)
{
    return 1 + 1. / f(depth);
}

int main(void)
{
    int depth{2};
    double prevRes{sqrt3(depth)};
    double res{sqrt3(++depth)};
    while(abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;
        res = sqrt3(++depth);
    }

    std::cout << "Answer is " << res << " at depth " << depth << ".\n";
}
</code>```

Output:

```<code>Answer is 1.73205 at depth 26.
</code>```

Title: Compute the square root of 3 in C++

Body:
The formula seems a bit wrong if I compare it to wikipedia. Note the 1 + is repeated at the start.

Next we can use a recursive function to perform the calculation and provide a number of iterations. Note that we can use a large return value to terminate the recursion (or even zero, but that would require more iterations as it is technically making the wrong assumption).

Finally we keep trying more iterations until the error is small enough.

#include <iostream>
#include <limits>
#include <cmath>

double f(int depth, bool odd = true)
{
    if(depth == 0)
        return std::numeric_limits<double>::max();
    return (odd ? 1 : 2) + 1. / f(--depth, !odd);
}

double sqrt3(int depth = 10)
{
    return 1 + 1. / f(depth);
}

int main(void)
{
    int depth{2};
    double prevRes{sqrt3(depth)};
    double res{sqrt3(++depth)};
    while(abs(prevRes - res) > 1.e-14)
    {
        prevRes = res;
        res = sqrt3(++depth);
    }

    std::cout << "Answer is " << res << " at depth " << depth << ".\n";
}

Output:

Answer is 1.73205 at depth 26.


问:
How to remote debug a Spring Cloud Data flow Task
We are using Spring XD for executing some batch jobs and considering to use Spring Cloud Dataflow. For this I wanted to remote debug a execution of a Task and I was not able to make it working.

I tried to export the following environment variable before the SCDF server is started:

```<code>spring.cloud.deployer.local.javaOpts=Xdebug -Xrunjdwp:transport=dt_socket,address=12201,server=y
</code>```

Also tried to pass as argument in the GUI while invoking the task:

```<code>app.<appname>.local.javaOpts=Xdebug -Xrunjdwp:transport=dt_socket,address=12201,server=y
</code>```

Nothing seems to be working.

答:
I'm able to debug the  composed-task-runner launched by SCDF  using the listen debugger mode, this will also work for your task as well.

Run Debugger in your IDE in listen mode on port 5006. (this project's classpath  should have composed-task-runner sources, put break point  some where )

Run SCDF with -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 option, attach debugger to the SCDF process in your IDE on port 5005 (attach mode).

Put breakpoint at this line :

String javaOptsString = getValue(deploymentProperties, "javaOpts");

in JavaCommandBuilder class (for spring-cloud-deployer-local v.1.3.0.M2 it's line #83).

Launch your task - debugger stops at breakpoint.

Step Over once in your IDE, the value of javaOptsString is null now. Using IDE, set the value of javaOptsString to

-agentlib:jdwp=transport=dt_socket,server=n,address=localhost:5006,suspend=y

Press Resume in IDE.

Your breakpoint set in #1 should be hit in few seconds.

If you know how to pass javaOpts as deployment properties of your task - you will be able to debug in listen mode without  this nightmare ;-). I've not found a way to escape = and , characters in the -agentlib:jdwp=transport=dt_socket,server=n,address=localhost:5006,suspend=y javaOpts deployment property.

Body:
We are using Spring XD for executing some batch jobs and considering to use Spring Cloud Dataflow. For this I wanted to remote debug a execution of a Task and I was not able to make it working.

I tried to export the following environment variable before the SCDF server is started:

spring.cloud.deployer.local.javaOpts=Xdebug -Xrunjdwp:transport=dt_socket,address=12201,server=y

Also tried to pass as argument in the GUI while invoking the task:

app.<appname>.local.javaOpts=Xdebug -Xrunjdwp:transport=dt_socket,address=12201,server=y

Nothing seems to be working.


问:
Cant build collider (websocket-based signaling server in Go)
Iam trying to build apprtc signaling server(collider).  Based on tutorial, we only need to enter

go get collidermain

after setting $GOPATH. But I got error like this

```<code> > go get collider/collidermain
src/collider/collidermain/main.go:9:2: no buildable Go source files in /home/abdulmanaf/poc/apprtcNewVersion/apprtc/src/collider
</code>```

Then I had tried to build collider folder. But I got error like this

```<code>> go get collider/collider
# golang.org/x/net/websocket
src/golang.org/x/net/websocket/dial.go:18:19: error: reference to undefined identifier ‘tls.DialWithDialer’
   conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig)
</code>```

What is the actual issue related to this? I need to build and deploy collider application

答:
Sounds like you're using a really old version of go. Could you run go version?

tls.DialWithDialer was added in go 1.3 in 2014.

Body:
Iam trying to build apprtc signaling server(collider).  Based on tutorial, we only need to enter

go get collidermain

after setting $GOPATH. But I got error like this

 > go get collider/collidermain
src/collider/collidermain/main.go:9:2: no buildable Go source files in /home/abdulmanaf/poc/apprtcNewVersion/apprtc/src/collider

Then I had tried to build collider folder. But I got error like this

> go get collider/collider
# golang.org/x/net/websocket
src/golang.org/x/net/websocket/dial.go:18:19: error: reference to undefined identifier ‘tls.DialWithDialer’
   conn, err = tls.DialWithDialer(dialer, "tcp", parseAuthority(config.Location), config.TlsConfig)

What is the actual issue related to this? I need to build and deploy collider application


问:
How can I multiply two Eigen::DiagonalMatrix and ad the result to an Eigen::SparseMatrix?
I'm trying to write a solver for a linear system, and coming from Matlab/NumPy and the like, I find Eigen's types a bit limited.

My current issue resolves around this:

```<code>D * DD + S
</code>```

Where D and DD are of type Eigen::DiagonalMatrix<double, Eigen::Dynamic, Eigen::Dynamic> and S is an Eigen::SparseMatrix`.

Is there an (efficient) way to do this? It seems rather basic so I must be missing something. I'm willing to give up D and DD being DiagonalMatrix and them being SparseMatrix instead, as long as the above expression is complicated too much.

答:
Assuming the sparse matrix S already has non-zero coefficients along the diagonal you can do:

```<code>S.diagonal() += D.cwiseProduct(DD);
</code>```

Body:
I'm trying to write a solver for a linear system, and coming from Matlab/NumPy and the like, I find Eigen's types a bit limited.

My current issue resolves around this:

D * DD + S

Where D and DD are of type Eigen::DiagonalMatrix<double, Eigen::Dynamic, Eigen::Dynamic> and S is an Eigen::SparseMatrix`.

Is there an (efficient) way to do this? It seems rather basic so I must be missing something. I'm willing to give up D and DD being DiagonalMatrix and them being SparseMatrix instead, as long as the above expression is complicated too much.

Body:
Assuming the sparse matrix S already has non-zero coefficients along the diagonal you can do:

S.diagonal() += D.cwiseProduct(DD);


问:
My react multiselect keeps expanding as i add the options

I am using react select module to construct a multi-select dropbox. however as i add more than one option, the box keeps expanding, I want it to remain fixed. What css property should I change or is there another way to do this. Refer the pictures to get a clear understanding.

My form inline code for select:

```<code><FormGroup
        controlId="ChannelType"
      >

        <div style={this.selectwidth}>
          <Select
            closeOnSelect={!stayOpen}
            multi={true}
            onChange={this.handleChannelSelect.bind(this)}
            options={ChannelTypes}
            placeholder="Select"
            removeSelected={false}
            simpleValue
          />
        </div>
        {' '}

      </FormGroup>
</code>```

link for css of react-select :link

答:
Set autosize prop to false

Link: https://www.npmjs.com/package/react-select#select-props

Body:
I am using react select module to construct a multi-select dropbox. however as i add more than one option, the box keeps expanding, I want it to remain fixed. What css property should I change or is there another way to do this. Refer the pictures to get a clear understanding.

My form inline code for select:

<FormGroup
        controlId="ChannelType"
      >

          <Select
            closeOnSelect={!stayOpen}
            multi={true}
            onChange={this.handleChannelSelect.bind(this)}
            options={ChannelTypes}
            placeholder="Select"
            removeSelected={false}
            simpleValue
          />

        {' '}

      </FormGroup>

link for css of react-select :link


问:
How do I add a sum with a limit?
I have looked around in stack overflow but nothing really helped me further.. So I hoped someone could answer my question/help directly.
I can't seem add a sum and this with a limit.
I want to get the average result for every week (sum with a limit basically).

```<code><form action="inft.php" method="POST">
    <button type="submit" name="asubmit">Average</button>
</form>

<?php

    include_once 'dbh.inc.php';

    $dpl = $db->query("SELECT SUM(`gewicht`) as `total` FROM bgewicht");

    $row = $dpl->fetch_assoc();

    echo $row['total'];

?>
</code>```

My apologies if this question was asked somewhere before, my apologies for my ignorance too. I just started programming.

With kind regards,

D.

答:
```<code>$dpl = $db->query("SELECT SUM(`gewicht`)
 FROM (SELECT gewicht
  FROM bgewicht
  ORDER BY gewicht DESC
  LIMIT 3
) as `total` FROM bgewicht");
</code>```

Title: How do I add a sum with a limit?

Body:
I have looked around in stack overflow but nothing really helped me further.. So I hoped someone could answer my question/help directly.
I can't seem add a sum and this with a limit.
I want to get the average result for every week (sum with a limit basically).

<form action="inft.php" method="POST">
    <button type="submit" name="asubmit">Average</button>
</form>

<?php

    include_once 'dbh.inc.php';

    $dpl = $db->query("SELECT SUM(`gewicht`) as `total` FROM bgewicht");

    $row = $dpl->fetch_assoc();

    echo $row['total'];

?>

My apologies if this question was asked somewhere before, my apologies for my ignorance too. I just started programming.

With kind regards,

D.


问:
How to use WCF service
We have 2 projects in our company, the 2nd calls the 1st through the WCF service that is hosted by ASP.NET web site.

My idea was to deploy asp.net with hosted WCF service and the 2nd team will add 'service reference' to their project. and using auto-generated classes will instantiate client for service and call its methods.

But, they insist me to create a DLL that will contains a interface (contract) implemented by WCF service and they will add reference to those DLL. And only using this interface from dll they are going to communicate.

What is a correct approach for 'consuming' WCF service?

P.S. I've read a lot about how to consume/host WCF service, but still can see a best approach for that.

P.P.S. We are working under VS 2008, .NET 3.5, but ideas for VS2010 and .NET 4.0 are also welcome.

答:
It is trivial to generate a client proxy dll for 2nd team. Use the svcutil command line tool in windows SDK to generate a proxy class and then use msbuild to build a proxy dll. This can even be automated in your build process and the dll is dropped to a known shared location on each build.

That said this is not best practice for SOA as for SOA the WSDL should define the interface and that is what you should provide to 2nd team. This can be via an url or as a file drop.

Title: How to use WCF service


问:
Footer at bottom of page OR below content, whichever is lower
I have looked and looked, and can't find a solution to this that works (have tried LOTS!).  I have a fixed header, and two columns that I want to expand with content, but want to appear full height if low on content.  Then a footer that I want to appear either below the content (when lots) or at the bottom of the page.  With the below HTML/CSS, the footer appears just off the viewscreen, but even worse, for some reason if I have enough text to push off the screen, my footer disappears!!

Edited:  I figured it out.  Yay!!  on to next step.

HTML - EDITED

```<code>    <header>
    <div class="fixed-top">
        <div style="height: 10px; background: #27AAE1;"></div>
        <div id="Top_Bar" class="row">
            <div class="col-sm-2">
                <a><img src="images/nmdlogo.png" height=80px;></a>
            </div>
            <div class="col-sm-10">
            <h1 "text-align=center";>Admin Panel</h1>
            </div>
        </div>
        <div style="height: 10px; background: #27AAE1;"></div>
    </div>
</header>

<main class="Site-content">
    <div class="container-fluid h-100">
        <div class="row h-100">
            <div id="Menu_Panel" class="col-sm-2"><!-- Left Side Menu Area  -->
            Menu
            </div><!-- End of col-sm-2 Left Side Menu Area -->

            <div id="Main_Panel" class="col-sm-10"><!-- Main Area -->
            Main Panel<br>
            </div><!-- End col-sm-10 Main Area -->
        </div><!-- End of Row -->
    </div><!-- End of Container -->
</main>

<footer>

            <div class="customHr"></div>
            <div class="col-sm-10 offset-sm-2">
                <span>Text Here</span><br>
                <a style="color: white; text-decoration: none; cursor: pointer; font-weight: bold;" href="#">Link Name</a>
            </div>
            <div class="customHr"></div>
            <div style="height: 10px; background: #27AAE1;"></div>

</footer>
</code>```

CSS - EDITED

```<code>.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
  background-color: #2f4050;
}

.Site-content {
  flex: 1;
  margin-top: 120px;
}
#Menu_Panel{
    background-color: #d10e1e;
}
#Main_Panel{
    background-color: #ffffff;
}

#Top_Bar{
    text-align: center;
    color:#ffffff;
    img-align: center;
    background-color: #2f4050;
    padding-top: 10px;
    padding-bottom: 10px;
}

footer {
    color:#ffffff;
    text-align: center;
}
.customHr {
    border-bottom: 1px solid #9fb1c2;
    margin-top: 10px;
    margin-bottom: 10px;
    font-size: .8em;
    padding-top: 5x;
    padding-bottom: 5px;
}
</code>```

答:
I imagine you're looking for a footer that sticks to the bottom of your page than?
Edited:
Following css (based on your original) should give you what you're looking for

```<code>* {
            margin: 0;
        }

        html {
            height: 100%;
            box-sizing: border-box;
        }

        *,
        *:before,
        *:after {
            box-sizing: inherit;
        }

        body {
            background-color: #2f4050;
            position: relative;
            margin: 0;
            padding-bottom: 6rem;
            min-height: 100%;
        }

        #Menu_Panel {
            background-color: #d10e1e;
            margin-top: 120px;
        }

        #Main_Panel {
            background-color: #ffffff;
            margin-top: 120px;
        }

        #Fixed_Top {
            position: fixed; /* Set the navbar to fixed position */
            top: 0;
        }

        #Top_Bar {
            text-align: center;
            color: #ffffff;
            img-align: center;
            background-color: #2f4050;
            padding-top: 10px;
            padding-bottom: 10px;
        }

        .footer {
            color: #ffffff;
            text-align: center;
            width: 100%;
            position: absolute;
            right: 0;
            bottom: 0;
            left: 0;
        }

        .customHr {
            border-bottom: 1px solid #9fb1c2;
            margin-top: 10px;
            margin-bottom: 10px;
            font-size: .8em;
            padding-top: 5x;
            padding-bottom: 5px;
        }
</code>```

Body:
I have looked and looked, and can't find a solution to this that works (have tried LOTS!).  I have a fixed header, and two columns that I want to expand with content, but want to appear full height if low on content.  Then a footer that I want to appear either below the content (when lots) or at the bottom of the page.  With the below HTML/CSS, the footer appears just off the viewscreen, but even worse, for some reason if I have enough text to push off the screen, my footer disappears!!

Edited:  I figured it out.  Yay!!  on to next step.

HTML - EDITED

Admin Panel

            Menu

            Main Panel

                Text Here

                Link Name

CSS - EDITED

.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
  background-color: #2f4050;
}

.Site-content {
  flex: 1;
  margin-top: 120px;
}
#Menu_Panel{
    background-color: #d10e1e;
}
#Main_Panel{
    background-color: #ffffff;
}

#Top_Bar{
    text-align: center;
    color:#ffffff;
    img-align: center;
    background-color: #2f4050;
    padding-top: 10px;
    padding-bottom: 10px;
}

footer {
    color:#ffffff;
    text-align: center;
}
.customHr {
    border-bottom: 1px solid #9fb1c2;
    margin-top: 10px;
    margin-bottom: 10px;
    font-size: .8em;
    padding-top: 5x;
    padding-bottom: 5px;
}

Body:
I imagine you're looking for a footer that sticks to the bottom of your page than?
Edited:
Following css (based on your original) should give you what you're looking for

* {
            margin: 0;
        }

        html {
            height: 100%;
            box-sizing: border-box;
        }

        *,
        *:before,
        *:after {
            box-sizing: inherit;
        }

        body {
            background-color: #2f4050;
            position: relative;
            margin: 0;
            padding-bottom: 6rem;
            min-height: 100%;
        }

        #Menu_Panel {
            background-color: #d10e1e;
            margin-top: 120px;
        }

        #Main_Panel {
            background-color: #ffffff;
            margin-top: 120px;
        }

        #Fixed_Top {
            position: fixed; /* Set the navbar to fixed position */
            top: 0;
        }

        #Top_Bar {
            text-align: center;
            color: #ffffff;
            img-align: center;
            background-color: #2f4050;
            padding-top: 10px;
            padding-bottom: 10px;
        }

        .footer {
            color: #ffffff;
            text-align: center;
            width: 100%;
            position: absolute;
            right: 0;
            bottom: 0;
            left: 0;
        }

        .customHr {
            border-bottom: 1px solid #9fb1c2;
            margin-top: 10px;
            margin-bottom: 10px;
            font-size: .8em;
            padding-top: 5x;
            padding-bottom: 5px;
        }


问:
Compiling with Babel: Is a preset-flag necessary when having a .babelrc-file?
I have learned and used the following syntax for compiling JavaScript-files using Babel:

```<code>babel main.js -o bundle.js --presets es2015
</code>```

I haven't known about the existence of .babelrc-files until today.

Now my question ...

If I have a .babelrc-file with the following content:

```<code>{
    "presets": ["es2015"]
}
</code>```

Is the ' --preset es2015 ' flag still necessary when compiling from the command  line?

Or can I leave it? Just having ' babel main.js -o bundle.js '?
And Babel takes the further configuration out of the .babelrc-file?

答: All .babelrc options are passed to the Babel API. You can safely ignore the command line parameters if the .babelrc is in the working directory when you're running the babel command.

Body:
I have learned and used the following syntax for compiling JavaScript-files using Babel:

babel main.js -o bundle.js --presets es2015

I haven't known about the existence of .babelrc-files until today.

Now my question ...

If I have a .babelrc-file with the following content:

{
    "presets": ["es2015"]
}

Is the ' --preset es2015 ' flag still necessary when compiling from the command  line?

Or can I leave it? Just having ' babel main.js -o bundle.js '?
And Babel takes the further configuration out of the .babelrc-file?


问:
How to fill web form using javascript
I want to fill the form data using javascript in chrome. I have filled all other fields correctly but the field(html) bellow is not working for me. (there must be other scripts working this form, i don't about that)

```<code><select name="month" class="valid">
<option value="">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Month</font>
    </font>
</option>
<option value="01">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">January</font>
    </font>
</option>
<option value="02">
    <font style="vertical-align: inherit;">
        <font style="vertical-align: inherit;">February</font>
    </font>
</option>
<option value="03">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">March</font>
    </font>
</option>
</code>```

        Month

        January

            February

        March

i have tried some code but it doesn't work.

```<code>var month = document.querySelector('input[name="month"]');
month.selectedIndex = 3;
</code>```

i am using this script in chrome console, is there any way i can fill this field with javascript?

here is the form link

答:
This code does exactly what you looking for. It selects March in your select.
Note: correct selection in not var month = document.querySelector('input[name="month"]'); Use instead

```<code>var month = document.querySelector('select[name="month"]');
</code>```

$(function() {
    var month = document.querySelector('select[name="month"]');
month.selectedIndex = 3;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="month" class="valid">
<option value="">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Month</font>
    </font>
</option>
<option value="01">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">January</font>
    </font>
</option>
<option value="02">
    <font style="vertical-align: inherit;">
        <font style="vertical-align: inherit;">February</font>
    </font>
</option>
<option value="03">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">March</font>
    </font>
</option>
</select></code>```

Title: How to fill web form using javascript

Body:
I want to fill the form data using javascript in chrome. I have filled all other fields correctly but the field(html) bellow is not working for me. (there must be other scripts working this form, i don't about that)

<select name="month" class="valid">
<option value="">
    Month

</option>
<option value="01">
    January

</option>
<option value="02">

        February

</option>
<option value="03">
    March

</option>

        Month

        January

            February

        March

i have tried some code but it doesn't work.

var month = document.querySelector('input[name="month"]');
month.selectedIndex = 3;

i am using this script in chrome console, is there any way i can fill this field with javascript?

here is the form link

Body:
This code does exactly what you looking for. It selects March in your select.
Note: correct selection in not var month = document.querySelector('input[name="month"]'); Use instead

var month = document.querySelector('select[name="month"]');

$(function() {
    var month = document.querySelector('select[name="month"]');
month.selectedIndex = 3;
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="month" class="valid">
<option value="">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">Month</font>
    </font>
</option>
<option value="01">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">January</font>
    </font>
</option>
<option value="02">
    <font style="vertical-align: inherit;">
        <font style="vertical-align: inherit;">February</font>
    </font>
</option>
<option value="03">
    <font style="vertical-align: inherit;"><font style="vertical-align: inherit;">March</font>
    </font>
</option>
</select>


问:
Enter triggers button click
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

```<code>$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})
</code>```

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

答: Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.</p>

ContentLicense: CC BY-SA 4.0

Title: Enter triggers button click

Body:
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.


问:
Can I optimise this further so that it runs faster?
As you can see in the following pprof output, I have these nested for loops which take most of the time of my program. Source is in golang but code is explained below:

```<code>  8.55mins    1.18hrs     20:   for k := range mapSource {
  4.41mins    1.20hrs     21:           if positions, found := mapTarget[k]; found {
         .          .     22:                   // save all matches
  1.05mins   1.05mins     23:                   for _, targetPos := range positions {
  2.25mins   2.33mins     24:                           for _, sourcePos := range mapSource[k] {
     1.28s     15.78s     25:                                   matches = append(matches, match{int32(targetPos), int32(sourcePos)})
         .          .     26:                           }
         .          .     27:                   }
         .          .     28:           }
         .          .     29:   }
</code>```

At the moment the structures I'm using are 2 map[int32][]int32, targetMap and sourceMap.

These maps contain, for a given key, an array of ints. Now I want to find the keys that match in both maps, and save the combinations of the elements in the arrays.

So for example:

```<code>sourceMap[1] = [3,4]
sourceMap[5] = [9,10]

targetMap[1] = [1,2,3]
targetMap[2] = [2,3]
targetMap[3] = [1,2]
</code>```

The only key in common is 1 and the result will be [(3,1), (3,2), (3,3), (4,1), (4,2), (4,3)]

Is there any possible way (a more appropriate data structure or whatever) that could improve the speed of my program?

In my case, maps can contain somewhere between 1000 and 150000 keys, while the arrays inside are usually pretty small.

EDIT: Concurrency is not an option as this is already being run several times in several threads at the same time.

答:
Can I optimise this further so that it runs faster?

Is there any possible way (a more appropriate data structure or
  whatever) that could improve the speed of my program?

Probably.

The XY problem is asking about your
  attempted solution rather than your actual problem. This leads to
  enormous amounts of wasted time and energy, both on the part of people
  asking for help, and on the part of those providing help.

We don't have even the most basic information about your problem, a description of the form, content, and frequency of your original input data, and your desired output. What original data should drive a benchmark?

I created some fictional original data, which produced some fictional output and results:

```<code>BenchmarkPeterSO-4   30    44089894 ns/op    5776666 B/op      31 allocs/op
BenchmarkIvan-4      10   152300554 ns/op   26023924 B/op    6022 allocs/op
</code>```

It is possible that your algorithms are slow.

Body:
As you can see in the following pprof output, I have these nested for loops which take most of the time of my program. Source is in golang but code is explained below:

  8.55mins    1.18hrs     20:   for k := range mapSource {
  4.41mins    1.20hrs     21:           if positions, found := mapTarget[k]; found {
         .          .     22:                   // save all matches
  1.05mins   1.05mins     23:                   for _, targetPos := range positions {
  2.25mins   2.33mins     24:                           for _, sourcePos := range mapSource[k] {
     1.28s     15.78s     25:                                   matches = append(matches, match{int32(targetPos), int32(sourcePos)})
         .          .     26:                           }
         .          .     27:                   }
         .          .     28:           }
         .          .     29:   }

At the moment the structures I'm using are 2 map[int32][]int32, targetMap and sourceMap.

These maps contain, for a given key, an array of ints. Now I want to find the keys that match in both maps, and save the combinations of the elements in the arrays.

So for example:

sourceMap[1] = [3,4]
sourceMap[5] = [9,10]

targetMap[1] = [1,2,3]
targetMap[2] = [2,3]
targetMap[3] = [1,2]

The only key in common is 1 and the result will be [(3,1), (3,2), (3,3), (4,1), (4,2), (4,3)]

Is there any possible way (a more appropriate data structure or whatever) that could improve the speed of my program?

In my case, maps can contain somewhere between 1000 and 150000 keys, while the arrays inside are usually pretty small.

EDIT: Concurrency is not an option as this is already being run several times in several threads at the same time.

Body:
Can I optimise this further so that it runs faster?

Is there any possible way (a more appropriate data structure or
  whatever) that could improve the speed of my program?

Probably.

The XY problem is asking about your
  attempted solution rather than your actual problem. This leads to
  enormous amounts of wasted time and energy, both on the part of people
  asking for help, and on the part of those providing help.

We don't have even the most basic information about your problem, a description of the form, content, and frequency of your original input data, and your desired output. What original data should drive a benchmark?

I created some fictional original data, which produced some fictional output and results:

BenchmarkPeterSO-4   30    44089894 ns/op    5776666 B/op      31 allocs/op
BenchmarkIvan-4      10   152300554 ns/op   26023924 B/op    6022 allocs/op

It is possible that your algorithms are slow.


问:
How do I remove the italics on the words in my navigation bar?
On all the other pages of the website the navigation bar is in normal font but for some reason the font on the home page nav bar is in italics. I've completely forgotten how to make it so it doesn't have italics or where to search to change it so please help

http://surbaisse.com/index.html

```<code>#tabsJ {
  float:left;
  width:100%;
  background:#F4F4F4;
  font-size:93%;
  line-height:normal;
      border-bottom:1px solid #24618E;
  }
#tabsJ ul {
    margin:0;
    padding:10px 10px 0 50px;
    list-style:none;
    text-align: center;
  }
#tabsJ li {
  display:inline-block;
  margin:0;
  padding:0;
  }
#tabsJ li a:hover {
  background color: #111
  }
#tabsJ a {
  float:left;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tableftJ.gif) no-repeat left top;
  margin:0;
  padding:0 0 0 5px;
  text-decoration:none;
  }
#tabsJ a span {
  float:left;
  display:block;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tabrightJ.gif) no-repeat right top;
  padding:5px 15px 4px 6px;
  color:#24618E;
  }
/* Commented Backslash Hack hides rule from IE5-Mac \*/
#tabsJ a span {float:none;}
/* End IE5-Mac hack */
#tabsJ a:hover span {
  color:#FFF;
  }
#tabsJ a:hover {
  background-position:0% -42px;
  }
#tabsJ a:hover span {
  background-position:100% -42px;
  }

    #tabsJ #current a {
            background-position:0% -42px;
    }
    #tabsJ #current a span {
            background-position:100% -42px;
            color:#FFF;
    }
</code>```

答:
You are using  it makes your text italic.Your markup structure is not good.

Add in your css on  #tabsJ font-style: normal;

Body:
On all the other pages of the website the navigation bar is in normal font but for some reason the font on the home page nav bar is in italics. I've completely forgotten how to make it so it doesn't have italics or where to search to change it so please help

http://surbaisse.com/index.html

#tabsJ {
  float:left;
  width:100%;
  background:#F4F4F4;
  font-size:93%;
  line-height:normal;
      border-bottom:1px solid #24618E;
  }
#tabsJ ul {
    margin:0;
    padding:10px 10px 0 50px;
    list-style:none;
    text-align: center;
  }
#tabsJ li {
  display:inline-block;
  margin:0;
  padding:0;
  }
#tabsJ li a:hover {
  background color: #111
  }
#tabsJ a {
  float:left;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tableftJ.gif) no-repeat left top;
  margin:0;
  padding:0 0 0 5px;
  text-decoration:none;
  }
#tabsJ a span {
  float:left;
  display:block;
  background:url(file:///C|/Users/xw4600/Documents/Bugatti Dave/tabrightJ.gif) no-repeat right top;
  padding:5px 15px 4px 6px;
  color:#24618E;
  }
/* Commented Backslash Hack hides rule from IE5-Mac \*/
#tabsJ a span {float:none;}
/* End IE5-Mac hack */
#tabsJ a:hover span {
  color:#FFF;
  }
#tabsJ a:hover {
  background-position:0% -42px;
  }
#tabsJ a:hover span {
  background-position:100% -42px;
  }

    #tabsJ #current a {
            background-position:0% -42px;
    }
    #tabsJ #current a span {
            background-position:100% -42px;
            color:#FFF;
    }

Body:
You are using <em> it makes your text italic.Your markup structure is not good.

Add in your css on  #tabsJ font-style: normal;


问:
Gmail API for monitoring login activity
Hey guys I am looking for an Google or Gmail API which will monitor the user login activity of his/her gmail account.  I got a app which does the same

Here is a link.
https://play.google.com/store/apps/details?id=com.logdog.websecurity&hl=en

Any help would be appreciated.

Thanks.

答:
To monitor the login activities of all of your account's users, you may want to use the Reports API: Login Activity Report. Each report uses the basic report endpoint request with report-specific parameters such as a user's email. The maximum time period for each report is the last 180 days.

Note: The login activity report only audits explicit password and SAML-based single sign-on (SSO) logins.

To retrieve all logins for all of your domain's services, use the following GET HTTP request and include the authorization token described in the authorization documentation.

Title: Gmail API for monitoring login activity


问:
Save data in db from excel in laravel
I need to import excel data in db. but is giving me tough time.
here is my controller function

```<code>      $path = Input::file('import_file')->getRealPath();
        $data = \Excel::load($path)->get();

        if($data->count()){
            foreach ($data as $key => $value) {
                $arr[] = ['product_id' => $value->price, 'details' =>
                $value->stock];

            }

            if(!empty($arr)){
                \DB::table('stock')->insert($arr);
                dd('Insert Record successfully.');
            }
        }
</code>```

where price and stock is fields in excel.
below is the error

```<code>          Property [price] does not exist on this collection instance.
</code>```

here is dd() of my controller function when i am trying to save excel data in db.

```<code>          SheetCollection {#375 ▼
        #title: ""
         #items: array:3 [▼
      0 => RowCollection {#498 ▼
  #heading: array:2 [▼
    0 => "stock"
    1 => "price"
  ]
  #title: "Sheet1"
  #items: array:3 [▼
    0 => CellCollection {#462 ▼
      #title: null
      #items: array:2 [▼
        "stock" => 2.0
        "price" => 3.0
      ]
    }
    1 => CellCollection {#481 ▼
      #title: null
      #items: array:2 [▼
        "stock" => 3.0
        "price" => 2.0
      ]
    }
    2 => CellCollection {#480 ▼
      #title: null
      #items: array:2 [▶]
    }
  ]
}
1 => RowCollection {#533 ▶}
</code>```

答:
CHANGE EXCEL SHEET COLUMN NAME LIKE THAT

price  stock

100     400

200     15

12     167

Title: Save data in db from excel in laravel

Body:
I need to import excel data in db. but is giving me tough time.
here is my controller function

      $path = Input::file('import_file')->getRealPath();
        $data = \Excel::load($path)->get();

        if($data->count()){
            foreach ($data as $key => $value) {
                $arr[] = ['product_id' => $value->price, 'details' =>
                $value->stock];

            }

            if(!empty($arr)){
                \DB::table('stock')->insert($arr);
                dd('Insert Record successfully.');
            }
        }

where price and stock is fields in excel.
below is the error

          Property [price] does not exist on this collection instance.

here is dd() of my controller function when i am trying to save excel data in db.

          SheetCollection {#375 ▼
        #title: ""
         #items: array:3 [▼
      0 => RowCollection {#498 ▼
  #heading: array:2 [▼
    0 => "stock"
    1 => "price"
  ]
  #title: "Sheet1"
  #items: array:3 [▼
    0 => CellCollection {#462 ▼
      #title: null
      #items: array:2 [▼
        "stock" => 2.0
        "price" => 3.0
      ]
    }
    1 => CellCollection {#481 ▼
      #title: null
      #items: array:2 [▼
        "stock" => 3.0
        "price" => 2.0
      ]
    }
    2 => CellCollection {#480 ▼
      #title: null
      #items: array:2 [▶]
    }
  ]
}
1 => RowCollection {#533 ▶}


问:
Java: How do I close a JFrame while opening another one?
My program starts with a picture with a textfield in a JFrame. I want when the user types start it closes the picture JFrame and opens another JFrame with the main program. I've tried

processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));

on the Image frame but it closes all the windows.

答:
you also can use this code

for example

```<code>  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
</code>```

Body:
you also can use this code

for example

  JFrame frame = new JFrame();
  frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);


问:
How to reset a React-Bootstrap Form after submit?
I added React-Bootstrap to my app. So I change a basic form with React-Bootstrap components.

I can't reset a form after a submit.

Here is my simplified code:

```<code>import React from 'react';
import { Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap';

class MyForm extends React.Component {

    onSubmit( event ) {
        event.preventDefault();
        const textAreaValue = this.textArea.value;
        console.log("textAreaValue : ", textAreaValue);

        // some code here...

        // ERROR HERE (but it works if I
        // replace bootstrap <Form>
        // component by a simple <form>
        this.messageForm.reset();
    }

    render() {

        return (
            <Form
                className="form"
                ref={ form => this.messageForm = form }
                onSubmit={ this.onSubmit.bind( this ) }
            >

                <FormGroup controlId="formControlsTextarea">
                    <ControlLabel>My Control Label</ControlLabel>
                    <FormControl
                        required
                        inputRef={ input => this.textArea = input }
                        componentClass="textarea" />
                </FormGroup>

                <Button type="submit">ok</Button>
            </Form>
        );

    }

}
export default MyForm;
</code>```

I could continue to use a normal  then it works but I wonder how to use that one component of React-Boostrap.

Has someone an idea?

The error:

```<code>× TypeError: this.messageForm.reset is not a function
</code>```

When I log this.messageForm it's a React-Bootstrap component. I also tested with inputRef instead of ref but it doesn't work

答:
Use https://redux-form.com/ to manage your input fields.

This way you have much control with your form fields.

https://codesandbox.io/s/7m0m386m26

Body:
I added React-Bootstrap to my app. So I change a basic form with React-Bootstrap components.

I can't reset a form after a submit.

Here is my simplified code:

import React from 'react';
import { Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap';

class MyForm extends React.Component {

    onSubmit( event ) {
        event.preventDefault();
        const textAreaValue = this.textArea.value;
        console.log("textAreaValue : ", textAreaValue);

        // some code here...

        // ERROR HERE (but it works if I
        // replace bootstrap <Form>
        // component by a simple <form>
        this.messageForm.reset();
    }

    render() {

        return (
            <Form
                className="form"
                ref={ form => this.messageForm = form }
                onSubmit={ this.onSubmit.bind( this ) }
            >

                <FormGroup controlId="formControlsTextarea">
                    <ControlLabel>My Control Label</ControlLabel>
                    <FormControl
                        required
                        inputRef={ input => this.textArea = input }
                        componentClass="textarea" />
                </FormGroup>

                <Button type="submit">ok</Button>
            </Form>
        );

    }

}
export default MyForm;

I could continue to use a normal  then it works but I wonder how to use that one component of React-Boostrap.

Has someone an idea?

The error:

× TypeError: this.messageForm.reset is not a function

When I log this.messageForm it's a React-Bootstrap component. I also tested with inputRef instead of ref but it doesn't work


问:
ngIf inside NgFor not working
I can't get this two ng-container-conditions inside ion-item get to work:

```<code><ion-list *ngIf="slide.options">
    <ion-item *ngFor="let option of slide.options">
        <ng-container *ngIf="option.type === 'boolean'">
            <ion-label>
                <h2 *ngIf="option.title" [innerHTML]="option.title"></h2>
                <p *ngIf="option.description" [innerHTML]="option.description"></p>
            </ion-label>
            <ion-toggle *ngIf="option.checked !== undefined || option.disabled !== undefined" [disabled]="option.disabled" [checked]="option.checked"></ion-toggle>
        </ng-container>
        <ng-container *ngIf="option.type === 'range'">
            <h2 *ngIf="option.title" [innerHTML]="option.title"></h2>
            <p *ngIf="option.description" [innerHTML]="option.description"></p>
            <ion-range *ngIf="option.min !== undefined || option.max !== undefined" [min]="option.min" [max]="option.max" [step]="option.steps" pin="true" snaps="true">
                <ion-label range-left>{{option.min}} {{option.unit}}</ion-label>
                <ion-label range-right>{{option.max}} {{option.unit}}</ion-label>
            </ion-range>
        </ng-container>
    </ion-item>
</ion-list>
</code>```

They are always seen as false. This results in an empty space:

But in this way (or when adding the same conditions directly to the ion-toggle and ion-range-elements) it was nearly working (except that the ngIf on ng-container again was always false, while the ngIf on ion-label was executing fine):

```<code><ion-list>
    <ion-item *ngFor="let option of slide.options">
        <ion-label *ngIf="option.checked !== undefined || option.disabled !== undefined">
            <h2 *ngIf="option.title" [innerHTML]="option.title"></h2>
            <p *ngIf="option.description" [innerHTML]="option.description"></p>
        </ion-label>
        <ng-container *ngIf="option.min !== undefined || option.max !== undefined">
            <h2 *ngIf="option.title" [innerHTML]="option.title"></h2>
            <p *ngIf="option.description" [innerHTML]="option.description"></p>
        </ng-container>
        <ion-toggle *ngIf="option.checked !== undefined || option.disabled !== undefined" [disabled]="option.disabled" [checked]="option.checked"></ion-toggle>
        <ion-range *ngIf="option.min !== undefined || option.max !== undefined" [min]="option.min" [max]="option.max" [step]="option.steps" pin="true" snaps="true">
            <ion-label range-left>{{option.min}} {{option.unit}}</ion-label>
            <ion-label range-right>{{option.max}} {{option.unit}}</ion-label>
        </ion-range>
    </ion-item>
</ion-list>
</code>```

What am I doing wrong?

答:
I got it working by not using ng-container for *ngIf but for the iteration with *ngFor and putting the *ngIf on the ion-item:

```<code><ion-list *ngIf="slide?.options">
    <ng-container *ngFor="let option of slide.options">

        <ion-item *ngIf="option?.type === 'boolean'">
            <ion-label>
                <h2 *ngIf="option?.title" [innerHTML]="option.title"></h2>
                <p *ngIf="option?.description" [innerHTML]="option.description"></p>
            </ion-label>
            <ion-toggle *ngIf="option?.checked !== undefined || option?.disabled !== undefined" [disabled]="option.disabled" [checked]="option.checked"></ion-toggle>
        </ion-item>

        <ion-item *ngIf="option?.type === 'range'">
            <ion-label class="range-pre-label">
                <h2 *ngIf="option?.title" [innerHTML]="option.title"></h2>
                <p *ngIf="option?.description" [innerHTML]="option.description"></p>
            </ion-label>
            <ion-range *ngIf="option?.min !== undefined || option?.max !== undefined" [min]="option.min" [max]="option.max" [step]="option.steps" pin="true" snaps="true">
                <ion-label range-left>{{option.min}} {{option.unit}}</ion-label>
                <ion-label range-right>{{option.max}} {{option.unit}}</ion-label>
            </ion-range>
        </ion-item>

    </ng-container>
</ion-list>
</code>```

Title: ngIf inside NgFor not working

Body:
I can't get this two ng-container-conditions inside ion-item get to work:

<ion-list *ngIf="slide.options">
    <ion-item *ngFor="let option of slide.options">
        <ng-container *ngIf="option.type === 'boolean'">
            <ion-label>

            </ion-label>
            <ion-toggle *ngIf="option.checked !== undefined || option.disabled !== undefined" [disabled]="option.disabled" [checked]="option.checked"></ion-toggle>
        </ng-container>
        <ng-container *ngIf="option.type === 'range'">

            <ion-range *ngIf="option.min !== undefined || option.max !== undefined" [min]="option.min" [max]="option.max" [step]="option.steps" pin="true" snaps="true">
                <ion-label range-left>{{option.min}} {{option.unit}}</ion-label>
                <ion-label range-right>{{option.max}} {{option.unit}}</ion-label>
            </ion-range>
        </ng-container>
    </ion-item>
</ion-list>

They are always seen as false. This results in an empty space:

But in this way (or when adding the same conditions directly to the ion-toggle and ion-range-elements) it was nearly working (except that the ngIf on ng-container again was always false, while the ngIf on ion-label was executing fine):

<ion-list>
    <ion-item *ngFor="let option of slide.options">
        <ion-label *ngIf="option.checked !== undefined || option.disabled !== undefined">

        </ion-label>
        <ng-container *ngIf="option.min !== undefined || option.max !== undefined">

        </ng-container>
        <ion-toggle *ngIf="option.checked !== undefined || option.disabled !== undefined" [disabled]="option.disabled" [checked]="option.checked"></ion-toggle>
        <ion-range *ngIf="option.min !== undefined || option.max !== undefined" [min]="option.min" [max]="option.max" [step]="option.steps" pin="true" snaps="true">
            <ion-label range-left>{{option.min}} {{option.unit}}</ion-label>
            <ion-label range-right>{{option.max}} {{option.unit}}</ion-label>
        </ion-range>
    </ion-item>
</ion-list>

What am I doing wrong?

Body:
I got it working by not using ng-container for *ngIf but for the iteration with *ngFor and putting the *ngIf on the ion-item:

<ion-list *ngIf="slide?.options">
    <ng-container *ngFor="let option of slide.options">

        <ion-item *ngIf="option?.type === 'boolean'">
            <ion-label>
                <h2 *ngIf="option?.title" [innerHTML]="option.title"></h2>
                <p *ngIf="option?.description" [innerHTML]="option.description"></p>
            </ion-label>
            <ion-toggle *ngIf="option?.checked !== undefined || option?.disabled !== undefined" [disabled]="option.disabled" [checked]="option.checked"></ion-toggle>
        </ion-item>

        <ion-item *ngIf="option?.type === 'range'">
            <ion-label class="range-pre-label">
                <h2 *ngIf="option?.title" [innerHTML]="option.title"></h2>
                <p *ngIf="option?.description" [innerHTML]="option.description"></p>
            </ion-label>
            <ion-range *ngIf="option?.min !== undefined || option?.max !== undefined" [min]="option.min" [max]="option.max" [step]="option.steps" pin="true" snaps="true">
                <ion-label range-left>{{option.min}} {{option.unit}}</ion-label>
                <ion-label range-right>{{option.max}} {{option.unit}}</ion-label>
            </ion-range>
        </ion-item>

    </ng-container>
</ion-list>


问:
Get IIS bindings at runtime
I wonder how to get the IIS binding settings of the current site (host name, port, IP address) at runtime using ASP.NET.
Does .NET provide any way to get these information?

Edit: I need a way to get the http and https ports configured to redirect to the right port when switching from http to https, and back from https to http if other ports then 80/443 are used. Is there a way to do this without extended privileges?

Regards

答:
I think you're looking for metabase access:

http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/43a51d34-7c81-413b-9727-ec9a19d0b428.mspx?mfr=true

Title: Get IIS bindings at runtime


问:
How to implement correctly own javascript library, angular 4
I want to implement my own javascript library in an andular4-cli project. Because its my own library, its not possible to include the library with npm.

tsconfig.json

```<code>{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "allowJs": true,
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}
</code>```

I implemented the library in angular.cli.json

```<code>"assets/myownlib.js"
</code>```

The component i want to use the library:

```<code>import { Component, OnInit } from '@angular/core';
import {DataService} from './tempdatagia.service';
import {MyLib} from '../../assets/myownlib';

@Component({
  selector: 'app-paho',
  templateUrl: './paho.component.html',
  styleUrls: ['./paho.component.css']
})
export class PahoComponent {
  // Create a client instance
  client: any;

  constructor(private tempdata: DataService) {

    this.client = new MyLib.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080,  'Steffen');

    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }
 .
 .
 .
}
</code>```

ERROR

in line import {MyLib} from '../../assets/myownlib';:

 "allow js is not set"

"cannot find namespace 'MyLib'."

答:
Look at your lib code. Did you use it like a module?

```<code>const someLib = function(){}
module.exports = someLib;
</code>```

Next, look at path in angular cli. I think that it has to be "../assets....".

If you are using it with typescript i think you wrote wrong path or your typescript code is incorrect. What is in your lib?

Body:
I want to implement my own javascript library in an andular4-cli project. Because its my own library, its not possible to include the library with npm.

tsconfig.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "allowJs": true,
    "outDir": "../out-tsc/app",
    "module": "es2015",
    "baseUrl": "",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

I implemented the library in angular.cli.json

"assets/myownlib.js"

The component i want to use the library:

import { Component, OnInit } from '@angular/core';
import {DataService} from './tempdatagia.service';
import {MyLib} from '../../assets/myownlib';

@Component({
  selector: 'app-paho',
  templateUrl: './paho.component.html',
  styleUrls: ['./paho.component.css']
})
export class PahoComponent {
  // Create a client instance
  client: any;

  constructor(private tempdata: DataService) {

    this.client = new MyLib.MQTT.Client('wpsdemo.gia.rwth-aachen.de', 8080,  'Steffen');

    this.onMessage();
    this.onConnectionLost();
    // connect the client
    this.client.connect({onSuccess: this.onConnected.bind(this)});
  }
 .
 .
 .
}

ERROR

in line import {MyLib} from '../../assets/myownlib';:

 "allow js is not set"

"cannot find namespace 'MyLib'."

Body:
Look at your lib code. Did you use it like a module?

const someLib = function(){}
module.exports = someLib;

Next, look at path in angular cli. I think that it has to be "../assets....".

If you are using it with typescript i think you wrote wrong path or your typescript code is incorrect. What is in your lib?