问:
Excel dependent dynamic lists based on Teacher Name
So I have a sheet with 2 tables (being retrieved from a SQL Query): Teachers and TeacherSets.

Teachers Table (single column):

```<code>(Header) Teachers
         Teacher1
         Teacher2
         Teacher3
</code>```

TeacherSets Table (2 columns):

```<code>Header    Teacher    Set
          Teacher1   ABC
          Teacher2   XYZ
          Teacher1   GHI
          Teacher2   AAA
</code>```

I am already using Teachers to retrieve a dropdown list but what I'd like to do is create another list that once I've selected the teacher from the first drop down, it only allows me to select only the matching sets for that teacher from table TeacherSets.

Selecting Teacher1 would only allow me to see ABC and GHI in the corresponding dropdown list.

I've had a read around and most of the solutions refer to selection based on lookups to multiple columns with defined names but this is slightly different or is it not?

Thanks,

答:
I've used this ability of Excel with named cell ranges and data validation rules using an INDIRECT forumla.

Here is a link to a sample with your data: click

Create lists of the Teachers and of each teacher's sets.

```<code>Teachers        Teacher1    Teacher2
Teacher1        ABC         XYZ
Teacher2        GHI         AAA
Teacher3
</code>```

Give the lists names

For each list, select the values, then select from menu

Formulas - Defined Names group - Define Name

The name should be equal to the column header (i.e. Teachers, Teacher1, Teacher2) and include the values of the list.

Add data validation to Teacher and Set columns

Select the cells of the column, then select from menu:

Data - Data Tools group - Data Validation

For the Set column the formula I used is =INDIRECT($F$10) referring to the first cell in the Teacher column.

That should do it. Hope it works for you.

Body:
So I have a sheet with 2 tables (being retrieved from a SQL Query): Teachers and TeacherSets.

Teachers Table (single column):

(Header) Teachers
         Teacher1
         Teacher2
         Teacher3

TeacherSets Table (2 columns):

Header    Teacher    Set
          Teacher1   ABC
          Teacher2   XYZ
          Teacher1   GHI
          Teacher2   AAA

I am already using Teachers to retrieve a dropdown list but what I'd like to do is create another list that once I've selected the teacher from the first drop down, it only allows me to select only the matching sets for that teacher from table TeacherSets.

Selecting Teacher1 would only allow me to see ABC and GHI in the corresponding dropdown list.

I've had a read around and most of the solutions refer to selection based on lookups to multiple columns with defined names but this is slightly different or is it not?

Thanks,

Body:
I've used this ability of Excel with named cell ranges and data validation rules using an INDIRECT forumla.

Here is a link to a sample with your data: click

Create lists of the Teachers and of each teacher's sets.

Teachers        Teacher1    Teacher2
Teacher1        ABC         XYZ
Teacher2        GHI         AAA
Teacher3

Give the lists names

For each list, select the values, then select from menu

Formulas - Defined Names group - Define Name

The name should be equal to the column header (i.e. Teachers, Teacher1, Teacher2) and include the values of the list.

Add data validation to Teacher and Set columns

Select the cells of the column, then select from menu:

Data - Data Tools group - Data Validation

For the Set column the formula I used is =INDIRECT($F$10) referring to the first cell in the Teacher column.

That should do it. Hope it works for you.


来源: stackexchange

问:
Not able to link properties file in deployed java program
I just finished my project everything is working fine but when i deployed it to .jar it was not showing images,
so i searched over the web and found a solution initially i was using this

```<code>File file = new File("src/sample/Drawables/1.jpg");
Image image = new Image(file.toURI().toString());

Imageview.setImage(image);
</code>```

This was working good when i was simply building through the IDE are running the application.

But when i tried to  run after deploying the application the image was not shown
so i found a solution

```<code>Image image = new Image(String.valueOf(getClass().getClassLoader().getResource("src/sample/Drawables/1.jpg")));
        Imageview.setImage(image);
</code>```

after doing this i the image was shown in the deployed application.

So i tried simmiler approch for prooperties file
initily the code was

```<code>            File file = new File("src/sample/PropertiesMain/Alpha.properties");

        if(!file.exists()){
            file.createNewFile();
        }
</code>```

So again this code was working fine until i deployed my application to jar file

the error given was java io exception cannot find file specified .

the i foolishly applied same approch as i did for image.

File file = new

```<code>File(String.valueOf(getClass().getClassLoader().getResource("src/sample/PropertiesMain/Alpha.properties")));

                if(!file.exists()){
                    file.createNewFile();
                }
</code>```

And obviously got this error

i need some help that how can i get that properties file!

please ask if you need any additional information !!

i am explaining that my question is not a duplicate as it is not asking about getting absolute path or anything my program was working good until i deployed it.
And i was looking help for because students usually don't know the absolute reasons of errors.
And not going to search something like This
By the way that question is not explaining anything close what i was asking in my question.

答:
I found my answer in this link
this is what i should use to read a file from the jar

InputStream is = myClass().getResourceAsStream("res/usernames.txt");
reader = new LineNumberReader( new InputStreamReader(is) );

ContentLicense: CC BY-SA 3.0

Body:
I just finished my project everything is working fine but when i deployed it to .jar it was not showing images,
so i searched over the web and found a solution initially i was using this

File file = new File("src/sample/Drawables/1.jpg");
Image image = new Image(file.toURI().toString());

Imageview.setImage(image);

This was working good when i was simply building through the IDE are running the application.

But when i tried to  run after deploying the application the image was not shown
so i found a solution

Image image = new Image(String.valueOf(getClass().getClassLoader().getResource("src/sample/Drawables/1.jpg")));
        Imageview.setImage(image);

after doing this i the image was shown in the deployed application.

So i tried simmiler approch for prooperties file
initily the code was

            File file = new File("src/sample/PropertiesMain/Alpha.properties");

        if(!file.exists()){
            file.createNewFile();
        }

So again this code was working fine until i deployed my application to jar file

the error given was java io exception cannot find file specified .

the i foolishly applied same approch as i did for image.

File file = new

File(String.valueOf(getClass().getClassLoader().getResource("src/sample/PropertiesMain/Alpha.properties")));

                if(!file.exists()){
                    file.createNewFile();
                }

And obviously got this error

i need some help that how can i get that properties file!

please ask if you need any additional information !!

i am explaining that my question is not a duplicate as it is not asking about getting absolute path or anything my program was working good until i deployed it.
And i was looking help for because students usually don't know the absolute reasons of errors.
And not going to search something like This
By the way that question is not explaining anything close what i was asking in my question.


问:
Spring-cloud Zuul retry when instance is down
Using Spring-cloud Angel.SR6:

Here is the configuration of my Spring-boot app with @EnableZuulProxy:

```<code>server.port=8765

ribbon.ConnectTimeout=500
ribbon.ReadTimeout=5000
ribbon.MaxAutoRetries=1
ribbon.MaxAutoRetriesNextServer=1
ribbon.OkToRetryOnAllOperations=true

zuul.routes.service-id.retryable=true
</code>```

I have 2 instances of service-id running on random ports.  These instances, as well as the Zuul instance, successfully register with Eureka, and I can access RESTful endpoints on the 2 service-id instances by accessing http://localhost:8765/service-id/.... and find that they are balanced in a round-robin manner.

I would like to kill one of the service-id instances and, when that defunct instance is next in line for forwarding, have Zuul attempt to contact it, fail, and retry with the other instance.

Is this possible, or am I misreading the documentation?  When I try the above config, the request 'destined' for the defunct instance fails with a 500 Forwarding error.  From the Zuul stacktrace:

```<code>com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:140)

....

Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-idRibbonCommand timed-out and no fallback available
</code>```

The subsequent request succeeds as expected.  This behavior continues until the defunct instance is removed from Zuul's registry.

EDIT: Updated to Brixton.M5.  No change in behavior.  Here's the Hystrix exception in more detail:

```<code>Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-id timed-out and no fallback available.
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:806) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:790) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1521) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1411) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:314) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:306) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable.unsafeSubscribe(Observable.java:7710) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:100) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:958) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:978) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:100) ~[hystrix-core-1.4.23.jar:1.4.23]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_66]
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
    ... 1 common frames omitted

Caused by: java.util.concurrent.TimeoutException: null
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:601) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:581) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    ... 15 common frames omitted
</code>```

答:
I had the same problem. This solved it for me:

Regarding to this article ribbon is only retring when the http client is set to ribbon's restclient. On default ribbon is using the Apache http client which does not retry any request.

