问:
aws ssl with load balancer - ec2 instance https requests seems not terminated by ELB
I am hosting a domain in aws and want to allow https requests to it. I have done the following steps.

requested a certificate from ACM, validated the emails and it is issued.

created a classic load balancer (LB) with http and https listeners that forward to the instance through http(80).

attached the certificate to the LB and added the instance that runs the website.

made sure the security groups attached to the instance and LB have http(80) and https(443) in the inbound rules.

the only outbound rule is (All traffic - All - All - 0.0.0.0/0) for both LB and instance security groups.

I then waited for the instance to be "inService" and tested the LB by browsing to its DNS and it opened. also http ://mydomain.com opened but when I tried https ://mydomain.com I get a message that the browser can't reach the server.

After some search I added the following 2 records.

A record with name "mydomain.com" and value "LB domain.com".

CNAME record with name "www" and value "mydomain.com".

I tried again but got the same results as above.
Finally I came to an answer that I should enable https in my instance server.

when I did this and browsed I got a "Secure Connection Failed" with Error code "SSL_ERROR_RX_RECORD_TOO_LONG".

it looks like the LB doesn't terminate the https requests to my domain.

Any idea what I have done wrong!

Update: I removed the A record I created but when I made a DNS lookup, I found an A record pointing to my elastic ip. and although I have a CNAME record, the DNS lookup showed that I have no CNAME records.

答:
Ok, it was a silly mistake. the person who was working before me registered the domain name in godaddy and just pointed to the instance using A record on godaddy. so the records I added in route53 were meaningless. so I made a CNAME record in godaddy that resolves to the ELB DNS and every thing is working fine now.

For those who may be stuck in similar problem, I will try to write some advice.

First, when you choose to add a load balancer, then your instance shouldn't be directly accessed by clients. you should redirect users to the ELB and the ELB will do the rest.
if you got your DNS from somewhere else rather than AWS, then follow the first paragraph in this answer. else if you have a working hosted zone for your domain in AWS then add an A record in Route53.

After this step if https is still not working. you can check whether the requests to your domain reaches the ELB or not. you can do this using load balancer log Access or cloudwatch. they both give you the requests that reached your loadbalancer. cloudwatch is simpler to use but log Access gives you more details for the request.

if requests don't reach then the record you added haven't propagated yet or you didn't add them in the right place (like I did).

if the requests did reach the ELB but there is still a problem then you might have missed something in the setup. make sure you make the 5 steps mentioned in the question. this video will be very helpful in this case.

Finally, it worth mentioning that if you use a certificate from ACM, you don't have to do any changes in the server running on your instance to make https work because in this case the ELB stands in front of your instance and it does all work for you. Of course you can make ssl between your ELB and
instance but this is another story.


来源: stackexchange

问:
jQuery get parent with specific class
I am listening to clicks on an element with a specific class. When I click inside this element I want to get this element, not the children I clicked on. How do I avoid getting children back when I call

```<code>event.target
</code>```

Here is fiddle I created to demonstrate the problem
https://jsfiddle.net/yxvfgkcs/

Since I get children back they get CSS applied to them instead of the parent.

How do I figure out I have clicked on a child of element and get the element with class selectable back?

答:
Since you're already using jQuery you can use .closest():

```<code>var clickedField = $(e.target).closest(".selectable");
</code>```

See updated JSFiddle

ContentLicense: CC BY-SA 3.0

Title: jQuery get parent with specific class

Body:
I am listening to clicks on an element with a specific class. When I click inside this element I want to get this element, not the children I clicked on. How do I avoid getting children back when I call

event.target

Here is fiddle I created to demonstrate the problem
https://jsfiddle.net/yxvfgkcs/

Since I get children back they get CSS applied to them instead of the parent.

How do I figure out I have clicked on a child of element and get the element with class selectable back?

Body:
Since you're already using jQuery you can use .closest():

var clickedField = $(e.target).closest(".selectable");

See updated JSFiddle


问:
Javascript - remove split method
I am trying to create the select application using Javascipt only. I got to know about this code on internet and it uses the split method to return value and .innerHTML. Now say if I do not want to use the split method and just return with .innerHTML into html element with no value, how to do that using for loop as used in this code ?</p>

```<code>   <!DOCTYPE html>
<html>
<head>
    <title>Select Options</title>
</head>
<body>

<h2>Choose your car</h2>
<hr>

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

<hr>

Choose Car Model
<select id="slct2" ></select>

</body>

<script type="text/javascript">
    function populate(s1,s2){
        var s1 = document.getElementById(s1);
        var s2 = document.getElementById(s2);
        s2.innerHTML = "";

        if(s1.value == "Hyundai") {
            var optionArray = ["|", "i10|i10","i20|i20", "Verna|Verna"]
        }
        for(var option in optionArray){
            var pair = optionArray[option].split("|");
            var newOption = document.createElement('option');
            newOption.value = pair[0];
            newOption.innerHTML = pair[1];
            s2.options.add(newOption);
        }
    }
</script>

</html>
</code>```

答:
Left value to "" to keep it empty.

```<code>for(var option in optionArray){
   var text = optionArray[option];
   var newOption = document.createElement('option');
   newOption.value = "";
   newOption.innerHTML = text;
   s2.options.add(newOption, null);
}
</code>```

Title: Javascript - remove split method

Body:
I am trying to create the select application using Javascipt only. I got to know about this code on internet and it uses the split method to return value and .innerHTML. Now say if I do not want to use the split method and just return with .innerHTML into html element with no value, how to do that using for loop as used in this code ?

   <!DOCTYPE html>

    <title>Select Options</title>

Choose your car

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

Choose Car Model
<select id="slct2" ></select>

Body:
Left value to "" to keep it empty.

for(var option in optionArray){
   var text = optionArray[option];
   var newOption = document.createElement('option');
   newOption.value = "";
   newOption.innerHTML = text;
   s2.options.add(newOption, null);
}


问:
Hide for desk top show for mobile css
I am trying to create separate page for mobile view it should be hidden for
 desk top see my css and html whats wrong in this code ?

Code:

```<code><form class="form-signin-login" method="post" id="login-form">
                    <input type="text" name="user_entered_id" id="user_entered_id" value="Email (or) Phone No" onblur="if(this.value=='') this.value='Email (or) Phone No'" onfocus="if(this.value =='Email (or) Phone No' ) this.value=''">
                     <input type="password" name="lgpassword" id="lgpassword" value="Password" onblur="if(this.value=='') this.value='Password'" onfocus="if(this.value =='Password' ) this.value=''">
                    <input type="submit" class="button" name="submit" value="Login">
            </form>

 <style>

body{
background-color:#000;}
    @media screen and (max-width:300px) {

.input[type=text], .input[type=password]{width: 100%;
padding: 12px 20px;
background-color:#000;
color:#fff;
outline:none;
border: none;
border-bottom: 1px solid #fff;

margin: 8px 0;
-webkit-box-shadow: 0 0 0px 1000px black inset;
-webkit-text-fill-color: white !important;

  }
 }

    </style>
</code>```

答: @media add min-width and max-width (for mobil and desktop), to hide use property visibility (value: visible | hidden | collapse | inherit |);Note: All other elements on the page do not change their position.</p>

Title: Hide for desk top show for mobile css

Body:
I am trying to create separate page for mobile view it should be hidden for
 desk top see my css and html whats wrong in this code ?

Code:

<form class="form-signin-login" method="post" id="login-form">
                    <input type="text" name="user_entered_id" id="user_entered_id" value="Email (or) Phone No" onblur="if(this.value=='') this.value='Email (or) Phone No'" onfocus="if(this.value =='Email (or) Phone No' ) this.value=''">
                     <input type="password" name="lgpassword" id="lgpassword" value="Password" onblur="if(this.value=='') this.value='Password'" onfocus="if(this.value =='Password' ) this.value=''">
                    <input type="submit" class="button" name="submit" value="Login">
            </form>


问:
Strange namespacing in .net core
in Visual Studio 2017 I have a solution with aspnet core project and about 10 net core libraries referenced to each other.

One of the libraries is xUnit test project. It referenced to another project it should use as aim for testing.

For example I have:

```<code>Project: MyProject.Domain
Test Project: MyProject.Domain.Tests
</code>```

MyProject.Domain.Tests is referenced to MyProject.Domain.

