问:
sql request with Count
I have this data base. Created 3 tables.

I need to query the database to extract the titles in which more than three authors.

I tried different ways, but I can not count the number of books written by three or more authors. How can I calculate how many echoes wrote the book in my table?

```<code> CREATE TABLE `authors` (
      `id` int(11) NOT NULL,
      `name` text CHARACTER SET utf8 NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `authors` (`id`, `name`) VALUES
(1, 'Orwell'),
(2, 'Balsak'),
(3, 'Gugo');

-- --------------------------------------------------------

CREATE TABLE `books` (
  `id` int(11) NOT NULL,
  `title` text CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books` (`id`, `title`) VALUES
(1, '1984'),
(2, 'crime and punishment'),
(3, 'Hunger games');

-- --------------------------------------------------------

CREATE TABLE `books_authos` (
  `author_id` int(11) DEFAULT NULL,
  `book_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books_authos` (`author_id`, `book_id`) VALUES
(1, 1),
(1, 3),
(1, 2),
(3, 2),
(2, 2);
</code>```

答:
You can try this query

```<code>SELECT count(books_authos.author_id) AS total_author, books.title FROM books_authos INNER JOIN books ON books.id = books_authos.book_id group by book_id
</code>```

Out put

```<code>total_author   title
1              1984
3              crime and punishment
1              Hunger games
</code>```

If you put condition on count for more than 3 then you will get book which has total >= 3

```<code>SELECT count(books_authos.author_id) AS total_author, books.title FROM books_authos INNER JOIN books ON books.id = books_authos.book_id group by book_id having total_author >= 3
</code>```

Output

```<code> total_author   title
3              crime and punishment
</code>```

If you need authors name then you can try this one

If you want author name then you can use GROUP_CONCAT with below query

```<code>SELECT b.*, COUNT(ba.author_id) AS total_author, GROUP_CONCAT(au.name) AS authors_name FROM books b
LEFT JOIN books_authos ba ON b.id = ba.book_id
LEFT JOIN authors au ON au.id = ba.author_id
GROUP BY b.id
</code>```

Output

```<code>total_author   title                    authors_name
 1               1984                   Orwell
 3              crime and punishment   Gugo, Balsak,Orwell
 1              Hunger games           Orwell
</code>```

Title: sql request with Count

Body:
I have this data base. Created 3 tables.

I need to query the database to extract the titles in which more than three authors.

I tried different ways, but I can not count the number of books written by three or more authors. How can I calculate how many echoes wrote the book in my table?

 CREATE TABLE `authors` (
      `id` int(11) NOT NULL,
      `name` text CHARACTER SET utf8 NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `authors` (`id`, `name`) VALUES
(1, 'Orwell'),
(2, 'Balsak'),
(3, 'Gugo');

-- --------------------------------------------------------

CREATE TABLE `books` (
  `id` int(11) NOT NULL,
  `title` text CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books` (`id`, `title`) VALUES
(1, '1984'),
(2, 'crime and punishment'),
(3, 'Hunger games');

-- --------------------------------------------------------

CREATE TABLE `books_authos` (
  `author_id` int(11) DEFAULT NULL,
  `book_id` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `books_authos` (`author_id`, `book_id`) VALUES
(1, 1),
(1, 3),
(1, 2),
(3, 2),
(2, 2);

Body:
You can try this query

SELECT count(books_authos.author_id) AS total_author, books.title FROM books_authos INNER JOIN books ON books.id = books_authos.book_id group by book_id

Out put

total_author   title
1              1984
3              crime and punishment
1              Hunger games

If you put condition on count for more than 3 then you will get book which has total >= 3

SELECT count(books_authos.author_id) AS total_author, books.title FROM books_authos INNER JOIN books ON books.id = books_authos.book_id group by book_id having total_author >= 3

Output

 total_author   title
3              crime and punishment

If you need authors name then you can try this one

If you want author name then you can use GROUP_CONCAT with below query

SELECT b.*, COUNT(ba.author_id) AS total_author, GROUP_CONCAT(au.name) AS authors_name FROM books b
LEFT JOIN books_authos ba ON b.id = ba.book_id
LEFT JOIN authors au ON au.id = ba.author_id
GROUP BY b.id

Output

total_author   title                    authors_name
 1               1984                   Orwell
 3              crime and punishment   Gugo, Balsak,Orwell
 1              Hunger games           Orwell


来源: stackexchange

问:
How to put a gray overlay on an image in CSS
I'd like to create a website that has a banner on every page with an image that has a gray overlay. In that way, white text on the image becomes more visible.
The result should look exactly like this: http://skoopopweg.weebly.com/programma.html.

I found ways to dull the image, but not to put an overlay on top of it.
Can anybody help?

This is my code in CSS for this class of images thus far:

```<code>.img-with-overlay{width:100%; position:relative;}
</code>```

And in html:

```<code><img class="img-with-overlay" src="img1.jpg" />
</code>```

答:
the idea:

use a div as a wrapper with position: relative

use a div as an overlay with position: absolute and background-color (you can change the first 3 values to set RGB color and the 4rth for the opacity level)

.img-wrapper {
  position: relative;
  width: 100%;
  font-size: 0;
}

.img-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(128,128,128,0.75);
}

.img-wrapper img {width: 100%;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="img-wrapper">
  <div class="img-overlay"></div>
  <img src="https://raw.githubusercontent.com/tgogos/CS_comics/master/imgs/106-tech-debt.png">
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'd like to create a website that has a banner on every page with an image that has a gray overlay. In that way, white text on the image becomes more visible.
The result should look exactly like this: http://skoopopweg.weebly.com/programma.html.

I found ways to dull the image, but not to put an overlay on top of it.
Can anybody help?

This is my code in CSS for this class of images thus far:

.img-with-overlay{width:100%; position:relative;}

And in html:

Body:
the idea:

use a div as a wrapper with position: relative

use a div as an overlay with position: absolute and background-color (you can change the first 3 values to set RGB color and the 4rth for the opacity level)

.img-wrapper {
  position: relative;
  width: 100%;
  font-size: 0;
}

.img-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(128,128,128,0.75);
}

.img-wrapper img {width: 100%;}

<div class="img-wrapper">
  <div class="img-overlay"></div>
  <img src="https://raw.githubusercontent.com/tgogos/CS_comics/master/imgs/106-tech-debt.png">
</div>

ContentLicense: CC BY-SA 4.0


问:
Component does not stop nested dependencies
I bumped into a following problem while using the component library - whenever a given component depends on another, the associated dependency in the system map does not release it's resources (i.e. is not stopped) on 'stop-system'.

I would assume that both lifecycle methods work in the dependency order and call start / stop for each component and its dependencies in a tree traversal of the dependency graph.

I haven't yet looked in detail, but I made a simple application that reproduces the problem in a simple unit test (call lein test):

https://github.com/fbielejec/component-app

答:
The reason your test fails is because you retrieve the database dependency from the :message-handlers, instead of the database dependency directly.  As you indicate yourself, the stop function of the database is correctly invoked, so the resource would be released (in a real-life situation).

However, the database dependency of the message handler still refers to the old database.  Due to the nature of immutability, that's not the same instance of the one that is the result of the stop function.

If you were to write the test like this, it would work:

```<code>(is (nil? (-> the-system
              system/start
              system/stop
              :database
              :connection)))
</code>```

This verification succeeds as expected.

I hope this answers your question?

Body:
The reason your test fails is because you retrieve the database dependency from the :message-handlers, instead of the database dependency directly.  As you indicate yourself, the stop function of the database is correctly invoked, so the resource would be released (in a real-life situation).

However, the database dependency of the message handler still refers to the old database.  Due to the nature of immutability, that's not the same instance of the one that is the result of the stop function.

If you were to write the test like this, it would work:

(is (nil? (-> the-system
              system/start
              system/stop
              :database
              :connection)))

This verification succeeds as expected.

I hope this answers your question?


问:
Add Object to Hashset with Iterator
```<code> HashSet<String> set = new HashSet<String>();
 set.add("test1");
 Iterator<String> it = set.iterator();

 while(it.hasNext()){
    it.next();
    set.add("sf");
    it.remove();
 }
</code>```

Throws me the exception:

```<code>Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.remove(Unknown Source)
</code>```

If I delete the set.add("sf"); it works obviously.
But why can't I add something to my HashSet while using the iterator?

答:
No, the Iterator interface doesn't support adding elements to the Collection during iteration.

If you were using a List instead of Set, you could have used a ListIterator that does support adding elements during iteration.

This is specified in the Javadoc of Iterator's remove() method:

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

The reason add() cannot be supported by Iterators over an arbitrary Collection is that some collections, such as HashSet which you are using, don't have an ordering of their elements. An element added while iterating over a HashSet may be added before or after the current position of the Iterator (depending on its hashCode), so the iterator's behavior after adding the element will be unpredictable.

Title: Add Object to Hashset with Iterator

Body:
 HashSet<String> set = new HashSet<String>();
 set.add("test1");
 Iterator<String> it = set.iterator();

 while(it.hasNext()){
    it.next();
    set.add("sf");
    it.remove();
 }

Throws me the exception:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.remove(Unknown Source)

If I delete the set.add("sf"); it works obviously.
But why can't I add something to my HashSet while using the iterator?


问:
Read an array recursively
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

```<code>void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}
</code>```

I would like to read an array recursively. I wrote the following function:

```<code>void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}
</code>```

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

答:
As other answers have mentioned, your handling of n is leading to problems. You can return 0 from the base case of sz == 0, otherwise return the result of the next recursive call, or -1 if scanf() fails. At each recursive call, increment a and decrement sz. The value returned in the calling function should be checked for input errors: 0 on success, -1 on failure.

Note that this is a tail recursion, which should be optimized by most good compilers.

```<code>#include <stdio.h>

int read_array(int *a, size_t sz);

int main(void)
{
    int arr[5];
    puts("Enter array elements:");
    if (read_array(arr, 5) != 0) {
        fprintf(stderr, "Input error\n");
    } else {
        for (size_t i = 0; i < 5; i++) {
            printf("%8d", arr[i]);
        }
        putchar('\n');
    }

    return 0;
}

int read_array(int *a, size_t sz)
{
    if (sz == 0 ) {
        return 0;
    }
    if (scanf("%d", a) == 1){
        return read_array(a + 1, sz - 1);
    } else {
        return -1;
    }
}
</code>```

Sample interaction:

Enter array elements:
1 2 3 4 5
       1       2       3       4       5

Enter array elements:
1 2 3 x 5
Input error
```

Title: Read an array recursively

Body:
I am learning how to apply recursion to arrays.

For example, I usually read arrays itiratively, this way:

void read_array(int *a, int n){
        int i;
        for(i = 0; i < n; ++i)
                scanf("%d", &a[i]);
        return;
}

I would like to read an array recursively. I wrote the following function:

void read_array(int *a, int n){
        int i = n - 1;
        if (n < 0)
                return;
        else{
                if(scanf("%d", &a[n - 1 - i]) == 1){
                        read_array(a, n - 1);
                        return;
                }
        }
}

It compiles, but when running it trows a segmentation fault error. It confuses me since the function contemplates a base case 0 that should stop it.

Body:
As other answers have mentioned, your handling of n is leading to problems. You can return 0 from the base case of sz == 0, otherwise return the result of the next recursive call, or -1 if scanf() fails. At each recursive call, increment a and decrement sz. The value returned in the calling function should be checked for input errors: 0 on success, -1 on failure.

Note that this is a tail recursion, which should be optimized by most good compilers.

#include <stdio.h>

int read_array(int *a, size_t sz);

int main(void)
{
    int arr[5];
    puts("Enter array elements:");
    if (read_array(arr, 5) != 0) {
        fprintf(stderr, "Input error\n");
    } else {
        for (size_t i = 0; i < 5; i++) {
            printf("%8d", arr[i]);
        }
        putchar('\n');
    }

    return 0;
}

int read_array(int *a, size_t sz)
{
    if (sz == 0 ) {
        return 0;
    }
    if (scanf("%d", a) == 1){
        return read_array(a + 1, sz - 1);
    } else {
        return -1;
    }
}

Sample interaction:

Enter array elements:
1 2 3 4 5
       1       2       3       4       5

Enter array elements:
1 2 3 x 5
Input error


问:
How to resolve integer overflow errors in R estimation
I'm trying to estimate a model using speedglm in R. The dataset is large (~69.88 million rows and 38 columns). Multiplying the number of rows and columns results in ~2.7 billion which is outside the integer limit. I can't provide the data, but the following examples recreate the issue.

```<code>library(speedglm)

# large example that works
require(biglm)
n <- 500000
k <- 500
y <- rgamma(n, 1.5, 1)
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
working.example <- speedglm(fo, data = da, family = Gamma(log))

# repeat with large enough size to break
k <- 5000       # 10 times larger than above
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
failed.example <- speedglm(fo, data = da, family = Gamma(log))

# attempting to resolve error with chunksize
attempted.fixed.example <- speedglm(fo, data = da, family = Gamma(log), chunksize = 10^6)
</code>```

This causes an error and integer overflow warning.

```<code>Error in if (!replace && is.null(prob) && n > 1e+07 && size <= n/2) .Internal(sample2(n,  :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In nrow(X) * ncol(X) : NAs produced by integer overflow
</code>```

I understand the warning, but I do not understand the error. They seem to be related in this case as they appear together after each attempt.

Removing columns allows the estimation to complete. It does not seem to matter which columns are removed; removing interacted or non-interacted variables will both result in a completed estimation. The chunksize option was added after receiving the error initially, but has not helped.

My questions are: (1) what causes the first error? (2) is there a way to estimate models using data such that the number of rows by the number of columns is larger than the integer limit? (3) is there a better na.action to use in this case?

Thanks,

JP.

Running: R version 3.3.3 (2017-03-06)

Actual code below:

```<code>dft_var <- c("cltvV0", "cltvV60", "cltvV120", "VCFLBRQ", "ageV0",
             "ageV1", "ageV8", "ageV80", "FICOV300", "FICOV650",
             "FICOV900", "SingleHouse", "Apt", "Mobile", "Duplex",
             "Row", "Modular", "Rural", "FirstTimeBuyer",
             "FirstTimeBuyerMissing", "brwtotinMissing", "IncomeRatio",
             "VintageBefore2001", "NFLD", "yoy.fcpwti:province_n")
logit1 <- speedglm(formula = paste("DefaultFlag ~ ",
                                   paste(dft_var, collapse = "+"),
                                   sep = ""),
                   family = binomial(logit),
                   na.action = na.exclude,
                   data = default.data,
                   chunksize = 1*10^7)
</code>```

答:
Thanks to @Andrey 's guidance I was able to solve the problem. The issue was the sample function in the is.sparse check. To bypass this I set sparse=FALSE in the options for speedglm (this should work for sparse=TRUE as well, though I haven't tried.) This is because speedglm calls is.sparse via speedglm.wfit in the following way:

```<code>if (is.null(sparse))
    sparse <- is.sparse(x = x, sparsellim, camp)
</code>```

So setting sparse avoids the is.sparse function.

Using the example above, the following should now work:

```<code>speedglm(fo, data = da, family = Gamma(log), sparse = FALSE)
</code>```

Body:
I'm trying to estimate a model using speedglm in R. The dataset is large (~69.88 million rows and 38 columns). Multiplying the number of rows and columns results in ~2.7 billion which is outside the integer limit. I can't provide the data, but the following examples recreate the issue.

library(speedglm)

# large example that works
require(biglm)
n <- 500000
k <- 500
y <- rgamma(n, 1.5, 1)
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
working.example <- speedglm(fo, data = da, family = Gamma(log))

# repeat with large enough size to break
k <- 5000       # 10 times larger than above
x <- round(matrix(rnorm(n*k), n, k), digits = 3)
colnames(x) <- paste("s", 1:k, sep = "")
da <- data.frame(y, x)
fo <- as.formula(paste("y~", paste(paste("s", 1:k, sep = ""), collapse = "+")))
failed.example <- speedglm(fo, data = da, family = Gamma(log))

# attempting to resolve error with chunksize
attempted.fixed.example <- speedglm(fo, data = da, family = Gamma(log), chunksize = 10^6)

This causes an error and integer overflow warning.

Error in if (!replace && is.null(prob) && n > 1e+07 && size <= n/2) .Internal(sample2(n,  :
  missing value where TRUE/FALSE needed
In addition: Warning message:
In nrow(X) * ncol(X) : NAs produced by integer overflow

I understand the warning, but I do not understand the error. They seem to be related in this case as they appear together after each attempt.

Removing columns allows the estimation to complete. It does not seem to matter which columns are removed; removing interacted or non-interacted variables will both result in a completed estimation. The chunksize option was added after receiving the error initially, but has not helped.

My questions are: (1) what causes the first error? (2) is there a way to estimate models using data such that the number of rows by the number of columns is larger than the integer limit? (3) is there a better na.action to use in this case?

Thanks,

JP.

Running: R version 3.3.3 (2017-03-06)

Actual code below:

dft_var <- c("cltvV0", "cltvV60", "cltvV120", "VCFLBRQ", "ageV0",
             "ageV1", "ageV8", "ageV80", "FICOV300", "FICOV650",
             "FICOV900", "SingleHouse", "Apt", "Mobile", "Duplex",
             "Row", "Modular", "Rural", "FirstTimeBuyer",
             "FirstTimeBuyerMissing", "brwtotinMissing", "IncomeRatio",
             "VintageBefore2001", "NFLD", "yoy.fcpwti:province_n")
logit1 <- speedglm(formula = paste("DefaultFlag ~ ",
                                   paste(dft_var, collapse = "+"),
                                   sep = ""),
                   family = binomial(logit),
                   na.action = na.exclude,
                   data = default.data,
                   chunksize = 1*10^7)

Body:
Thanks to @Andrey 's guidance I was able to solve the problem. The issue was the sample function in the is.sparse check. To bypass this I set sparse=FALSE in the options for speedglm (this should work for sparse=TRUE as well, though I haven't tried.) This is because speedglm calls is.sparse via speedglm.wfit in the following way:

if (is.null(sparse))
    sparse <- is.sparse(x = x, sparsellim, camp)

So setting sparse avoids the is.sparse function.

Using the example above, the following should now work:

speedglm(fo, data = da, family = Gamma(log), sparse = FALSE)


问:
How can I start the server with the code configuration rather than the XML file configuration?
I want to start the server with the code configuration rather than the XML file configuration, but the silo server cannot start without calling the LoadOrleansConfig method.</p>

```<code>string providerName = "MySql.Data.MySqlClient";
string mysqlConnString = "mysqlConnString";

var config = new ClusterConfiguration();
config.Globals.DeploymentId = "OrleansTest";
config.Globals.AdoInvariant = providerName;
config.Globals.DataConnectionString = mysqlConnString;

config.Globals.LivenessType = LivenessProviderType.Custom;
config.Globals.ReminderServiceType = ReminderServiceProviderType.Custom;
config.Globals.MembershipTableAssembly = "OrleansSQLUtils";
config.Globals.ReminderTableAssembly = "OrleansSQLUtils";

config.Defaults.HostNameOrIPAddress = "localhost";
config.Defaults.Port = 11111;
config.Defaults.ProxyGatewayEndpoint = new IPEndPoint(IPAddress.Loopback, 30000);

using (var host = new SiloHost("Default"))
{
    host.Config = config;
    host.InitializeOrleansSilo();
    var result = host.StartOrleansSilo();
    Console.WriteLine("server startup {0}", result ? "successful" : "failure");
    Console.ReadLine();
    host.StopOrleansSilo();
}
</code>```

答:
By default, starting the silo will swallow any exceptions. Start it like this and you'll get a bit more info:

```<code>var result = host.StartOrleansSilo(catchExceptions: false);
</code>```

In this case, you get:

"Cannot start silo Default due to prior initialization error"

That's nothing you didn't already know. To fix the problem, set up your SiloHost like this:

```<code>using (var host = new SiloHost("Default", config))
</code>```

Body:
I want to start the server with the code configuration rather than the XML file configuration, but the silo server cannot start without calling the LoadOrleansConfig method.

string providerName = "MySql.Data.MySqlClient";
string mysqlConnString = "mysqlConnString";

var config = new ClusterConfiguration();
config.Globals.DeploymentId = "OrleansTest";
config.Globals.AdoInvariant = providerName;
config.Globals.DataConnectionString = mysqlConnString;

config.Globals.LivenessType = LivenessProviderType.Custom;
config.Globals.ReminderServiceType = ReminderServiceProviderType.Custom;
config.Globals.MembershipTableAssembly = "OrleansSQLUtils";
config.Globals.ReminderTableAssembly = "OrleansSQLUtils";

config.Defaults.HostNameOrIPAddress = "localhost";
config.Defaults.Port = 11111;
config.Defaults.ProxyGatewayEndpoint = new IPEndPoint(IPAddress.Loopback, 30000);

using (var host = new SiloHost("Default"))
{
    host.Config = config;
    host.InitializeOrleansSilo();
    var result = host.StartOrleansSilo();
    Console.WriteLine("server startup {0}", result ? "successful" : "failure");
    Console.ReadLine();
    host.StopOrleansSilo();
}

Body:
By default, starting the silo will swallow any exceptions. Start it like this and you'll get a bit more info:

var result = host.StartOrleansSilo(catchExceptions: false);

In this case, you get:

"Cannot start silo Default due to prior initialization error"

That's nothing you didn't already know. To fix the problem, set up your SiloHost like this:

using (var host = new SiloHost("Default", config))


问:
A Simple Countdown with for loop
Hi I'm trying to create a simple countdown.

Here is my code but it's not working.

Can you help me find the problem?

```<code>function count() {
    for (var cc=20,cc > 0,cc--) {
        document.getElementById("cco").innerHTML=cc;
    }
}
count();
</code>```

答:
When making countdown make sure that start and end elements are correct.

Count up:

```<code>for (var x=0;x < 10;x++) console.log(x);
</code>```

goes from 0 to 9

Incorrect countdown:

```<code>for (var x=10;x > 0;x--) console.log(x);
</code>```

goes from 10 to 1

Correct countdown:

```<code>for (var x=10-1;x >= 0;x--) console.log(x);
</code>```

goes from 9 to 0

Title: A Simple Countdown with for loop

Body:
Hi I'm trying to create a simple countdown.

Here is my code but it's not working.

Can you help me find the problem?

function count() {
    for (var cc=20,cc > 0,cc--) {
        document.getElementById("cco").innerHTML=cc;
    }
}
count();

Body:
When making countdown make sure that start and end elements are correct.

Count up:

for (var x=0;x < 10;x++) console.log(x);

goes from 0 to 9

Incorrect countdown:

for (var x=10;x > 0;x--) console.log(x);

goes from 10 to 1

Correct countdown:

for (var x=10-1;x >= 0;x--) console.log(x);

goes from 9 to 0


问:
How can i get the DD/MM/YYYY formar in my datepicker?
im from spain and i need to put the DD/MM/YYYY format in my datepicker, here is the code

Inicio de castigo

  <input type='text' id="from" name="from" class="form-control" readonly />

Final de castigo

  <input type='text' name="to" id="to" class="form-control" readonly />

```
</div>
</div>
</p>

<p>I put in the script the MM-DD-YYYY fromat but when i pick the calendar he gives me the MM-DD-YYYY format, that is the uk hour. Today is 07 of June of 2017, and when i open it, it says that is 6 of July 2017. How can i solve that? It can be a problem of the datetimepicker.es.js files? . Thanks for the help guys :)</p>

<p>I have more information in that file, there are all the scripts i use</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script type="text/javascript" src="<?=$base_url?>js/es-ES.js"></script>
<script src="<?=$base_url?>js/jquery.min.js"></script>
<script src="<?=$base_url?>js/moment.js"></script>
<script src="<?=$base_url?>js/bootstrap.min.js"></script>
<script src="<?=$base_url?>js/bootstrap-datetimepicker.js"></script>
<link rel="stylesheet" href="<?=$base_url?>css/bootstrap-datetimepicker.min.css" />
<script src="<?=$base_url?>js/bootstrap-datetimepicker.es.js"></script></code>```

答:
You can merge your code and shorten it like this:</p>

```<code>$('#from, #to').datetimepicker({
      format: 'DD/MM/YYYY',
      maxViewMode: 0,
      language: 'es',
      daysOfWeekDisabled: '0,6',
      todayHighlight: true,
      minDate: new Date(1, 1, 2017),
      pickTime: false
});
</code>```

Body:
im from spain and i need to put the DD/MM/YYYY format in my datepicker, here is the code

Inicio de castigo

  <input type='text' id="from" name="from" class="form-control" readonly />

Final de castigo

  <input type='text' name="to" id="to" class="form-control" readonly />

I put in the script the MM-DD-YYYY fromat but when i pick the calendar he gives me the MM-DD-YYYY format, that is the uk hour. Today is 07 of June of 2017, and when i open it, it says that is 6 of July 2017. How can i solve that? It can be a problem of the datetimepicker.es.js files? . Thanks for the help guys :)

I have more information in that file, there are all the scripts i use

<link rel="stylesheet" href="<?=$base_url?>css/bootstrap-datetimepicker.min.css" />

Body:
You can merge your code and shorten it like this:

$('#from, #to').datetimepicker({
      format: 'DD/MM/YYYY',
      maxViewMode: 0,
      language: 'es',
      daysOfWeekDisabled: '0,6',
      todayHighlight: true,
      minDate: new Date(1, 1, 2017),
      pickTime: false
});


问:
Creating your own TinyURL
I have just found this great tutorial as it is something that I need.

However, after having a look, it seems that this might be inefficient. The way it works is, first generate a unique key then check if it exists in the database to make sure it really is unique. However, the larger the database gets the slower the function gets, right?

Instead, I was thinking, is there a way to add ordering to this function? So all that has to be done is check the previous entry in the DB and increment the key. So it will always be unique?

```<code>function generate_chars()

{

    $num_chars = 4; //max length of random chars
    $i = 0;
    $my_keys = "123456789abcdefghijklmnopqrstuvwxyz"; //keys to be chosen from
    $keys_length = strlen($my_keys);
    $url  = "";
    while($i<$num_chars)
    {
        $rand_num = mt_rand(1, $keys_length-1);
        $url .= $my_keys[$rand_num];
        $i++;
    }
    return $url;
}

function isUnique($chars)

{
    //check the uniqueness of the chars
    global $link;
    $q = "SELECT * FROM `urls` WHERE `unique_chars`='".$chars."'";
    $r = mysql_query($q, $link);
    //echo mysql_num_rows($r); die();
    if( mysql_num_rows($r)>0 ):
        return false;
    else:
        return true;
    endif;
}
</code>```

答:
I have also created small tinyurl service.

I wrote a script in Python that was generating keys and store in MySQL table named tokens with status U(Unused).

But, I am doing it in offline mode. I have a corn job on my VPS. It runs a script every 10 minutes. The script check if there are less than 1000 keys in the table, it keep generating keys and inserting them if they are unique and not already exists in the table until the key's count up to 1000.

For my service, 1000 keys for 10 minutes are more than enough, you can set the timing or number of keys generated according to your need.

Now when any tiny url needs to be created on my website, my PHP script just fetch any key which is unused from the table and marked its status as T(taken). PHP script does not have to bother about its uniqueness as my python script already populated only unique keys.

ContentLicense: CC BY-SA 2.5

Title: Creating your own TinyURL

Body:
I have just found this great tutorial as it is something that I need.

However, after having a look, it seems that this might be inefficient. The way it works is, first generate a unique key then check if it exists in the database to make sure it really is unique. However, the larger the database gets the slower the function gets, right?

Instead, I was thinking, is there a way to add ordering to this function? So all that has to be done is check the previous entry in the DB and increment the key. So it will always be unique?

function generate_chars()

{

    $num_chars = 4; //max length of random chars
    $i = 0;
    $my_keys = "123456789abcdefghijklmnopqrstuvwxyz"; //keys to be chosen from
    $keys_length = strlen($my_keys);
    $url  = "";
    while($i<$num_chars)
    {
        $rand_num = mt_rand(1, $keys_length-1);
        $url .= $my_keys[$rand_num];
        $i++;
    }
    return $url;
}

function isUnique($chars)

{
    //check the uniqueness of the chars
    global $link;
    $q = "SELECT * FROM `urls` WHERE `unique_chars`='".$chars."'";
    $r = mysql_query($q, $link);
    //echo mysql_num_rows($r); die();
    if( mysql_num_rows($r)>0 ):
        return false;
    else:
        return true;
    endif;
}


问:
How to read a file to a list of lists?
I want to create a list of lists from a file that contains the following data:

```<code>101 Rahul
102 Julie
103 Helena
104 Kally
</code>```

CODE

```<code>lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)
</code>```

Output I Want

```<code>[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]
</code>```

Output I m getting

```<code>['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']
</code>```

答:
Easiest way is to do it by list comprehension as the following:

```<code>with open("student_details.txt" , "r+") as f:
    lis = [line.split() for line in f]
</code>```

or if you want to loop you can loop through the file without reading it:

```<code>with open("student_details.txt" , "r+") as f:
    lis = []
    for line in f:
        lis.append(line.split())
</code>```

Title: How to read a file to a list of lists?

Body:
I want to create a list of lists from a file that contains the following data:

101 Rahul
102 Julie
103 Helena
104 Kally

CODE

lis = []

with open("student_details.txt" , "r+") as f:
    for i in range(1,3,1):
        for data in f.read().split():
            lis.append(data)
print(lis)

Output I Want

[[101,Rahul] ,[102,Julie] ,[103,Helena] ,[104,Kally]]

Output I m getting

['101', 'Rahul', '102', 'Julie', '103', 'Helena', '104', 'Kally']

Body:
Easiest way is to do it by list comprehension as the following:

with open("student_details.txt" , "r+") as f:
    lis = [line.split() for line in f]

or if you want to loop you can loop through the file without reading it:

with open("student_details.txt" , "r+") as f:
    lis = []
    for line in f:
        lis.append(line.split())


问:
Execute jQuery code after all CSS rules have been applied
$(document).ready() executes the code when all HTML elements have been loaded.

How to execute jQuery code after all of the CSS rules have been applied?

I have few stylesheets linked to the page and it takes some time to load the page. Element layout changes during the time of the loading.

For usability purposes I need to correct the element layout after all of them have target sizes. Otherwise I get wrong sizes of those elements.

Now I do it on focus or after some timeout, but need this after the page loads.

答: $(window).load() fires after the whole page (images, CSS, etc.) has loaded.


问:
Thread-safety of xll functions
I have this stupid xll function :

```<code>__declspec(dllexport) long F(long arg1, long arg2)
{
    return arg1 + arg2;
}
</code>```

I guess there's no problem with it, the resulting excel function will be thread-safe.

But what about a function taking arrays and returning arrays ? Consider for instance the function :

```<code>__declspec(dllexport) LPXLOPER12 WINAPI G(LPXLOPER12 arrayin1, LPXLOPER12 arrayin2)
{
    static XLOPER12 xlArray; // the reference to this one is going to be returned
    // treating arrayin1 and arrayin2 and outputting something in xlArray
    return static_cast<LPXLOPER12>(&xlArray);
}
</code>```

Obviously the static is bad for thread-safety and concurrent call in excel. How should I modify my function to ensure thread-safety ?

EDIT

Example of code using handles :

```<code>__declspec(dllexport) LPXLOPER12 WINAPI CreateComplex(LPXLOPER12 arrayin1, LPXLOPER12 arrayin2)
{
    static XLOPER12 xlArray;
    xlArray.xltype = xltypeStr;
    if (arrayin1->xltype != xltypeNum)
    {
        xlArray.val.str = L"blah";
        return static_cast<LPXLOPER12>(&xlArray);
    }
    if (arrayin2->xltype != xltypeNum)
    {
        xlArray.val.str = L"blahblah";
        return static_cast<LPXLOPER12>(&xlArray);
    }
    double real = arrayin1->val.num;
    double imag = arrayin2->val.num;
    Complex * z = new Complex(real, imag);
    char * handle = StoreObject("Complex", z);
    xlArray.xltype = xltypeStr;
    FromCharPtrToWChartPtr(handle, &xlArray.val.str);
    return static_cast<LPXLOPER12>(&xlArray);
}

__declspec(dllexport) double WINAPI GetComplexNorm(LPXLOPER12 arrayin)
{
    char *handle = nullptr;
    FromWChartPtrToWharPtr(arrayin->val.str, &handle);
    Complex * z = (Complex*)RetrieveObject(handle);
    double res = z->getNorm();
    return res;
}
</code>```

Complex being a classic complex numbers class, and the "memory" functions being as follows (beware it's old C code) :

```<code>#include "stdafx.h"
#include <string.h>
#include "memory.h"
#include <stdio.h>
#include "XLCALL.H"
#include <cstdlib>

void FromCharPtrToWChartPtr(char * from, XCHAR **to)
{
    size_t len = strlen(from);
    *to = new XCHAR[len + 1];
    *to[0] = static_cast<XCHAR>(len);
    if (len > 0)
    {
        mbstowcs(*to + 1, from, len + 1);
    }
}

void FromWChartPtrToWharPtr(XCHAR * from, char **to)
{
    size_t len = from[0];
    *to = new char[len + 1];
    wcstombs(*to, from + 1, len);
}

typedef struct _TObject
{
    char *name;
    int   version; /* increments by 1 for every new store operation */
    void *data;
    void *next;
} TObject;

static TObject *cache = NULL;

#define SEPARATOR '#'

TObject* FindNode(char* name)
{
    TObject *node = cache;
    while (node)
    {
        if (_stricmp(node->name, name) == 0)
            break;

        node = (TObject*)node->next;
    }

    return node;
}

#define FAILURE -1
#define SUCCESS 0

char* StoreObject(char* name, void* data)
{
    static char *routine = "StoreObject";
    int          status = FAILURE;
    char        *handle = NULL;
    TObject     *node;

    static char buffer[255];

    if (data == NULL)
    {
        // error to handle later
        goto done;
    }

    if (name == NULL)
    {
        // error to handle later
        goto done;
    }

    if (strlen(name) > 200)
    {
        // error to handle later
        goto done;
    }

    node = FindNode(name);
    if (node == NULL)
    {
        node = new TObject();
        if (node == NULL)
            goto done;

        node->name = _strdup(name);
        node->version = 1;
        node->data = data;
        node->next = cache;
        cache = node;
    }
    else
    {
        node->version += 1;
        delete node->data; // should I template taylor the object destruction diffenrently ?
        node->data = data;
    }

    sprintf(buffer, "%s%c%d\0", node->name, SEPARATOR, node->version);
    handle = _strdup(buffer);
    if (handle == NULL)
        goto done;

    strcpy(handle, buffer);
    status = SUCCESS;

done:
    if (status != SUCCESS)
    {
        // error to handle later
        delete handle;
        handle = NULL;
    }

    return handle;
}

void* RetrieveObject(char* handle)
{
    static char *routine = "RetrieveObject";
    int          status = FAILURE;
    void        *data = NULL;
    char        *name = NULL;
    TObject     *node;
    char        *sep;

    if (handle == NULL)
    {
        // error to handle later
        goto done;
    }

    name = _strdup(handle);
    if (name == NULL)
        goto done;

    /* remove version number from lookup string */
    sep = strchr(name, SEPARATOR);
    if (sep != NULL)
        *sep = '\0';

    node = FindNode(name);
    if (node == NULL)
    {
        // error to handle later
        goto done;
    }

    data = node->data;
    status = SUCCESS;

done:
    if (status != SUCCESS)
    {
        // error to handle later
        data = NULL;
    }

    delete name;
    return data;
}

void FreeObjects()
{
    TObject *next = cache;
    TObject *node;

    while (next)
    {
        node = next;
        next = (TObject*)node->next;
        delete node->name;
        delete node->data;
        delete node;
    }
}
</code>```

答: There is a good presentation on this MSN webpage, indeed static is not thread safe, you need to allocate the new variable to a thread local safe memory. You can have a look to the function get_thread_local_xloper12 in the aforementioned page.

Title: Thread-safety of xll functions

Body:
I have this stupid xll function :

__declspec(dllexport) long F(long arg1, long arg2)
{
    return arg1 + arg2;
}

I guess there's no problem with it, the resulting excel function will be thread-safe.

But what about a function taking arrays and returning arrays ? Consider for instance the function :

__declspec(dllexport) LPXLOPER12 WINAPI G(LPXLOPER12 arrayin1, LPXLOPER12 arrayin2)
{
    static XLOPER12 xlArray; // the reference to this one is going to be returned
    // treating arrayin1 and arrayin2 and outputting something in xlArray
    return static_cast<LPXLOPER12>(&xlArray);
}

Obviously the static is bad for thread-safety and concurrent call in excel. How should I modify my function to ensure thread-safety ?

EDIT

Example of code using handles :

__declspec(dllexport) LPXLOPER12 WINAPI CreateComplex(LPXLOPER12 arrayin1, LPXLOPER12 arrayin2)
{
    static XLOPER12 xlArray;
    xlArray.xltype = xltypeStr;
    if (arrayin1->xltype != xltypeNum)
    {
        xlArray.val.str = L"blah";
        return static_cast<LPXLOPER12>(&xlArray);
    }
    if (arrayin2->xltype != xltypeNum)
    {
        xlArray.val.str = L"blahblah";
        return static_cast<LPXLOPER12>(&xlArray);
    }
    double real = arrayin1->val.num;
    double imag = arrayin2->val.num;
    Complex * z = new Complex(real, imag);
    char * handle = StoreObject("Complex", z);
    xlArray.xltype = xltypeStr;
    FromCharPtrToWChartPtr(handle, &xlArray.val.str);
    return static_cast<LPXLOPER12>(&xlArray);
}

__declspec(dllexport) double WINAPI GetComplexNorm(LPXLOPER12 arrayin)
{
    char *handle = nullptr;
    FromWChartPtrToWharPtr(arrayin->val.str, &handle);
    Complex * z = (Complex*)RetrieveObject(handle);
    double res = z->getNorm();
    return res;
}

Complex being a classic complex numbers class, and the "memory" functions being as follows (beware it's old C code) :

#include "stdafx.h"
#include <string.h>
#include "memory.h"
#include <stdio.h>
#include "XLCALL.H"
#include <cstdlib>

void FromCharPtrToWChartPtr(char * from, XCHAR **to)
{
    size_t len = strlen(from);
    *to = new XCHAR[len + 1];
    *to[0] = static_cast<XCHAR>(len);
    if (len > 0)
    {
        mbstowcs(*to + 1, from, len + 1);
    }
}

void FromWChartPtrToWharPtr(XCHAR * from, char **to)
{
    size_t len = from[0];
    *to = new char[len + 1];
    wcstombs(*to, from + 1, len);
}

typedef struct _TObject
{
    char *name;
    int   version; /* increments by 1 for every new store operation */
    void *data;
    void *next;
} TObject;

static TObject *cache = NULL;

#define SEPARATOR '#'

TObject* FindNode(char* name)
{
    TObject *node = cache;
    while (node)
    {
        if (_stricmp(node->name, name) == 0)
            break;

        node = (TObject*)node->next;
    }

    return node;
}

#define FAILURE -1
#define SUCCESS 0

char* StoreObject(char* name, void* data)
{
    static char *routine = "StoreObject";
    int          status = FAILURE;
    char        *handle = NULL;
    TObject     *node;

    static char buffer[255];

    if (data == NULL)
    {
        // error to handle later
        goto done;
    }

    if (name == NULL)
    {
        // error to handle later
        goto done;
    }

    if (strlen(name) > 200)
    {
        // error to handle later
        goto done;
    }

    node = FindNode(name);
    if (node == NULL)
    {
        node = new TObject();
        if (node == NULL)
            goto done;

        node->name = _strdup(name);
        node->version = 1;
        node->data = data;
        node->next = cache;
        cache = node;
    }
    else
    {
        node->version += 1;
        delete node->data; // should I template taylor the object destruction diffenrently ?
        node->data = data;
    }

    sprintf(buffer, "%s%c%d\0", node->name, SEPARATOR, node->version);
    handle = _strdup(buffer);
    if (handle == NULL)
        goto done;

    strcpy(handle, buffer);
    status = SUCCESS;

done:
    if (status != SUCCESS)
    {
        // error to handle later
        delete handle;
        handle = NULL;
    }

    return handle;
}

void* RetrieveObject(char* handle)
{
    static char *routine = "RetrieveObject";
    int          status = FAILURE;
    void        *data = NULL;
    char        *name = NULL;
    TObject     *node;
    char        *sep;

    if (handle == NULL)
    {
        // error to handle later
        goto done;
    }

    name = _strdup(handle);
    if (name == NULL)
        goto done;

    /* remove version number from lookup string */
    sep = strchr(name, SEPARATOR);
    if (sep != NULL)
        *sep = '\0';

    node = FindNode(name);
    if (node == NULL)
    {
        // error to handle later
        goto done;
    }

    data = node->data;
    status = SUCCESS;

done:
    if (status != SUCCESS)
    {
        // error to handle later
        data = NULL;
    }

    delete name;
    return data;
}

void FreeObjects()
{
    TObject *next = cache;
    TObject *node;

    while (next)
    {
        node = next;
        next = (TObject*)node->next;
        delete node->name;
        delete node->data;
        delete node;
    }
}


问:
Horizontal progess bar with SASS (CSS3)
I'm creating and Angular2 component to achieve the following behavior:

I have an array (strings) in the component named "stepList". This is my view:

```<code><ul class="step">
    <li class="step__item selected" *ngFor="let step of stepList">
        {{step.label}}
    </li>
</ul>
</code>```

And this is my CSS:

```<code>.step{
    display: flex;

    &__item {
       display: block;
       padding-left: 25px;
    }
}
</code>```

With the current code, I have the items (names) rendered, but I don't know how to get the line with the circles underneath them.

Thanks in advance!

答: Padding on the label with a border-bottom to get the line. Create a div with a set height and width (so, for a circle, use the same height and width), forming a square. Add a border-radius of 50% which will make it circular in shape and put the div inside the label. Position absolutely so that it appears over the border-bottom.</p>

Title: Horizontal progess bar with SASS (CSS3)

Body:
I'm creating and Angular2 component to achieve the following behavior:

I have an array (strings) in the component named "stepList". This is my view:

        {{step.label}}

And this is my CSS:

.step{
    display: flex;

    &__item {
       display: block;
       padding-left: 25px;
    }
}

With the current code, I have the items (names) rendered, but I don't know how to get the line with the circles underneath them.

Thanks in advance!


问:
Declaring variable sized array without using dynamic memory allocation
I want to allocate variable sized 2D array in a function without using new operator such that this 2D array is available to other functions in the same file.

```<code>    void draw(int i)
    {   size=i;   }

    void assign(char symbol)
    {
        char one[size][size];
        /// ... Assigning values to one  ...
    }
    void display()
    {   /// Displaying values of one[size][size]
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            cout<<one[i][j];
            cout<<endl;
        }
    }
