问:
No connection could be made because the target machine actively refused it (PHP / WAMP)
Note: I realise this could be seen as a duplicate but i have looked at the other responses and they didn't fix the problem for me.

I have recently installed Zend Studio and Zend Server with the mysql plugin on Windows 7.

I am not a qualified server administrator but neither am i completely incompetent; i have dedicated my day trying to get a local development 'server' up to cut down on upload/download times.

When I say server/machine i mean my home computer

I have come to a grinding halt trying to get mysql to work with Zend Server.

The error I keep receiving is (or verbose):

```<code>#2002 Cannot log in to the MySQL server
or (if i change to 'config' authentication type)
#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).
</code>```

I have tried:

Change $cfg['Servers'][$i]['host'] from 'localhost' to '127.0.0.1'

Add/Remove $cfg['Servers'][$i]['socket'] = '';

Change from cookie to config auth type

reinstall server and mysql

Disable firewalls

Restarting machine

Zend's approach was to 'configure the phpmyadmin setup screen'... done that i don't know how many times.

Can anyone on here lend a hand, or point me in a direction that I haven't tried yet?

答: I have just removed the mysql service and installed it again. It works for me</p>

ContentLicense: CC BY-SA 4.0

Body:
Note: I realise this could be seen as a duplicate but i have looked at the other responses and they didn't fix the problem for me.

I have recently installed Zend Studio and Zend Server with the mysql plugin on Windows 7.

I am not a qualified server administrator but neither am i completely incompetent; i have dedicated my day trying to get a local development 'server' up to cut down on upload/download times.

When I say server/machine i mean my home computer

I have come to a grinding halt trying to get mysql to work with Zend Server.

The error I keep receiving is (or verbose):

#2002 Cannot log in to the MySQL server
or (if i change to 'config' authentication type)
#2002 - No connection could be made because the target machine actively refused it.

The server is not responding (or the local server's socket is not correctly configured).

I have tried:

Change $cfg['Servers'][$i]['host'] from 'localhost' to '127.0.0.1'

Add/Remove $cfg['Servers'][$i]['socket'] = '';

Change from cookie to config auth type

reinstall server and mysql

Disable firewalls

Restarting machine

Zend's approach was to 'configure the phpmyadmin setup screen'... done that i don't know how many times.

Can anyone on here lend a hand, or point me in a direction that I haven't tried yet?


来源: stackexchange

问:
Lambda variable names - to short name, or not to short name?
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);
</code>```

Some question this naming, and would prefer to see long typed out names, like this:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);
</code>```

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

答:
It may be asking a lot to ask a question for 'consensus' on 'naming'.  :)

I agree that 'the importance of a good name' is proportional to the scope of the name.  Jon Skeet's answer of preferring

```<code>from person in source ...
</code>```

is compelling, but if the name is used a lot and especially if the input is better named, I think I prefer

```<code>from p in persons ...
</code>```

OwnerDisplayName: TheSoftwareJedi

ContentLicense: CC BY-SA 2.5

Body:
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);

Some question this naming, and would prefer to see long typed out names, like this:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

LastEditorDisplayName: TheSoftwareJedi

Body:
It may be asking a lot to ask a question for 'consensus' on 'naming'.  :)

I agree that 'the importance of a good name' is proportional to the scope of the name.  Jon Skeet's answer of preferring

from person in source ...

is compelling, but if the name is used a lot and especially if the input is better named, I think I prefer

from p in persons ...

OwnerDisplayName: Brian


问:
How to model a questionnaire database relation using dynamic properties
I'm somewhat new to Ruby and Rails and I'm trying to figure out how to model the following relation using Ruby's dynamic language features....

The domain is essentially a questionnaire, so I have Users, Questions, and Answers.

A User has an id and a name. An Answer has a userid and a questionid and a value property which is the user's answer to that particular question.

Each question has a unique 'Code', so for example, a question might be, "What is your favourite color?", and code would be "fav_color".

If I have a User instance, I want to be able to do: user.fav_color to get/set this answer.

I figure I could try and user method_missing and then make a finder call like in this example:
http://rpheath.com/posts/241-how-to-use-method-missing

Or can I dynamically add properties to a class at run-time like here:

Ruby - dynamically add property to class (at runtime)

But I need to read / write to the database....simply storing these dynamic properties in an instance variable is no good for me.

Any help would be much appreciated...or advice on a better way to approach this problem :)

答:
```<code>code = "fav_color"
User.class_eval do
  define_method code do
    read_attribute code
  end
  define_method "#{code}=" do |value|
    write_attribute code, value
  end
end
</code>```

read_attribute

write_attribute

Body:
code = "fav_color"
User.class_eval do
  define_method code do
    read_attribute code
  end
  define_method "#{code}=" do |value|
    write_attribute code, value
  end
end

read_attribute

write_attribute


问:
String returns in finally and try block
I came across this question and I am unable to understand the reason of the output it is giving.

The program is:

```<code>public static String method(){

    String s = new String();
    try
    {
        s = "return value from try block";
        return s;
    }
    catch (Exception e)
    {
        s = s + "return value from catch block";
        return s;
    }
    finally
    {
        s = s + "return value from finally block";
    }

}
</code>```

The output is:

return value from try block

Now, I debugged it and the value of s at return s statement in try block was return value from try block, return value from catch block after it returned from finally block.

Still the output is :

return value from try block

Can any one please explain this behavior?

答:
First of all, let us understand how Java handles method calls.
There is separate stack memory for every thread. When we call any method, Java internally inserts a record at top of the stack. The record contains some details like parameters & object etc.

Here one interesting field is there: the return value. Whenever the return statement is encountered, the field is updated. Now observe the code.

In the try block, the return value field is set to the return value from the try block. Now as per the execution sequence the finally block is executed. Now the finally block modifies the string reference s. It didn't modify the return value field which is previously settled by try block. Finally the method call completed & Java internally pop the record & return the return value field. So it returns the return value from the try block.

If the finally block return the string after modification, then the return value field is updated again and the updated string will be returned.

ContentLicense: CC BY-SA 3.0

Title: String returns in finally and try block

Body:
I came across this question and I am unable to understand the reason of the output it is giving.

The program is:

public static String method(){

    String s = new String();
    try
    {
        s = "return value from try block";
        return s;
    }
    catch (Exception e)
    {
        s = s + "return value from catch block";
        return s;
    }
    finally
    {
        s = s + "return value from finally block";
    }

}

The output is:

return value from try block

Now, I debugged it and the value of s at return s statement in try block was return value from try block, return value from catch block after it returned from finally block.

Still the output is :

return value from try block

Can any one please explain this behavior?


问:
Parameterize docker build by passing jar file name from command line
I am trying to parameterize the final jar file name in docker build. I need docker-maven-plugin to take jar file name passed via command line parameter. Maven build is not throwing any error while building image.

If I hard-code the jar file name in dockerfile, it is working fine.

Maven command to docker build:

```<code>mvn -X -s settings.xml docker:build -DJAR_FILE_NAME=${filename}
</code>```

My docker file:

```<code>RUN curl -kfsSL https://example.com/UnlimitedJCEPolicyJDK8/US_export_policy.jar > US_export_policy.jar \
&& curl -kfsSL https://example.com//UnlimitedJCEPolicyJDK8/local_policy.jar > local_policy.jar \
    && mv local_policy.jar ${JAVA_HOME}/jre/lib/security \
    && mv US_export_policy.jar ${JAVA_HOME}/jre/lib/security \
    && rm -rf US_export_policy.jar local_policy.jar

ENV JAVA_KEYSTORE ${JAVA_HOME}/jre/lib/security/cacerts
RUN curl -kfsSL https://example.com/mycert.cer > mycert.cer \
    && ${JAVA_HOME}/bin/keytool -v -importcert -file mycert.cer -keystore ${JAVA_KEYSTORE} -storepass dummy -alias dummy -noprompt \
    && rm mycert.cer

VOLUME /tmp
#ADD myservice-2.0.2-SNAPSHOT.jar app.jar   <-hard-coded name works fine

RUN echo "final jar file name"
RUN echo ${JAR_FILE_NAME}

ADD ${JAR_FILE_NAME} app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]
</code>```

My POM.xml

```<code><plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.0</version>
    <configuration>
        <imageName>${docker.image.prefix}/myservice</imageName>
        <dockerDirectory>src/main/docker</dockerDirectory>
        <resources>
            <resource>
                <targetPath>${docker.resource.targetPath}</targetPath>
                <directory>${project.build.directory}</directory>
                <include>${project.build.finalName}.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>
</code>```

Output from docker build process:

```<code>Step 6 : VOLUME /tmp
 ---> Using cache
 ---> xxxxxxxxx
Step 7 : RUN /bin/bash -c echo JAR_FILE_NAME1 in docker :$JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 8 : RUN /bin/bash -c echo JAR_FILE_NAME2 in docker :${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 9 : RUN echo $JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 10 : RUN echo "final jar file name"
 ---> Using cache
 ---> xxxxxxxxx
Step 11 : RUN echo ${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 12 : ADD ${JAR_FILE_NAME} app.jar
 ---> Using cache
 ---> xxxxxxxxx
Step 13 : RUN bash -c 'touch /app.jar'
 ---> Using cache
 ---> xxxxxxxxx
Step 14 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
 ---> Using cache
 ---> xxxxxxxxx
Successfully built xxxxxxxxx
[INFO] Built xxx/myservice
</code>```

Output while pulling image:

```<code>I0603 13:48:32.849159 23106 exec.cpp:132] Version: 0.23.0
I0603 13:48:32.857393 23114 exec.cpp:206] Executor registered on slave 20170523-104056-1453378314-5050-11670-S48
Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.
Error: Invalid or corrupt jarfile /app.jar
</code>```

答: Why don't you use a regular docker build command instead of going through maven? You can use a maven base image, something like maven:onbuild even. An example here may help.

Body:
I am trying to parameterize the final jar file name in docker build. I need docker-maven-plugin to take jar file name passed via command line parameter. Maven build is not throwing any error while building image.

If I hard-code the jar file name in dockerfile, it is working fine.

Maven command to docker build:

mvn -X -s settings.xml docker:build -DJAR_FILE_NAME=${filename}

My docker file:

RUN curl -kfsSL https://example.com/UnlimitedJCEPolicyJDK8/US_export_policy.jar > US_export_policy.jar \
&& curl -kfsSL https://example.com//UnlimitedJCEPolicyJDK8/local_policy.jar > local_policy.jar \
    && mv local_policy.jar ${JAVA_HOME}/jre/lib/security \
    && mv US_export_policy.jar ${JAVA_HOME}/jre/lib/security \
    && rm -rf US_export_policy.jar local_policy.jar

ENV JAVA_KEYSTORE ${JAVA_HOME}/jre/lib/security/cacerts
RUN curl -kfsSL https://example.com/mycert.cer > mycert.cer \
    && ${JAVA_HOME}/bin/keytool -v -importcert -file mycert.cer -keystore ${JAVA_KEYSTORE} -storepass dummy -alias dummy -noprompt \
    && rm mycert.cer

VOLUME /tmp
#ADD myservice-2.0.2-SNAPSHOT.jar app.jar   <-hard-coded name works fine

RUN echo "final jar file name"
RUN echo ${JAR_FILE_NAME}

ADD ${JAR_FILE_NAME} app.jar
RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/app.jar"]

My POM.xml

<plugin>
    <groupId>com.spotify</groupId>
    <artifactId>docker-maven-plugin</artifactId>
    <version>0.4.0</version>
    <configuration>
        <imageName>${docker.image.prefix}/myservice</imageName>
        <dockerDirectory>src/main/docker</dockerDirectory>
        <resources>
            <resource>
                <targetPath>${docker.resource.targetPath}</targetPath>
                <directory>${project.build.directory}</directory>
                <include>${project.build.finalName}.jar</include>
            </resource>
        </resources>
    </configuration>
</plugin>

Output from docker build process:

Step 6 : VOLUME /tmp
 ---> Using cache
 ---> xxxxxxxxx
Step 7 : RUN /bin/bash -c echo JAR_FILE_NAME1 in docker :$JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 8 : RUN /bin/bash -c echo JAR_FILE_NAME2 in docker :${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 9 : RUN echo $JAR_FILE_NAME
 ---> Using cache
 ---> xxxxxxxxx
Step 10 : RUN echo "final jar file name"
 ---> Using cache
 ---> xxxxxxxxx
Step 11 : RUN echo ${JAR_FILE_NAME}
 ---> Using cache
 ---> xxxxxxxxx
Step 12 : ADD ${JAR_FILE_NAME} app.jar
 ---> Using cache
 ---> xxxxxxxxx
Step 13 : RUN bash -c 'touch /app.jar'
 ---> Using cache
 ---> xxxxxxxxx
Step 14 : ENTRYPOINT java -Djava.security.egd=file:/dev/./urandom -jar /app.jar
 ---> Using cache
 ---> xxxxxxxxx
Successfully built xxxxxxxxx
[INFO] Built xxx/myservice

Output while pulling image:

I0603 13:48:32.849159 23106 exec.cpp:132] Version: 0.23.0
I0603 13:48:32.857393 23114 exec.cpp:206] Executor registered on slave 20170523-104056-1453378314-5050-11670-S48
Usage of loopback devices is strongly discouraged for production use. Either use `--storage-opt dm.thinpooldev` or use `--storage-opt dm.no_warn_on_loop_devices=true` to suppress this warning.
Error: Invalid or corrupt jarfile /app.jar


答:
finally

finally is used in a try/catch statement to execute code "always"

```<code>lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}
</code>```

Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable

Title: String returns in finally and try block

Body:
finally

finally is used in a try/catch statement to execute code "always"

lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}

Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable


问:
Binding model dynamically in angular2
I want to bind modal dynamically in Angular2. Here is my code

```<code><div *ngFor="let interest of interest_data;" class="row">
    <a class="btn btn-xs btn-link" data-toggle="modal" data-target="#{{interest.id}}">
       <i class="fa fa-pencil"></i>
    </a>
</div>
</code>```

and the target modal element is as below

```<code><div *ngFor="let interest of interest_data;">
    <div class="modal fade" id="interest.id"  tabindex="-1" role="dialog"
    aria-labelledby="modalLabel" aria-hidden="true">
    </div>
</div>
</code>```

Its not working . What is the proper way of doing it ?

答:
Try using [attr.data-target] and [attr.id].
I think you want to do something like this:

```<code><div *ngFor="let interest of interest_data;">

  <div>
    <a class="btn btn-xs btn-link" data-toggle="modal" [attr.data-target]="'#' + interest.id">
      open modal
      <i class="fa fa-pencil"></i>
    </a>
  </div>

  <div class="modal fade" [attr.id]="interest.id" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        modal data
      </div>
    </div>
  </div>

</div>
</code>```

Make sure to include JQuery and bootstrap.js.

Cheers

Title: Binding model dynamically in angular2

Body:
I want to bind modal dynamically in Angular2. Here is my code

and the target modal element is as below

Its not working . What is the proper way of doing it ?

Body:
Try using [attr.data-target] and [attr.id].
I think you want to do something like this:

<div *ngFor="let interest of interest_data;">

  <div>
    <a class="btn btn-xs btn-link" data-toggle="modal" [attr.data-target]="'#' + interest.id">
      open modal
      <i class="fa fa-pencil"></i>
    </a>
  </div>

  <div class="modal fade" [attr.id]="interest.id" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        modal data
      </div>
    </div>
  </div>

</div>

Make sure to include JQuery and bootstrap.js.

Cheers


问:
How to get old console logs (javascript)
I want to get a list of logs which are sent to browser's console. Is there any way to do it.</p>

```<code>console.log("lol");
console.log("imao");

list
->["lol", "imao"]
</code>```

答:
As @Mike 'Pomax' Kamermans mentioned, overriding the original .log() function / method, would be a better choice ...

let list = [];

let log = console.log;  //backup log fn
console.log = (...args) => {  //override log fn
  list.push(...args);
  log(...args);
};

console.log('lol');
console.log('lmao');
console.log(list);```

Body:
I want to get a list of logs which are sent to browser's console. Is there any way to do it.

console.log("lol");
console.log("imao");

list
->["lol", "imao"]


问:
HTMLUnit cannot find element
Using HTMLUnit I am trying to click a button on a certain site after logging in with Java

The login appears to be successful however, when I attempt to click a button (which uses a JS script and is defined by id="buttonGetDetails"), it throws an error that it cannot find an element by that id

"true" is a bool that I set and "login successful" is a System.out.println to use during testing

```<code>Error:
elementName=[*] attributeName=[id] attributeValue=[buttonGetDetails]
true
Login successful
    at com.gargoylesoftware.htmlunit.html.HtmlPage.getHtmlElementById(HtmlPage.java:1597)
</code>```

答: The page might take some time to load after you login and your code to find the button executes before the page is loaded. Try using explicit wait. http://toolsqa.com/selenium-webdriver/implicit-explicit-n-fluent-wait/</p>

Title: HTMLUnit cannot find element

Body:
Using HTMLUnit I am trying to click a button on a certain site after logging in with Java

The login appears to be successful however, when I attempt to click a button (which uses a JS script and is defined by id="buttonGetDetails"), it throws an error that it cannot find an element by that id

"true" is a bool that I set and "login successful" is a System.out.println to use during testing

Error:
elementName=[*] attributeName=[id] attributeValue=[buttonGetDetails]
true
Login successful
    at com.gargoylesoftware.htmlunit.html.HtmlPage.getHtmlElementById(HtmlPage.java:1597)


问:
Loopback 3 discards error information on multiple validation errors, turning 422 to 500, how can I solve that?
I'm migrating from Loopback 2 tot 3.

I currently have an issue with validation errors and strong-error-handler

When I post a bulk create which results in multiple validation errors, those get returned as an array of ValidationErrors.
Those errors get grouped by strong-error handler in a 500 internal server error, which is how it was before, but the details of the errors get discarded, when debug is set to false.

In my example I upload an array of tags, but for each tag, a uniqueness validation is executed. When 2 or more tags are already in the database, I have an array of errors, instead of a single validation error

I need a way to determine why the validation failed on the client side, but the details of the errors are discarded now.

Am I doing something wrong here, or should this be considered as a bug?

答:
From the strongloop error handler documentation in loopback,

In production mode, strong-error-handler omits details from error responses to prevent leaking sensitive information:

More information

For 5xx errors, the output contains only the status code and the status name from the HTTP specification.

For 4xx errors, the output contains the full error message (error.message) and the contents of the details property (error.details) that ValidationError typically uses to provide machine-readable details about validation problems. It also includes error.code to allow a machine-readable error code to be passed through which could be used, for example, for translation.

Am I doing something wrong here, or should this be considered as a bug?

No this is the intended behaviour

Safe error fields

You can set the stack trace as "safe-error-field" so that it will be displayed in production.
For example, the stack field is not displayed by default if you run the loopback in production mode.
If you still want to display the stack field, then change the config json in the server/middleware.json

```<code>"final:after": {
    "strong-error-handler": {
      "params": {
        "safeFields": ["stack"]
     }
   }
 }