In these projects I have classes with namespaces like project names.
So the strange thing happened when I can use public class from MyProject.Domain WITHOUT using MyProject.Domain.

Can anybody explain it ?

答:
If I understand you correctly, you're wondering why a type in the namespace MyProject.Domain.Tests can access types in the namespace MyProject.Domain without any usings. The reason for that is that the specification says so. From Namespace and type names (edited by removing irrelevant parts):

The meaning of a namespace_or_type_name is determined as follows:

If the namespace_or_type_name is of the form I:

For each namespace N, starting with the namespace in which the namespace_or_type_name
  occurs, continuing with each enclosing namespace (if any), and ending
  with the global namespace, the following steps are evaluated until an
  entity is located:

If N contains an accessible type having name I, then:

The namespace_or_type_name refers to the type.

Title: Strange namespacing in .net core

Body:
in Visual Studio 2017 I have a solution with aspnet core project and about 10 net core libraries referenced to each other.

One of the libraries is xUnit test project. It referenced to another project it should use as aim for testing.

For example I have:

Project: MyProject.Domain
Test Project: MyProject.Domain.Tests

MyProject.Domain.Tests is referenced to MyProject.Domain.

In these projects I have classes with namespaces like project names.
So the strange thing happened when I can use public class from MyProject.Domain WITHOUT using MyProject.Domain.

Can anybody explain it ?


问:
How to convert target values with pig?
I have some data with a target of 4 values and I want three of these to become part of one single using latin pig.

```<code>Input:                     Output:
ID     | Target            ID     | Target
-----------------          -----------------
test1      1               test1      1
test2      1               test2      1
test3      2               test3      2
test4      2               test4      2
test5      3               test5      2
test6      4               test6      2
test7      2               test7      2
</code>```

Someone knows the best way to do it

答:
Use Bincond to check for target value greater than 1 and if true replace it with the value you want,in this case 2.</p>

```<code>A = LOAD 'data.txt' USING PigStorage('\t') AS (Id:chararray,target:int);
B = FOREACH A GENERATE Id,(target > 1 ? 2 : target);
DUMP B;
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to convert target values with pig?

Body:
I have some data with a target of 4 values and I want three of these to become part of one single using latin pig.

Input:                     Output:
ID     | Target            ID     | Target
-----------------          -----------------
test1      1               test1      1
test2      1               test2      1
test3      2               test3      2
test4      2               test4      2
test5      3               test5      2
test6      4               test6      2
test7      2               test7      2

Someone knows the best way to do it

Body:
Use Bincond to check for target value greater than 1 and if true replace it with the value you want,in this case 2.

A = LOAD 'data.txt' USING PigStorage('\t') AS (Id:chararray,target:int);
B = FOREACH A GENERATE Id,(target > 1 ? 2 : target);
DUMP B;


问:
While loop stuck at random points on the code
i need help, i had my friend to help me debug this code, and we found that the code stops at random points on the code, sometimes on first loop, sometimes on last loop and so on.
the code is just to make a 9x9 sudoku board with all the rules applied. when i tested each block separately it worked and printed a well done sudoku board, but the problem here is that is gets stuck somehow.
help will be appreciated.</p>

```<code>int[,] helpblock = new int[10, 10];
int[,] helplines = new int[10, 10];
int[,] helpcols = new int[10, 10];
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        helplines[i, j] = 0;
        helpcols[i, j] = 0;
        helpblock[i, j] = 0;
    }
}

Random rnf = new Random();
int help1;
for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        help1 = rnf.Next(1, 10);
        if (i == 0 || i == 1 || i == 2) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[0, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[1, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[2, help1]++;
            }
        } else if (i == 3 || i == 4 || i == 5) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[3, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[4, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[5, help1]++;

            }
        } else if (i == 6 || i == 7 || i == 8) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[6, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[7, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[8, help1]++;
            }
        }
    }
}

PrintSudoku(map);
</code>```

答:
These loops look deadly:

```<code>while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
    System.Threading.Thread.Sleep(1);
    help1 = rnf.Next(1, 10);
}
</code>```

If the new value of help1 doesn't change the while condition to false, it will loop forever.

Body:
i need help, i had my friend to help me debug this code, and we found that the code stops at random points on the code, sometimes on first loop, sometimes on last loop and so on.
the code is just to make a 9x9 sudoku board with all the rules applied. when i tested each block separately it worked and printed a well done sudoku board, but the problem here is that is gets stuck somehow.
help will be appreciated.

int[,] helpblock = new int[10, 10];
int[,] helplines = new int[10, 10];
int[,] helpcols = new int[10, 10];
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        helplines[i, j] = 0;
        helpcols[i, j] = 0;
        helpblock[i, j] = 0;
    }
}

Random rnf = new Random();
int help1;
for (int i = 0; i < 9; i++) {
    for (int j = 0; j < 9; j++) {
        help1 = rnf.Next(1, 10);
        if (i == 0 || i == 1 || i == 2) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[0, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[0, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[1, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[1, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[2, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[2, help1]++;
            }
        } else if (i == 3 || i == 4 || i == 5) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[3, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }
                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[3, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[4, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[4, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[5, help1]++;

            }
        } else if (i == 6 || i == 7 || i == 8) {
            if (j == 0 || j == 1 || j == 2) {
                if (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[6, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[6, help1]++;
            } else if (j == 3 || j == 4 || j == 5) {
                if (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[7, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[7, help1]++;
            } else if (j == 6 || j == 7 || j == 8) {
                if (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                    while (helplines[i, help1] != 0 || helpblock[8, help1] != 0 || helpcols[j, help1] != 0) {
                        System.Threading.Thread.Sleep(1);
                        help1 = rnf.Next(1, 10);
                    }
                }

                map[i, j] = help1;
                helplines[i, help1]++;
                helpcols[j, help1]++;
                helpblock[8, help1]++;
            }
        }
    }
}

PrintSudoku(map);

Body:
These loops look deadly:

while (helplines[i, help1] != 0 || helpblock[5, help1] != 0 || helpcols[j, help1] != 0) {
    System.Threading.Thread.Sleep(1);
    help1 = rnf.Next(1, 10);
}

If the new value of help1 doesn't change the while condition to false, it will loop forever.


问:
array push of records obtained from mongo db
In MEAN stack, I am trying to store the records obtained from mongo db in an array, but I am not able to store the record in an array.

This is my code, I am trying to push the records obtained from projectimage to fulldetails[] array, but it failed. Suggest me the possible solution to store the mongo db records to array

```<code>    var express = require("express"),
     router = express.Router(),
     project = require("../../models/project.js"),
     projectimage = require("../../models/projectimages.js"),

             var details=data;
                 var fulldetails=[];

for (var i = 0; i < details.length; i++) {
    var prjct_id=details[i]._id;
    console.log('below'+i);
    fulldetails.push(details[i]);
    projectimage.findOne({projectId: prjct_id}, function(err, data){
       fulldetails.concat(data);
                   });
    console.log(fulldetails);
       return false;
}
</code>```

答:
I think what do you want is to get an array from your Mongo collection, correct me if I am wrong.

I am also assuming that Mongo query runs successfully, and returns the records correctly. then you can use toArray function to get array in callback.

```<code>// let's say Furniture is your collection
let furniture = Furniture.find({});
let details = [];
furniture.toArray((err, array) => {
  if (err) return;
  details = array; // now details has your collections' documents
});
</code>```

For more refer this

Let me know if this is not what you were looking for.

Body:
In MEAN stack, I am trying to store the records obtained from mongo db in an array, but I am not able to store the record in an array.

This is my code, I am trying to push the records obtained from projectimage to fulldetails[] array, but it failed. Suggest me the possible solution to store the mongo db records to array

    var express = require("express"),
     router = express.Router(),
     project = require("../../models/project.js"),
     projectimage = require("../../models/projectimages.js"),

             var details=data;
                 var fulldetails=[];

for (var i = 0; i < details.length; i++) {
    var prjct_id=details[i]._id;
    console.log('below'+i);
    fulldetails.push(details[i]);
    projectimage.findOne({projectId: prjct_id}, function(err, data){
       fulldetails.concat(data);
                   });
    console.log(fulldetails);
       return false;
}

Body:
I think what do you want is to get an array from your Mongo collection, correct me if I am wrong.

I am also assuming that Mongo query runs successfully, and returns the records correctly. then you can use toArray function to get array in callback.

// let's say Furniture is your collection
let furniture = Furniture.find({});
let details = [];
furniture.toArray((err, array) => {
  if (err) return;
  details = array; // now details has your collections' documents
});

For more refer this

Let me know if this is not what you were looking for.


问:
Python to save webpages in pdf format
So, I have a list of webpages that I want to save as pdf. They are like http://nptel.ac.in/courses/115103028/module1/lec1/3.html. The list is very long that's why I am using python to automate the process. This is my code

```<code>import pdfkit
import urllib2