Due the fact that ribbon's restclient is deprecated you should consider using spring-retry (https://github.com/spring-projects/spring-retry)

Keep in mind that you also have to handle the hystrix timeouts for zuul as well when you configure your retries on ribbon.

Body:
Using Spring-cloud Angel.SR6:

Here is the configuration of my Spring-boot app with @EnableZuulProxy:

server.port=8765

ribbon.ConnectTimeout=500
ribbon.ReadTimeout=5000
ribbon.MaxAutoRetries=1
ribbon.MaxAutoRetriesNextServer=1
ribbon.OkToRetryOnAllOperations=true

zuul.routes.service-id.retryable=true

I have 2 instances of service-id running on random ports.  These instances, as well as the Zuul instance, successfully register with Eureka, and I can access RESTful endpoints on the 2 service-id instances by accessing http://localhost:8765/service-id/.... and find that they are balanced in a round-robin manner.

I would like to kill one of the service-id instances and, when that defunct instance is next in line for forwarding, have Zuul attempt to contact it, fail, and retry with the other instance.

Is this possible, or am I misreading the documentation?  When I try the above config, the request 'destined' for the defunct instance fails with a 500 Forwarding error.  From the Zuul stacktrace:

com.netflix.zuul.exception.ZuulException: Forwarding error
    at org.springframework.cloud.netflix.zuul.filters.route.RibbonRoutingFilter.forward(RibbonRoutingFilter.java:140)

....

Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-idRibbonCommand timed-out and no fallback available

The subsequent request succeeds as expected.  This behavior continues until the defunct instance is removed from Zuul's registry.

EDIT: Updated to Brixton.M5.  No change in behavior.  Here's the Hystrix exception in more detail:

Caused by: com.netflix.hystrix.exception.HystrixRuntimeException: service-id timed-out and no fallback available.
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:806) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$16.call(AbstractCommand.java:790) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$DeprecatedOnFallbackHookApplication$1.onError(AbstractCommand.java:1521) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$FallbackHookApplication$1.onError(AbstractCommand.java:1411) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:314) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:306) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:162) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable$2.call(Observable.java:154) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.Observable.unsafeSubscribe(Observable.java:7710) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:100) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70) ~[rxjava-1.0.14.jar:1.0.14]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$1.run(AbstractCommand.java:958) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:41) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable$1.call(HystrixContextRunnable.java:37) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.strategy.concurrency.HystrixContextRunnable.run(HystrixContextRunnable.java:57) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$HystrixObservableTimeoutOperator$2.tick(AbstractCommand.java:978) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.util.HystrixTimer$1.run(HystrixTimer.java:100) ~[hystrix-core-1.4.23.jar:1.4.23]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_66]
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) ~[na:1.8.0_66]
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) ~[na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_66]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_66]
    ... 1 common frames omitted

Caused by: java.util.concurrent.TimeoutException: null
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:601) ~[hystrix-core-1.4.23.jar:1.4.23]
    at com.netflix.hystrix.AbstractCommand$9.call(AbstractCommand.java:581) ~[hystrix-core-1.4.23.jar:1.4.23]
    at rx.internal.operators.OperatorOnErrorResumeNextViaFunction$1.onError(OperatorOnErrorResumeNextViaFunction.java:99) ~[rxjava-1.0.14.jar:1.0.14]
    ... 15 common frames omitted


问:
Insert form action link based on radio select field
I have a simple form field with two different radio select field:

```<code><form method="get" id="searchform" action="<?php $btn_link; ?>">
  <div class="alternativ-suchefeld">
    <div class="radioboxarea">
      <input type="radio" name="buttonname" value="value_button_1" checked>
      Button 1</div>
    <div class="radioboxarea">
      <input type="radio" name="buttonname" value="value_button_2" >
      Button 2</div>
    <input type="submit" id="searchSubmit" value="Search"  />
  </div>
</form>
</code>```

If I'm choosing "Button 1" and submit, the action link "$btn_link" should be "link1.php".
If "Button 2" is selected, the action link should be called "link2.php".

Has someone an idea, how to realize this ? Thank you!

答:
Do like this

Script

```<code> $('input[name="buttonname"]').change(function() {
  var v = $(this).val();
  if (v == "value_button_1") {
    $('#searchform').attr('action', 'link1.php');
  } else if (v == "value_button_2") {
    $('#searchform').attr('action', 'link2.php');
  }
});
</code>```

Working fiddle here

Body:
I have a simple form field with two different radio select field:

<form method="get" id="searchform" action="<?php $btn_link; ?>">

      <input type="radio" name="buttonname" value="value_button_1" checked>
      Button 1

      <input type="radio" name="buttonname" value="value_button_2" >
      Button 2

    <input type="submit" id="searchSubmit" value="Search"  />

</form>

If I'm choosing "Button 1" and submit, the action link "$btn_link" should be "link1.php".
If "Button 2" is selected, the action link should be called "link2.php".

Has someone an idea, how to realize this ? Thank you!

Body:
Do like this

Script

 $('input[name="buttonname"]').change(function() {
  var v = $(this).val();
  if (v == "value_button_1") {
    $('#searchform').attr('action', 'link1.php');
  } else if (v == "value_button_2") {
    $('#searchform').attr('action', 'link2.php');
  }
});

Working fiddle here


问:
Making a Database search engine like Google
I'm new to creating websites.I'm creating a Telephone directory search Engine.(Using PostgreSql,CGI scripts).My Database is having Name,Tel.No,City,State,Address.

Upto now I have created a search field like "google" where I can give any of the above Database entries and search.But now I want to give like "name+city+..." So that I can minimize the output entries.

答: You can create the function where the WHERE clause can be created dynamically after checking which fields have been passed by the user to perform the search Query.</p>

ContentLicense: CC BY-SA 2.5


问:
mysql select * from table where is not null
Is it possible to do a select * from table where is not null?

Essentially i want all results from a table but if a column has a null value for a row i dont want to see null in my output file which is a csv file?

答:
If you group_concat a bunch of columns and any of those columns contains a null then the result is null. So you could build a prepared statement using this characteristic to together with the column names harvested from information_schema columns.

```<code>drop table if exists t;
create table t (tID int, Name varchar(20),   Type varchar(20),   Start_Date date,  End_Date date);
insert into t values
(1,   null , 'Retail' , '2010-01-01', '2010-07-21'),
(1,   'Cust_1' , null   , '2010-07-22', '2012-05-17'),
(1,   'Cust_1' , 'Corp'   , '2012-05-18', '2012-12-31');

select group_concat(column_name) into @gc from information_schema.columns where table_name = 't' and table_schema = 'sandbox';
set @sqlstmt = concat('select * from t where concat(', @gc, ') is not null;');

#select @sqlstmt;

prepare sqlstmt from @sqlstmt;
execute sqlstmt;
deallocate prepare sqlstmt;
</code>```

Result

```<code>+------+--------+------+------------+------------+
| tID  | Name   | Type | Start_Date | End_Date   |
+------+--------+------+------------+------------+
|    1 | Cust_1 | Corp | 2012-05-18 | 2012-12-31 |
+------+--------+------+------------+------------+
1 row in set (0.00 sec)
</code>```

Body:
If you group_concat a bunch of columns and any of those columns contains a null then the result is null. So you could build a prepared statement using this characteristic to together with the column names harvested from information_schema columns.

drop table if exists t;
create table t (tID int, Name varchar(20),   Type varchar(20),   Start_Date date,  End_Date date);
insert into t values
(1,   null , 'Retail' , '2010-01-01', '2010-07-21'),
(1,   'Cust_1' , null   , '2010-07-22', '2012-05-17'),
(1,   'Cust_1' , 'Corp'   , '2012-05-18', '2012-12-31');

select group_concat(column_name) into @gc from information_schema.columns where table_name = 't' and table_schema = 'sandbox';
set @sqlstmt = concat('select * from t where concat(', @gc, ') is not null;');

#select @sqlstmt;

prepare sqlstmt from @sqlstmt;
execute sqlstmt;
deallocate prepare sqlstmt;

Result

+------+--------+------+------------+------------+
| tID  | Name   | Type | Start_Date | End_Date   |
+------+--------+------+------------+------------+
|    1 | Cust_1 | Corp | 2012-05-18 | 2012-12-31 |
+------+--------+------+------------+------------+
1 row in set (0.00 sec)


问:
Create an unordered map from a vector of structs
Say I have a class that can easily express key-value semantics:

```<code>template <class T1, class T2>
struct data_t{
    T1 m1;
    T2 m2;
};
</code>```

What would be the most efficient way to create an unordered map out of a vector of such structs?

My approach

I tried to define a conversion operator for my class

```<code>operator std::pair<T1, T2> () { return {m1, m2};  } // typo noted by PasserBy
</code>```

But this doesn't seem to work

```<code>std::vector<data_t> v;
std::unordered_map<T1, T2> um(v.begin(), v.end()); // compilation error
</code>```

My particular use case has a pointer type T1 and a value type T2 so I suppose there wouldn't be a need to define hash functions (?). Also the reason I'm trying to do it through a conversion operator is to be able to add elements to that unordered map in the same fashion:

```<code>um.insert(itn, ite); // insert from a range of the source vector
</code>```

答:
First, there is a typo in your conversion operator

```<code>operator std::pair<T1, T2>() const { return {m1, m2}; }
</code>```

And it should generally be marked const too.

The reason for a compile error is that unordered_map<T1, T2> holds std::pair<const T1, T2>, which your vector doesn't hold.

So this works

```<code>std::vector<data_t<const T1, T2>> v;
std::unordered_map<T1, T2> um(v.begin(), v.end());
</code>```

provided that T1 has a proper hash function.

So does using a different conversion operator

```<code>operator std::pair<const T1, T2>() const { return {m1, m2}; }
std::vector<data_t<T1, T2>> v;
std::unordered_map<T1, T2> um(v.begin(), v.end());
</code>```

Body:
Say I have a class that can easily express key-value semantics:

template <class T1, class T2>
struct data_t{
    T1 m1;
    T2 m2;
};

What would be the most efficient way to create an unordered map out of a vector of such structs?

My approach

I tried to define a conversion operator for my class

operator std::pair<T1, T2> () { return {m1, m2};  } // typo noted by PasserBy

But this doesn't seem to work

std::vector<data_t> v;
std::unordered_map<T1, T2> um(v.begin(), v.end()); // compilation error

My particular use case has a pointer type T1 and a value type T2 so I suppose there wouldn't be a need to define hash functions (?). Also the reason I'm trying to do it through a conversion operator is to be able to add elements to that unordered map in the same fashion:

um.insert(itn, ite); // insert from a range of the source vector

Body:
First, there is a typo in your conversion operator

operator std::pair<T1, T2>() const { return {m1, m2}; }

And it should generally be marked const too.

The reason for a compile error is that unordered_map<T1, T2> holds std::pair<const T1, T2>, which your vector doesn't hold.

So this works

std::vector<data_t<const T1, T2>> v;
std::unordered_map<T1, T2> um(v.begin(), v.end());

provided that T1 has a proper hash function.

So does using a different conversion operator

operator std::pair<const T1, T2>() const { return {m1, m2}; }
std::vector<data_t<T1, T2>> v;
std::unordered_map<T1, T2> um(v.begin(), v.end());


问:
Image not showing in Django
I don't know why the images aren't showing in Django. Something to do with the media root?

settings code

```<code>STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')'
</code>```

models code

```<code>from django.db import models
</code>```

from django.core.urlresolvers import reverse

Create your models here.

class Post(models.Model):

```<code>## Post Properties
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
summary = models.CharField(max_length=255)
content = models.TextField()
published = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='img',default='media/placeholder.png')

class Meta:
    ordering = ['-created']

    def __unicode__(self):
        return u'%s'% self.title

def get_absolute_url(self):
        return reverse('blog.views.post', args=[self.slug])
</code>```

I didn't add a url for the picture, could that be a problem?

urls

```<code>urlpatterns = [
url(r'^post/(.*)', blogViews.post),
url(r'^about/$', blogViews.about),
url(r'^$', blogViews.index),
url(r'^admin/', admin.site.urls),
</code>```

index.html code

```<code><img src="{{post.image}}">
<p> {{post.image}} </p>
</code>```

**Views.py **

```<code>from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponse
from .models import Post

# Create your views here.

def index(request):
    posts = Post.objects.all()
    return render(request, 'index.html', {'posts': posts})

def post(request, slug):
    return render_to_response('post.html', {
    'post': get_object_or_404(Post,slug=slug)
    })

def about(request):
    return render(request, 'about.html', {})
</code>```

In the website all that shows is a blank picture as well as the file name (either 'placeholder.png' which is the default or img/... which I uploaded through admin)

Edit:

This was marked as a duplicate, I saw that post and tried to change my code to reflect that code but it wasn't working. Figured it would be better to post my own.

Thanks in advance, first question on this site!

答:
Try this,

```<code><img src="{{post.image.url}}">
</code>```

Also, add in your urls.py,

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

For learning more about serving static, refer the documentation here...

Title: Image not showing in Django

Body:
I don't know why the images aren't showing in Django. Something to do with the media root?

settings code

STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')'

models code

from django.db import models

from django.core.urlresolvers import reverse

Create your models here.

class Post(models.Model):

## Post Properties
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique=True)
summary = models.CharField(max_length=255)
content = models.TextField()
published = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to='img',default='media/placeholder.png')

class Meta:
    ordering = ['-created']

    def __unicode__(self):
        return u'%s'% self.title

def get_absolute_url(self):
        return reverse('blog.views.post', args=[self.slug])

I didn't add a url for the picture, could that be a problem?

urls

urlpatterns = [
url(r'^post/(.*)', blogViews.post),
url(r'^about/$', blogViews.about),
url(r'^$', blogViews.index),
url(r'^admin/', admin.site.urls),

index.html code

 {{post.image}}

**Views.py **

from django.shortcuts import render, render_to_response, get_object_or_404
from django.http import HttpResponse
from .models import Post

# Create your views here.

def index(request):
    posts = Post.objects.all()
    return render(request, 'index.html', {'posts': posts})

def post(request, slug):
    return render_to_response('post.html', {
    'post': get_object_or_404(Post,slug=slug)
    })

def about(request):
    return render(request, 'about.html', {})

In the website all that shows is a blank picture as well as the file name (either 'placeholder.png' which is the default or img/... which I uploaded through admin)

Edit:

This was marked as a duplicate, I saw that post and tried to change my code to reflect that code but it wasn't working. Figured it would be better to post my own.

Thanks in advance, first question on this site!

Body:
Try this,

<img src="{{post.image.url}}">

Also, add in your urls.py,

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

For learning more about serving static, refer the documentation here...


问:
ng-options with array object angularjs
I have data like this :

EDIT

I solved my problem by change to acti[0] . But now I get wrong value in select . How can I solve this

答:
Access the first object of the array

```<code>ng-options ="k as v for (k,v) in provinces[0]
</code>```

demo

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.provinces =    [
    {
    00844:"Hà Nội",
    00848:"TPHCM",
    008418:"Hòa Bình",
    008419:"Hà Giang",
    008420:"Lào Cai",
    008422:"Sơn La",
    008425:"Lạng Sơn",
    008426:"Cao Bằng",
    008427:"Tuyên Quang",
    008429:"Yên Bái",
    008430:"Ninh Bình",
    008431:"Hải Phòng"
    }
    ]
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <select ng-model="formDataAddress.province"
                ng-options ="k as v for (k,v) in provinces[0]"  ng-selected="">
                 </select>
</div></code>```

Title: ng-options with array object angularjs

Body:
Access the first object of the array

ng-options ="k as v for (k,v) in provinces[0]

demo

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.provinces =    [
    {
    00844:"Hà Nội",
    00848:"TPHCM",
    008418:"Hòa Bình",
    008419:"Hà Giang",
    008420:"Lào Cai",
    008422:"Sơn La",
    008425:"Lạng Sơn",
    008426:"Cao Bằng",
    008427:"Tuyên Quang",
    008429:"Yên Bái",
    008430:"Ninh Bình",
    008431:"Hải Phòng"
    }
    ]
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <select ng-model="formDataAddress.province"
                ng-options ="k as v for (k,v) in provinces[0]"  ng-selected="">
                 </select>
</div>


问:
Make git highlight tab characters in a diff?
I'm trying to ensure that I don't commit code that uses tab characters for indentation. This is a soft constraint that I'm applying to my own commits (right now we don't have a standard for indentation characters, but I'd like to use spaces, since there's no disagreement on the width of a space, but some people use width-4 tabs versus width-8 tabs).

The easiest way to check such constraints is often to look at the actual output of git diff every time you are about to commit and see if there are any problems. For example, for me, by default, trailing whitespace is highlighted and windows newlines are also visible in the diff, so if I'm about to accidentally commit code with trailing whitespace, I will be alerted to this. Is there a way to make tab characters also show up in git diff?

答:
I have made a pre-commit hook that stops you from committing tab-indented code https://github.com/martinjoiner/portable-code-pre-commit-hook it looks like this...

I routinely use it on all my projects now. Feel free to use it yourself.

I work on a team that write code in a mix of Mac, Windows and Linux environments as well as reviewing it in-browser via the Github website. The team are really happy to have a helping hand checking their code so it looks consistent across all those places.

If you find any problems please let me know, I'd like the chance to improve any weaknesses. Thanks.


问:
update data using jquery
I have a page that lists records from a database call. I want to have an 'edit' link on each row that will popup a Jquery dialog so that the row can be edited. My question is how do I pass the data from the selected row to the jquery dialog box so that it can be edited?
i have the code which open jquery popup but the textboxes are empty.

```<code><div id="boxes">

<div id="dialog2" class="window">
<form method="post" action="update_books_a.php">
  <input name="name" type="text" value="<?php echo $ing['book_name']; ?>"/><br/>
  <input name="author" type="text" value="<?php echo $ing['author']; ?>"/>

    <input type="hidden" name="book_id" value="<?php print $ing['book_id'];?>" />
    <br/><br/>
<input type="submit" value="Update" class="close"/>
</form>
</div></code>```

myphp code is

```<code>$select=mysql_query("select * from books where book_id='$book_id'") or die(mysql_error());
while($ing=mysql_fetch_array($select))
{
 ?>
<tr>
    <td><a href="#dialog2" name="modal"><?php echo $ing['book_name'];?></a></td>
    <td><?php echo $ing['author'];?></td></tr>
</code>```

the jquery code is

```<code>

$(document).ready(function() {

    //select all the a tag with name equal to modal
    $('a[name=modal]').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();

        //Get the A tag
        var id = $(this).attr('href');

        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set heigth and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});

        //transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow",0.8);

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);

        //transition effect
        $(id).fadeIn(2000);

    });

    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();

        $('#mask').hide();
        $('.window').hide();
    });

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });

});