</code>```

Body:
From the strongloop error handler documentation in loopback,

In production mode, strong-error-handler omits details from error responses to prevent leaking sensitive information:

More information

For 5xx errors, the output contains only the status code and the status name from the HTTP specification.

For 4xx errors, the output contains the full error message (error.message) and the contents of the details property (error.details) that ValidationError typically uses to provide machine-readable details about validation problems. It also includes error.code to allow a machine-readable error code to be passed through which could be used, for example, for translation.

Am I doing something wrong here, or should this be considered as a bug?

No this is the intended behaviour

Safe error fields

You can set the stack trace as "safe-error-field" so that it will be displayed in production.
For example, the stack field is not displayed by default if you run the loopback in production mode.
If you still want to display the stack field, then change the config json in the server/middleware.json

"final:after": {
    "strong-error-handler": {
      "params": {
        "safeFields": ["stack"]
     }
   }
 }


问:
Java HashSet (Long vs Integer)
I was solving this problem, (41 from Project Euler), where I noticed that contains method of HashSet is working differently for Long as compared to Integer (I might be wrong here, please correct me if I am).

The question is -

We shall say that an n-digit number is pandigital if it makes use of
  all the digits 1 to n exactly once. For example, 2143 is a 4-digit
  pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

My code for checking whether the number is Pandigital or not is -

```<code>private static boolean isPan(Long n) {
        HashSet<Long> list = new HashSet<Long>();
        int count = 0;
        while(n != 0){
            list.add(n%10);
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }
</code>```

This code gave me an infinite loop. So, I changed my code like this -

```<code>private static boolean isPan(Long n) {
        HashSet<Integer> list = new HashSet<Integer>();
        int count = 0;
        while(n != 0){
            list.add((int) (n%10));
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }
</code>```

I just changed, HashSet<Long> to HashSet<Integer> and list.add(n%10) to list.add((int) n%10).

This gave me the correct answer, 7652413. So, can anyone explain why the contains method works differently for Long when compared to Integer?

答:
If you want your code run correctly,see your code whose list is HashSet<Long>:

```<code>for(int i = 1; i<= count; i++){
    if(!list.contains(i)) return false;
}
</code>```

you can change the type of variable i to long,or change if(!list.contains(i)) return false; to the if(!list.contains(Long.valueOf(i))) return false;

Because of the contains will check element in existence by the element's method equals.In above code,the variable i is auto-boxed to Integer instance,because the variable i is primitive int.
And see the Integer equals:

```<code>public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}
</code>```

but your list element's type is Long,so the line if(!list.contains(i)) return false; will return false always.

Title: Java HashSet (Long vs Integer)

Body:
I was solving this problem, (41 from Project Euler), where I noticed that contains method of HashSet is working differently for Long as compared to Integer (I might be wrong here, please correct me if I am).

The question is -

We shall say that an n-digit number is pandigital if it makes use of
  all the digits 1 to n exactly once. For example, 2143 is a 4-digit
  pandigital and is also prime.

What is the largest n-digit pandigital prime that exists?

My code for checking whether the number is Pandigital or not is -

private static boolean isPan(Long n) {
        HashSet<Long> list = new HashSet<Long>();
        int count = 0;
        while(n != 0){
            list.add(n%10);
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }

This code gave me an infinite loop. So, I changed my code like this -

private static boolean isPan(Long n) {
        HashSet<Integer> list = new HashSet<Integer>();
        int count = 0;
        while(n != 0){
            list.add((int) (n%10));
            count++;
            n /= 10;
        }
        for(int i = 9; i>count; i--){
            if(list.contains(i)) return false;
        }
        for(int i = 1; i<= count; i++){
            if(!list.contains(i)) return false;
        }
        return true;
    }

I just changed, HashSet<Long> to HashSet<Integer> and list.add(n%10) to list.add((int) n%10).

This gave me the correct answer, 7652413. So, can anyone explain why the contains method works differently for Long when compared to Integer?

Body:
If you want your code run correctly,see your code whose list is HashSet<Long>:

for(int i = 1; i<= count; i++){
    if(!list.contains(i)) return false;
}

you can change the type of variable i to long,or change if(!list.contains(i)) return false; to the if(!list.contains(Long.valueOf(i))) return false;

Because of the contains will check element in existence by the element's method equals.In above code,the variable i is auto-boxed to Integer instance,because the variable i is primitive int.
And see the Integer equals:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

but your list element's type is Long,so the line if(!list.contains(i)) return false; will return false always.


问:
Get index within jquery tmpl
No, this is not a repeat of this question... a little related though, so i will use the code from that Q for comparison.

I am attempting to get the index from within a nested template, using the {{tmpl}} tag. Using the tmlp tag is much like an {{each}} tag as in the question linked above, however the $index property is not present.

```<code><script id="answerTable" type="text/x-jquery-tmpl">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
     {{tmpl(answersObj) '#answers' }}
    </table>
</script>

<script id="answers" type="text/x-jquery-tmpl">
    <tr>
        <th><input type="radio" name="group1" value="---!INDEX HERE!---" /></th>
        <td>${AnswerText}</td>
    </tr>
</script>
</code>```

I dont want to wind up with a messy way to do this- i would prefer to modify the lib if possible. Anyone have any ideas where the current lib could be modified to support this feature - git hub source. This code is a little over my head, im short on time, and understanding this lib is not within my current projects scope ;)

答:
OK had to modify the template lib.
see this link for github patch.

line 150-155 of original (current version) of jquery.tmpl.js

```<code>ret = jQuery.isArray( data ) ?
        jQuery.map( data, function( dataItem ) {
        return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
        }) :
        [ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
</code>```

modified to support $index

```<code>ret = jQuery.isArray( data ) ?
        jQuery.map( data, function( dataItem, index ) {
        if(dataItem){dataItem.$index = index;}
        return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
        }) :
        [ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;
</code>```

Title: Get index within jquery tmpl

Body:
No, this is not a repeat of this question... a little related though, so i will use the code from that Q for comparison.

I am attempting to get the index from within a nested template, using the {{tmpl}} tag. Using the tmlp tag is much like an {{each}} tag as in the question linked above, however the $index property is not present.

I dont want to wind up with a messy way to do this- i would prefer to modify the lib if possible. Anyone have any ideas where the current lib could be modified to support this feature - git hub source. This code is a little over my head, im short on time, and understanding this lib is not within my current projects scope ;)

Body:
OK had to modify the template lib.
see this link for github patch.

line 150-155 of original (current version) of jquery.tmpl.js

ret = jQuery.isArray( data ) ?
        jQuery.map( data, function( dataItem ) {
        return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
        }) :
        [ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;

modified to support $index

ret = jQuery.isArray( data ) ?
        jQuery.map( data, function( dataItem, index ) {
        if(dataItem){dataItem.$index = index;}
        return dataItem ? newTmplItem( options, parentItem, tmpl, dataItem ) : null;
        }) :
        [ newTmplItem( options, parentItem, tmpl, data ) ];
return topLevel ? jQuery( build( parentItem, null, ret ) ) : ret;


问:
Widgets don't respond when re-added through code
I am working on a launcher. It let's users add widgets from the list, it works fine.
I store information about the widget (PackageName, ClassName and it's co-ordinates on the screen) in my database when the user adds one to the screen.

When the application is restarted (or the device itself) I add those (user selected) widgets back through code:

```<code>// APPWIDGET_HOST_ID is any number you like
appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
AppWidgetProviderInfo newAppWidgetProviderInfo = new AppWidgetProviderInfo();

// Get an id
int appWidgetId = appWidgetHost.allocateAppWidgetId();

// Get the list of installed widgets
List<AppWidgetProviderInfo> appWidgetInfos = new ArrayList<AppWidgetProviderInfo>();
appWidgetInfos = appWidgetManager.getInstalledProviders();

for(int j = 0; j < appWidgetInfos.size(); j++)
{
    if (appWidgetInfos.get(j).provider.getPackageName().equals(PackageName) && appWidgetInfos.get(j).provider.getClassName().equals(ClassName))
    {
        // Get the full info of the required widget
        newAppWidgetProviderInfo = appWidgetInfos.get(j);
        break;
    }
 }

// Create Widget
AppWidgetHostView hostView = appWidgetHost.createView(this, appWidgetId, newAppWidgetProviderInfo);
hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

// Add it to your layout
RelativeLayout widgetLayout = (RelativeLayout) findViewById(R.id.widgetLayout);
widgetLayout.addView(hostView);
</code>```

The widget is successfully added to the layout but it seems like it's not enabled/updated. It doesn't respond to clicks (for instance, Analog Clock) and doesn't show any data (for instance, Music player widget), although I have put this:

```<code>@Override
protected void onStart() {
    super.onStart();
    appWidgetHost.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    appWidgetHost.stopListening();
}
</code>```

I am stuck on it since quite a long time. Searched a lot but it seems I'm the only one in this world with this problem.

答:
We can invoke a dialog asking user to permit our app to be able to bind widget IDs with the following code:

```<code>Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, sSavedWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, mWidgetInfo.provider);
startActivityForResult(intent, REQUEST_BIND_WIDGET);
</code>```

And bind widget IDs to make them actually work with:

```<code>Bundle opts = new Bundle();
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, maxWidth);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, minHeight);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, maxWidth);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, maxHeight);

widgetManager.bindAppWidgetIdIfAllowed(widgetId, mWidgetInfo, opts);
</code>```

For more information refer:

AppWidgetManager.ACTION_APPWIDGET_BIND

AppWidgetManager.bindAppWidgetIdIfAllowed()

I wish someone would have answered the same 5 years ago.

Body:
I am working on a launcher. It let's users add widgets from the list, it works fine.
I store information about the widget (PackageName, ClassName and it's co-ordinates on the screen) in my database when the user adds one to the screen.

When the application is restarted (or the device itself) I add those (user selected) widgets back through code:

// APPWIDGET_HOST_ID is any number you like
appWidgetManager = AppWidgetManager.getInstance(this);
appWidgetHost = new AppWidgetHost(this, APPWIDGET_HOST_ID);
AppWidgetProviderInfo newAppWidgetProviderInfo = new AppWidgetProviderInfo();

// Get an id
int appWidgetId = appWidgetHost.allocateAppWidgetId();

// Get the list of installed widgets
List<AppWidgetProviderInfo> appWidgetInfos = new ArrayList<AppWidgetProviderInfo>();
appWidgetInfos = appWidgetManager.getInstalledProviders();

for(int j = 0; j < appWidgetInfos.size(); j++)
{
    if (appWidgetInfos.get(j).provider.getPackageName().equals(PackageName) && appWidgetInfos.get(j).provider.getClassName().equals(ClassName))
    {
        // Get the full info of the required widget
        newAppWidgetProviderInfo = appWidgetInfos.get(j);
        break;
    }
 }

// Create Widget
AppWidgetHostView hostView = appWidgetHost.createView(this, appWidgetId, newAppWidgetProviderInfo);
hostView.setAppWidget(appWidgetId, newAppWidgetProviderInfo);

// Add it to your layout
RelativeLayout widgetLayout = (RelativeLayout) findViewById(R.id.widgetLayout);
widgetLayout.addView(hostView);

The widget is successfully added to the layout but it seems like it's not enabled/updated. It doesn't respond to clicks (for instance, Analog Clock) and doesn't show any data (for instance, Music player widget), although I have put this:

@Override
protected void onStart() {
    super.onStart();
    appWidgetHost.startListening();
}

@Override
protected void onStop() {
    super.onStop();
    appWidgetHost.stopListening();
}

I am stuck on it since quite a long time. Searched a lot but it seems I'm the only one in this world with this problem.

Body:
We can invoke a dialog asking user to permit our app to be able to bind widget IDs with the following code:

Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, sSavedWidgetId);
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, mWidgetInfo.provider);
startActivityForResult(intent, REQUEST_BIND_WIDGET);

And bind widget IDs to make them actually work with:

Bundle opts = new Bundle();
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, maxWidth);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, minHeight);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, maxWidth);
opts.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, maxHeight);

widgetManager.bindAppWidgetIdIfAllowed(widgetId, mWidgetInfo, opts);

For more information refer:

AppWidgetManager.ACTION_APPWIDGET_BIND

AppWidgetManager.bindAppWidgetIdIfAllowed()

I wish someone would have answered the same 5 years ago.


问:
Google maps autocomplete, fix to the input
I'm trying to add a google maps autocomplete input to my ionic app. It works pretty well except when I scroll. As shown on the image:

So I tried different things like changing the position of .pac-container but it doesn't solve the problem.
When I inspect the page, it seems that the results container loads at the end of the page, so it's not easy to make the block stick to the input bar.

I already searched everywhere and didn't fidn any suitable solution ? Does someone have an idea how to do it ?
(It's actually just a simple code like this:

function initialize() {
    var options = {componentRestrictions: {country: 'uk'}, types: ['geocode']}
    new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')),
        options
    );
}

initialize();
```