</code>```

Execution order of functions is draw -> assign -> display

This question may have been asked earlier.
But my problem is..
-> I can't declare the array outside assign function globally because value of size is not known.
-> I can't use "one" array in "display" function because its scope is limited to "assign" function.

And I also don't want to use either new or malloc operators.
Please help if there is any alternative available.

答:
If you don't want to use dynamic memory allocation then you must pay the cost of assigning some extra memory than what is required.
You define the size of array to be large enough to handle the data at hand.
like,

int arr[my_limit];

note that my_limit must be a constant expression.

In the program mentioned in the question, memory needs for the array 'one' is determined only at the runtime and hence it is a good practice to use dynamic memory allocation.

Body:
I want to allocate variable sized 2D array in a function without using new operator such that this 2D array is available to other functions in the same file.

    void draw(int i)
    {   size=i;   }

    void assign(char symbol)
    {
        char one[size][size];
        /// ... Assigning values to one  ...
    }
    void display()
    {   /// Displaying values of one[size][size]
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            cout<<one[i][j];
            cout<<endl;
        }
    }

Execution order of functions is draw -> assign -> display

This question may have been asked earlier.
But my problem is..
-> I can't declare the array outside assign function globally because value of size is not known.
-> I can't use "one" array in "display" function because its scope is limited to "assign" function.

And I also don't want to use either new or malloc operators.
Please help if there is any alternative available.


问:
Vue.js data: undefined
I am new to Vue.js.

Please advice me.

I get comments: undefined so comments are not displaying.
xhr is normal with 200.

Thank you
Thank you
Thank you
Thank you
Thank you

```<code><template>
 <div>
  <ul class="media-list">
     <li class="media" v-for="comment in comments">
         {{ $comment.body }}
     </li>
  </ul>