page = urllib2.urlopen('http://nptel.ac.in/courses/115103028/module1/lec1/3.html')

page_content = page.read()

with open('page_content.html', 'w') as fid:
    fid.write(page_content)

txt=open("page_content.html").read().split("\n")

txt1=""
for i in txt:
    if not ".html" in i:
        txt1+=i+"\n"

with open('page_content.html',"w") as f:
    f.write(txt1)

config = pdfkit.configuration(wkhtmltopdf="C:\Program Files (x86)\wkhtmltopdf\\bin\\wkhtmltopdf.exe")
pdfkit.from_file('page_content.html', 'out.pdf',configuration=config)
</code>```

But the output pdf I am getting doesn't have any images of equations, just text. How do I solve this?
Also, I'm opening the file 2nd time to remove the numbers from the top and bottom of the webpage, you can help me improve this too.

EDIT:

This is the code now I'm using

```<code>import os.path,pdfkit,bs4,urllib2,sys
reload(sys)
sys.setdefaultencoding('utf8')
url = 'http://nptel.ac.in/courses/115103028/module1/lec1/3.html'

directory, filename = os.path.split(url)

html_text = urllib2.urlopen(url).read()

html_text = html_text.replace('src="', 'src="'+directory+"/").replace('href="', 'href="'+directory+"/")

page = bs4.BeautifulSoup(html_text, "html5lib")
for ul in page.findAll("ul", {"id":"pagin"}):
    ul.extract() # Deletes the tag and everything inside it

html_text = str(page)
config = pdfkit.configuration(wkhtmltopdf="C:\Program Files (x86)\wkhtmltopdf\\bin\\wkhtmltopdf.exe")
pdfkit.from_string(html_text, "out.pdf", configuration=config)
</code>```

It still showing those error, a part of the error message , And the output pdf does not have any images

```<code>Loading pages (1/6)
Warning: Failed to load http://nptel.ac.in/courses/115103028/css/style.css (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image041.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image042.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image043.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image045.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image046.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image048.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image049.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image050.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image051.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image052.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image053.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image054.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image055.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image056.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image057.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image064.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image065.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image067.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image068.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image069.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image070.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image071.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image072.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image073.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image074.png (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/1h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/2h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/3h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/4h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/5h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/6h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/7h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/8h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/9h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/10h.jpg (ignore)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
</code>```

答:
When I run your code pdfkit outputs a lot of warnings, which look like this:

```<code>Warning: Failed to load file:///C:/Users/.../images/image041.png (ignore)
</code>```

pdfkit tries to find the images in the website on my computer and because i didn't download them, they can not be found. A small hack around that problem is to convert the relative paths in the HTML source code to absolute paths:

```<code>import os.path

url = 'http://nptel.ac.in/courses/115103028/module1/lec1/3.html'

directory, filename = os.path.split(url)

html_text = urllib2.urlopen(url).read()

html_text = html_text.replace('src="', 'src="'+directory+"/") \
                     .replace('href="', 'href="'+directory+"/")
</code>```

Here directory is the directory in which the website is found, in this example it is http://nptel.ac.in/courses/115103028/module1/lec1 and this way

```<code><img src="images/image041.png" width="63" height="21">
</code>```

becomes

```<code><img src="http://nptel.ac.in/courses/115103028/module1/lec1/images/image041.png" width="63" height="21">
</code>```

Now you can use pdfkit.from_string instead of pdfkit.from_file to create a PDF file without storing some temporary information:

```<code>pdfkit.from_string(html_text, "out.pdf", configuration=config)
</code>```

To remove the links to the other pages (which are displayed as numbers) from the top and bottom of the site you have a ton of possibilities. My favorite one is using BeautifulSoup to find the ul tags with id="pagin". These tags contain the links to the other pages and you can just delete them:

```<code>import bs4

page = bs4.BeautifulSoup(html_text)
for ul in page.findAll("ul", {"id":"pagin"}):
    ul.extract() # Deletes the tag and everything inside it