jsfiddle

Thanks

答:
I just encountered the same problem when I was implementing the Autocomplete on a form inside a scrollable modal. If you only have one Autocomplete object then the solution is relatively easy.

First make sure that your element's parent has a relative position.

Then you need to select the .pac-container and append it to the parent.

```<code>$("#autocomplete").parent()
    .css({position: "relative"})
    .append(".pac-container");
</code>```

Finally set the .pac-container left and top position to be below your element. This needs to be done in a stylesheet with the !important declaration to ensure it overrides the inline styles set by Google's code.

```<code>// these values will need to be calculated based on your layout
.pac-container {
    top: 40px !important;
    left: 0px !important;
}
</code>```

This obviously wont work if you have multiple Autocomplete objects on a single page. Luckily I figured out a way to handle that scenario and recently published it in a jQuery plugin designed to make autocompleting address forms a breeze.

Body:
I'm trying to add a google maps autocomplete input to my ionic app. It works pretty well except when I scroll. As shown on the image:

So I tried different things like changing the position of .pac-container but it doesn't solve the problem.
When I inspect the page, it seems that the results container loads at the end of the page, so it's not easy to make the block stick to the input bar.

I already searched everywhere and didn't fidn any suitable solution ? Does someone have an idea how to do it ?
(It's actually just a simple code like this:

function initialize() {
    var options = {componentRestrictions: {country: 'uk'}, types: ['geocode']}
    new google.maps.places.Autocomplete(
        (document.getElementById('autocomplete')),
        options
    );
}

initialize();

jsfiddle

Thanks

Body:
I just encountered the same problem when I was implementing the Autocomplete on a form inside a scrollable modal. If you only have one Autocomplete object then the solution is relatively easy.

First make sure that your element's parent has a relative position.

Then you need to select the .pac-container and append it to the parent.

$("#autocomplete").parent()
    .css({position: "relative"})
    .append(".pac-container");

Finally set the .pac-container left and top position to be below your element. This needs to be done in a stylesheet with the !important declaration to ensure it overrides the inline styles set by Google's code.

// these values will need to be calculated based on your layout
.pac-container {
    top: 40px !important;
    left: 0px !important;
}

This obviously wont work if you have multiple Autocomplete objects on a single page. Luckily I figured out a way to handle that scenario and recently published it in a jQuery plugin designed to make autocompleting address forms a breeze.


问:
Javascript: Nav bar disappears when scrolling up and reaches the top
I have created a navigation bar on my website (still in development). This navigation bar appears when a visitor is scrolling up. However, the nav bar remains all the way to the top. At the top I have the original menu, so need to have the nav bar as well.

What I would like to achieve is that the menu bar disappears as soon as the visitor hits a certain point, like hitting a div and it disappears. So far no luck with it. I use -70px (position:fixed) to place the nav bar outside the viewport and make it via Javascript appear when a visitor is scrolling up.

This is the Javascript for the nav bar:

```<code>var lastScrollTop = pageYOffset || document.documentElement.scrollTop;

window.addEventListener("scroll", function() {
   var st = window.pageYOffset || document.documentElement.scrollTop;
   if (st > lastScrollTop) {
// Scroll Down

$('.navbar').css({
   "transform": "translate3d(0,-70px,0)"
});

} else {
 // Scroll Up

$('.navbar').css({
   "transform": "translate3d(0,70px,0)"
});
}
   lastScrollTop = st;
}, false);
</code>```

Any help to make the nav bar disappear when hitting a certain div scrolling up will be much appreciated. Thanks in advance!

This is the closest I got, see below. Basically it does what I need (disable the nav bar in a certain area, in this case 350px from the bottom). I just need it to be the top, not the bottom.

```<code>$(window).scroll(function() {
var pxFromBottom = 350;
if ($(window).scrollTop() + $(window).height() > $(document).height() - pxFromBottom) {
$('.navbar').css({
  "transform": "translate3d(0,-70px,0)"
});
}
});
</code>```

答:
You could do this using Headroom.js. It's a lightweight (2KB), high-performance JS widget (no dependencies!) that allows you to change classes based on the user's scroll.

I would advice to hide your header with translateY(-100%) instead of using pixel values, so even if your header height changes it would still work fine.

Quick demo below:

var header = document.querySelector('.header');
var headroom = new Headroom(header, {
  "offset": 200,
  "tolerance": 5,
  "classes": {
    "unpinned": "header--unpinned"
  }
});
headroom.init();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.header {
  position:fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 2rem;
  color: white;
  background: black;
  transition: all .4s cubic-bezier(.770,0,.175,1);
}

.header--unpinned {
  transform: translateY(-100%);
}

/* Demo purposes only */
body { height: 2000px; margin: 0; }
p { padding: 2rem; }
/* Demo purposes only */</code>```

Header

Scroll ↓

Scroll ↓

Scroll ↓

Scroll ↓

```

There's a lot more you can do, like changing the header color on scroll (e.g. Poppulo's website) or even using different animations (see Headroom.js playroom).

Body:
I have created a navigation bar on my website (still in development). This navigation bar appears when a visitor is scrolling up. However, the nav bar remains all the way to the top. At the top I have the original menu, so need to have the nav bar as well.

What I would like to achieve is that the menu bar disappears as soon as the visitor hits a certain point, like hitting a div and it disappears. So far no luck with it. I use -70px (position:fixed) to place the nav bar outside the viewport and make it via Javascript appear when a visitor is scrolling up.

This is the Javascript for the nav bar:

var lastScrollTop = pageYOffset || document.documentElement.scrollTop;

window.addEventListener("scroll", function() {
   var st = window.pageYOffset || document.documentElement.scrollTop;
   if (st > lastScrollTop) {
// Scroll Down

$('.navbar').css({
   "transform": "translate3d(0,-70px,0)"
});

} else {
 // Scroll Up

$('.navbar').css({
   "transform": "translate3d(0,70px,0)"
});
}
   lastScrollTop = st;
}, false);

Any help to make the nav bar disappear when hitting a certain div scrolling up will be much appreciated. Thanks in advance!

This is the closest I got, see below. Basically it does what I need (disable the nav bar in a certain area, in this case 350px from the bottom). I just need it to be the top, not the bottom.

$(window).scroll(function() {
var pxFromBottom = 350;
if ($(window).scrollTop() + $(window).height() > $(document).height() - pxFromBottom) {
$('.navbar').css({
  "transform": "translate3d(0,-70px,0)"
});
}
});

Body:
You could do this using Headroom.js. It's a lightweight (2KB), high-performance JS widget (no dependencies!) that allows you to change classes based on the user's scroll.

I would advice to hide your header with translateY(-100%) instead of using pixel values, so even if your header height changes it would still work fine.

Quick demo below:

var header = document.querySelector('.header');
var headroom = new Headroom(header, {
  "offset": 200,
  "tolerance": 5,
  "classes": {
    "unpinned": "header--unpinned"
  }
});
headroom.init();

.header {
  position:fixed;
  top: 0;
  left: 0;
  right: 0;
  padding: 2rem;
  color: white;
  background: black;
  transition: all .4s cubic-bezier(.770,0,.175,1);
}

.header--unpinned {
  transform: translateY(-100%);
}

/* Demo purposes only */
body { height: 2000px; margin: 0; }
p { padding: 2rem; }
/* Demo purposes only */

<script src="https://unpkg.com/headroom.js"></script>

<header class="header">Header</header>

<!-- Demo purposes only -->
<p>Scroll ↓</p><p>Scroll ↓</p><p>Scroll ↓</p><p>Scroll ↓</p>
<!-- Demo purposes only -->

There's a lot more you can do, like changing the header color on scroll (e.g. Poppulo's website) or even using different animations (see Headroom.js playroom).


问:
Element not clickable - error work around not working as expected using Python and Selenium webdriver
While trying to scrape review data from tripadvisor's new website, am trying to click on the more button to expand the reviews before picking them up. The code works fine on the first page, but throws error on the subsequent pages.
Here's the part of code that I am using:

```<code>for num in range(page_count):
    try:
        if num != 0:
            try:
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt.click()
                driver.implicitly_wait(5)
            except NoSuchElementException:
                print("this is a NEE1")
                driver.refresh()
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #actions = ActionChains(driver).move_to_element(nxt).click().perform()
                driver.implicitly_wait(5)
            except WebDriverException:
                print("this is a WDE1")
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                actions = ActionChains(driver).move_to_element(nxt)
                driver.implicitly_wait(2)
                actions.click()
                actions.perform()
        try:
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, 'loadingWhiteBox'))
            #more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            more.click()
            time.sleep(1)
        except TimeoutException:
            print("There is no 'more' button on page %d" % (num+1))
        except WebDriverException:
            print("this is a WDE2")
            more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, "loadingWhiteBox"))
#            actions = ActionChains(driver).move_to_element(more)
#            driver.implicitly_wait(2)
#            actions.click()
#            actions.perform()
            time.sleep(1)

        review_result = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'entry')))
        review_date = driver.find_element_by_css_selector("span.ratingDate.relativeDate").get_attribute('title')

        with open('input.txt', 'a') as fid:
            for date,review in zip(review_date,review_result):
                         fid.write(unidecode(review_date))
                         fid.write(sep1)
                         fid.write(unidecode(review.text))
                         fid.write(sep)
                         fid.write(line_break)
</code>```