</div>
</template>

<script>
 export default {
    data () {
        return {
            comments: []
        }
    },
    props: {
        postid: null
    },
    methods: {
        getComments () {
            this.$http.get('/blog/' + this.postid + '/comments').then((response) => {
                this.comments = response.json().data;
            });
        }
    },
    mounted () {
        this.getComments();
    }
}
</code>```

答:
Basically there are two problems:

$comment don't exist

You have no data on response.json().data, that's why you get a undefined

I used a different API just to test it (as I don't have access to yours).

TEMPLATE

```<code><div id="app">
  <ul class="media-list">
    <li class="media" v-for="comment in comments">
      {{ comment.familyName + ', ' + comment.givenName }}
    </li>
  </ul>
</div>
</code>```

SCRIPT

```<code>new Vue({
    el: '#app',
  data () {
    return {
      comments: []
    }
  },
  props: {
    postid: null
  },
  methods: {
    getComments () {
      this.$http.get('//ergast.com/api/f1/drivers.json').then((response) => {
        this.comments = response.body.MRData.DriverTable.Drivers;
      });
    }
  },
  mounted () {
    this.getComments();
  }
});
</code>```

Check out a working example here

Title: Vue.js data: undefined

Body:
I am new to Vue.js.

Please advice me.

I get comments: undefined so comments are not displaying.
xhr is normal with 200.

Thank you
Thank you
Thank you
Thank you
Thank you

<template>

         {{ $comment.body }}

</template>

Body:
Basically there are two problems:

$comment don't exist

You have no data on response.json().data, that's why you get a undefined

I used a different API just to test it (as I don't have access to yours).

TEMPLATE

<div id="app">
  <ul class="media-list">
    <li class="media" v-for="comment in comments">
      {{ comment.familyName + ', ' + comment.givenName }}
    </li>
  </ul>
</div>

SCRIPT

new Vue({
    el: '#app',
  data () {
    return {
      comments: []
    }
  },
  props: {
    postid: null
  },
  methods: {
    getComments () {
      this.$http.get('//ergast.com/api/f1/drivers.json').then((response) => {
        this.comments = response.body.MRData.DriverTable.Drivers;
      });
    }
  },
  mounted () {
    this.getComments();
  }
});

Check out a working example here


问:
c# Serial port close
Already use this class, in Form1 and Form2

```<code>public class DataInput
{
    public event Action<string> DataReceived;

    private readonly SerialPort mySerialPort;

    public DataInput(string portName)
    {
        mySerialPort = new SerialPort();
        mySerialPort.PortName = portName;
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
        mySerialPort.Open();
    }

    private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string received = mySerialPort.ReadExisting();
        DataReceived?.Invoke(received);
    }
}
</code>```

Now when i close Form2 with this.Close(); i need close the Serial port too.
Because when i opend the form again it says Access to the port 'COM1' is denied.

How can i close the port??

答:
Combine @Ketan's solution and your code:

```<code>public class DataInput
{
    public event Action<string> DataReceived;

    ...

    public void Close()
    {
        if(mySerialPort.IsOpen)
        {
            mySerialPort.Close();
        }
    }
}
</code>```

In Form2:

```<code>private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    dataInput.Close();
}
</code>```

Title: c# Serial port close

Body:
Already use this class, in Form1 and Form2

public class DataInput
{
    public event Action<string> DataReceived;

    private readonly SerialPort mySerialPort;

    public DataInput(string portName)
    {
        mySerialPort = new SerialPort();
        mySerialPort.PortName = portName;
        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
        mySerialPort.Open();
    }

    private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        string received = mySerialPort.ReadExisting();
        DataReceived?.Invoke(received);
    }
}

Now when i close Form2 with this.Close(); i need close the Serial port too.
Because when i opend the form again it says Access to the port 'COM1' is denied.

How can i close the port??

Body:
Combine @Ketan's solution and your code:

public class DataInput
{
    public event Action<string> DataReceived;

    ...

    public void Close()
    {
        if(mySerialPort.IsOpen)
        {
            mySerialPort.Close();
        }
    }
}

In Form2:

private void Form2_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    dataInput.Close();
}


问:
Javascript sum of arrays and average
I have an issue with getting the sum of two arrays and combining their averages while rounding off.

I don't want to hardcode but rather pass two random arrays.
so here is the code but it keeps returning NaN

function sumAverage(arr) {
  var result = 0;
  // Your code here
  // set an array
  arr = [];
  a = [];
  b = [];
  arr[0] = a;
  arr[1] = b;

  var sum = 0;

  // compute sum of elements in the array
  for (var j = 0; j < a.length; j++) {
    sum += a[j];
  }

  // get the  average of elements in the array
  var total = 0;
  total += sum / a.length;

  var add = 0;

  for (var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;

  result += math + total;

  Math.round(result);

  return result;
}
console.log(sumAverage([
  [2, 3, 4, 5],
  [6, 7, 8, 9]
]));```