html_text = unicode(page)
</code>```

And now html_text does not contain those unwanted links anymore. To install BeautifulSoup just use pip: python -m pip install bs4

This solution obviously only works if all your websites are structured that way, if they are not you could also delete all a tags to get rid of those links, but be careful not to delete wanted information.

Title: Python to save webpages in pdf format

Body:
So, I have a list of webpages that I want to save as pdf. They are like http://nptel.ac.in/courses/115103028/module1/lec1/3.html. The list is very long that's why I am using python to automate the process. This is my code

import pdfkit
import urllib2

page = urllib2.urlopen('http://nptel.ac.in/courses/115103028/module1/lec1/3.html')

page_content = page.read()

with open('page_content.html', 'w') as fid:
    fid.write(page_content)

txt=open("page_content.html").read().split("\n")

txt1=""
for i in txt:
    if not ".html" in i:
        txt1+=i+"\n"

with open('page_content.html',"w") as f:
    f.write(txt1)

config = pdfkit.configuration(wkhtmltopdf="C:\Program Files (x86)\wkhtmltopdf\\bin\\wkhtmltopdf.exe")
pdfkit.from_file('page_content.html', 'out.pdf',configuration=config)

But the output pdf I am getting doesn't have any images of equations, just text. How do I solve this?
Also, I'm opening the file 2nd time to remove the numbers from the top and bottom of the webpage, you can help me improve this too.

EDIT:

This is the code now I'm using

import os.path,pdfkit,bs4,urllib2,sys
reload(sys)
sys.setdefaultencoding('utf8')
url = 'http://nptel.ac.in/courses/115103028/module1/lec1/3.html'

directory, filename = os.path.split(url)

html_text = urllib2.urlopen(url).read()

html_text = html_text.replace('src="', 'src="'+directory+"/").replace('href="', 'href="'+directory+"/")

page = bs4.BeautifulSoup(html_text, "html5lib")
for ul in page.findAll("ul", {"id":"pagin"}):
    ul.extract() # Deletes the tag and everything inside it

html_text = str(page)
config = pdfkit.configuration(wkhtmltopdf="C:\Program Files (x86)\wkhtmltopdf\\bin\\wkhtmltopdf.exe")
pdfkit.from_string(html_text, "out.pdf", configuration=config)

It still showing those error, a part of the error message , And the output pdf does not have any images

Loading pages (1/6)
Warning: Failed to load http://nptel.ac.in/courses/115103028/css/style.css (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image041.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image042.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image043.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image045.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image046.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image048.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image049.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image050.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image051.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image052.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image053.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image054.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image055.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image056.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image057.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image064.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image065.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image067.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image068.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image069.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image070.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image071.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image072.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image073.png (ignore)
Warning: Failed to load http://nptel.ac.in/courses/115103028/module1/lec1/images/image074.png (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/1h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/2h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/3h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/4h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/5h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/6h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/7h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/8h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/9h.jpg (ignore)
Warning: Failed to load file:///C:/Users/KOUSHI~1/AppData/images/10h.jpg (ignore)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done

Body:
When I run your code pdfkit outputs a lot of warnings, which look like this:

Warning: Failed to load file:///C:/Users/.../images/image041.png (ignore)

pdfkit tries to find the images in the website on my computer and because i didn't download them, they can not be found. A small hack around that problem is to convert the relative paths in the HTML source code to absolute paths:

import os.path

url = 'http://nptel.ac.in/courses/115103028/module1/lec1/3.html'

directory, filename = os.path.split(url)

html_text = urllib2.urlopen(url).read()

html_text = html_text.replace('src="', 'src="'+directory+"/") \
                     .replace('href="', 'href="'+directory+"/")

Here directory is the directory in which the website is found, in this example it is http://nptel.ac.in/courses/115103028/module1/lec1 and this way

<img src="images/image041.png" width="63" height="21">

becomes

<img src="http://nptel.ac.in/courses/115103028/module1/lec1/images/image041.png" width="63" height="21">

Now you can use pdfkit.from_string instead of pdfkit.from_file to create a PDF file without storing some temporary information:

pdfkit.from_string(html_text, "out.pdf", configuration=config)

To remove the links to the other pages (which are displayed as numbers) from the top and bottom of the site you have a ton of possibilities. My favorite one is using BeautifulSoup to find the ul tags with id="pagin". These tags contain the links to the other pages and you can just delete them:

import bs4

page = bs4.BeautifulSoup(html_text)
for ul in page.findAll("ul", {"id":"pagin"}):
    ul.extract() # Deletes the tag and everything inside it

html_text = unicode(page)

And now html_text does not contain those unwanted links anymore. To install BeautifulSoup just use pip: python -m pip install bs4

This solution obviously only works if all your websites are structured that way, if they are not you could also delete all a tags to get rid of those links, but be careful not to delete wanted information.


问:
Should I perform input validation on the forms or in the class set method?
Say I have a database which stores information on customers, and there is an application with various forms to register customers, edit customers, delete customers, etc...

Should input validation (for example, checking the customer's post code is in the correct format) be placed in the Customer class or be done on the form?  Currently I have it in the class and I am throwing a custom exception if the value is not of the correct format.

答:
IMHO, you should do this in both places. Things like required field are good examples of UI validation and frameworks support this out of the box. </p>

<p>But that doesn't mean your business layer shouldn't still check if the required values are present, specially if you have api's that can be called without the UI layer. Also the business layer must validate more complex cases like existing username, etc. </p>

Body:
IMHO, you should do this in both places. Things like required field are good examples of UI validation and frameworks support this out of the box.

But that doesn't mean your business layer shouldn't still check if the required values are present, specially if you have api's that can be called without the UI layer. Also the business layer must validate more complex cases like existing username, etc.


问:
Omitting the datatype (e.g. "unsigned" instead of "unsigned int")
I know that if the data type declaration is omitted in C/C++ code in such way: unsigned test=5;, the compiler automatically makes this variable an int (an unsigned int in this case). I've heard that it's a C standard and it will work in all compilers.

But I've also heard that doing this is considered a bad practice.

What do you think? Should I really type unsigned int instead of just unsigned?

Are short, long and long long also datatypes?

答:
As @Konrad Rudolph says, unsigned is a datatype.  It's really just an alias for unsigned int.

As to the question of using unsigned being bad practice?  I would say no, there is nothing wrong with using unsigned as a datatype specifier.  Professionals won't be thrown by this, and any coding standard that says you have to use unsigned int is needlessly draconian, in my view.

ContentLicense: CC BY-SA 2.5


问:
Optim.jl: negative inverse Hessian
I am using the Optim.jl library to minimise a function in Julia, using a BFGS algorithm. Today, I have asked a question about the same library, but to avoid confusion I decided to split it in two.

I would like also to get an estimate of the negative inverse Hessian after the optimisation, for further calculations.

In the GitHub website of the Optim library, I found the following working example:

```<code>using Optim
rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
result        = optimize(rosenbrock, zeros(2), BFGS())
</code>```

How can I get the negative inverse Hessian after the optimisation from result? Is there any field in it identifying either the Hessian, the Inverse Hessian or the negative inverse Hessian?

EDIT

Thanks for the comments. Do you think that it would be more efficient to edit "optimize.jl" so that the function would return also the inverse Hessian? See below for a working example - the edit has been introduced at line 226:

```<code> if state.method_string == "BFGS"
         return MultivariateOptimizationResults(state.method_string,
                                                initial_x,
                                                f_increased ? state.x_previous : state.x,
                                                f_increased ? state.f_x_previous : state.f_x,
                                                iteration,
                                                iteration == options.iterations,
                                                x_converged,
                                                options.x_tol,
                                                f_converged,
                                                options.f_tol,
                                                g_converged,
                                                options.g_tol,
                                                f_increased,
                                                tr,
                                                state.f_calls,
                                                state.g_calls,
                                                state.h_calls), state.invH
    else
         return MultivariateOptimizationResults(state.method_string,
                                                 initial_x,
                                                 f_increased ? state.x_previous : state.x,
                                                 f_increased ? state.f_x_previous : state.f_x,
                                                 iteration,
                                                 iteration == options.iterations,
                                                 x_converged,
                                                 options.x_tol,
                                                 f_converged,
                                                 options.f_tol,
                                                 g_converged,
                                                 options.g_tol,
                                                 f_increased,
                                                 tr,
                                                 state.f_calls,
                                                 state.g_calls,
                                                 state.h_calls)
     end
</code>```

Or just:

```<code>return MultivariateOptimizationResults(state.method_string,
                                        initial_x,
                                        f_increased ? state.x_previous : state.x,
                                        f_increased ? state.f_x_previous : state.f_x,
                                        iteration,
                                        iteration == options.iterations,
                                        x_converged,
                                        options.x_tol,
                                        f_converged,
                                        options.f_tol,
                                        g_converged,
                                        options.g_tol,
                                        f_increased,
                                        tr,
                                        state.f_calls,
                                        state.g_calls,
                                        state.h_calls), state
</code>```

To have full access to "state" after the optimization.

EDIT 2

Since this change will be introduced in the new version of the Optim.jl library, there is no need to continue this discussion. For now, the the extended_trace and the after_while! tricks work. Personally, I prefer the latter, so I will close the discussion giving @Dan Getz the correct answer.

答:
I know of one way, but whether it's worth it as opposed to estimating the inverse Hessian yourself I'm not sure.  If you pass Optim.Options(store_trace=true, extended_trace=true), you can get a record of the optimization path which includes the last ~invH.  For example, after

```<code>result = optimize(rosenbrock, zeros(2), BFGS(),
                  Optim.Options(store_trace=true, extended_trace=true));
</code>```

we can get

```<code>julia> result.trace[end]
    16     5.471433e-17     2.333740e-09
 * Current step size: 1.0091356566200325
 * g(x): [2.33374e-9,-1.22984e-9]
 * ~inv(H): [0.498092 0.996422; 0.996422 1.9983]
 * x: [1.0,1.0]

julia> result.trace[end].metadata["~inv(H)"]
2×2 Array{Float64,2}:
 0.498092  0.996422
 0.996422  1.9983