Below is the error:

```<code>> WebDriverException: unknown error: Element <span class="taLnk
> ulBlueLinks"
> onclick="ta.prwidgets.call('handlers.clickCollapse',event,this);">...</span>
> is not clickable at point (292, 615). Other element would receive the
> click: <div class="loadingWhiteBox"></div>
</code>```

I looked up to a number of posts related to same issues and found out few work around for the error and tried them all. The only thing that seemed to be working was using ActionChains, which is currently uncommented in the code. It doesn't throws any error but it wouldn't actually click on the more button and expand the reviews. Moreover, the code processes till a certain page and then get stuck on the same page till the loop ends picking same reviews again and again. I am unable to find any solution for this issue. Please help.

The element is attached to the tag

span.taLnk.ulBlueLinks

答:
It looks like loading white box web element is overlapping the more button. From your code, I have seen the code to wait for invisibility of white box. Please put this code before clicking on more button as given below.

```<code>WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, 'loadingWhiteBox'))
more =driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
more.click()
</code>```

Please try to increase the timeout if you get timeout exception.

Body:
While trying to scrape review data from tripadvisor's new website, am trying to click on the more button to expand the reviews before picking them up. The code works fine on the first page, but throws error on the subsequent pages.
Here's the part of code that I am using:

for num in range(page_count):
    try:
        if num != 0:
            try:
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt.click()
                driver.implicitly_wait(5)
            except NoSuchElementException:
                print("this is a NEE1")
                driver.refresh()
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                #actions = ActionChains(driver).move_to_element(nxt).click().perform()
                driver.implicitly_wait(5)
            except WebDriverException:
                print("this is a WDE1")
                #nxt = driver.find_element_by_css_selector("a.nav.next.rndBtn.ui_button.primary.taLnk")
                nxt = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.nav.next.arrowNav.taLnk")))
                actions = ActionChains(driver).move_to_element(nxt)
                driver.implicitly_wait(2)
                actions.click()
                actions.perform()
        try:
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, 'loadingWhiteBox'))
            #more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            more.click()
            time.sleep(1)
        except TimeoutException:
            print("There is no 'more' button on page %d" % (num+1))
        except WebDriverException:
            print("this is a WDE2")
            more = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
            more = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.taLnk.ulBlueLinks")))
            #more.location_once_scrolled_into_view
            #driver.execute_script("arguments[0].scrollIntoView();", more)
            #WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, "loadingWhiteBox"))
#            actions = ActionChains(driver).move_to_element(more)
#            driver.implicitly_wait(2)
#            actions.click()
#            actions.perform()
            time.sleep(1)

        review_result = WebDriverWait(driver, 20).until(EC.presence_of_all_elements_located((By.CLASS_NAME, 'entry')))
        review_date = driver.find_element_by_css_selector("span.ratingDate.relativeDate").get_attribute('title')

        with open('input.txt', 'a') as fid:
            for date,review in zip(review_date,review_result):
                         fid.write(unidecode(review_date))
                         fid.write(sep1)
                         fid.write(unidecode(review.text))
                         fid.write(sep)
                         fid.write(line_break)

Below is the error:

> WebDriverException: unknown error: Element  ulBlueLinks"
> onclick="ta.prwidgets.call('handlers.clickCollapse',event,this);">...
> is not clickable at point (292, 615). Other element would receive the
> click:

I looked up to a number of posts related to same issues and found out few work around for the error and tried them all. The only thing that seemed to be working was using ActionChains, which is currently uncommented in the code. It doesn't throws any error but it wouldn't actually click on the more button and expand the reviews. Moreover, the code processes till a certain page and then get stuck on the same page till the loop ends picking same reviews again and again. I am unable to find any solution for this issue. Please help.

The element is attached to the tag

span.taLnk.ulBlueLinks

Body:
It looks like loading white box web element is overlapping the more button. From your code, I have seen the code to wait for invisibility of white box. Please put this code before clicking on more button as given below.

WebDriverWait(driver, 20).until(EC.invisibility_of_element_located(By.CLASS_NAME, 'loadingWhiteBox'))
more =driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
more.click()

Please try to increase the timeout if you get timeout exception.


问:
How to add each line from string to listbox vb.net
Okay my website is connected to mysql database and it reads off strings of data from the database into plain text. I want to get each line from my website and add it to a list box.

This is what I have so far.

```<code>Dim GetInfo As String = WBInfo.DownloadString("https://MyWebsite.com/test.php?id=data")
</code>```

GetInfo Outputs Like:

user1:user2:user3

user2:user3:user4

user3:user4:user5

etc..

```<code>For Each line In GetInfo
    Dim parts As String() = line.ToString.Split(New Char() {":"c})
    ListBox1.Items.Add(parts(1))
    ListBox1.Items.Add(parts(2))
    ListBox1.Items.Add(parts(3))
Next
</code>```

答:
In first,  use

```<code>Dim parts As String() = line.ToString.Split(":"c)
</code>```

Note,  the indexes of an array starts from 0. Also you can use For Each loop statement instead of indexes,  for example:

```<code>For Each part As String In parts
    ListBox1.Items.Add(part)
Next
</code>```

To maintain performance while items are added to the ListBox use BeginUpdate() and EndUpdate() methods.

Body:
Okay my website is connected to mysql database and it reads off strings of data from the database into plain text. I want to get each line from my website and add it to a list box.

This is what I have so far.

Dim GetInfo As String = WBInfo.DownloadString("https://MyWebsite.com/test.php?id=data")

GetInfo Outputs Like:

user1:user2:user3

user2:user3:user4

user3:user4:user5

etc..

For Each line In GetInfo
    Dim parts As String() = line.ToString.Split(New Char() {":"c})
    ListBox1.Items.Add(parts(1))
    ListBox1.Items.Add(parts(2))
    ListBox1.Items.Add(parts(3))
Next

Body:
In first,  use

Dim parts As String() = line.ToString.Split(":"c)

Note,  the indexes of an array starts from 0. Also you can use For Each loop statement instead of indexes,  for example:

For Each part As String In parts
    ListBox1.Items.Add(part)
Next

To maintain performance while items are added to the ListBox use BeginUpdate() and EndUpdate() methods.


问:
Play: How to improve error handling and avoid creation of unnecessary throwable instances
Creating and throwing exceptions is an expensive task... and often in web applications is not necessary to throw exceptions at all. If an error occurs in a service class used by the controller, then throwing an exception makes sense... but if the controller is already aware of the issue (e.g. user not found) it is just OK to return a JSON that describes the problem.

A solution could be an Error case class that extends Throwable only when necessary, i.e. when a service invoked by the controller fails:

```<code>object MyErrors {

  trait Error { def getMessage: String }
  final case class UserNotFound(userId: Strig) extends Error { def getMessage = s"user $userId not found" }
  final case class UserNotFoundException(userId: String) extends Throwable (s"user $userId not found") with Error
  final case class DuplicateKey(key: Strig) extends Error { def getMessage = s"key $key already exists" }
  final case class DuplicateKeyException(key: String) extends Throwable (s"key $key already exists") with Error
  ...
}
</code>```

Regardless of whether or not the Error is a Throwable, I can handle possible errors like this:

```<code>object Users extends Controller {

  ...

  def find(id: String) = Action { request =>
    userService.find(id).map {
      case Some(user) => Ok(success(user.toJson))
      case None =>
        // UserNotFound implements Error but does not inherits from Throwable
        errors.toResult(UserNotFound(id))
    }.recover { case e =>
      // e is thrown by userService.find() and extends Throwable and implements Error (e.g. DuplicateKeyException)
      errors.toResult(e)
    }
  }
}
</code>```

errors.toResult maps the current exception or error to the appropriate HTTP result (e.g. BadRequest, NotFound, etc.) and converts e to JSON - see this post for the complete implementation.

Now my question is: is there a less intricate way to accomplish this? As you can see I had to create two distinct case classes for a single error (in the example I repeat the error message twice just to keep things simple)...

答:
Well, it doesn't have to be messy. Asynchronous is an 'effect" and can be stacked on top of disjunction(Either) in a way that newer Monad(think of it Monad of Monad) can be used in for comprehension. This actually enriches the algebra without changing the core behaviour or previous transformations. In order to avoid unwrapping twice, use Monad transformer such as EitherT from cats, scalaz or similar library.

In this case, it will be EitherT[Future, A, B] which internally wraps Future[Either[A,B]]. Take a look at this example: Herding cats

Also find more on stacking effects in this talk.

Body:
Creating and throwing exceptions is an expensive task... and often in web applications is not necessary to throw exceptions at all. If an error occurs in a service class used by the controller, then throwing an exception makes sense... but if the controller is already aware of the issue (e.g. user not found) it is just OK to return a JSON that describes the problem.

A solution could be an Error case class that extends Throwable only when necessary, i.e. when a service invoked by the controller fails:

object MyErrors {

  trait Error { def getMessage: String }
  final case class UserNotFound(userId: Strig) extends Error { def getMessage = s"user $userId not found" }
  final case class UserNotFoundException(userId: String) extends Throwable (s"user $userId not found") with Error
  final case class DuplicateKey(key: Strig) extends Error { def getMessage = s"key $key already exists" }
  final case class DuplicateKeyException(key: String) extends Throwable (s"key $key already exists") with Error
  ...
}

Regardless of whether or not the Error is a Throwable, I can handle possible errors like this:

object Users extends Controller {

  ...

  def find(id: String) = Action { request =>
    userService.find(id).map {
      case Some(user) => Ok(success(user.toJson))
      case None =>
        // UserNotFound implements Error but does not inherits from Throwable
        errors.toResult(UserNotFound(id))
    }.recover { case e =>
      // e is thrown by userService.find() and extends Throwable and implements Error (e.g. DuplicateKeyException)
      errors.toResult(e)
    }
  }
}

errors.toResult maps the current exception or error to the appropriate HTTP result (e.g. BadRequest, NotFound, etc.) and converts e to JSON - see this post for the complete implementation.