答:
Just try this method..this kind of issues sometimes occured for me.

For example

```<code> var total = 0;
 total = total + sum / a.length;
</code>```

And every concat use this method..

Title: Javascript sum of arrays and average

Body:
Just try this method..this kind of issues sometimes occured for me.

For example

 var total = 0;
 total = total + sum / a.length;

And every concat use this method..


问:
Find Character In Primary Key and Update a field
I'm working on a e-commerce website that uses CMS that uses MS Access 2000 database. The CMS generates the website pages on upload so there's no database online other than Perl files to control the shopping cart. The CMS allows the creation of duplicate products that can be placed elsewhere on the site

I have a table called PRODUCTS in my database. Whereby if a product is a duplicate of the original it contains ! in the primary key

Within the Product table I wish to turn off a setting for all the duplicate products only in the database.

I'm trying to create an SQL statement which would say..

FROM Products
Where Product_Reference contains the character !
Set Can_Be_Ordered_Online to False

Can anyone help?

答:
In regular MySQL it will be something like this:

```<code>UPDATE Products
    SET Products.Can_Be_Ordered_Online = 0
    WHERE Products.Product_Reference LIKE '*!*';
</code>```

It's hard to find MS Access 2000 docs online these days :(
Luckily, I've found this document about LIKE condition, therefore I've just updated my answer. % character is MySQL and other SQL-s wildcard, apparently in MS Access 2003 (and with some luck in MSA 2000 too!) the wildcard char are *, # and ?.