body {
font-family:verdana;
font-size:15px;
}

a {color:#333; text-decoration:none}
a:hover {color:#ccc; text-decoration:none}

#mask {
  position:absolute;
  left:0;
  top:0;
  z-index:9000;
  background-color:#000;
  display:none;
}

#boxes .window {
  position:absolute;
  left:0;
  top:0;
  width:440px;
  height:200px;
  display:none;
  z-index:9999;
  padding:20px;
}

#boxes #dialog2 {
  background:url(../images/notice.png) no-repeat 0 0 transparent;
  width:326px;
  height:229px;
  padding:50px 0 20px 25px;
}</code>```

答:
You can extract the text value of each element using the .text() method.

If you need the html value you can use .html() or yourNode.innerHTML

Title: update data using jquery

Body:
I have a page that lists records from a database call. I want to have an 'edit' link on each row that will popup a Jquery dialog so that the row can be edited. My question is how do I pass the data from the selected row to the jquery dialog box so that it can be edited?
i have the code which open jquery popup but the textboxes are empty.

<form method="post" action="update_books_a.php">
  <input name="name" type="text" value="<?php echo $ing['book_name']; ?>"/>

  <input name="author" type="text" value="<?php echo $ing['author']; ?>"/>

    <input type="hidden" name="book_id" value="<?php print $ing['book_id'];?>" />

<input type="submit" value="Update" class="close"/>
</form>

myphp code is

$select=mysql_query("select * from books where book_id='$book_id'") or die(mysql_error());
while($ing=mysql_fetch_array($select))
{
 ?>

    <?php echo $ing['book_name'];?>
    <?php echo $ing['author'];?>

the jquery code is

$(document).ready(function() {

    //select all the a tag with name equal to modal
    $('a[name=modal]').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();

        //Get the A tag
        var id = $(this).attr('href');

        //Get the screen height and width
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set heigth and width to mask to fill up the whole screen
        $('#mask').css({'width':maskWidth,'height':maskHeight});

        //transition effect
        $('#mask').fadeIn(1000);
        $('#mask').fadeTo("slow",0.8);

        //Get the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        //Set the popup window to center
        $(id).css('top',  winH/2-$(id).height()/2);
        $(id).css('left', winW/2-$(id).width()/2);

        //transition effect
        $(id).fadeIn(2000);

    });

    //if close button is clicked
    $('.window .close').click(function (e) {
        //Cancel the link behavior
        e.preventDefault();

        $('#mask').hide();
        $('.window').hide();
    });

    //if mask is clicked
    $('#mask').click(function () {
        $(this).hide();
        $('.window').hide();
    });

});

body {
font-family:verdana;
font-size:15px;
}

a {color:#333; text-decoration:none}
a:hover {color:#ccc; text-decoration:none}

#mask {
  position:absolute;
  left:0;
  top:0;
  z-index:9000;
  background-color:#000;
  display:none;
}

#boxes .window {
  position:absolute;
  left:0;
  top:0;
  width:440px;
  height:200px;
  display:none;
  z-index:9999;
  padding:20px;
}

#boxes #dialog2 {
  background:url(../images/notice.png) no-repeat 0 0 transparent;
  width:326px;
  height:229px;
  padding:50px 0 20px 25px;
}


问:
Angular2 - pass value to parent/child component
I need to pass a parameter or to modify an exposed property on a component given this app.component structure:

app.component.html

```<code><app-appheader></app-appheader>
<app-appmenu></app-appmenu>
<div class="main-container">
    <router-outlet>
        <span *ngIf="showLoader" class="loading"></span>
    </router-outlet>
</div>
<app-appfooter></app-appfooter>
</code>```

In detail, I need to pass a parameter to app-appmenu component from the component loaded in router-outlet...

I don'w know what are the steps in order to do it.

Thanks to support

答:
You have several ways to pass data from components.

In the documentation (this link) you'll find them, but I suggest you to use a shared service.

The structure would be somewhat this:

Component A has data. Calls Shared Service.

Component B is subscribed to the method of Shared Service, as soon as Component A calls it, Component B "requests to Shared Service the data".

Shared Service returns the data from its method to all subscribed components (of the method), therefore, returns data to Component B.

See the Shared Service as a middleman between components.

It doesn't take into consideration the level of the components (child, parent, grand parent, etc.). It works with call method/trigger subscriptions.

Body:
I need to pass a parameter or to modify an exposed property on a component given this app.component structure:

app.component.html

<app-appheader></app-appheader>
<app-appmenu></app-appmenu>

    <router-outlet>

    </router-outlet>

<app-appfooter></app-appfooter>

In detail, I need to pass a parameter to app-appmenu component from the component loaded in router-outlet...

I don'w know what are the steps in order to do it.

Thanks to support


问:
Call From kv.local/172.20.12.168 to localhost:8020 failed on connection exception, when using tera gen
I am working with hadoop teragen to check the hadoop mapreduce benchmarking with the terasort.
But when i run the following command,

hadoop jar  /Users/**/Documents/hadoop-2.6.4/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.6.4.jar teragen -Dmapreduce.job.maps=100 1t random-data

I got the following exception,

```<code>17/06/01 15:09:21 WARN util.NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable
17/06/01 15:09:22 INFO client.RMProxy: Connecting to ResourceManager at /127.0.0.1:8032
17/06/01 15:09:23 INFO terasort.TeraSort: Generating -727379968 using 100
17/06/01 15:09:23 INFO mapreduce.JobSubmitter: number of splits:100
17/06/01 15:09:23 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1496303775726_0003
17/06/01 15:09:23 INFO impl.YarnClientImpl: Submitted application application_1496303775726_0003
17/06/01 15:09:23 INFO mapreduce.Job: The url to track the job: http://localhost:8088/proxy/application_1496303775726_0003/
17/06/01 15:09:23 INFO mapreduce.Job: Running job: job_1496303775726_0003
17/06/01 15:09:27 INFO mapreduce.Job: Job job_1496303775726_0003 running in uber mode : false
17/06/01 15:09:27 INFO mapreduce.Job:  map 0% reduce 0%
17/06/01 15:09:27 INFO mapreduce.Job: Job job_1496303775726_0003 failed with state FAILED due to: Application application_1496303775726_0003 failed 2 times due to AM Container for appattempt_1496303775726_0003_000002 exited with  exitCode: -1000
For more detailed output, check application tracking page:http://localhost:8088/proxy/application_1496303775726_0003/Then, click on links to logs of each attempt.
Diagnostics: Call From KV.local/172.20.12.168 to localhost:8020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
java.net.ConnectException: Call From KV.local/172.20.12.168 to localhost:8020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:791)
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:731)
    at org.apache.hadoop.ipc.Client.call(Client.java:1473)
    at org.apache.hadoop.ipc.Client.call(Client.java:1400)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:232)
    at com.sun.proxy.$Proxy34.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.getFileInfo(ClientNamenodeProtocolTranslatorPB.java:752)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:187)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at com.sun.proxy.$Proxy35.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.DFSClient.getFileInfo(DFSClient.java:1977)
    at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1118)
    at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1114)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1114)
    at org.apache.hadoop.yarn.util.FSDownload.copy(FSDownload.java:251)
    at org.apache.hadoop.yarn.util.FSDownload.access$000(FSDownload.java:61)
    at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:359)
    at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:357)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
    at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:356)
    at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:60)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:530)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:494)
    at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:608)
    at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:706)
    at org.apache.hadoop.ipc.Client$Connection.access$2800(Client.java:369)
    at org.apache.hadoop.ipc.Client.getConnection(Client.java:1522)
    at org.apache.hadoop.ipc.Client.call(Client.java:1439)
    ... 31 more