Now my question is: is there a less intricate way to accomplish this? As you can see I had to create two distinct case classes for a single error (in the example I repeat the error message twice just to keep things simple)...


问:
jquery.on() get reference to attached listener
I attach an event listeners:

```<code>selector.on('DOMSubtreeModified', {email: email}, handler);

function handler(event) {
                    if (hasLoaded()) {
                        selector.off('DOMSubtreeModified', handler);
                        otherStuff(event.email);
                    }
                }
</code>```

This can happen multiple times and when the first event triggers the off method, all listeners get removed. Is it possible to trigger off only on for the specific attachment. something like:

```<code>var listener = selector.on('DOMSubtreeModified', function() {
                    if (hasLoaded()) {
                        selector.off(listener);
                        otherStuff(email);
                    }
                });
</code>```

答:
You could use removeEventListener method.</p>

```<code>var listener = selector.addEventListener('DOMSubtreeModified', function() {
    if (hasLoaded()){
        selector.removeEventListener('DOMSubtreeModified', listener);
        otherStuff(email);
    }
});
</code>```

Body:
I attach an event listeners:

selector.on('DOMSubtreeModified', {email: email}, handler);

function handler(event) {
                    if (hasLoaded()) {
                        selector.off('DOMSubtreeModified', handler);
                        otherStuff(event.email);
                    }
                }

This can happen multiple times and when the first event triggers the off method, all listeners get removed. Is it possible to trigger off only on for the specific attachment. something like:

var listener = selector.on('DOMSubtreeModified', function() {
                    if (hasLoaded()) {
                        selector.off(listener);
                        otherStuff(email);
                    }
                });

Body:
You could use removeEventListener method.

var listener = selector.addEventListener('DOMSubtreeModified', function() {
    if (hasLoaded()){
        selector.removeEventListener('DOMSubtreeModified', listener);
        otherStuff(email);
    }
});


问:
Pass form data to the called activity
How do i get all the user input fields from signupActivity which is currently taking email, passwords and rest of the fields as input from the user and use it in finalactivity.

I already have made the xml layout and wonder how can i display all these fields to a newer activity which is called when signup button is pressed.

My SignupActivity.java:-

```<code>public class SignupActivity extends AppCompatActivity {
    @Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signing);
        ButterKnife.bind(this);
        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  signup();
            }
        });
    }
    public void signup(){
        //call the finalactivity and do the
    }
}
</code>```

And now finally the signup() function should call the activity finalActivity and print the info. Maybe like this-
For eg in the finalactivity i want to display-

Your name is :"name here"

  And your email is :"email here"

My question is different from How do I pass data between Activities in Android application? as i want to pass multiple variables (~50) and obviously dont want to create 50 Intents.

答:
One way to solve this problem is using Intent.

pass the required data from SignUp Activity to finalActivity using Intent

```<code>public void signup(){
    Intent intent  = new Intent(SignUp.this,finalactivity.class );
    intent.putExtra("name", name);//name you get from EditText
    intent.putExtra("email", email);//emailyou get from EditText
    startActivity( intent );
}
</code>```