Nice history lesson :)

Body:
In regular MySQL it will be something like this:

UPDATE Products
    SET Products.Can_Be_Ordered_Online = 0
    WHERE Products.Product_Reference LIKE '*!*';

It's hard to find MS Access 2000 docs online these days :(
Luckily, I've found this document about LIKE condition, therefore I've just updated my answer. % character is MySQL and other SQL-s wildcard, apparently in MS Access 2003 (and with some luck in MSA 2000 too!) the wildcard char are *, # and ?.

Nice history lesson :)


问:
Custom UITableviewCell IBOutlet always nil
I have a custom UITableViewCell subclass with a simple IBOutlet setup for a UILabel.

```<code>class SegmentCell: UITableViewCell {

    @IBOutlet weak var test: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        test.text = "Some Text"
    }

    required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
    }

}
</code>```

Convinced I have everything set up correct have followed other answers, but the UILabel is always nil.

ViewController:
viewDidLoad:

```<code>self.tableView.registerClass(SegmentCell.self, forCellReuseIdentifier: "Cell")
</code>```

cellForForAtIndexPath

```<code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! SegmentCell
    return cell
}
</code>```

Cell is set to Custom

Reuse identifier is correct

Cells class is SegmentCell

Tableview content is Dynamic Prototypes

What am I missing?