</code>```

As the error show, it is not able to connect to localhost:8020, but when i chech the namenode web UI, it shows that the namenode is active. Please see the below screenshot:

I found many posts related to this, but none helped me out. I also checked out the hosts file, which contains the following line:

127.0.0.1 localhost

172.20.12.168 localhost

Can anybody help me out sorting out this problem?

答:
The following procedure helped me out in solving the issue:

Stop all the services.

Delete namenode and datanode directories as specified in hdfs-site.xml.

Create new namenode and datanode directories and modify hdfs-site.xml accordingly.

in core-site.xml, make the following changes or add the following properties:

```<code><property>
  <name>fs.defaultFS</name>
  <value>hdfs://172.20.12.168/</value>
</property>
<property>
  <name>fs.default.name</name>
  <value>hdfs://172.20.12.168:8020</value>
</property>
</code>```

Make the following changes in  hadoop-2.6.4/etc/hadoop/hadoop-env.sh file:

```<code>export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home
</code>```

Restart dfs, yarn and mr as follows:

```<code> start-dfs.sh
 start-yarn.sh
 mr-jobhistory-daemon.sh start historyserver
</code>```

Body:
I am working with hadoop teragen to check the hadoop mapreduce benchmarking with the terasort.
But when i run the following command,

hadoop jar  /Users/**/Documents/hadoop-2.6.4/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.6.4.jar teragen -Dmapreduce.job.maps=100 1t random-data

I got the following exception,

17/06/01 15:09:21 WARN util.NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable
17/06/01 15:09:22 INFO client.RMProxy: Connecting to ResourceManager at /127.0.0.1:8032
17/06/01 15:09:23 INFO terasort.TeraSort: Generating -727379968 using 100
17/06/01 15:09:23 INFO mapreduce.JobSubmitter: number of splits:100
17/06/01 15:09:23 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1496303775726_0003
17/06/01 15:09:23 INFO impl.YarnClientImpl: Submitted application application_1496303775726_0003
17/06/01 15:09:23 INFO mapreduce.Job: The url to track the job: http://localhost:8088/proxy/application_1496303775726_0003/
17/06/01 15:09:23 INFO mapreduce.Job: Running job: job_1496303775726_0003
17/06/01 15:09:27 INFO mapreduce.Job: Job job_1496303775726_0003 running in uber mode : false
17/06/01 15:09:27 INFO mapreduce.Job:  map 0% reduce 0%
17/06/01 15:09:27 INFO mapreduce.Job: Job job_1496303775726_0003 failed with state FAILED due to: Application application_1496303775726_0003 failed 2 times due to AM Container for appattempt_1496303775726_0003_000002 exited with  exitCode: -1000
For more detailed output, check application tracking page:http://localhost:8088/proxy/application_1496303775726_0003/Then, click on links to logs of each attempt.
Diagnostics: Call From KV.local/172.20.12.168 to localhost:8020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
java.net.ConnectException: Call From KV.local/172.20.12.168 to localhost:8020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:791)
    at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:731)
    at org.apache.hadoop.ipc.Client.call(Client.java:1473)
    at org.apache.hadoop.ipc.Client.call(Client.java:1400)
    at org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:232)
    at com.sun.proxy.$Proxy34.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.getFileInfo(ClientNamenodeProtocolTranslatorPB.java:752)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:187)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at com.sun.proxy.$Proxy35.getFileInfo(Unknown Source)
    at org.apache.hadoop.hdfs.DFSClient.getFileInfo(DFSClient.java:1977)
    at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1118)
    at org.apache.hadoop.hdfs.DistributedFileSystem$18.doCall(DistributedFileSystem.java:1114)
    at org.apache.hadoop.fs.FileSystemLinkResolver.resolve(FileSystemLinkResolver.java:81)
    at org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:1114)
    at org.apache.hadoop.yarn.util.FSDownload.copy(FSDownload.java:251)
    at org.apache.hadoop.yarn.util.FSDownload.access$000(FSDownload.java:61)
    at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:359)
    at org.apache.hadoop.yarn.util.FSDownload$2.run(FSDownload.java:357)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
    at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:356)
    at org.apache.hadoop.yarn.util.FSDownload.call(FSDownload.java:60)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused
    at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
    at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717)
    at org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:530)
    at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:494)
    at org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:608)
    at org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:706)
    at org.apache.hadoop.ipc.Client$Connection.access$2800(Client.java:369)
    at org.apache.hadoop.ipc.Client.getConnection(Client.java:1522)
    at org.apache.hadoop.ipc.Client.call(Client.java:1439)
    ... 31 more

As the error show, it is not able to connect to localhost:8020, but when i chech the namenode web UI, it shows that the namenode is active. Please see the below screenshot:

I found many posts related to this, but none helped me out. I also checked out the hosts file, which contains the following line:

127.0.0.1 localhost

172.20.12.168 localhost

Can anybody help me out sorting out this problem?

Body:
The following procedure helped me out in solving the issue:

Stop all the services.

Delete namenode and datanode directories as specified in hdfs-site.xml.

Create new namenode and datanode directories and modify hdfs-site.xml accordingly.

in core-site.xml, make the following changes or add the following properties:

<property>
  <name>fs.defaultFS</name>
  <value>hdfs://172.20.12.168/</value>
</property>
<property>
  <name>fs.default.name</name>
  <value>hdfs://172.20.12.168:8020</value>
</property>

Make the following changes in  hadoop-2.6.4/etc/hadoop/hadoop-env.sh file:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home

Restart dfs, yarn and mr as follows:

 start-dfs.sh
 start-yarn.sh
 mr-jobhistory-daemon.sh start historyserver


问:
what is the difference between BFC and stacking context?
these makes me so confuse.

what is the difference between  Block_Formatting_Context and stacking_context ?

thank you !

答:
A stacking context consists of seven different layers (from bottom to top):

the background and borders of the element that establishes the stacking context

the stacking contexts of descendants with negative stack levels

block-level descendants in the normal flow

floated descendants and their contents

inline-level descendants in the normal flow

positioned descendants whose z-index is auto or 0

the stacking contexts of descendants with positive stack levels

A new block formatting context can be created by adding any one of the necessary CSS conditions like overflow: scroll, overflow: hidden, display: flex, float: left, or display: table to the container. Though any of the above mentioned conditions can create a block formatting context, there will also be some other effects like:

display: table may create problems in responsiveness

overflow: scroll may show unwanted scrollbars

float: left will push the element to the left, with other elements wrapping around it

overflow: hidden will clip elements that overflow


问:
String was not recognized as a valid DateTime error when compare two datetime variable
```<code>string date1="06/06/2017";
string date2="06/05/2017";
</code>```

The dates are in format mm/dd/yyyy.I need to compare two dates

```<code>string test = DateTime.ParseExact(date1, "DD/M/yyyy", CultureInfo.InvariantCulture);
</code>```

I am unable to find out why I am getting error like String was not recognized as a valid DateTime.

答:
Use ToString() method like this
        DateTime.ParseExact(date1,"MM/dd/yyyy",CultureInfo.InvariantCulture).ToString();

this should solve your problem. problem is you cannot implicitly convert DateTime to string.

Body:
string date1="06/06/2017";
string date2="06/05/2017";

The dates are in format mm/dd/yyyy.I need to compare two dates

string test = DateTime.ParseExact(date1, "DD/M/yyyy", CultureInfo.InvariantCulture);

I am unable to find out why I am getting error like String was not recognized as a valid DateTime.


问:
Why is System.out.println so slow?
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

```<code>package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}
</code>```

答:
If you're printing to the console window, not to a file, that will be the killer.

Every character has to be painted, and on every line the whole window has to be scrolled.
If the window is partly overlaid with other windows, it also has to do clipping.

That's going to take far more cycles than what your program is doing.

Usually that's not a bad price to pay, since console output is supposed to be for your reading pleasure :)

Title: Why is System.out.println so slow?

Body:
Is this something common to all programming languages? Doing multiple print followed by a println seems faster  but moving everything to a string and just printing that seems fastest. Why?

EDIT: For example, Java can find all the prime numbers up to 1 million in less than a second - but printing then all out each on their own println can take minutes! Up to a 10 billion can hours to print!

EX:

package sieveoferatosthenes;
public class Main {
    public static void main(String[] args) {
        int upTo = 10000000;
        boolean primes[] = new boolean[upTo];
        for( int b = 0; b < upTo; b++ ){
            primes[b] = true;
        }
        primes[0] = false;
        primes[1] = false;

        int testing = 1;

        while( testing <= Math.sqrt(upTo)){
            testing ++;
            int testingWith = testing;
            if( primes[testing] ){
                while( testingWith < upTo ){
                    testingWith = testingWith + testing;
                    if ( testingWith >= upTo){
                    }
                    else{
                        primes[testingWith] = false;
                    }

                }
            }
        }
        for( int b = 2; b < upTo; b++){
            if( primes[b] ){
                System.out.println( b );
            }
        }
    }
}


问:
Android BLE Device Button press Alert in android
I am working with BLE device.I perform the code using android GATT and it scan device and also I send immediate alert in BLE device from mobile using writeCharacteristic and BLE device is beep.But now I want to Alert in android Mobile when I press BLE device button. That exactly I don't know how to do.

Thank You.

答:
For this you have to listen for characteristics change. When you will press the BLE button, a characteristics must be change inside its hardware (set any flag value depends on hardware's firmware coding). When characteristics changed, characteristics method will called. You can perform required functionality there.

```<code> @Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic
                                                             characteristic)
    {

     Here we received ble button pressed event callback. Do stuff here.

 }