In finalactivity, in OnCreate() method do this

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.final_activity);

    name=(EditText) findViewById(R.id.editText1);
    email=(EditText) findViewById(R.id.editText2);

    String name_v=getIntent().getStringExtra("name");
    String email_v=getIntent().getStringExtra("email");
    name.setText(name_v);
    pass.setText(email_v);

}
</code>```

Hope this helps

Title: Pass form data to the called activity

Body:
How do i get all the user input fields from signupActivity which is currently taking email, passwords and rest of the fields as input from the user and use it in finalactivity.

I already have made the xml layout and wonder how can i display all these fields to a newer activity which is called when signup button is pressed.

My SignupActivity.java:-

public class SignupActivity extends AppCompatActivity {
    @Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signing);
        ButterKnife.bind(this);
        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  signup();
            }
        });
    }
    public void signup(){
        //call the finalactivity and do the
    }
}

And now finally the signup() function should call the activity finalActivity and print the info. Maybe like this-
For eg in the finalactivity i want to display-

Your name is :"name here"

  And your email is :"email here"

My question is different from How do I pass data between Activities in Android application? as i want to pass multiple variables (~50) and obviously dont want to create 50 Intents.

Body:
One way to solve this problem is using Intent.

pass the required data from SignUp Activity to finalActivity using Intent

public void signup(){
    Intent intent  = new Intent(SignUp.this,finalactivity.class );
    intent.putExtra("name", name);//name you get from EditText
    intent.putExtra("email", email);//emailyou get from EditText
    startActivity( intent );
}

In finalactivity, in OnCreate() method do this

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.final_activity);

    name=(EditText) findViewById(R.id.editText1);
    email=(EditText) findViewById(R.id.editText2);

    String name_v=getIntent().getStringExtra("name");
    String email_v=getIntent().getStringExtra("email");
    name.setText(name_v);
    pass.setText(email_v);

}

Hope this helps


问:
"require is not defined" Using webpack 2
I'm having problems with bundle my app using webpack, I've reading in the site similar problems though I've trying all the recommendations and I can't figure it out what's wrong.

Everything bundles well. However when I open the browser show me this error:

Uncaught ReferenceError: require is not defined

webpack-dist.conf.js

```<code>const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const FailPlugin = require('webpack-fail-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const pkg = require('../package.json');
const autoprefixer = require('autoprefixer');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  module: {
    loaders: [
      {
        test: /\.json$/,
        loaders: [
          'json-loader'
        ]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        enforce: 'pre'
      },
      {
        test: /\.(css|scss)$/,
        loaders: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?minimize!sass-loader!postcss-loader'
        })
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: [
          'ng-annotate-loader',
          'babel-loader'
        ]
      },
      {
        test: /\.html$/,
        loaders: [
          'html-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    FailPlugin,
    new HtmlWebpackPlugin({
      template: conf.path.src('index.html')
    }),
    new webpack.optimize.UglifyJsPlugin({
      output: {comments: false},
      compress: {unused: true, dead_code: true, warnings: false} // eslint-disable-line camelcase
    }),
    new ExtractTextPlugin('index-[contenthash].css'),
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor'}),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: () => [autoprefixer]
      }
    })
  ],
  target: 'node',
  externals: [nodeExternals()],
  output: {
    path: path.join(process.cwd(), conf.paths.dist),
    filename: '[name]-[hash].js'
  },
  entry: {
    app: `./${conf.path.src('index')}`,
    vendor: Object.keys(pkg.dependencies)
  }
};
</code>```

package.json

```<code>{
  "dependencies": {
  "angular": "^1.6.2",
  "angular-ui-router": "1.0.0-beta.3",
  "body-parser": "^1.17.2",
  "cookie-parser": "^1.4.3",
  "debug": "^2.6.8",
  "express": "^4.15.3",
  "morgan": "^1.8.2",
  "pug": "^2.0.0-rc.2"
},
"devDependencies": {
  "@types/angular": "^1.6.6",
  "@types/angular-mocks": "^1.5.9",
  "@types/angular-ui-router": "^1.1.36",
  "@types/jquery": "^2.0.40",
  "angular-mocks": "^1.6.2",
  "autoprefixer": "^6.7.3",
  "babel-core": "^6.23.1",
  "babel-eslint": "^7.1.1",
  "babel-loader": "^6.3.2",
  "babel-plugin-istanbul": "^4.0.0",
  "babel-polyfill": "^6.23.0",
  "babel-preset-es2015": "^6.22.0",
  "babel-preset-es2017": "^6.24.1",
  "bootstrap": "^4.0.0-alpha.6",
  "browser-sync": "^2.18.8",
  "browser-sync-spa": "^1.0.3",
  "css-loader": "^0.26.4",
  "del": "^2.2.2",
  "es6-shim": "^0.35.3",
  "eslint": "^3.15.0",
  "eslint-config-angular": "^0.5.0",
  "eslint-config-xo-space": "^0.15.0",
  "eslint-loader": "^1.6.1",
  "eslint-plugin-angular": "^1.6.1",
  "eslint-plugin-babel": "^4.0.1",
  "extract-text-webpack-plugin": "^2.0.0-rc.3",
  "file-loader": "^0.11.1",
  "font-awesome": "^4.7.0",
  "gulp": "gulpjs/gulp#4ed9a4a3275559c73a396eff7e1fde3824951ebb",
  "gulp-angular-filesort": "^1.1.1",
  "gulp-angular-templatecache": "^2.0.0",
  "gulp-filter": "^5.0.0",
  "gulp-htmlmin": "^3.0.0",
  "gulp-hub": "frankwallis/gulp-hub#d461b9c700df9010d0a8694e4af1fb96d9f38bf4",
  "gulp-insert": "^0.5.0",
  "gulp-ng-annotate": "^2.0.0",
  "gulp-sass": "^3.1.0",
  "gulp-util": "^3.0.8",
  "html-loader": "^0.4.4",
  "html-webpack-plugin": "^2.28.0",
  "jasmine": "^2.5.3",
  "jquery": "^3.2.1",
  "json-loader": "^0.5.4",
  "karma": "^1.4.1",
  "karma-angular-filesort": "^1.0.2",
  "karma-coverage": "^1.1.1",
  "karma-jasmine": "^1.1.0",
  "karma-junit-reporter": "^1.2.0",
  "karma-ng-html2js-preprocessor": "^1.0.0",
  "karma-phantomjs-launcher": "^1.0.2",
  "karma-phantomjs-shim": "^1.4.0",
  "karma-webpack": "^2.0.2",
  "mdbootstrap": "^4.3.2",
  "ng-annotate-loader": "^0.2.0",
  "node-sass": "^4.5.0",
  "phantomjs-prebuilt": "^2.1.14",
  "postcss-loader": "^1.3.1",
  "sass-loader": "^6.0.1",
  "style-loader": "^0.13.1",
  "tether": "^1.4.0",
  "url-loader": "^0.5.8",
  "webpack": "^2.2.1",
  "webpack-fail-plugin": "^1.0.5",
  "webpack-node-externals": "^1.6.0"
},
"scripts": {
"start": "node app.js",
"build": "gulp",
"serve": "gulp serve",
"serve:dist": "gulp serve:dist",
"test": "gulp test",
"test:auto": "gulp test:auto"
},
"eslintConfig": {
"globals": {
  "expect": true
},
"root": true,
"env": {
  "browser": true,
  "jasmine": true
},
"parser": "babel-eslint",
"extends": [
  "xo-space/esnext"
  ]
}
}
</code>```

I'll be thankful if anyone can help.

答:
You're using an incorrect target:

```<code>target: 'node'
</code>```

This means that the bundle is intended to be used in a Node.js (server-side) program, not a browser. You can change it to web, or just remove that line (because web is the default).

Body:
I'm having problems with bundle my app using webpack, I've reading in the site similar problems though I've trying all the recommendations and I can't figure it out what's wrong.

Everything bundles well. However when I open the browser show me this error:

Uncaught ReferenceError: require is not defined

webpack-dist.conf.js

const webpack = require('webpack');
const conf = require('./gulp.conf');
const path = require('path');

const HtmlWebpackPlugin = require('html-webpack-plugin');
const FailPlugin = require('webpack-fail-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const pkg = require('../package.json');
const autoprefixer = require('autoprefixer');
const nodeExternals = require('webpack-node-externals');

module.exports = {
  module: {
    loaders: [
      {
        test: /\.json$/,
        loaders: [
          'json-loader'
        ]
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
        enforce: 'pre'
      },
      {
        test: /\.(css|scss)$/,
        loaders: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?minimize!sass-loader!postcss-loader'
        })
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loaders: [
          'ng-annotate-loader',
          'babel-loader'
        ]
      },
      {
        test: /\.html$/,
        loaders: [
          'html-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
    FailPlugin,
    new HtmlWebpackPlugin({
      template: conf.path.src('index.html')
    }),
    new webpack.optimize.UglifyJsPlugin({
      output: {comments: false},
      compress: {unused: true, dead_code: true, warnings: false} // eslint-disable-line camelcase
    }),
    new ExtractTextPlugin('index-[contenthash].css'),
    new webpack.optimize.CommonsChunkPlugin({name: 'vendor'}),
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: () => [autoprefixer]
      }
    })
  ],
  target: 'node',
  externals: [nodeExternals()],
  output: {
    path: path.join(process.cwd(), conf.paths.dist),
    filename: '[name]-[hash].js'
  },
  entry: {
    app: `./${conf.path.src('index')}`,
    vendor: Object.keys(pkg.dependencies)
  }
};

package.json

{
  "dependencies": {
  "angular": "^1.6.2",
  "angular-ui-router": "1.0.0-beta.3",
  "body-parser": "^1.17.2",
  "cookie-parser": "^1.4.3",
  "debug": "^2.6.8",
  "express": "^4.15.3",
  "morgan": "^1.8.2",
  "pug": "^2.0.0-rc.2"
},
"devDependencies": {
  "@types/angular": "^1.6.6",
  "@types/angular-mocks": "^1.5.9",
  "@types/angular-ui-router": "^1.1.36",
  "@types/jquery": "^2.0.40",
  "angular-mocks": "^1.6.2",
  "autoprefixer": "^6.7.3",
  "babel-core": "^6.23.1",
  "babel-eslint": "^7.1.1",
  "babel-loader": "^6.3.2",
  "babel-plugin-istanbul": "^4.0.0",
  "babel-polyfill": "^6.23.0",
  "babel-preset-es2015": "^6.22.0",
  "babel-preset-es2017": "^6.24.1",
  "bootstrap": "^4.0.0-alpha.6",
  "browser-sync": "^2.18.8",
  "browser-sync-spa": "^1.0.3",
  "css-loader": "^0.26.4",
  "del": "^2.2.2",
  "es6-shim": "^0.35.3",
  "eslint": "^3.15.0",
  "eslint-config-angular": "^0.5.0",
  "eslint-config-xo-space": "^0.15.0",
  "eslint-loader": "^1.6.1",
  "eslint-plugin-angular": "^1.6.1",
  "eslint-plugin-babel": "^4.0.1",
  "extract-text-webpack-plugin": "^2.0.0-rc.3",
  "file-loader": "^0.11.1",
  "font-awesome": "^4.7.0",
  "gulp": "gulpjs/gulp#4ed9a4a3275559c73a396eff7e1fde3824951ebb",
  "gulp-angular-filesort": "^1.1.1",
  "gulp-angular-templatecache": "^2.0.0",
  "gulp-filter": "^5.0.0",
  "gulp-htmlmin": "^3.0.0",
  "gulp-hub": "frankwallis/gulp-hub#d461b9c700df9010d0a8694e4af1fb96d9f38bf4",
  "gulp-insert": "^0.5.0",
  "gulp-ng-annotate": "^2.0.0",
  "gulp-sass": "^3.1.0",
  "gulp-util": "^3.0.8",
  "html-loader": "^0.4.4",
  "html-webpack-plugin": "^2.28.0",
  "jasmine": "^2.5.3",
  "jquery": "^3.2.1",
  "json-loader": "^0.5.4",
  "karma": "^1.4.1",
  "karma-angular-filesort": "^1.0.2",
  "karma-coverage": "^1.1.1",
  "karma-jasmine": "^1.1.0",
  "karma-junit-reporter": "^1.2.0",
  "karma-ng-html2js-preprocessor": "^1.0.0",
  "karma-phantomjs-launcher": "^1.0.2",
  "karma-phantomjs-shim": "^1.4.0",
  "karma-webpack": "^2.0.2",
  "mdbootstrap": "^4.3.2",
  "ng-annotate-loader": "^0.2.0",
  "node-sass": "^4.5.0",
  "phantomjs-prebuilt": "^2.1.14",
  "postcss-loader": "^1.3.1",
  "sass-loader": "^6.0.1",
  "style-loader": "^0.13.1",
  "tether": "^1.4.0",
  "url-loader": "^0.5.8",
  "webpack": "^2.2.1",
  "webpack-fail-plugin": "^1.0.5",
  "webpack-node-externals": "^1.6.0"
},
"scripts": {
"start": "node app.js",
"build": "gulp",
"serve": "gulp serve",
"serve:dist": "gulp serve:dist",
"test": "gulp test",
"test:auto": "gulp test:auto"
},
"eslintConfig": {
"globals": {
  "expect": true
},
"root": true,
"env": {
  "browser": true,
  "jasmine": true
},
"parser": "babel-eslint",
"extends": [
  "xo-space/esnext"
  ]
}
}

I'll be thankful if anyone can help.

Body:
You're using an incorrect target:

target: 'node'

This means that the bundle is intended to be used in a Node.js (server-side) program, not a browser. You can change it to web, or just remove that line (because web is the default).


问:
How to select first # rows from album and album details
I'm currently developing a photoalbum page for a website I'm working on, and my idea was to create an overview of all photoalbums, showing the 5 most recently added pictures. The photoalbum uses two MySQL tables, one containing the album details (eg: album name, album id) and one containing the pictures (I store them into the database as blobs) along with the corresponding album id.

However, I sofar haven't been able to figure out a query which allows me to fetch all of the album details and the id's for the 5 most recent pictures corresponding to the album. I hope you can help me out a bit.

The tables look like this:

Table: photoalbums

```<code>id | album_name | album_created
-------------------------------------
1  | testalbum  | 2010-11-07 19:33:20
2  | some more  | 2010-11-15 18:48:29
</code>```

Table: pictures

```<code>id | file   | thumbnail | name  | album_id
------------------------------------------
1  | binary | binary    | test1 | 1
2  | binary | binary    | test2 | 1
3  | binary | binary    | test3 | 2
4  | binary | binary    | test4 | 2
5  | binary | binary    | test5 | 1
</code>```

It looks to me like I'm going to need a subquery, or performing a separate query per album. I would rather avoid using multiple queries..

Can anybody help me finding the right way to do this? Thanks in advance.

答:
This query will get you all the album details and all the pictures sorted by ID descending in a comma-separated field. I can only assume the highest picture.id is the most recent, since you don't have a date_inserted column for the pictures.

```<code>SELECT a.*, GROUP_CONCAT(p.id ORDER BY p.id DESC) as picID FROM photoalbums AS a INNER JOIN pictures AS p ON p.album_id=a.id GROUP BY p.album_id
</code>```

As I said, this will get all of the pictures in decreasing ID order. With php it should be a simple matter of exploding on the comma and slicing off the first 5 IDs.

I must thank you for this fun little project, but I've got to move on and unfortunately didn't get it exactly where you want it just using an sql query.

Body:
I'm currently developing a photoalbum page for a website I'm working on, and my idea was to create an overview of all photoalbums, showing the 5 most recently added pictures. The photoalbum uses two MySQL tables, one containing the album details (eg: album name, album id) and one containing the pictures (I store them into the database as blobs) along with the corresponding album id.

However, I sofar haven't been able to figure out a query which allows me to fetch all of the album details and the id's for the 5 most recent pictures corresponding to the album. I hope you can help me out a bit.

The tables look like this:

Table: photoalbums

id | album_name | album_created
-------------------------------------
1  | testalbum  | 2010-11-07 19:33:20
2  | some more  | 2010-11-15 18:48:29

Table: pictures

id | file   | thumbnail | name  | album_id
------------------------------------------
1  | binary | binary    | test1 | 1
2  | binary | binary    | test2 | 1
3  | binary | binary    | test3 | 2
4  | binary | binary    | test4 | 2
5  | binary | binary    | test5 | 1

It looks to me like I'm going to need a subquery, or performing a separate query per album. I would rather avoid using multiple queries..

Can anybody help me finding the right way to do this? Thanks in advance.

Body:
This query will get you all the album details and all the pictures sorted by ID descending in a comma-separated field. I can only assume the highest picture.id is the most recent, since you don't have a date_inserted column for the pictures.

SELECT a.*, GROUP_CONCAT(p.id ORDER BY p.id DESC) as picID FROM photoalbums AS a INNER JOIN pictures AS p ON p.album_id=a.id GROUP BY p.album_id

As I said, this will get all of the pictures in decreasing ID order. With php it should be a simple matter of exploding on the comma and slicing off the first 5 IDs.

I must thank you for this fun little project, but I've got to move on and unfortunately didn't get it exactly where you want it just using an sql query.


问:
Different out for same function in Java against Python
I have a formula to evaluate

```<code>((x+y-1)*(x+y-2))/2 + x
</code>```

and get the string representation of it.
So in Java 1.7 I write

```<code>public static void main(String[] args)
{
    int x = 99999;
    int y = 99999;
    int answer = ((x+y-1)*(x+y-2))/2 + x;
    String s = Integer.toString(answer);
    System.out.println(s);
}
</code>```

and in Python 2.7

```<code>def answer(x, y):
  z = ((x+y-1)*(x+y-2))/2 + x
  return str(z);