答:
You should register it first in the viewDidLoad function.</p>

```<code>self.tableView.registerClass(CustomCell.self, forCellReuseIdentifier: "Cell")
</code>```

Body:
I have a custom UITableViewCell subclass with a simple IBOutlet setup for a UILabel.

class SegmentCell: UITableViewCell {

    @IBOutlet weak var test: UILabel!

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        test.text = "Some Text"
    }

    required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
    }

}

Convinced I have everything set up correct have followed other answers, but the UILabel is always nil.

ViewController:
viewDidLoad:

self.tableView.registerClass(SegmentCell.self, forCellReuseIdentifier: "Cell")

cellForForAtIndexPath

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! SegmentCell
    return cell
}

Cell is set to Custom

Reuse identifier is correct

Cells class is SegmentCell

Tableview content is Dynamic Prototypes

What am I missing?

Body:
You should register it first in the viewDidLoad function.

self.tableView.registerClass(CustomCell.self, forCellReuseIdentifier: "Cell")


问:
How to deepen array by having parent id-s (JavaScript)
The problem is like this. I have a flat array of Comment objects. Every comment object has parent_id in it. Ones without parents have parent_id set to null.
Now I want to have it nested. I mean like you see in HackerNews for example. For example add a field in Comment object, say children and in that field have all comments that are children or grandchildren or whatever of this comment. I did it with heavy way, I want to see much clearer and much more clever algorithm (I think mine is really heavy).
Here is my version.

```<code>find_children(pid = null) => {
  result = comments.filter(pid)
  if(result.length > 0) {
    result.forEach(currentComment => {
      currentComment.children = find_children(currentComment.parent_id)
    }
  }
}
</code>```

EDIT: Well actually I wrote the solution and it's working correctly. I want to get some reviews of it if possible, if it's a acceptable solution, can it be improved and so on.

```<code>export const nest_comments = (comments, parent_id = null) => {
  // defaults to null just to make it easier to call
  const current_children = filter(comments, {'parent_comment': parent_id});
  // first find the children by current parent_id
  if (current_children.length !== 0) { // if it's not empty (termination case)
    // then for each add new field called children which is actually again is
    // chunk of comments, so can be nested, that's why we recurse over
    // array again
    return current_children.map(current_comment => {
      current_comment.children = nest_comments(comments, current_comment.id)
      return current_comment
    })
  }
  else return undefined // undefined as in this case js will ignore the field
    // I think it needs to be other value though
}
</code>```

答:
You could use a Map to key your comments by id so to achieve a constant look-up time, when looking for a parent. You could pass this Map as the this object to a filter on the original array, and let that filter add each node to their respective parent's children array, and let that filter return the root.

Here is an implementation:

function makeTree(comments) {
    return comments.filter(function (comment) {
        let p = this.get(comment.parent_id);
        if (p) p.children = (p.children || []).concat(comment);
        return !p;
    }, new Map(comments.map( c => [c.id, c] )))[0];
}

// Sample data
var comments = [
    { id: 1, parent_id: null },
    { id: 2, parent_id: 1 },
    { id: 3, parent_id: 1 },
    { id: 4, parent_id: 2 },
    { id: 5, parent_id: 4 },
    { id: 6, parent_id: 3 },
];

// Perform the conversion
var root = makeTree(comments);

console.log(root);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
The problem is like this. I have a flat array of Comment objects. Every comment object has parent_id in it. Ones without parents have parent_id set to null.
Now I want to have it nested. I mean like you see in HackerNews for example. For example add a field in Comment object, say children and in that field have all comments that are children or grandchildren or whatever of this comment. I did it with heavy way, I want to see much clearer and much more clever algorithm (I think mine is really heavy).
Here is my version.