</code>```

There are at least two things I don't like about this approach, though:

The first is that turning on extended_trace=true seems to force show_trace=true -- you'll notice I didn't show the output of the computation!  Feels like a bug.  This can be mitigated (though not removed) by setting show_every to something big, or avoided by redirecting the stdout entirely.

The second is that we should probably be able to get access to the last state without storing the whole path, but whether this is actually an issue will depend upon the size of your problem.

Title: Optim.jl: negative inverse Hessian

Body:
I am using the Optim.jl library to minimise a function in Julia, using a BFGS algorithm. Today, I have asked a question about the same library, but to avoid confusion I decided to split it in two.

I would like also to get an estimate of the negative inverse Hessian after the optimisation, for further calculations.

In the GitHub website of the Optim library, I found the following working example:

using Optim
rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
result        = optimize(rosenbrock, zeros(2), BFGS())

How can I get the negative inverse Hessian after the optimisation from result? Is there any field in it identifying either the Hessian, the Inverse Hessian or the negative inverse Hessian?

EDIT

Thanks for the comments. Do you think that it would be more efficient to edit "optimize.jl" so that the function would return also the inverse Hessian? See below for a working example - the edit has been introduced at line 226:

 if state.method_string == "BFGS"
         return MultivariateOptimizationResults(state.method_string,
                                                initial_x,
                                                f_increased ? state.x_previous : state.x,
                                                f_increased ? state.f_x_previous : state.f_x,
                                                iteration,
                                                iteration == options.iterations,
                                                x_converged,
                                                options.x_tol,
                                                f_converged,
                                                options.f_tol,
                                                g_converged,
                                                options.g_tol,
                                                f_increased,
                                                tr,
                                                state.f_calls,
                                                state.g_calls,
                                                state.h_calls), state.invH
    else
         return MultivariateOptimizationResults(state.method_string,
                                                 initial_x,
                                                 f_increased ? state.x_previous : state.x,
                                                 f_increased ? state.f_x_previous : state.f_x,
                                                 iteration,
                                                 iteration == options.iterations,
                                                 x_converged,
                                                 options.x_tol,
                                                 f_converged,
                                                 options.f_tol,
                                                 g_converged,
                                                 options.g_tol,
                                                 f_increased,
                                                 tr,
                                                 state.f_calls,
                                                 state.g_calls,
                                                 state.h_calls)
     end

Or just:

return MultivariateOptimizationResults(state.method_string,
                                        initial_x,
                                        f_increased ? state.x_previous : state.x,
                                        f_increased ? state.f_x_previous : state.f_x,
                                        iteration,
                                        iteration == options.iterations,
                                        x_converged,
                                        options.x_tol,
                                        f_converged,
                                        options.f_tol,
                                        g_converged,
                                        options.g_tol,
                                        f_increased,
                                        tr,
                                        state.f_calls,
                                        state.g_calls,
                                        state.h_calls), state

To have full access to "state" after the optimization.

EDIT 2

Since this change will be introduced in the new version of the Optim.jl library, there is no need to continue this discussion. For now, the the extended_trace and the after_while! tricks work. Personally, I prefer the latter, so I will close the discussion giving @Dan Getz the correct answer.

Body:
I know of one way, but whether it's worth it as opposed to estimating the inverse Hessian yourself I'm not sure.  If you pass Optim.Options(store_trace=true, extended_trace=true), you can get a record of the optimization path which includes the last ~invH.  For example, after

result = optimize(rosenbrock, zeros(2), BFGS(),
                  Optim.Options(store_trace=true, extended_trace=true));

we can get

julia> result.trace[end]
    16     5.471433e-17     2.333740e-09
 * Current step size: 1.0091356566200325
 * g(x): [2.33374e-9,-1.22984e-9]
 * ~inv(H): [0.498092 0.996422; 0.996422 1.9983]
 * x: [1.0,1.0]

julia> result.trace[end].metadata["~inv(H)"]
2×2 Array{Float64,2}:
 0.498092  0.996422
 0.996422  1.9983

There are at least two things I don't like about this approach, though:

The first is that turning on extended_trace=true seems to force show_trace=true -- you'll notice I didn't show the output of the computation!  Feels like a bug.  This can be mitigated (though not removed) by setting show_every to something big, or avoided by redirecting the stdout entirely.

The second is that we should probably be able to get access to the last state without storing the whole path, but whether this is actually an issue will depend upon the size of your problem.


问:
remove specific string in python2.7
I have a list as follows:

```<code>>>> header
['Id', ["['GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']"]]
>>> type(header)
list
</code>```

And, how can I change it to a string as follows;

```<code>['Id','GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']
</code>```

I'm try used re.split('\[|\]|\"',str(header)) . But the resulted is not I want to get.

```<code>['',
 "'Id', ",
 '',
 '',
 "'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt'",
 '',
 '',
 '',
 '']
</code>```

So, any suggestion is hope.

Title: remove specific string in python2.7

Body:
I have a list as follows:

>>> header
['Id', ["['GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']"]]
>>> type(header)
list

And, how can I change it to a string as follows;

['Id','GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']

I'm try used re.split('\[|\]|\"',str(header)) . But the resulted is not I want to get.

['',
 "'Id', ",
 '',
 '',
 "'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt'",
 '',
 '',
 '',
 '']

So, any suggestion is hope.

Body:
How about this?

>>> header = ['Id', ["['GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']"]]
>>> str(header).replace('[','').replace(']','').replace('"','').replace("'",'').split(', ')
['Id', 'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']


问:
Unable to retrieve field value for async validation in a redux form
It is how I set up my redux form

```<code>import React, { PropTypes } from 'react';
import { reduxForm, Field } from 'redux-form/immutable';
...

const asyncValidate = ( values, dispatch, props ) => {
  // print out the value for inspection
  console.log(`>>>> ${values.coupon}`);
}

...

const CheckoutForm = reduxForm({
  form: 'Checkout',
  asyncValidate,

})(cardDetailsForCheckoutForm);
</code>```

The field I want to validate is called coupon. I need to validate it in an async manner because it requires a check on the server side. Somehow I cannot get the coupon value as values.coupon. It just returns as undefined

But according to the example (http://redux-form.com/6.0.0-rc.1/examples/asyncValidation/), I should be able to retrieve the value. Why it fails?

答: I find that after I restart the browser, the code works as expected.</p>

Body:
It is how I set up my redux form

import React, { PropTypes } from 'react';
import { reduxForm, Field } from 'redux-form/immutable';
...

const asyncValidate = ( values, dispatch, props ) => {
  // print out the value for inspection
  console.log(`>>>> ${values.coupon}`);
}

...

const CheckoutForm = reduxForm({
  form: 'Checkout',
  asyncValidate,

})(cardDetailsForCheckoutForm);

The field I want to validate is called coupon. I need to validate it in an async manner because it requires a check on the server side. Somehow I cannot get the coupon value as values.coupon. It just returns as undefined

But according to the example (http://redux-form.com/6.0.0-rc.1/examples/asyncValidation/), I should be able to retrieve the value. Why it fails?


问:
ImportError: cannot import name 'logsumexp' when importing sklearn.model_selection
I was trying to import sklearn.model_selection with Jupiter Notebook under anaconda environment with python 3.5, but I was warned that I didn't have "model_selection" module, so I did conda update scikit-learn.

After that, I received a message of ImportError: cannot import name 'logsumexp' when importing sklearn.model_selection.

I reinstalled sklearn and scipy, but still received the same error message. May I have some advice?

答:
I came across exactly the same problem just now. After I updated scikit-learn and tried to import sklearn.model_selection, the ImportError appeared.

I just restarted anaconda and ran it again.

It worked. Don't know why.


问:
Caching select query data on server side
I am writing an express app, where I'm pushing data from my views to a database. But most of the data is mapped to some other data in database tables.

For example, is a choose student name drop down-  once you choose the student by his name , a drop down below - will show all roles that he is allowed for.

So I'm following this pattern of

```<code>app.post('\action1', function(req,res){
  function querySomething(){
    var defered = Q.defer();
      connection.query(some_select_query,defered.makeNodeResolver());
      return defered.promise;
    }

  function querySomethingElse(){
    var defered = Q.defer();
      connection.query(some_other_select_query,defered.makeNodeResolver());
      return defered.promise;
    }

   Q.all([querySomething(), querySomethingElse()]).then((results,err) => {
       connection.release()
       if(results){
          res.render('some_view.ejs', {
             result1:results[0][0],
             result2:results[1][0]
          });
       }
       else{
         res.render('error.ejs',{});
       }
   })
})
</code>```

Now the problem is that I have to follow this pattern of selecting something from multiple tables, pass all these function to a promise- and when the results is passed back, goto my view with all those result objects - so that I can use them in my view - as a means of doing drop downs dependent on one another.

Sometimes I have to re-write this multiple times.

Doing a select query like this would be performance intensive especially if all views are using the result of the same query.

Is there any way I can build a cached data store on my express server side code and query that instead of the actual database??

If there is an insert or an update - i will refresh this store and just do a new select * that one time.

What libraries are there on top of express which will help me do this??

Does mysql-cache does the same thing?? I'm also using connection pooling with createPool.

How do I achieve this - or do I just restore to using big mvc's like sails to rewrite my app?

答:
You can try apiCache npm module.

"Sometimes I have to re-write this multiple times."

Based on the business need, you may want to handle each use case separately and this scenario doesn't deal with caching.

Doing a select query like this would be performance intensive especially if all views are using the result of the same query.

This is a classic example for the need of server-side caching.

Body:
I am writing an express app, where I'm pushing data from my views to a database. But most of the data is mapped to some other data in database tables.

For example, is a choose student name drop down-  once you choose the student by his name , a drop down below - will show all roles that he is allowed for.

So I'm following this pattern of

app.post('\action1', function(req,res){
  function querySomething(){
    var defered = Q.defer();
      connection.query(some_select_query,defered.makeNodeResolver());
      return defered.promise;
    }

  function querySomethingElse(){
    var defered = Q.defer();
      connection.query(some_other_select_query,defered.makeNodeResolver());
      return defered.promise;
    }

   Q.all([querySomething(), querySomethingElse()]).then((results,err) => {
       connection.release()
       if(results){
          res.render('some_view.ejs', {
             result1:results[0][0],
             result2:results[1][0]
          });
       }
       else{
         res.render('error.ejs',{});
       }
   })
})

Now the problem is that I have to follow this pattern of selecting something from multiple tables, pass all these function to a promise- and when the results is passed back, goto my view with all those result objects - so that I can use them in my view - as a means of doing drop downs dependent on one another.

Sometimes I have to re-write this multiple times.

Doing a select query like this would be performance intensive especially if all views are using the result of the same query.

Is there any way I can build a cached data store on my express server side code and query that instead of the actual database??

If there is an insert or an update - i will refresh this store and just do a new select * that one time.

What libraries are there on top of express which will help me do this??

Does mysql-cache does the same thing?? I'm also using connection pooling with createPool.

How do I achieve this - or do I just restore to using big mvc's like sails to rewrite my app?


问:
How to change the background color of the overflow menu in android
I want to change the background color of the overflow popup menu to match the background of the main screen.  Does anyone know how I could do that?

Thanks.

答:
If you are using a Toolbar, first you need to add this line to your toolbar layout:

```<code>app:popupTheme="@style/ThemeOverlay.MyTheme"
</code>```

It should look like this:

```<code><android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/primary"
    app:titleTextColor="@color/white"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/ThemeOverlay.MyTheme"/>