print(answer(99999,99999))
</code>```

Java gave me the out put of 672047173 while Python gave me 19999400005 and seems the value from Python is correct. What is the reason behind this difference.

答:
Because integer range in java is minimum -2,147,483,648 and a maximum value of 2,147,483,647.

int answer = ((x+y-1)*(x+y-2))/2 + x;

In this line you are assigning higher range value to integer. It causes integer overflow on the arithmetic operation. So that is why you are getting incorrect value to get correct value you have to use Long data type.

```<code>public static void main(String[] args)
{
    int x = 99999;
    int y = 99999;
    long answer = (((x+y-1)*1l)*((x+y-2)*1l))/2 + x;
    String s = Long.toString(answer);
    System.out.println(s);
}
</code>```

Body:
I have a formula to evaluate

((x+y-1)*(x+y-2))/2 + x

and get the string representation of it.
So in Java 1.7 I write

public static void main(String[] args)
{
    int x = 99999;
    int y = 99999;
    int answer = ((x+y-1)*(x+y-2))/2 + x;
    String s = Integer.toString(answer);
    System.out.println(s);
}

and in Python 2.7

def answer(x, y):
  z = ((x+y-1)*(x+y-2))/2 + x
  return str(z);

print(answer(99999,99999))

Java gave me the out put of 672047173 while Python gave me 19999400005 and seems the value from Python is correct. What is the reason behind this difference.

Body:
Because integer range in java is minimum -2,147,483,648 and a maximum value of 2,147,483,647.

int answer = ((x+y-1)*(x+y-2))/2 + x;

In this line you are assigning higher range value to integer. It causes integer overflow on the arithmetic operation. So that is why you are getting incorrect value to get correct value you have to use Long data type.

public static void main(String[] args)
{
    int x = 99999;
    int y = 99999;
    long answer = (((x+y-1)*1l)*((x+y-2)*1l))/2 + x;
    String s = Long.toString(answer);
    System.out.println(s);
}


问:
How does snprintf alignment bytes
Following the answer of here, I wanted to see how many bytes a snprintf uses. The following code

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

int main() {
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:%llx", 0, 0, 0, 0, 0, 0));
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:", 0, 0, 0, 0, 0));
    printf("%d\n", snprintf(NULL, 0, "%llx", 0));
    return 0;
}
</code>```

returns

```<code>22
10
1
</code>```

I do not understand how the %llx at the end of other data printed can use 12 bytes while it uses only 1 byte if it is used alone. Does snprintf do any byte alignment?

答:
Your code has a bug. The %llx format specifier is only for long longs. Try:

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

int main() {
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:%llx", 0, 0LL, 0LL, 0LL, 0LL, 0LL));
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:", 0, 0LL, 0LL, 0LL, 0LL));
    printf("%d\n", snprintf(NULL, 0, "%llx", 0LL));
    return 0;
}
</code>```

Title: How does snprintf alignment bytes

Body:
Following the answer of here, I wanted to see how many bytes a snprintf uses. The following code

#include "stdio.h"

int main() {
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:%llx", 0, 0, 0, 0, 0, 0));
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:", 0, 0, 0, 0, 0));
    printf("%d\n", snprintf(NULL, 0, "%llx", 0));
    return 0;
}

returns

22
10
1

I do not understand how the %llx at the end of other data printed can use 12 bytes while it uses only 1 byte if it is used alone. Does snprintf do any byte alignment?

Body:
Your code has a bug. The %llx format specifier is only for long longs. Try:

#include "stdio.h"

int main() {
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:%llx", 0, 0LL, 0LL, 0LL, 0LL, 0LL));
    printf("%d\n", snprintf(NULL, 0, "%d:%llx:%d:%llx:%llx:", 0, 0LL, 0LL, 0LL, 0LL));
    printf("%d\n", snprintf(NULL, 0, "%llx", 0LL));
    return 0;
}


问:
Erroneous example in official Python tutorial (Chapter 9.10)?
I copied the following example from Python 3.6.1 Documentation, Chapter 9.10 into Jupyter Notebook (Python version 3.6.1):

```<code>xvec = [10, 20, 30]

yvec = [7, 5, 3]

sum(x*y for x,y in zip(xvec, yvec))         # dot product
</code>```

While the official documentation says that it would print 260, I got the following error in Notebook:

```<code>----> 4 sum(x*y for x,y in zip(xvec, yvec))
TypeError: 'int' object is not callable
</code>```

This is definitely not just a question on 'int object is not callable', but more on the palpable error in what is considered to be the gospel for Python.

答:
If by mistake you have overwritten zip() or/and sum(), which leads that your current code will not work. You can restore their default functionalities using del, like this example:

```<code>>>> zip = [1]
>>> zip
[1]
>>> del zip
>>> zip
<function zip>
</code>```

So, you can try :

```<code>>>> del zip
>>> del sum
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))
</code>```

And it will output:

```<code>260
</code>```

Body:
I copied the following example from Python 3.6.1 Documentation, Chapter 9.10 into Jupyter Notebook (Python version 3.6.1):

xvec = [10, 20, 30]

yvec = [7, 5, 3]

sum(x*y for x,y in zip(xvec, yvec))         # dot product

While the official documentation says that it would print 260, I got the following error in Notebook:

----> 4 sum(x*y for x,y in zip(xvec, yvec))
TypeError: 'int' object is not callable

This is definitely not just a question on 'int object is not callable', but more on the palpable error in what is considered to be the gospel for Python.

Body:
If by mistake you have overwritten zip() or/and sum(), which leads that your current code will not work. You can restore their default functionalities using del, like this example:

>>> zip = [1]
>>> zip
[1]
>>> del zip
>>> zip
<function zip>

So, you can try :

>>> del zip
>>> del sum
>>> xvec = [10, 20, 30]
>>> yvec = [7, 5, 3]
>>> sum(x*y for x,y in zip(xvec, yvec))

And it will output:

260


问:
jQuery.ajax() blocked due to CSP within WebExtension
I'm developing a Mozilla Firefox extension, which needs to communicate with my server on localhost:8080.

```<code>jQuery.ajax({
        type: query_method,
        url: "http://localhost:8080/item",
        data: item,
        dataType: "jsonp",
        success: function(result) {
            return result.code;
        },
        error: function(request, status) {
            /*
             todo handle internal error
             */
            console.log(request);
            console.log(status);
        }
    });
</code>```

Thanks to the CSP, I cannot use jQuery.ajax() to GET/POST/DELETE/PUT. It all gives me the following error message:

```<code>Content Security Policy:
The page's settings blocked the loading of a resource at
http://localhost:8080/...
("script-src moz-extension://a79d13c4-898a-482a-9bc9-d016e8dae8f5
https://* moz-extension: blob: filesystem: 'unsafe-eval' 'unsafe-inline'").
</code>```

And of course, I've tried some so-called solutions like:

"content_security_policy": "script-src 'self'; object-src 'self'; report-uri http://localhost:8080" -> no use

"content_security_policy": "script-src 'self'; object-src 'self' http:" -> Error processing content_security_policy: SyntaxError: ‘object-src’ directive contains a forbidden http: protocol source

Could anybody give a real solution to send HTTP request and receive data from a Firefox extension?

Why is using jQuery.ajax()` loading a resource? If so, I cannot use HTTP protocol to do any request.

Body:
I'm developing a Mozilla Firefox extension, which needs to communicate with my server on localhost:8080.

jQuery.ajax({
        type: query_method,
        url: "http://localhost:8080/item",
        data: item,
        dataType: "jsonp",
        success: function(result) {
            return result.code;
        },
        error: function(request, status) {
            /*
             todo handle internal error
             */
            console.log(request);
            console.log(status);
        }
    });

Thanks to the CSP, I cannot use jQuery.ajax() to GET/POST/DELETE/PUT. It all gives me the following error message:

Content Security Policy:
The page's settings blocked the loading of a resource at
http://localhost:8080/...
("script-src moz-extension://a79d13c4-898a-482a-9bc9-d016e8dae8f5
https://* moz-extension: blob: filesystem: 'unsafe-eval' 'unsafe-inline'").

And of course, I've tried some so-called solutions like:

"content_security_policy": "script-src 'self'; object-src 'self'; report-uri http://localhost:8080" -> no use

"content_security_policy": "script-src 'self'; object-src 'self' http:" -> Error processing content_security_policy: SyntaxError: ‘object-src’ directive contains a forbidden http: protocol source

Could anybody give a real solution to send HTTP request and receive data from a Firefox extension?

Why is using jQuery.ajax()` loading a resource? If so, I cannot use HTTP protocol to do any request.

Body:
The problem is not that an XHR is blocked by CSP, it is that you're using jquery and jsonp. Webextensions can perform cross-origin XHRs if you allow them in the manifest, but jsonp attempts to evaluate the resource as a <script> tag instead of actually performing an XHR.

Ditch jquery, allow localhost in the manifest and use standardized APIs such as XHR or fetch()


问:
LaTex Beamer: increase space between frametitle and content
I'm using \usetheme{Warsaw} and want to set smaller space between frametitle and content (text, pics, formulas).
As I know, I could change it by some kind of this command:
%\addtobeamertemplate{frametitle}{something}{\vspace*{Xcm}}
But honestly, I don't understand it.
Maybe I could change \vspace{Y} line in beamerthemeWarsaw.sty, but I coldn't find this file. I only found reference to it in a /var/lib/texmf/ls-R-TEXLIVEDIST file.
Thanks in advance.
P.S. I could use \vspace{-Zcm} in every frame, but I think it is not a good way.</p>

答:
In my distribution the beamerthemeWarsaw.sty file is located at /usr/share/texmf/tex/latex/beamer/base/themes/theme/. But I think you should be looking at the style files in the directory /usr/share/texmf/tex/latex/beamer/base/. The file you want is perhaps beamerbaseframecomponents.sty. This has the dimensions of margins, etc.

However, I am sure you have noticed that as you fill up a slide with content, the space between the frametitle and content keeps decreasing. So, if you need to reduce this space in only some of the slides, \vspace might be an easier option.

Hope this helps.