</code>```

For receiving characteristics change callback first you have to enable the notification like this.

```<code>          BluetoothGattCharacteristic characteristic = gatt.getService(mServiceUuuid).getCharacteristic(mCharOneUuuid);
            gatt.setCharacteristicNotification(characteristic, true);
            List<BluetoothGattDescriptor> list = characteristic.getDescriptors();
            for (int i = 0; i < list.size(); i++) {
                BluetoothGattDescriptor desc = list.get(i);
                desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                gatt.writeDescriptor(desc);
            }
</code>```

Body:
For this you have to listen for characteristics change. When you will press the BLE button, a characteristics must be change inside its hardware (set any flag value depends on hardware's firmware coding). When characteristics changed, characteristics method will called. You can perform required functionality there.

 @Override
public void onCharacteristicChanged(BluetoothGatt gatt,
                                        BluetoothGattCharacteristic
                                                             characteristic)
    {

     Here we received ble button pressed event callback. Do stuff here.

 }

For receiving characteristics change callback first you have to enable the notification like this.

          BluetoothGattCharacteristic characteristic = gatt.getService(mServiceUuuid).getCharacteristic(mCharOneUuuid);
            gatt.setCharacteristicNotification(characteristic, true);
            List<BluetoothGattDescriptor> list = characteristic.getDescriptors();
            for (int i = 0; i < list.size(); i++) {
                BluetoothGattDescriptor desc = list.get(i);
                desc.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                gatt.writeDescriptor(desc);
            }


问:
Converting a custom date string into SQL datetime2
I have to load a CSV file into a temp table in SQL server 2008. There is a column in the CSV file which contains a date string formatted like this 11/04/2017 at 08:24:52. How can I parse this string and insert it into a datetime2 column?

The following results in expected conversion error - Conversion failed when converting date and/or time from character string.

```<code>  create table #temp
  (
    date_col datetime2(2),
    some_id varchar(20)
  )

  insert into #temp(date_col , some_id )
  values ('11/04/2017 at 08:24:52', '2323434')
</code>```

答:
You can use stuff to remove the at and convert using style 103 (assuming dd/mm/yyyy) or 101 (assuming mm/dd/yyyy):

```<code>DECLARE @Date varchar(30) = '11/04/2017 at 08:24:52'

SELECT CONVERT(datetime2, STUFF(@Date, 12, 3, ''), 103)
</code>```

Result:

```<code>    11.04.2017 08:24:52
</code>```

Body:
I have to load a CSV file into a temp table in SQL server 2008. There is a column in the CSV file which contains a date string formatted like this 11/04/2017 at 08:24:52. How can I parse this string and insert it into a datetime2 column?

The following results in expected conversion error - Conversion failed when converting date and/or time from character string.

  create table #temp
  (
    date_col datetime2(2),
    some_id varchar(20)
  )

  insert into #temp(date_col , some_id )
  values ('11/04/2017 at 08:24:52', '2323434')

Body:
You can use stuff to remove the at and convert using style 103 (assuming dd/mm/yyyy) or 101 (assuming mm/dd/yyyy):

DECLARE @Date varchar(30) = '11/04/2017 at 08:24:52'

SELECT CONVERT(datetime2, STUFF(@Date, 12, 3, ''), 103)

Result:

    11.04.2017 08:24:52


问:
Function not defined error reactjs
I have one function in Action file and need to call it from componenent file with parameters but while calling it, its giving error for function not defined

Component Code :

```<code>    handleClick(e){

         addinput({input1:this.refs.inp1.value,input2:this.refs.inp2.value}) // This function I have defined in action file

      }
</code>```

Action file code :

```<code>export function addinput(myval1) {
 return {
   type: 'ADD_INPUT',
   payload: myval1
 };
}
</code>```

I am getting below error in console

```<code>Uncaught ReferenceError: addinput is not defined
</code>```

Whats I am doing wrong here !!

答:
What you need to do is import the function from action file in your component like

```<code>import {addinput} from './path/to/action'
</code>```

and I am assuming your usiong redux, you can bind the action to props with connect and bindActionCreators function

```<code>import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'

...

class MyComponentName extends React.Component{

  handleClick = (e) => {
        this.props.addinput({input1:this.refs.inp1.value,input2:this.refs.inp2.value})

      }
}