</code>```

You need to use that line to tell your Toolbar which theme to use. Then, you add the following theme to your styles.xml file:

```<code><style name="ThemeOverlay.MyTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="android:colorBackground">@color/primary</item>
    <item name="android:textColor">@color/white</item>
</style>
</code>```

In the place I put "@color/primary" and "@color/white", you can use any color you want, and you can also put hex values like #000000.

Body:
If you are using a Toolbar, first you need to add this line to your toolbar layout:

app:popupTheme="@style/ThemeOverlay.MyTheme"

It should look like this:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:minHeight="?attr/actionBarSize"
    android:background="@color/primary"
    app:titleTextColor="@color/white"
    app:layout_scrollFlags="scroll|enterAlways"
    app:popupTheme="@style/ThemeOverlay.MyTheme"/>

You need to use that line to tell your Toolbar which theme to use. Then, you add the following theme to your styles.xml file:

<style name="ThemeOverlay.MyTheme" parent="ThemeOverlay.AppCompat.Light">
    <item name="android:colorBackground">@color/primary</item>
    <item name="android:textColor">@color/white</item>
</style>

In the place I put "@color/primary" and "@color/white", you can use any color you want, and you can also put hex values like #000000.


问:
oracle 12c Testing triggers on views
I have created view in Oracle 12c using the following code:

```<code>CREATE VIEW ConcertView AS
SELECT a.ConcertNo, a.Concert_Name, a.Price, a.Duration, a.City, b.EventDate, b.Even t_Name
FROM Concert a,Events b
WHERE a.ConcertNo = b.ConcertNo
 AND a.ConcertNo != 'CN002'
</code>```

The view creates without any errors. I then create a trigger on the view using the following code:

```<code>CREATE OR REPLACE TRIGGER check_month
INSTEAD OF DELETE OR INSERT OR UPDATE ON ConcertView

DECLARE
    ConcertDate date;
BEGIN
    IF (to_char(EventDate, 'DD-MM-YY') = 'JUL')  THEN
        raise_application_error(-20000, 'Concerts cannot be run during JULY');
    END IF;
END;

Trigger created.
</code>```

The trigger creates without any errors.

I am trying to ensure that concerts cannot be run during July.
However the trigger does not take any action.  Could anybody please let me know what I am doing wrong, or explain how to test a trigger?

答:
Replace this sentence:

```<code>IF (to_char(EventDate, 'DD-MM-YY') = 'JUL')
</code>```

For this:

```<code>IF to_char(EventDate, 'MON') = 'JUL'
</code>```

In the first sentence you are comparing the date in the format DD-MM-YY with the name of the month. In the second, you're going to compare the name of the month.

You can check the doc here:
Oracle Doc.

Title: oracle 12c Testing triggers on views

Body:
I have created view in Oracle 12c using the following code:

CREATE VIEW ConcertView AS
SELECT a.ConcertNo, a.Concert_Name, a.Price, a.Duration, a.City, b.EventDate, b.Even t_Name
FROM Concert a,Events b
WHERE a.ConcertNo = b.ConcertNo
 AND a.ConcertNo != 'CN002'

The view creates without any errors. I then create a trigger on the view using the following code:

CREATE OR REPLACE TRIGGER check_month
INSTEAD OF DELETE OR INSERT OR UPDATE ON ConcertView

DECLARE
    ConcertDate date;
BEGIN
    IF (to_char(EventDate, 'DD-MM-YY') = 'JUL')  THEN
        raise_application_error(-20000, 'Concerts cannot be run during JULY');
    END IF;
END;

Trigger created.

The trigger creates without any errors.

I am trying to ensure that concerts cannot be run during July.
However the trigger does not take any action.  Could anybody please let me know what I am doing wrong, or explain how to test a trigger?

Body:
Replace this sentence:

IF (to_char(EventDate, 'DD-MM-YY') = 'JUL')

For this:

IF to_char(EventDate, 'MON') = 'JUL'

In the first sentence you are comparing the date in the format DD-MM-YY with the name of the month. In the second, you're going to compare the name of the month.

You can check the doc here:
Oracle Doc.


问:
MYSQLI Connection refused when connecting to another docker container running MariaDB
I'm starting to get my hands dirty with Docker and I'm trying to get my PHP application running in a docker container with nginx to connect to the database running in another container running MariaDB.

When I run the containers, I can connect without any problems to the database from my computer (using Sequel Pro) but when i try to connect to the database from the PHP application running in the nginx container I get the following mysqli error:

Warning: mysqli_connect(): (HY000/2002): Connection refused in >/app/web/php/db-config.php on line 7
  Failed to connect to the database, died with error:

The db-config.php where the error happens is as follows:

```<code>    define('DB_HOST', '0.0.0.0:3306');
    define('DB_NAME', 'Jumpooling');
    define('DB_USER', 'root');
    define('DB_PASSWORD', 'root');

    $con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Failed to connect to the database, died with error:');
</code>```

All the docker-compose.yml file content is in this repository.

What am I missing?

答:
I managed to find the solution in this answer.

The problem was that the host was not to be defined as an IP address but with the link name that it is given in the docker-compose.yml file, that is db.

The final db-config.php is, thus:

```<code>define('DB_HOST', 'db');
define('DB_NAME', 'Jumpooling');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');