find_children(pid = null) => {
  result = comments.filter(pid)
  if(result.length > 0) {
    result.forEach(currentComment => {
      currentComment.children = find_children(currentComment.parent_id)
    }
  }
}

EDIT: Well actually I wrote the solution and it's working correctly. I want to get some reviews of it if possible, if it's a acceptable solution, can it be improved and so on.

export const nest_comments = (comments, parent_id = null) => {
  // defaults to null just to make it easier to call
  const current_children = filter(comments, {'parent_comment': parent_id});
  // first find the children by current parent_id
  if (current_children.length !== 0) { // if it's not empty (termination case)
    // then for each add new field called children which is actually again is
    // chunk of comments, so can be nested, that's why we recurse over
    // array again
    return current_children.map(current_comment => {
      current_comment.children = nest_comments(comments, current_comment.id)
      return current_comment
    })
  }
  else return undefined // undefined as in this case js will ignore the field
    // I think it needs to be other value though
}

Body:
You could use a Map to key your comments by id so to achieve a constant look-up time, when looking for a parent. You could pass this Map as the this object to a filter on the original array, and let that filter add each node to their respective parent's children array, and let that filter return the root.

Here is an implementation:

function makeTree(comments) {
    return comments.filter(function (comment) {
        let p = this.get(comment.parent_id);
        if (p) p.children = (p.children || []).concat(comment);
        return !p;
    }, new Map(comments.map( c => [c.id, c] )))[0];
}

// Sample data
var comments = [
    { id: 1, parent_id: null },
    { id: 2, parent_id: 1 },
    { id: 3, parent_id: 1 },
    { id: 4, parent_id: 2 },
    { id: 5, parent_id: 4 },
    { id: 6, parent_id: 3 },
];

// Perform the conversion
var root = makeTree(comments);

console.log(root);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to redirect to new page using ajax
I have created a login form,It POST data to another php page via ajax and check the user name and password validation.If user name or password is wrong it it display the error message on the login form.but If user authentication is OK it should redirect to corresponding page.but now it is loading in side the login form.How to redirect this successfully ?

this is back end logic

```<code>if ( password_verify($password, $user['passwrd']) ) {

        $userrole=$user['role'];

        switch($userrole){
            case 'admin':
                $_SESSION['username']=$username;
                $_SESSION['role']="admin";
                // This is how we'll know the user is logged in
                $_SESSION['logged_in'] = true;
                header('Location: admin-view.php');
                break;
</code>```

This code in front end page

```<code><script type="text/javascript">
    var frm= $('#login-form');
    frm.submit(function(e){
      e.preventDefault();

      $.ajax({
        type:frm.attr('method'),
        url:frm.attr('action'),
        data:frm.serialize(),
        success:function(data){
          $('#feedback').html(data).fadeIn( 300 ).delay( 1500 ).fadeOut( 400 );
        },
        error:function(data){
          console.log('An error occurred !');
          console.log(data);
        }
      });

    });

</script>
</code>```

答:
Right now you are passing the whole page as json data yoou need to relocate to the page like

```<code>    success:function(data){
            if(data==true)
{
window.location.href ="/YourPag.html";
}
);
            }
</code>```

,

Title: How to redirect to new page using ajax

Body:
I have created a login form,It POST data to another php page via ajax and check the user name and password validation.If user name or password is wrong it it display the error message on the login form.but If user authentication is OK it should redirect to corresponding page.but now it is loading in side the login form.How to redirect this successfully ?

this is back end logic

if ( password_verify($password, $user['passwrd']) ) {

        $userrole=$user['role'];

        switch($userrole){
            case 'admin':
                $_SESSION['username']=$username;
                $_SESSION['role']="admin";
                // This is how we'll know the user is logged in
                $_SESSION['logged_in'] = true;
                header('Location: admin-view.php');
                break;

This code in front end page

Body:
Right now you are passing the whole page as json data yoou need to relocate to the page like

    success:function(data){
            if(data==true)
{
window.location.href ="/YourPag.html";
}
);
            }

,


问:
What are some optimization techniques for MySQL table with 300+ million records?
I am looking at storing some JMX data from JVMs on many servers for about 90 days.  This data would be statistics like heap size and thread count.  This will mean that one of the tables will have around 388 million records.

From this data I am building some graphs so you can compare the stats retrieved from the Mbeans.  This means I will be grabbing some data at an interval using timestamps.

So the real question is, Is there anyway to optimize the table or query so you can perform these queries in a reasonable amount of time?

Thanks,

Josh

答: Well, for a start, I would suggest you use "offline" processing to produce 'graph ready' data (for most of the common cases) rather than trying to query the raw data on demand.</p>

OwnerDisplayName: Josh Harris

OwnerDisplayName: Andrew Rollings


问:
Check time in stored procedure
I have a stored procedure that takes a lot of time to execute. We want it to execute during the night, but it has to check for the current time every now and then, and at a given time it has to stop executing. How do I do that? Please provide me with the code I can use in my stored procedure. We are using Microsoft SQL Server 2005.</p>

答: Create Maintenance plan and sprecify start time for it. Create "Execute T-SQL statement task" in this plan and specify execution timeout for it (in seconds).</p>

Title: Check time in stored procedure


问:
Check date is within one year python
I have a date string formatted like this: "2017-05-31T06:44:13Z".

I need to check whether this date is within a one year span from today's date.

Which is the best method to do it: convert it into a timestamp and check, or convert into a date format?

答:
Convert the timestamp to a datetime object so it can be compared with other datetime objects using <, >, =.

```<code>from datetime import datetime
from dateutil.relativedelta import relativedelta

# NOTE this format basically ignores the timezone. This may or may not be what you want
date_to_check = datetime.strptime('2017-05-31T06:44:13Z', '%Y-%m-%dT%H:%M:%SZ')
today = datetime.today()
one_year_from_now = today + relativedelta(years=1)

if today <= date_to_check <= one_year_from_now:
    #   do whatever
</code>```

Title: Check date is within one year python

Body:
Convert the timestamp to a datetime object so it can be compared with other datetime objects using <, >, =.

from datetime import datetime
from dateutil.relativedelta import relativedelta

# NOTE this format basically ignores the timezone. This may or may not be what you want
date_to_check = datetime.strptime('2017-05-31T06:44:13Z', '%Y-%m-%dT%H:%M:%SZ')
today = datetime.today()
one_year_from_now = today + relativedelta(years=1)

if today <= date_to_check <= one_year_from_now:
    #   do whatever


问:
Change the background of one google sheets column based on the date in another column
I've seen lots of answers for various other conditions under which to do this. However I can't seem to modify any of these to work for a date range. What I want is for the column color of column E to change if the date in column H is between today and 5 days from today.

I've tried varying versions of this formula: H3:H150 =today() +5 with no success

This doesn't give me the range of between now and 5 days from now but I could do multiple rules like this and just go down on each one(=today() +4, =today() +3, etc) but obviously I need this rule to work first.

Thanks!

答:
Conditional formatting is more helpful than you seem to be expecting. Clear formatting from the column to be formatted, select it and Format, Conditional formatting..., Format cells if... Custom formula is and:

```<code>=and(H1>today(),H1<today()+6,H1<>"")
</code>```

Then select fill of choice and Done.

This should format the next five days (change the angled brackets around for the past five days).

Setting the range is achieved with selection of the column to be formatted (not the one with dates in it - H). If only to apply to Rows3:150 (and in general it is a good idea, for speed of processing, to restrict the ranges to which CF is applied) then either start by selecting Rows3:150 in the column to be formatted (instead of the entire column) or adjust the Apply to range for the rule, but in either case use H3 in place of H1 in the formula above.

CF should automatically apply the rule as written to the first row in the selected range and then adjust it for the second and subsequent rows in the way copying down would adjust the formula (if at all) were it in a cell in the sheet.

Body:
Conditional formatting is more helpful than you seem to be expecting. Clear formatting from the column to be formatted, select it and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and(H1>today(),H1<today()+6,H1<>"")

Then select fill of choice and Done.

This should format the next five days (change the angled brackets around for the past five days).

Setting the range is achieved with selection of the column to be formatted (not the one with dates in it - H). If only to apply to Rows3:150 (and in general it is a good idea, for speed of processing, to restrict the ranges to which CF is applied) then either start by selecting Rows3:150 in the column to be formatted (instead of the entire column) or adjust the Apply to range for the rule, but in either case use H3 in place of H1 in the formula above.

CF should automatically apply the rule as written to the first row in the selected range and then adjust it for the second and subsequent rows in the way copying down would adjust the formula (if at all) were it in a cell in the sheet.


问:
addNode of a managed WAS node fails on Deployment Manager
On an Linux machine (Machine_A), we currently have a Deployment Manager (commerce profile, DMGR profile).
On another Machine - Machine_B (commerce profile) we are creating a managed WAS node.
We need to add this node in our Deployment's Manager Cell on Machine_A. I have federated node for commerce profile in machine_A but when I am federating node with commerce profile in Machine_B then error occurred.

Error:-
ADMU0010E: Error obtaining repository client com.ibm.websphere.management.exception.AdminException: ADMU0038E: The Deployment Manager's IP address resolves as 127.0.0.1, but the Deployment Manager is not on the local machine.  The Deployment Manager's host name configuration or DNS is configured incorrectly.

答: You have problems in your hostname configurations. Check the /etc/hosts files on both machines and make sure there are hostnames (not localhost) entries in both mapped to the correct IP addresses. If you created DMGR profile using localhost, thats incorrect, and I'd suggest to recreate profiles or you will have to run scripts that changes the host names in profiles.</p>


问:
Python linear search not working
For some reason this python linear search will not work. Every time I run it and input a value that is in the list, it does not tell me that the item is in the list and just runs through.
It does not give any syntax error so must be something logical. Any ideas?</p>

```<code>def linearSearch():
numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
pointer = 0
print("What would you like to search for?")
searchTerm = input()
try:
    val = int(searchTerm)
except ValueError:
    print("Please enter an integer")
    linearSearch()
while pointer < len(numbers):
    if numbers[pointer] == searchTerm:
        print("Item has been found at " + pointer)
    else:
        pointer = pointer + 1
</code>```

答:
```<code>if numbers[pointer] == searchTerm:
</code>```

I think you meant to write:

```<code>if numbers[pointer] == val:
</code>```

searchTerm is a string (assuming we're in Python 3.X), so it will never compare equal to any of the integers in the list.

Additional problems:

You can't concatenate a string and an integer, so "Item has been found at" + pointer will crash. Try using print("Item has been found at", pointer) instead.

Your loop prints "Item has been found at..." infinitely, because you don't increment pointer when you find the item. Try adding a break after the print.

If the user doesn't enter an integer, you call linearSearch() again. But the original call is still on the stack, and will continue to execute once the inner call completes. Then it will crash with UnboundLocalError: local variable 'val' referenced before assignment, because val was never successfully created in that context. Consider a non-recursive approach, for example:

```<code>def linearSearch():
    numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
    pointer = 0
    print("What would you like to search for?")
    while True:
        try:
            val = int(input())
            break
        except ValueError:
            print("Please enter an integer")
    while pointer < len(numbers):
        if numbers[pointer] == val:
            print("Item has been found at", pointer)
            break
        else:
            pointer = pointer + 1

linearSearch()
</code>```

Title: Python linear search not working

Body:
For some reason this python linear search will not work. Every time I run it and input a value that is in the list, it does not tell me that the item is in the list and just runs through.
It does not give any syntax error so must be something logical. Any ideas?

def linearSearch():
numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
pointer = 0
print("What would you like to search for?")
searchTerm = input()
try:
    val = int(searchTerm)
except ValueError:
    print("Please enter an integer")
    linearSearch()
while pointer < len(numbers):
    if numbers[pointer] == searchTerm:
        print("Item has been found at " + pointer)
    else:
        pointer = pointer + 1

Body:
if numbers[pointer] == searchTerm:

I think you meant to write:

if numbers[pointer] == val:

searchTerm is a string (assuming we're in Python 3.X), so it will never compare equal to any of the integers in the list.

Additional problems:

You can't concatenate a string and an integer, so "Item has been found at" + pointer will crash. Try using print("Item has been found at", pointer) instead.

Your loop prints "Item has been found at..." infinitely, because you don't increment pointer when you find the item. Try adding a break after the print.

If the user doesn't enter an integer, you call linearSearch() again. But the original call is still on the stack, and will continue to execute once the inner call completes. Then it will crash with UnboundLocalError: local variable 'val' referenced before assignment, because val was never successfully created in that context. Consider a non-recursive approach, for example:

def linearSearch():
    numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
    pointer = 0
    print("What would you like to search for?")
    while True:
        try:
            val = int(input())
            break
        except ValueError:
            print("Please enter an integer")
    while pointer < len(numbers):
        if numbers[pointer] == val:
            print("Item has been found at", pointer)
            break
        else:
            pointer = pointer + 1

linearSearch()


答:
Use a border-bottom and a pseudo element:

.step{
  display: flex;
}

.step__item {
  display: block;
  position: relative;
  padding: 0 12px 25px;
  border-bottom: 1px solid lightgray;
}

.step__item::before {
  display: block;
  position: absolute;
  bottom: -5px;
  left: calc(50% - 5px);
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: gray;
  content: '';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="step">
    <li class="step__item selected">
        CATEGORIA
    </li>

    <li class="step__item selected">
        ATTRIBUTES
    </li>
</ul></code>```

And the SCSS code:

```<code>.step{
    display: flex;

    &__item {
        display: block;
        position: relative;
        padding: 0 12px 25px;
        border-bottom: 1px solid lightgray;

        &::before {
            display: block;
            position: absolute;
            bottom: -5px;
            left: calc(50% - 5px);
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: gray;
            content: '';
        }
    }
}
</code>```

Title: Horizontal progess bar with SASS (CSS3)

Body:
I'm creating and Angular2 component to achieve the following behavior:

I have an array (strings) in the component named "stepList". This is my view:

        {{step.label}}

And this is my CSS:

.step{
    display: flex;

    &__item {
       display: block;
       padding-left: 25px;
    }
}

With the current code, I have the items (names) rendered, but I don't know how to get the line with the circles underneath them.

Thanks in advance!

Body:
Use a border-bottom and a pseudo element:

.step{
  display: flex;
}

.step__item {
  display: block;
  position: relative;
  padding: 0 12px 25px;
  border-bottom: 1px solid lightgray;
}

.step__item::before {
  display: block;
  position: absolute;
  bottom: -5px;
  left: calc(50% - 5px);
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: gray;
  content: '';
}

<ul class="step">
    <li class="step__item selected">
        CATEGORIA
    </li>

    <li class="step__item selected">
        ATTRIBUTES
    </li>
</ul>

And the SCSS code:

.step{
    display: flex;

    &__item {
        display: block;
        position: relative;
        padding: 0 12px 25px;
        border-bottom: 1px solid lightgray;

        &::before {
            display: block;
            position: absolute;
            bottom: -5px;
            left: calc(50% - 5px);
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: gray;
            content: '';
        }
    }
}


答:
http://jsfiddle.net/exjxw7m6/

```<code>ul.progress-bar {
    height: 300px;
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    overflow: hidden;
    &::after {
        content: "";
        position: absolute;
        top:5px;
        left:5px;
        background: #777;
        height: 5px;
        width: 100%;
    }
    li {
        background: #000;
        border-radius: 100px;
        width: 15px;
        height: 15px;
        z-index: 1;
        position: relative;
        &.stop ~ li {
            background: #777;
            &::after {
                height: 0;
            }
        }
        &::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 5px;
            background: #000;
            width: 5px;
            height: 100vh;
        }
    }
}
</code>```

more info here: (credit) Progress bar made of solid line, with dots as steps

Title: Horizontal progess bar with SASS (CSS3)

Body:
http://jsfiddle.net/exjxw7m6/

ul.progress-bar {
    height: 300px;
    list-style: none;
    margin: 0;
    padding: 0;
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    overflow: hidden;
    &::after {
        content: "";
        position: absolute;
        top:5px;
        left:5px;
        background: #777;
        height: 5px;
        width: 100%;
    }
    li {
        background: #000;
        border-radius: 100px;
        width: 15px;
        height: 15px;
        z-index: 1;
        position: relative;
        &.stop ~ li {
            background: #777;
            &::after {
                height: 0;
            }
        }
        &::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 5px;
            background: #000;
            width: 5px;
            height: 100vh;
        }
    }
}

more info here: (credit) Progress bar made of solid line, with dots as steps


问:
PYTHON WebServer Daemon
The following code is a WebServer written by me.

```<code>#!/usr/bin/python

import BaseHTTPServer
import CGIHTTPServer

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 80)
handler.cgi_dicrectories = ["/cgi"]

httpd = server(server_address, handler)

try:
        httpd.serve_forever()
except KeyboardInterrupt:
        httpd.shutdown()
</code>```

The problem is that every time I use it, I have to launch it.
How can I make it become a Demon and make it work in the background?

答: You cat use RunIt or write daemon on python (see a python-daemon)</p>

Title: PYTHON WebServer Daemon

Body:
The following code is a WebServer written by me.

#!/usr/bin/python

import BaseHTTPServer
import CGIHTTPServer

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 80)
handler.cgi_dicrectories = ["/cgi"]

httpd = server(server_address, handler)

try:
        httpd.serve_forever()
except KeyboardInterrupt:
        httpd.shutdown()

The problem is that every time I use it, I have to launch it.
How can I make it become a Demon and make it work in the background?


问:
Generating unique, ordered Pythagorean triplets
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks.</p>

```<code>import math

def main():
    for x in range (1, 1000):
        for y in range (1, 1000):
            for z in range(1, 1000):
                if x*x == y*y + z*z:
                    print y, z, x
                    print '-'*50

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

答:
```<code>from  math import sqrt
from itertools import combinations

#Pythagorean triplet - a^2 + b^2 = c^2 for (a,b) <= (1999,1999)
def gen_pyth(n):
if n >= 2000 :
  return
ELEM =   [  [ i,j,i*i + j*j ] for i , j in list(combinations(range(1, n +   1 ), 2)) if sqrt(i*i + j*j).is_integer() ]
print (*ELEM , sep = "\n")

gen_pyth(200)
</code>```

OwnerDisplayName: marc lincoln

Body:
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks.

import math

def main():
    for x in range (1, 1000):
        for y in range (1, 1000):
            for z in range(1, 1000):
                if x*x == y*y + z*z:
                    print y, z, x
                    print '-'*50

if __name__ == '__main__':
    main()


答:
you can redirect to another page in javascript
like this

```<code>window.location.href = "http://stackoverflow.com";
</code>```

good luck

Title: How to redirect to new page using ajax

Body:
you can redirect to another page in javascript
like this

window.location.href = "http://stackoverflow.com";

good luck


答:
Basically I see a mistake here:
     arr[0] = a; arr[1] = b;

That should be
    a= arr[0]; b= arr[1];

and then remove:
             arr = [];

I suggest you write your function like this:

```<code>function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}
</code>```

Title: Javascript sum of arrays and average

Body:
I have an issue with getting the sum of two arrays and combining their averages while rounding off.

I don't want to hardcode but rather pass two random arrays.
so here is the code but it keeps returning NaN

function sumAverage(arr) {
  var result = 0;
  // Your code here
  // set an array
  arr = [];
  a = [];
  b = [];
  arr[0] = a;
  arr[1] = b;

  var sum = 0;

  // compute sum of elements in the array
  for (var j = 0; j < a.length; j++) {
    sum += a[j];
  }

  // get the  average of elements in the array
  var total = 0;
  total += sum / a.length;

  var add = 0;

  for (var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;

  result += math + total;

  Math.round(result);

  return result;
}
console.log(sumAverage([
  [2, 3, 4, 5],
  [6, 7, 8, 9]
]));

Body:
Basically I see a mistake here:
     arr[0] = a; arr[1] = b;

That should be
    a= arr[0]; b= arr[1];

and then remove:
             arr = [];

I suggest you write your function like this:

function sum(arr) {
var arr1 = arr[0]
var sum1 = 0;
arr1.map(function(e){sum1+=e});
var arr2 = arr[1]
var sum2 = 0;
arr2.map(function(e){sum2+=e});
return Math.round(sum1/arr1.length + sum2/arr2.length);
}


问:
Regex alphanumeric with special characters
I need to validate input string using regex which should met below requirements:

If All Numbers -> Error

If All Special Characters -> Error

If only Numbers + special Characters -> Error

Remaining all should be flagged as non error.

I couldn't get all my test cases passed.

Here is my regex:

```<code>\d*([a-zA-Z,\/().]*[a-zA-Z][\d,\/().]*)[a-zA-Z\d\s]*$
</code>```

For the special characters, I get a specific list ,\/(). to let them in. Can anyone help me to understand this?

答:
Going strictly by your requirements, the following would do:

```<code>[^\d,\\\/().]
</code>```

which matches if there is any "triggering" character (non digit, non special)

If you want to match the whole string, use

```<code>^.*[^\d,\\\/().].*$
</code>```

Body:
I need to validate input string using regex which should met below requirements:

If All Numbers -> Error

If All Special Characters -> Error

If only Numbers + special Characters -> Error

Remaining all should be flagged as non error.

I couldn't get all my test cases passed.

Here is my regex:

\d*([a-zA-Z,\/().]*[a-zA-Z][\d,\/().]*)[a-zA-Z\d\s]*$

For the special characters, I get a specific list ,\/(). to let them in. Can anyone help me to understand this?

Body:
Going strictly by your requirements, the following would do:

[^\d,\\\/().]

which matches if there is any "triggering" character (non digit, non special)

If you want to match the whole string, use

^.*[^\d,\\\/().].*$


问:
Server access through private network
I am currently working on a server (I made using java) to share informations between computers within the same private network.

My problem is:

I can access this server through http://localhost or 127.0.0.1 on my "server machine"

but i cannot access it from another computer using the "server machine" local IP adress.

Trying with XAMPP, the port 80 is accessible by everyone but with my java server: no access, i got a "Timeout" exception from the remote client (still on the same private network)

My question is:

How is XAMPP (or Apache) able to forward port 80 to let every other computer access the "server machine" ?

What do i need to setup on MY server in order to let those computers access MY server ?

答:
You are probably binding your application to localhost (127.0.0.1) only, making it reachable only from your machine.

What do i need to setup on MY server in order to let those computers access MY server ?

Try binding the app to other network interfaces, or simply try 0.0.0.0 for test (this will bind to ALL of them). Note that this is usually not a preferred method, especially if you have a public IP configured on that machine.

How is XAMPP (or Apache) able to forward port 80 to let every other computer access the "server machine" ?

Check the Apache module mod_proxy for this.

Title: Server access through private network


问:
Insert text at the beginning of every new line
I'm having an issue. I'm making a video transcription solution. When I hit Enter, I need to add a time flag — so that the user could type until they hit Enter again, but all I get is the time flag at the end of each line.

I appreciate any help.

Expected Result

```<code>[hh:mm:ss] my text
</code>```

Actual Result

```<code>my text [hh:mm:ss]
my new text
</code>```

Code

```<code>//if (!(start_element.hasAttribute('title'))) {
  start_element.setAttributes({
    'title': tim
  });

  var charCode = (evt.which) ? evt.which : event.keyCode;

  console.log(evt.data.keyCode);

  if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('[' + tim + ']');
  }
//}
</code>```

答:
At the end, you could use regex to move all time flags from the end to the beginning.
Use /^(.*)(\[[0-9][0-9]?:[[0-9][0-9]?\])$/gm(Regex101) to find it, and replace with $2 $1. Because it only matches at the end of the line, it shouldn't pick up any in the middle, if someone were to place a manual timestamp.

Explanation (from Regex101)

/^(.*)([[0-9][0-9]?:[[0-9][0-9]?])$/gm

^ asserts position at start of a line

1st Capturing Group (.*)

.* matches any character (except for line terminators)

Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group ([[0-9][0-9]?:[[0-9][0-9]?])

[ matches the character [ literally (case sensitive)

Match a single character present in the list below [0-9]

0-9 a single character in the range between 0 (ASCII 48) and 9 (ASCII 57) (case sensitive)

Match a single character present in the list below [0-9]?

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

0-9 a single character in the range between 0 (ASCII 48) and 9 (ASCII 57) (case sensitive)

: matches the character : literally (case sensitive)

Match a single character present in the list below [[0-9]

[ matches the character [ literally (case sensitive)

0-9 a single character in the range between 0 (ASCII 48) and 9 (ASCII 57) (case sensitive)

Match a single character present in the list below [0-9]?

] matches the character ] literally (case sensitive)

$ asserts position at the end of a line

Global pattern flags

g modifier: global. All matches (don't return after first match)

m modifier: multi line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)>

Body:
I'm having an issue. I'm making a video transcription solution. When I hit Enter, I need to add a time flag — so that the user could type until they hit Enter again, but all I get is the time flag at the end of each line.

I appreciate any help.

Expected Result

[hh:mm:ss] my text

Actual Result

my text [hh:mm:ss]
my new text

Code

//if (!(start_element.hasAttribute('title'))) {
  start_element.setAttributes({
    'title': tim
  });

  var charCode = (evt.which) ? evt.which : event.keyCode;

  console.log(evt.data.keyCode);

  if (evt.data.keyCode == 13) {
    CKEDITOR.instances.editor1.insertHtml('[' + tim + ']');
  }
//}