function mapDispatchToProps(dispatch){
     return bindActionCreators({addInput}, dispatch)
}
export default connect(null, mapDispatchToProps)(MyComponentName)
</code>```

Title: Function not defined error reactjs

Body:
I have one function in Action file and need to call it from componenent file with parameters but while calling it, its giving error for function not defined

Component Code :

    handleClick(e){

         addinput({input1:this.refs.inp1.value,input2:this.refs.inp2.value}) // This function I have defined in action file

      }

Action file code :

export function addinput(myval1) {
 return {
   type: 'ADD_INPUT',
   payload: myval1
 };
}

I am getting below error in console

Uncaught ReferenceError: addinput is not defined

Whats I am doing wrong here !!

Body:
What you need to do is import the function from action file in your component like

import {addinput} from './path/to/action'

and I am assuming your usiong redux, you can bind the action to props with connect and bindActionCreators function

import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'

...

class MyComponentName extends React.Component{

  handleClick = (e) => {
        this.props.addinput({input1:this.refs.inp1.value,input2:this.refs.inp2.value})

      }
}

function mapDispatchToProps(dispatch){
     return bindActionCreators({addInput}, dispatch)
}
export default connect(null, mapDispatchToProps)(MyComponentName)


问:
Runnig selenium Grid
I am trying to run a test using the selenium server which will enable cross browser testing, but I'm getting this error

I have downloaded the standalone server and ran it through comand prompt and got a grid console such as the image file attached and my guess is only webdriver part is enabled and remote control part is not if so PLease guid me on how to solve this [Grid console][1]

this is the error
FAILED: test
org.openqa.selenium.WebDriverException: The path to the driver executable must be set by the webdriver.chrome.driver system property; for more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://chromedriver.storage.googleapis.com/index.html
Command duration or timeout: 256 milliseconds
Build info: version: 'unknown', revision: 'unknown', time: 'unknown'
System info: host: 'AKHIL-PC', ip: '192.158.0.29', os.name: 'Windows 10', os.arch: 'x86', os.version: '10.0', java.version: '1.8.0_131'
Driver info: driver.version: RemoteWebDriver

答:
The error suggests that you are missing chrome driver. did you download the chrome driver form here?

Did you add the chrome driver to your path variable

In Windows, goto System -> Advanced System Settings -> Advanced (Tab) -> Environment Variables

Under System variables, scroll to the Variable named Path -> Edit… (button) -> Variable value ->
Scroll to the end of the field, add a semicolon and append the local path of chromedriver.exe to the
end of the value field. Click OK:

To verify, open the Command Line (Run cmd.exe) -> Type chromedriver ->Hit Enter -> ChromeDriver

Also, restart the selenium standalone hubs and nodes

Let me know if it works

EDIT:
And if you configure your node via a xml file like:

```<code>{
  "capabilities":
  [
    {
      "browserName": "chrome",
      "platform": "WINDOWS",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "webdriver.chrome.driver": "C:/Selenium/drivers/chromedriver.exe",
      "binary":"C:/Program Files/Google/Chrome/Application/chrome.exe"
    }
  "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
  "maxSession": 5,
  "port": 5555,
  "register": true,
  "registerCycle": 5000,
  "hub": "<address to hub>",
  "nodeStatusCheckTimeout": 5000,
  "nodePolling": 5000,
  "role": "node",
  "unregisterIfStillDownAfter": 60000,
  "downPollingLimit": 2,
  "debug": false,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {}
}
</code>```

Change the webdriver.chrome.driver and binary to your own path.
and the  to your hub url
And start your node via:

```<code>java -jar selenium-server-standalone-<version>.jar -role node -nodeConfig nodeConfig.json
</code>```

Title: Runnig selenium Grid

Body:
The error suggests that you are missing chrome driver. did you download the chrome driver form here?

Did you add the chrome driver to your path variable

In Windows, goto System -> Advanced System Settings -> Advanced (Tab) -> Environment Variables

Under System variables, scroll to the Variable named Path -> Edit… (button) -> Variable value ->
Scroll to the end of the field, add a semicolon and append the local path of chromedriver.exe to the
end of the value field. Click OK:

To verify, open the Command Line (Run cmd.exe) -> Type chromedriver ->Hit Enter -> ChromeDriver

Also, restart the selenium standalone hubs and nodes

Let me know if it works

EDIT:
And if you configure your node via a xml file like:

{
  "capabilities":
  [
    {
      "browserName": "chrome",
      "platform": "WINDOWS",
      "maxInstances": 5,
      "seleniumProtocol": "WebDriver",
      "webdriver.chrome.driver": "C:/Selenium/drivers/chromedriver.exe",
      "binary":"C:/Program Files/Google/Chrome/Application/chrome.exe"
    }
  "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
  "maxSession": 5,
  "port": 5555,
  "register": true,
  "registerCycle": 5000,
  "hub": "<address to hub>",
  "nodeStatusCheckTimeout": 5000,
  "nodePolling": 5000,
  "role": "node",
  "unregisterIfStillDownAfter": 60000,
  "downPollingLimit": 2,
  "debug": false,
  "servlets" : [],
  "withoutServlets": [],
  "custom": {}
}

Change the webdriver.chrome.driver and binary to your own path.
and the  to your hub url
And start your node via:

java -jar selenium-server-standalone-<version>.jar -role node -nodeConfig nodeConfig.json


问:
IllegalArgumentException when setting public member
I've been playing around with reflection in Java... and I'm a little bit baffled.

I was hoping that the program below would allow me to change the value of a public member variable within a class. However, I receive an IllegalArgumentException. Any ideas?

```<code>public class ColinTest {

    public String msg = "fail";

    public ColinTest() { }

    public static void main(String args[]) throws Exception {
        ColinTest test = new ColinTest();
        Class c = test.getClass();
        Field[] decfields = c.getDeclaredFields();
        decfields[0].set("msg", "success");

        System.out.println(ColinTest.msg)
    }
}
</code>```

I receive this message -

```<code>Exception in thread "main" java.lang.IllegalArgumentException
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:37)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:57)
    at java.lang.reflect.Field.set(Field.java:656)
    at ColinTest.main(ColinTest.java:44)