$con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, 3306) or die('Failed to connect to the database, died with error:');
</code>```

Body:
I'm starting to get my hands dirty with Docker and I'm trying to get my PHP application running in a docker container with nginx to connect to the database running in another container running MariaDB.

When I run the containers, I can connect without any problems to the database from my computer (using Sequel Pro) but when i try to connect to the database from the PHP application running in the nginx container I get the following mysqli error:

Warning: mysqli_connect(): (HY000/2002): Connection refused in >/app/web/php/db-config.php on line 7
  Failed to connect to the database, died with error:

The db-config.php where the error happens is as follows:

    define('DB_HOST', '0.0.0.0:3306');
    define('DB_NAME', 'Jumpooling');
    define('DB_USER', 'root');
    define('DB_PASSWORD', 'root');

    $con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Failed to connect to the database, died with error:');

All the docker-compose.yml file content is in this repository.

What am I missing?

Body:
I managed to find the solution in this answer.

The problem was that the host was not to be defined as an IP address but with the link name that it is given in the docker-compose.yml file, that is db.

The final db-config.php is, thus:

define('DB_HOST', 'db');
define('DB_NAME', 'Jumpooling');
define('DB_USER', 'root');
define('DB_PASSWORD', 'root');

$con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, 3306) or die('Failed to connect to the database, died with error:');


问:
Angular 1.5.x/Jasmine - Expected spy to have been called but it was never called
POST-EDIT: I've just solved the issue, though maybe someone has a better solution. I'll post my solution soon, but if someone has a correct solution I'll accept their answer.

I'm migrating my application from 1.4 to 1.5 and changing all my controllers and directives to components. I now have a test that once worked not working and I'd like some guidance.

I'm trying to spy on a service method and according to the unit test it's not calling. This is not the case as an API call is made when the application is run. Here is the message I receive:

This is my component file:

```<code>(function(){
    "use strict";

    angular.module("app").component("profileComponent", {
        templateUrl: "/templates/profile.component.html",
        controllerAs: "vm",
        bindings: {
            resolvedUser: "<"
        },
        controller: function(ImageService, $state){
            const vm = this;
            const resolvedUser = this.resolvedUser;

            resolvedUser ? vm.user = resolvedUser : $state.go("404");

            vm.$onInit = function(){
                ImageService.findByName(vm.user.pokemon.name)
                    .then(function(res){
                        vm.user.pokemon.id = res.id;
                        vm.user.pokemon.image = res.sprites.front_default;
                        vm.user.pokemon.type = res.types[0].type.name;
                    })
                    .catch(function(res){
                        vm.user.pokemon.image = "https://www.native-instruments.com/forum/data/avatars/m/328/328352.jpg?1439377390";
                    });
            }

        }
    });
})();
</code>```

And here is the relevant parts from my spec file. I've made a comment where the test is failing:

```<code>describe("profile.component", function(){
    var profileComponent, ImageService, $q, $httpBackend, $state, resolvedUser, jazzSpy, IS,
        API = "http://pokeapi.co/api/v2/pokemon/";

    var RESPONSE_SUCCESS = // very large variable I've omitted for brevity.

beforeEach(angular.mock.module("app"));
    beforeEach(angular.mock.module("ui.router"));

    beforeEach(inject(function(_ImageService_, _$q_, _$httpBackend_, _$state_, _$rootScope_){
        ImageService = _ImageService_;
        $q = _$q_;
        $httpBackend = _$httpBackend_;
        $state = _$state_;
        $rootScope = _$rootScope_;
        $rootScope.$new();
    }));

    describe("profileComponent with a valid user and valid Pokemon", function(){

        beforeEach(inject(function(_$componentController_){
            singleUser = { id: 2, name: "Erlich Bachman", email: "erlich@aviato.com", phone: 4155552233, pokemon: { isPresent: true, name: "celebi"}, icon: { isPresent: false, name: null} };
            let bindings = {resolvedUser: singleUser, ImageService: ImageService, $state: $state };
            profileComponent = _$componentController_("profileComponent", { $scope: {} }, bindings);
            profileComponent.$onInit();
        }));

            beforeEach(function(){
                spyOn(ImageService, "findByName").and.callThrough();
            });

            it("should set state to resolvedUser", function(){
                expect(profileComponent.user).toEqual(singleUser);
            });

            it("should expect ImageService to be defined", function(){
                expect(ImageService.findByName).toBeDefined();
            });

            it("should call ImageService.findByName() and return Pokemon icon", function(){

                  expect(profileComponent.user.pokemon.name).toEqual("celebi");

                $httpBackend.whenGET(API + "celebi").respond(200, $q.when(RESPONSE_SUCCESS));
                $httpBackend.flush();

                // This is where the test fails
                  expect(ImageService.findByName).toHaveBeenCalledWith("celebi");
            });
        });
</code>```

答:
As mentioned before, $onInit needs to be called after spyOn:</p>

```<code>beforeEach(function(){
    spyOn(ImageService, "findByName").and.callThrough();
    profileComponent.$onInit();
});
</code>```

Body:
POST-EDIT: I've just solved the issue, though maybe someone has a better solution. I'll post my solution soon, but if someone has a correct solution I'll accept their answer.

I'm migrating my application from 1.4 to 1.5 and changing all my controllers and directives to components. I now have a test that once worked not working and I'd like some guidance.

I'm trying to spy on a service method and according to the unit test it's not calling. This is not the case as an API call is made when the application is run. Here is the message I receive:

This is my component file:

(function(){
    "use strict";

    angular.module("app").component("profileComponent", {
        templateUrl: "/templates/profile.component.html",
        controllerAs: "vm",
        bindings: {
            resolvedUser: "<"
        },
        controller: function(ImageService, $state){
            const vm = this;
            const resolvedUser = this.resolvedUser;

            resolvedUser ? vm.user = resolvedUser : $state.go("404");

            vm.$onInit = function(){
                ImageService.findByName(vm.user.pokemon.name)
                    .then(function(res){
                        vm.user.pokemon.id = res.id;
                        vm.user.pokemon.image = res.sprites.front_default;
                        vm.user.pokemon.type = res.types[0].type.name;
                    })
                    .catch(function(res){
                        vm.user.pokemon.image = "https://www.native-instruments.com/forum/data/avatars/m/328/328352.jpg?1439377390";
                    });
            }

        }
    });
})();

And here is the relevant parts from my spec file. I've made a comment where the test is failing:

describe("profile.component", function(){
    var profileComponent, ImageService, $q, $httpBackend, $state, resolvedUser, jazzSpy, IS,
        API = "http://pokeapi.co/api/v2/pokemon/";

    var RESPONSE_SUCCESS = // very large variable I've omitted for brevity.

beforeEach(angular.mock.module("app"));
    beforeEach(angular.mock.module("ui.router"));

    beforeEach(inject(function(_ImageService_, _$q_, _$httpBackend_, _$state_, _$rootScope_){
        ImageService = _ImageService_;
        $q = _$q_;
        $httpBackend = _$httpBackend_;
        $state = _$state_;
        $rootScope = _$rootScope_;
        $rootScope.$new();
    }));

    describe("profileComponent with a valid user and valid Pokemon", function(){

        beforeEach(inject(function(_$componentController_){
            singleUser = { id: 2, name: "Erlich Bachman", email: "erlich@aviato.com", phone: 4155552233, pokemon: { isPresent: true, name: "celebi"}, icon: { isPresent: false, name: null} };
            let bindings = {resolvedUser: singleUser, ImageService: ImageService, $state: $state };
            profileComponent = _$componentController_("profileComponent", { $scope: {} }, bindings);
            profileComponent.$onInit();
        }));

            beforeEach(function(){
                spyOn(ImageService, "findByName").and.callThrough();
            });

            it("should set state to resolvedUser", function(){
                expect(profileComponent.user).toEqual(singleUser);
            });

            it("should expect ImageService to be defined", function(){
                expect(ImageService.findByName).toBeDefined();
            });

            it("should call ImageService.findByName() and return Pokemon icon", function(){

                  expect(profileComponent.user.pokemon.name).toEqual("celebi");

                $httpBackend.whenGET(API + "celebi").respond(200, $q.when(RESPONSE_SUCCESS));
                $httpBackend.flush();

                // This is where the test fails
                  expect(ImageService.findByName).toHaveBeenCalledWith("celebi");
            });
        });

Body:
As mentioned before, $onInit needs to be called after spyOn:

beforeEach(function(){
    spyOn(ImageService, "findByName").and.callThrough();
    profileComponent.$onInit();
});


问:
Can I take a snapshot of a website from the command line?
I am writing documentation for a website  database interface. Is it possible to write a script that, when executed, takes the most recent snapshot of the website and saves it as an image file?

note: I am using the tags ruby, bash, and python since those are the languages used in our group (along with R and FORTRAN; for sport, I'll set a 100 point bounty If anyone can post a FORTRAN solution).

update: as @birryree notes, a previous question provides the answer. Considering the FORTRAN offer is just for sport, perhaps this is a duplicate?

答:
This can be done with selenium.  First set up seleniumrc. Then using any of the language apis, use the captureScreenshot() method.  Here is an example in java:

http://www.cloudtesting.com/blog/2009/06/24/capturing-screen-shots-of-browsers-with-selenium-and-cloud-testing-part-1/

Note that selenium will need a display to render to, but you can also use a virtual frame buffer like Xvfb on Linux (probably installed by default)

I would also recommend the seleniumIDE firefox plugin as it can basically write the code for you in any language.


问:
Javascript - remove split method
I am trying to create the select application using Javascipt only. I got to know about this code on internet and it uses the split method to return value and .innerHTML. Now say if I do not want to use the split method and just return with .innerHTML into html element with no value, how to do that using for loop as used in this code ?</p>

```<code>   <!DOCTYPE html>
<html>
<head>
    <title>Select Options</title>
</head>
<body>

<h2>Choose your car</h2>
<hr>

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

<hr>

Choose Car Model
<select id="slct2" ></select>

</body>

<script type="text/javascript">
    function populate(s1,s2){
        var s1 = document.getElementById(s1);
        var s2 = document.getElementById(s2);
        s2.innerHTML = "";

        if(s1.value == "Hyundai") {
            var optionArray = ["|", "i10|i10","i20|i20", "Verna|Verna"]
        }
        for(var option in optionArray){
            var pair = optionArray[option].split("|");
            var newOption = document.createElement('option');
            newOption.value = pair[0];
            newOption.innerHTML = pair[1];
            s2.options.add(newOption);
        }
    }
</script>

</html>
</code>```

答:
You have to be aware, that using for... in loop over an array, won't return you the elements actually, but their indexes. I would suggest you to use simple for loop instead.

function populate(s1, s2) {
  var s1 = document.getElementById(s1);
  var s2 = document.getElementById(s2);
  s2.innerHTML = "";

  var optionArray = ["i10", "i20", "Verna"];

  for (var i = 0; i < optionArray.length; i++) {
    var newOption = document.createElement('option');
    newOption.value = optionArray[i];
    newOption.innerHTML = optionArray[i];
    s2.appendChild(newOption);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Choose your car</h2>
<hr> Choose Car Make:
<select id="slct1" onchange="populate('slct1','slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

<hr> Choose Car Model
<select id="slct2"></select></code>```

Title: Javascript - remove split method

Body:
I am trying to create the select application using Javascipt only. I got to know about this code on internet and it uses the split method to return value and .innerHTML. Now say if I do not want to use the split method and just return with .innerHTML into html element with no value, how to do that using for loop as used in this code ?

   <!DOCTYPE html>

    <title>Select Options</title>

Choose your car

Choose Car Make:
<select id="slct1" onchange="populate(this.id,'slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

Choose Car Model
<select id="slct2" ></select>

Body:
You have to be aware, that using for... in loop over an array, won't return you the elements actually, but their indexes. I would suggest you to use simple for loop instead.

function populate(s1, s2) {
  var s1 = document.getElementById(s1);
  var s2 = document.getElementById(s2);
  s2.innerHTML = "";

  var optionArray = ["i10", "i20", "Verna"];

  for (var i = 0; i < optionArray.length; i++) {
    var newOption = document.createElement('option');
    newOption.value = optionArray[i];
    newOption.innerHTML = optionArray[i];
    s2.appendChild(newOption);
  }
}

<h2>Choose your car</h2>
<hr> Choose Car Make:
<select id="slct1" onchange="populate('slct1','slct2')">
    <option value=""></option>
    <option value="Hyundai">Hyundai</option>
    <option value="Honda">Honda</option>
    <option value="Maruti">Maruti</option>
</select>

<hr> Choose Car Model
<select id="slct2"></select>


问:
Handle all http errors in the same way
All calls to my api are made through a service I created with the "GET, POST, PUT, DELETE, PATCH" methods. If any of these calls fail I would like to show the error in an alert and if the error status is 401 redirect the user to the login. How can I make a generic error handler?

api.service.ts

```<code>import { Injectable } from '@angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import lodash from 'lodash';

@Injectable()
export class ApiService {

  url: string = 'https://leetags-api.herokuapp.com';
  options: RequestOptions = new RequestOptions({
    withCredentials: true
  });

  constructor(private http: Http) {}

  get(endpoint: string, params?: any, options: RequestOptionsArgs = {}): Observable<Response> {
    if (params) {
      const urlSearchParams: URLSearchParams = new URLSearchParams();
      lodash.forEach(params, (value: any, key: string): void => urlSearchParams.set(key, value));
      options.search = !options.search ? urlSearchParams : options.search;
    }

    return this.http.get(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  post(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.post(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  put(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  delete(endpoint: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.delete(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  patch(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

}
</code>```

答:
You can also make a catch() method in your service and assign it to the catch handler of your http call. The .catch block is automatically called whenever a api call fails.

Your above http statement should then look like following (for GET):

```<code>get() {
        return this._http.get(this.getUserUrl)
                .map((response: Response) => response.json())
                .catch(this.myCatchFunction);
    }

myCatchFunction(error: Response){
 //look here for specific codes present in response error and handle accordingly
}
</code>```

Hope this helps

Title: Handle all http errors in the same way

Body:
All calls to my api are made through a service I created with the "GET, POST, PUT, DELETE, PATCH" methods. If any of these calls fail I would like to show the error in an alert and if the error status is 401 redirect the user to the login. How can I make a generic error handler?

api.service.ts

import { Injectable } from '@angular/core';
import { Http, RequestOptions, RequestOptionsArgs, Response, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import lodash from 'lodash';

@Injectable()
export class ApiService {

  url: string = 'https://leetags-api.herokuapp.com';
  options: RequestOptions = new RequestOptions({
    withCredentials: true
  });

  constructor(private http: Http) {}

  get(endpoint: string, params?: any, options: RequestOptionsArgs = {}): Observable<Response> {
    if (params) {
      const urlSearchParams: URLSearchParams = new URLSearchParams();
      lodash.forEach(params, (value: any, key: string): void => urlSearchParams.set(key, value));
      options.search = !options.search ? urlSearchParams : options.search;
    }

    return this.http.get(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  post(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.post(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  put(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

  delete(endpoint: string, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.delete(`${this.url}/${endpoint}`, this.options.merge(options));
  }

  patch(endpoint: string, body: any, options?: RequestOptionsArgs): Observable<Response> {
    return this.http.put(`${this.url}/${endpoint}`, body, this.options.merge(options));
  }

}

Body:
You can also make a catch() method in your service and assign it to the catch handler of your http call. The .catch block is automatically called whenever a api call fails.

Your above http statement should then look like following (for GET):

get() {
        return this._http.get(this.getUserUrl)
                .map((response: Response) => response.json())
                .catch(this.myCatchFunction);
    }

myCatchFunction(error: Response){
 //look here for specific codes present in response error and handle accordingly
}

Hope this helps


问:
How to write file from within php - Permission denied
Sorry to ask a basic question, but I cannot find the answer.  I am trying to write to a file from within PHP but it fails with Permission denied, and I don't know why.
My code is

```<code><!DOCTYPE HTML>
<html>
<head>
    <title>File test</title>

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);

echo 'Current script owner: ' . get_current_user();
echo '<br>WhoAmI: '. shell_exec( 'whoami' );
echo '<br>cwd: '.getcwd();
$plist = fopen("plist.txt", "w") or die("Unable to open file!");
fwrite($plist, 'some text');
fclose($plist);
?>
</code>```

This is the output I see

```<code>Current script owner: mick
WhoAmI: www-data
cwd: /home/mick/Documents/www/test
Warning: fopen(plist.txt): failed to open stream: Permission denied in /home/mick/Documents/www/test/fileTest.php on line 13
Unable to open file!
</code>```

My user (mick) obviously owns the directory I am trying to write to and www-data is a member of the 'mick' group. I have also set the directory to 777 to try to get it to work but still get the error.  What have I missed here?

答:
You need give permission for www-data user. You can do it by running these commands:

```<code>sudo chown www-data:www-data /home/mick/Documents/www/test
sudo chmod 777 /home/mick/Documents/www/test
</code>```

The above code gives full access for user www-data to the directory.

Or add w+ inner fopen. It will create the file if doesn't exist.

Body:
Sorry to ask a basic question, but I cannot find the answer.  I am trying to write to a file from within PHP but it fails with Permission denied, and I don't know why.
My code is

<!DOCTYPE HTML>

    <title>File test</title>

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);

echo 'Current script owner: ' . get_current_user();
echo '
WhoAmI: '. shell_exec( 'whoami' );
echo '
cwd: '.getcwd();
$plist = fopen("plist.txt", "w") or die("Unable to open file!");
fwrite($plist, 'some text');
fclose($plist);
?>

This is the output I see

Current script owner: mick
WhoAmI: www-data
cwd: /home/mick/Documents/www/test
Warning: fopen(plist.txt): failed to open stream: Permission denied in /home/mick/Documents/www/test/fileTest.php on line 13
Unable to open file!

My user (mick) obviously owns the directory I am trying to write to and www-data is a member of the 'mick' group. I have also set the directory to 777 to try to get it to work but still get the error.  What have I missed here?

Body:
You need give permission for www-data user. You can do it by running these commands:

sudo chown www-data:www-data /home/mick/Documents/www/test
sudo chmod 777 /home/mick/Documents/www/test

The above code gives full access for user www-data to the directory.

Or add w+ inner fopen. It will create the file if doesn't exist.