</code>```

Thanks.

答:
I stumbled accros this page, because weirdly, I can not sets public string field in my class. The code will add new row in ArrayList in each for loop. The problem is, I put instantiation code of new object (using reflection that is) only once, outside the inner for.

```<code>private ArrayList processDataSetResultSetAsArrayList(ResultSet resultSet, String fqnModel) {
    ArrayList result = new ArrayList();

    try {
        ResultSetMetaData metaData;
        int nColoumn;
        String columnName;
        String fieldValue;
        Field field;
        Object modelInstance;

        metaData = resultSet.getMetaData();
        nColoumn = metaData.getColumnCount();
        resultSet.beforeFirst();
        Class modelClass = Class.forName(fqnModel);
        while (resultSet.next()) {
            modelInstance = modelClass.newInstance();
            for (int i = 1; i <= nColoumn; i++) {
                columnName = metaData.getColumnName(i);
                field = modelInstance.getClass().getDeclaredField(columnName);
                fieldValue = resultSet.getString(i);
                field.set(modelInstance, fieldValue);
            }
            result.add(modelInstance);
        }
    } catch (Exception ex) {
        Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}
</code>```

Inspect that now I move the Class.forName(fqnModel) outside the while loop. Because surely we only need to create Class object only once. But then, before each for loop, I create a model object that eventually will be added in a ArrayList.

To be clear, this is my BiroModel class look like:

```<code>public class BiroModel extends Model {
public String idbiro = "";
public String biro = "";

public BiroModel() {
}

public BiroModel(String table, String pkField) {
    super(table, pkField);
    fqn = BiroModel.class.getName();

}

public String getBiro() {
    return biro;
}

public void setBiro(String biro) {
    this.biro = biro;
}

public String getIdbiro() {
    return idbiro;
}

public void setIdbiro(String idbiro) {
    this.idbiro = idbiro;
}
</code>```

}

I create a convention here, that all field object should be declared public. But, because I need EL syntax, I still need to create getter/setter for this public field.

Body:
I've been playing around with reflection in Java... and I'm a little bit baffled.

I was hoping that the program below would allow me to change the value of a public member variable within a class. However, I receive an IllegalArgumentException. Any ideas?

public class ColinTest {

    public String msg = "fail";

    public ColinTest() { }

    public static void main(String args[]) throws Exception {
        ColinTest test = new ColinTest();
        Class c = test.getClass();
        Field[] decfields = c.getDeclaredFields();
        decfields[0].set("msg", "success");

        System.out.println(ColinTest.msg)
    }
}

I receive this message -

Exception in thread "main" java.lang.IllegalArgumentException
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:37)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:57)
    at java.lang.reflect.Field.set(Field.java:656)
    at ColinTest.main(ColinTest.java:44)

Thanks.

Body:
I stumbled accros this page, because weirdly, I can not sets public string field in my class. The code will add new row in ArrayList in each for loop. The problem is, I put instantiation code of new object (using reflection that is) only once, outside the inner for.

private ArrayList processDataSetResultSetAsArrayList(ResultSet resultSet, String fqnModel) {
    ArrayList result = new ArrayList();

    try {
        ResultSetMetaData metaData;
        int nColoumn;
        String columnName;
        String fieldValue;
        Field field;
        Object modelInstance;

        metaData = resultSet.getMetaData();
        nColoumn = metaData.getColumnCount();
        resultSet.beforeFirst();
        Class modelClass = Class.forName(fqnModel);
        while (resultSet.next()) {
            modelInstance = modelClass.newInstance();
            for (int i = 1; i <= nColoumn; i++) {
                columnName = metaData.getColumnName(i);
                field = modelInstance.getClass().getDeclaredField(columnName);
                fieldValue = resultSet.getString(i);
                field.set(modelInstance, fieldValue);
            }
            result.add(modelInstance);
        }
    } catch (Exception ex) {
        Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

Inspect that now I move the Class.forName(fqnModel) outside the while loop. Because surely we only need to create Class object only once. But then, before each for loop, I create a model object that eventually will be added in a ArrayList.

To be clear, this is my BiroModel class look like:

public class BiroModel extends Model {
public String idbiro = "";
public String biro = "";

public BiroModel() {
}

public BiroModel(String table, String pkField) {
    super(table, pkField);
    fqn = BiroModel.class.getName();

}

public String getBiro() {
    return biro;
}

public void setBiro(String biro) {
    this.biro = biro;
}

public String getIdbiro() {
    return idbiro;
}

public void setIdbiro(String idbiro) {
    this.idbiro = idbiro;
}

}

I create a convention here, that all field object should be declared public. But, because I need EL syntax, I still need to create getter/setter for this public field.


答:
You just need to remove the at along with one of the spaces and then tell SQL Server which format you have your days and months in:

```<code>select convert(datetime2, replace('11/04/2017 at 08:24:52',' at',''),103) -- 2017-04-11 08:24:52.0000000
      ,convert(datetime2, replace('11/04/2017 at 08:24:52',' at',''),101) -- 2017-11-04 08:24:52.0000000
</code>```

Title: Converting a custom date string into SQL datetime2

Body:
You just need to remove the at along with one of the spaces and then tell SQL Server which format you have your days and months in:

select convert(datetime2, replace('11/04/2017 at 08:24:52',' at',''),103) -- 2017-04-11 08:24:52.0000000
      ,convert(datetime2, replace('11/04/2017 at 08:24:52',' at',''),101) -- 2017-11-04 08:24:52.0000000


问:
DD and DU anomalys in function
I recently started using PMD to keep my code clean and it's been going well, but I've run into a few problems in the following function.

```<code>private final void readFile() throws Exception{
    code.clear();
    imports.clear();

    //DD anomaly
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;

    try{
        fileReader = new FileReader(file);
        bufferedReader = new BufferedReader(fileReader);

        String line;
        //DU anomaly
        boolean code_started = false;
        //DU anomaly
        while((line = bufferedReader.readLine()) != null){
            if(code_started)    code.add(line);
            else{
                if(lineIsImport(line))
                    imports.add(line);
                else if(lineIsClassDeclaretion(line)){
                    code_started = true;
                    code.add(line);
                }
            }
        }
    }
    catch(FileNotFoundException fn_ex){
        throw new Exception("File not found!");
    }
    catch(IOException io_ex){
        throw new Exception("Failed to read file: " + file.getName() + "!");
    }
    finally{
        try{
            if(bufferedReader != null)
                bufferedReader.close();
            if(fileReader != null)
                fileReader.close();
        }
        catch(IOException io_ex){
            throw new Exception("Failed to close reader");
        }
    }
}
</code>```

The first DD anomaly:

```<code>FileReader fileReader = null;
BufferedReader bufferedReader = null;
</code>```

If I don't set both to null the anomaly disappears, but I get an error in the finally block. I have no idea what the correct way of writing this should be.

Next is the DU anomaly:

```<code>boolean code_started = false;
</code>```

If I don't set the variable the anomaly disappears, but again an error a few lines down.

The last is a DU anomaly:

```<code>while((line = bufferedReader.readLine()) != null)
</code>```

This anomaly is probably the same as the one above, but again I have no idea how to fix it.

I would be grateful if somebody could explain or show how to write this function in a manner that won't cause PMD to show the anomaly.

答:
If you are using Java 7 or higher you can  try-with-resources. The try-with-resources statement ensures that each resource is closed at the end of the statement. Below is the example how you can use it.

Go Through: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for more info.

```<code>        File file = null;
        //Automatically closes resources try-with-resources block
        try( FileReader fileReader = new FileReader(file);BufferedReader bufferedReader = new BufferedReader(fileReader);){
            String line;
            boolean code_started = false;
            while((line = bufferedReader.readLine()) != null){
               //Code Goes Here
            }
        }catch(FileNotFoundException fn_ex){
            throw new Exception("File not found!");
        }
        catch(IOException io_ex){
            throw new Exception("Failed to read file: " + file.getName() + "!");
        }
</code>```

Title: DD and DU anomalys in function

Body:
I recently started using PMD to keep my code clean and it's been going well, but I've run into a few problems in the following function.

private final void readFile() throws Exception{
    code.clear();
    imports.clear();

    //DD anomaly
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;

    try{
        fileReader = new FileReader(file);
        bufferedReader = new BufferedReader(fileReader);

        String line;
        //DU anomaly
        boolean code_started = false;
        //DU anomaly
        while((line = bufferedReader.readLine()) != null){
            if(code_started)    code.add(line);
            else{
                if(lineIsImport(line))
                    imports.add(line);
                else if(lineIsClassDeclaretion(line)){
                    code_started = true;
                    code.add(line);
                }
            }
        }
    }
    catch(FileNotFoundException fn_ex){
        throw new Exception("File not found!");
    }
    catch(IOException io_ex){
        throw new Exception("Failed to read file: " + file.getName() + "!");
    }
    finally{
        try{
            if(bufferedReader != null)
                bufferedReader.close();
            if(fileReader != null)
                fileReader.close();
        }
        catch(IOException io_ex){
            throw new Exception("Failed to close reader");
        }
    }
}

The first DD anomaly:

FileReader fileReader = null;
BufferedReader bufferedReader = null;

If I don't set both to null the anomaly disappears, but I get an error in the finally block. I have no idea what the correct way of writing this should be.

Next is the DU anomaly:

boolean code_started = false;

If I don't set the variable the anomaly disappears, but again an error a few lines down.

The last is a DU anomaly:

while((line = bufferedReader.readLine()) != null)

This anomaly is probably the same as the one above, but again I have no idea how to fix it.

I would be grateful if somebody could explain or show how to write this function in a manner that won't cause PMD to show the anomaly.

Body:
If you are using Java 7 or higher you can  try-with-resources. The try-with-resources statement ensures that each resource is closed at the end of the statement. Below is the example how you can use it.

Go Through: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html for more info.

        File file = null;
        //Automatically closes resources try-with-resources block
        try( FileReader fileReader = new FileReader(file);BufferedReader bufferedReader = new BufferedReader(fileReader);){
            String line;
            boolean code_started = false;
            while((line = bufferedReader.readLine()) != null){
               //Code Goes Here
            }
        }catch(FileNotFoundException fn_ex){
            throw new Exception("File not found!");
        }
        catch(IOException io_ex){
            throw new Exception("Failed to read file: " + file.getName() + "!");
        }


问:
Kendo grid date filter localization
I try since one hour or more to change the localization of the date column filter type language. And I can't.

Here what I have :

On my _Layout : kendo.culture("fr-FR");

And when I load a page (anywhere on the app) :

But in the filter combo :

What is happening and what am I missing ?

Edit :

I forgot to say that the date filters are the only ones with this problem, string and number filters are correct.

答:
Found it !

I don't understand what exactly is the problem here...
I load the good culture file, number and string filters are ok, but not the date.

But in the kendo settings I have the good so...

```<code>$(document).ready(function () {
    $(".k-grid").each(function () {
        var grid = $(this).data("kendoGrid");
        if (grid) {
            grid.bind("filterMenuInit", onFilterMenuInit);
        }
    });
});

function onFilterMenuInit(e) {
    if (this.dataSource.options.schema.model.fields[e.field].type === 'date') {
        var filters = new Array();
        var raw = kendo.ui.FilterMenu.prototype.options.operators.date;
        for (var property in raw) {
            if (raw.hasOwnProperty(property)) {
                filters.push({ value: property, text: raw[property] });
            }
        }
        e.container.find("select:eq(0)").data("kendoDropDownList").dataSource.data(filters);
    }
}
</code>```

Title: Kendo grid date filter localization

Body:
Found it !

I don't understand what exactly is the problem here...
I load the good culture file, number and string filters are ok, but not the date.

But in the kendo settings I have the good so...

$(document).ready(function () {
    $(".k-grid").each(function () {
        var grid = $(this).data("kendoGrid");
        if (grid) {
            grid.bind("filterMenuInit", onFilterMenuInit);
        }
    });
});

function onFilterMenuInit(e) {
    if (this.dataSource.options.schema.model.fields[e.field].type === 'date') {
        var filters = new Array();
        var raw = kendo.ui.FilterMenu.prototype.options.operators.date;
        for (var property in raw) {
            if (raw.hasOwnProperty(property)) {
                filters.push({ value: property, text: raw[property] });
            }
        }
        e.container.find("select:eq(0)").data("kendoDropDownList").dataSource.data(filters);
    }
}