问:
Java. Array, save previous values
Cant figure out how to do this thing. I need to store and count number of "jumps" and direction of "jump" in array.
Console has to display something like this:

: Jump 1, direction Left

: Jump 2, direction Right

In my code below, when I print array elements,  int jump always equals to 0;

I tried many variations, sometimes I got (for example):

```<code>jump();

jump();

jump();

jump();
</code>```

And it prints: {0,0,0,4} , instead of {1,2,3,4};

```<code>public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;

public void jump() {
    jump++;
    if (jump > 50) {
        System.out.println("need a rest");
        return;
    } else {

        for (int i = 0; i < jumpArray.length; i++) {
            jumpArray[i] = new Jump();
        }
    }
    jumpArray[jump].storeJump = jump;
    jumpArray[jump].storeDirection = direction;

}

public static void main(String[] args) {
    Jump jumper = new Jump();
    jumper.jump();
    jumper.jump();

    for (int i = 0; i < jumper.jump; i++) {
        System.out.println(jumper.jumpArray[i].jump);

    }

}

}
</code>```

答:
I think the code below will solve your problem, but I think You should improve your code.</p>

```<code>int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;

public void jumping() {
    jump++;
    if (jump > 50) {
        System.out.println("need a rest");
        return;
    } else {
        jumpArray[jump] = new Jump();
    }
    jumpArray[jump].storeJump = jump;
    jumpArray[jump].storeDirection = direction;

}

public static void main(String[] args) {
    Jump jumper = new Jump();
    jumper.jumping();
    jumper.jumping();

    Set<Jump> mySet = new HashSet<Jump>(Arrays.asList(jumper.jumpArray));

    for (int i = 1; i < mySet.size(); i++) {
        System.out.println(jumper.jumpArray[i].storeJump);
    }
}
</code>```

Title: Java. Array, save previous values

Body:
Cant figure out how to do this thing. I need to store and count number of "jumps" and direction of "jump" in array.
Console has to display something like this:

: Jump 1, direction Left

: Jump 2, direction Right

In my code below, when I print array elements,  int jump always equals to 0;

I tried many variations, sometimes I got (for example):

jump();

jump();

jump();

jump();

And it prints: {0,0,0,4} , instead of {1,2,3,4};

public class Jump {
int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;

public void jump() {
    jump++;
    if (jump > 50) {
        System.out.println("need a rest");
        return;
    } else {

        for (int i = 0; i < jumpArray.length; i++) {
            jumpArray[i] = new Jump();
        }
    }
    jumpArray[jump].storeJump = jump;
    jumpArray[jump].storeDirection = direction;

}

public static void main(String[] args) {
    Jump jumper = new Jump();
    jumper.jump();
    jumper.jump();

    for (int i = 0; i < jumper.jump; i++) {
        System.out.println(jumper.jumpArray[i].jump);

    }

}

}

Body:
I think the code below will solve your problem, but I think You should improve your code.

int jump;
String direction;
Jump[] jumpArray = new Jump[100];
int storeJump;
String storeDirection;

public void jumping() {
    jump++;
    if (jump > 50) {
        System.out.println("need a rest");
        return;
    } else {
        jumpArray[jump] = new Jump();
    }
    jumpArray[jump].storeJump = jump;
    jumpArray[jump].storeDirection = direction;

}

public static void main(String[] args) {
    Jump jumper = new Jump();
    jumper.jumping();
    jumper.jumping();

    Set<Jump> mySet = new HashSet<Jump>(Arrays.asList(jumper.jumpArray));

    for (int i = 1; i < mySet.size(); i++) {
        System.out.println(jumper.jumpArray[i].storeJump);
    }
}


来源: stackexchange

问:
jQuery to loop through elements with the same class
I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?

答:
you can do it this way</p>

```<code>$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
you can do it this way

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});

ContentLicense: CC BY-SA 2.5


问:
tidyverse spread with duplicate keys and fill NAs based on unique keys
Consider the minimal example:

```<code>library(tidyverse)
ex <-tribble(
  ~id, ~property, ~value,
  1,    "A",      9,
  1,    "A",      8,
  1,    "B",      7,
  2,    "A",      6,
  2,    "B",      5
)
</code>```

My goal is to spread the property into columns to get this table:

```<code>tribble(
  ~id, ~A, ~B,
  1,  9,  7,
  1,  8,  7,
  2,  6,  5
)
</code>```

Grouping by id and property and adding a key gets close but leaves NA:

```<code>## almost but not quite
ex %>%
  group_by(id, property) %>%
  mutate(key = row_number()) %>%
  spread(property, value) %>%
  select(-key) -> X
X
</code>```

Gives:

```<code>     id     A     B
1     1     9     7
2     1     8    NA
3     2     6     5
</code>```

I can solve this in the minimal example by splitting out the above by each property, dropping NAs, and joining back by id:

```<code>inner_join(
  na.omit(select(X, id, A)),
  na.omit(select(X, id, B))
)
</code>```

but clearly that does not generalize to arbitrary set of properties.  What is a better tidyverse strategy to do this?

NOTE: Several previous questions speak to the first half of this, e.g. constructing the key column so that spread does not fail, but couldn't see something addressing the NAs.

答:
You can use fill from tidyr:

```<code>library(dplyr)
library(tidyr)

ex %>%
  group_by(id, property) %>%
  mutate(key = row_number()) %>%
  spread(property, value) %>%
  select(-key) %>%
  group_by(id) %>%
  fill(-id)
</code>```

Result:

```<code># A tibble: 3 x 3
# Groups:   id [2]
     id     A     B
  <dbl> <dbl> <dbl>
1     1     9     7
2     1     8     7
3     2     6     5
</code>```

Body:
Consider the minimal example:

library(tidyverse)
ex <-tribble(
  ~id, ~property, ~value,
  1,    "A",      9,
  1,    "A",      8,
  1,    "B",      7,
  2,    "A",      6,
  2,    "B",      5
)

My goal is to spread the property into columns to get this table:

tribble(
  ~id, ~A, ~B,
  1,  9,  7,
  1,  8,  7,
  2,  6,  5
)

Grouping by id and property and adding a key gets close but leaves NA:

## almost but not quite
ex %>%
  group_by(id, property) %>%
  mutate(key = row_number()) %>%
  spread(property, value) %>%
  select(-key) -> X
X

Gives:

     id     A     B
1     1     9     7
2     1     8    NA
3     2     6     5

I can solve this in the minimal example by splitting out the above by each property, dropping NAs, and joining back by id:

inner_join(
  na.omit(select(X, id, A)),
  na.omit(select(X, id, B))
)

but clearly that does not generalize to arbitrary set of properties.  What is a better tidyverse strategy to do this?

NOTE: Several previous questions speak to the first half of this, e.g. constructing the key column so that spread does not fail, but couldn't see something addressing the NAs.

Body:
You can use fill from tidyr:

library(dplyr)
library(tidyr)

ex %>%
  group_by(id, property) %>%
  mutate(key = row_number()) %>%
  spread(property, value) %>%
  select(-key) %>%
  group_by(id) %>%
  fill(-id)

Result:

# A tibble: 3 x 3
# Groups:   id [2]
     id     A     B
  <dbl> <dbl> <dbl>
1     1     9     7
2     1     8     7
3     2     6     5


问:
NIFI for heterogeneous clusters
I am new to NIFI and trying to understand its architecture.
From what I understood, the primary node in the cluster is selected internally by the system and user has no control over it. Also, we can configure some processors to run only on Primary Node (Isolated Processors).

My doubt is that if my cluster is heterogeneous and I want to run the Isolated (CPU-intensive) processors on the powerful node, is it possible to configure that node as primary?

答:
Currently it the primary node is automatically chosen by the NiFi cluster and you cannot choose which node it is. If the primary node goes down, then a new node will be elected as primary.

Generally the concept of primary node is used to trigger source processors that you would only want to execute once. For example, when using ListSFTP you would likely want to run this on primary node only, otherwise all the nodes in your cluster are going to list the same files.

Title: NIFI for heterogeneous clusters


问:
Why can't the compiler prevent these runtime cast exceptions?
```<code>class Program
    {
        static void Main(string[] args)
        {
            DateTime newYears = new DateTime(2013, 1, 1);
            PromoteEmployee(newYears);
        }

        public static void PromoteEmployee(object o)
        {
            // At this point, the compiler doesn't know exactly what type of object o refers to. So the compiler allows the code to compile...

            Employee e = (Employee)o; // this results in invalid cast exception at runtime
        }
    }

    class Employee
    {

    }
</code>```

But I think the compiler does know or it can easily know by looking at all places where this method is being referenced as to what type is being passed to PromoteEmployee (at least for such cases where no runtime conditions decide what type gets passed in)

So why should casting exceptions be left to occur at runtime when the compiler with some extra logic easily pick them up ?

答:
So what you basically want is for the compiler to check everywhere in your code where you call your function, then check the passed parameter type and then for every call go to every line inside the function where the parameter is used and check if the receiving type is able to be converted or casted to every type it is checked against.

Possible? Maybe, but only in a handful of cases that wouldn't make worth the extra compile time it would take.

Also, imagine this case:

```<code>    static void Main(string[] args)
    {
        DateTime newYears = new DateTime(2013, 1, 1);
        object ob = newYears;
        PromoteEmployee(ob);
    }
</code>```

This means the compiler would also had to go through every single value assignation the parameter suffers before being passed to the function.

So, bottom line: yeah, it is technically possible, but is not worth the effort, the time, and would encourage bad programming practices.

Body:
class Program
    {
        static void Main(string[] args)
        {
            DateTime newYears = new DateTime(2013, 1, 1);
            PromoteEmployee(newYears);
        }

        public static void PromoteEmployee(object o)
        {
            // At this point, the compiler doesn't know exactly what type of object o refers to. So the compiler allows the code to compile...

            Employee e = (Employee)o; // this results in invalid cast exception at runtime
        }
    }

    class Employee
    {

    }

But I think the compiler does know or it can easily know by looking at all places where this method is being referenced as to what type is being passed to PromoteEmployee (at least for such cases where no runtime conditions decide what type gets passed in)

So why should casting exceptions be left to occur at runtime when the compiler with some extra logic easily pick them up ?

Body:
So what you basically want is for the compiler to check everywhere in your code where you call your function, then check the passed parameter type and then for every call go to every line inside the function where the parameter is used and check if the receiving type is able to be converted or casted to every type it is checked against.

Possible? Maybe, but only in a handful of cases that wouldn't make worth the extra compile time it would take.

Also, imagine this case:

    static void Main(string[] args)
    {
        DateTime newYears = new DateTime(2013, 1, 1);
        object ob = newYears;
        PromoteEmployee(ob);
    }

This means the compiler would also had to go through every single value assignation the parameter suffers before being passed to the function.

So, bottom line: yeah, it is technically possible, but is not worth the effort, the time, and would encourage bad programming practices.


问:
Jquery focus is not working with slick slider
I have a slick slider with caption for each image, I want to get currently focusing(using tab) caption to make some changes on it, but I can see the focus is working on the caption elements, but I can't capture it

HTML

```<code><div class="customer-logos">
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image1.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image2.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image3.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image4.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image5.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image6.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image7.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image8.png"><a>Test</a></div>
</div>
</code>```

JS:

```<code>$(document).ready(function(){
            $('.customer-logos').slick({
                slidesToShow: 4,
                slidesToScroll: 1,
                autoplay: true,
                autoplaySpeed: 10000,
                arrows: false,
                dots: false,
                    pauseOnHover: false,
                    responsive: [{
                    breakpoint: 768,
                    settings: {
                        slidesToShow: 3
                    }
                }, {
                    breakpoint: 520,
                    settings: {
                        slidesToShow: 2
                    }
                }]
            });
        });

    $("a").on('focus',function(e) {
    console.log($(this))
                    $(this).addClass('focused');
    });
    $("a").on('blur',function(e) {

                $(this).removeClass('focused');
    });
</code>```

Fiddle example

答:
The problem is because jquery url you used. I used https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js and working well.

$(document).ready(function(){
    $('.customer-logos').slick({
  slidesToShow: 4,
  slidesToScroll: 1,
  autoplay: true,
  autoplaySpeed: 3000,
  arrows: false,
  dots: false,
   pauseOnHover: false,
   responsive: [{
   breakpoint: 768,
   settings: {
    slidesToShow: 3
   }
  }, {
   breakpoint: 520,
   settings: {
    slidesToShow: 2
   }
  }]
    });
});
$("a").on('focus',function(e) {
   alert("a focus");
   $(this).addClass('focused');
});
$("a").on('blur',function(e) {
  $(this).removeClass('focused');
});

 ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Slider */
.slick-slide {
    margin: 0px 20px;
}

.slick-slide img {
    width: 100%;
}

.slick-slider
{
    position: relative;

    display: block;
    box-sizing: border-box;

    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;

    -webkit-touch-callout: none;
    -khtml-user-select: none;
    -ms-touch-action: pan-y;
        touch-action: pan-y;
    -webkit-tap-highlight-color: transparent;
}

.slick-list
{
    position: relative;

    display: block;
    overflow: hidden;

    margin: 0;
    padding: 0;
}
.slick-list:focus
{
    outline: none;
}
.slick-list.dragging
{
    cursor: pointer;
    cursor: hand;
}

.slick-slider .slick-track,
.slick-slider .slick-list
{
    -webkit-transform: translate3d(0, 0, 0);
       -moz-transform: translate3d(0, 0, 0);
        -ms-transform: translate3d(0, 0, 0);
         -o-transform: translate3d(0, 0, 0);
            transform: translate3d(0, 0, 0);
}

.slick-track
{
    position: relative;
    top: 0;
    left: 0;

    display: block;
}
.slick-track:before,
.slick-track:after
{
    display: table;

    content: '';
}
.slick-track:after
{
    clear: both;
}
.slick-loading .slick-track
{
    visibility: hidden;
}

.slick-slide
{
    display: none;
    float: left;

    height: 100%;
    min-height: 1px;
}
[dir='rtl'] .slick-slide
{
    float: right;
}
.slick-slide img
{
    display: block;
}
.slick-slide.slick-loading img
{
    display: none;
}
.slick-slide.dragging img
{
    pointer-events: none;
}
.slick-initialized .slick-slide
{
    display: block;
}
.slick-loading .slick-slide
{
    visibility: hidden;
}
.slick-vertical .slick-slide
{
    display: block;

    height: auto;

    border: 1px solid transparent;
}
.slick-arrow.slick-hidden {
    display: none;
}
*.focused {
 outline-width: 2px ;
 outline-color: #282828;
 outline-style: dotted;
}</code>```

  Test

  Test

  Test

  ```

Body:
I have a slick slider with caption for each image, I want to get currently focusing(using tab) caption to make some changes on it, but I can see the focus is working on the caption elements, but I can't capture it

HTML

  Test

  Test

  Test

  Test

  Test

  Test

  Test

Test

JS:

$(document).ready(function(){
            $('.customer-logos').slick({
                slidesToShow: 4,
                slidesToScroll: 1,
                autoplay: true,
                autoplaySpeed: 10000,
                arrows: false,
                dots: false,
                    pauseOnHover: false,
                    responsive: [{
                    breakpoint: 768,
                    settings: {
                        slidesToShow: 3
                    }
                }, {
                    breakpoint: 520,
                    settings: {
                        slidesToShow: 2
                    }
                }]
            });
        });

    $("a").on('focus',function(e) {
    console.log($(this))
                    $(this).addClass('focused');
    });
    $("a").on('blur',function(e) {

                $(this).removeClass('focused');
    });

Fiddle example

Body:
The problem is because jquery url you used. I used https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js and working well.

$(document).ready(function(){
    $('.customer-logos').slick({
  slidesToShow: 4,
  slidesToScroll: 1,
  autoplay: true,
  autoplaySpeed: 3000,
  arrows: false,
  dots: false,
   pauseOnHover: false,
   responsive: [{
   breakpoint: 768,
   settings: {
    slidesToShow: 3
   }
  }, {
   breakpoint: 520,
   settings: {
    slidesToShow: 2
   }
  }]
    });
});
$("a").on('focus',function(e) {
   alert("a focus");
   $(this).addClass('focused');
});
$("a").on('blur',function(e) {
  $(this).removeClass('focused');
});

/* Slider */
.slick-slide {
    margin: 0px 20px;
}

.slick-slide img {
    width: 100%;
}

.slick-slider
{
    position: relative;

    display: block;
    box-sizing: border-box;

    -webkit-user-select: none;
       -moz-user-select: none;
        -ms-user-select: none;
            user-select: none;

    -webkit-touch-callout: none;
    -khtml-user-select: none;
    -ms-touch-action: pan-y;
        touch-action: pan-y;
    -webkit-tap-highlight-color: transparent;
}

.slick-list
{
    position: relative;

    display: block;
    overflow: hidden;

    margin: 0;
    padding: 0;
}
.slick-list:focus
{
    outline: none;
}
.slick-list.dragging
{
    cursor: pointer;
    cursor: hand;
}

.slick-slider .slick-track,
.slick-slider .slick-list
{
    -webkit-transform: translate3d(0, 0, 0);
       -moz-transform: translate3d(0, 0, 0);
        -ms-transform: translate3d(0, 0, 0);
         -o-transform: translate3d(0, 0, 0);
            transform: translate3d(0, 0, 0);
}

.slick-track
{
    position: relative;
    top: 0;
    left: 0;

    display: block;
}
.slick-track:before,
.slick-track:after
{
    display: table;

    content: '';
}
.slick-track:after
{
    clear: both;
}
.slick-loading .slick-track
{
    visibility: hidden;
}

.slick-slide
{
    display: none;
    float: left;

    height: 100%;
    min-height: 1px;
}
[dir='rtl'] .slick-slide
{
    float: right;
}
.slick-slide img
{
    display: block;
}
.slick-slide.slick-loading img
{
    display: none;
}
.slick-slide.dragging img
{
    pointer-events: none;
}
.slick-initialized .slick-slide
{
    display: block;
}
.slick-loading .slick-slide
{
    visibility: hidden;
}
.slick-vertical .slick-slide
{
    display: block;

    height: auto;

    border: 1px solid transparent;
}
.slick-arrow.slick-hidden {
    display: none;
}
*.focused {
 outline-width: 2px ;
 outline-color: #282828;
 outline-style: dotted;
}

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.js"></script>
<div class="customer-logos">
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image1.png">
  <a>Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image2.png">
  <a >Test</a>
  </div>
  <div class="slide"><img src="https://www.solodev.com/assets/carousel/image3.png">
  <a >Test</a>
  </div>
</div>


问:
Where can I find org.jenkinsci.plugins.workflow.steps.FlowInterruptedException with gradle?
I have the following build.gradle

```<code>apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'java'
repositories {
    mavenCentral()
    maven {
        url 'https://repo.jenkins-ci.org/releases'
    }
    maven {
        url 'https://repo.jenkins-ci.org/public'
    }
}
sourceSets {
    main {
        groovy {
            srcDirs = ['src']
        }
    }
    test {
        groovy {
            srcDirs = ['test']
        }
    }
}
dependencies {
    compile group: 'org.jenkins-ci.main', name: 'jenkins-core', version: '2.76'
    compile group: 'org.jenkins-ci.plugins.workflow', name: 'workflow-step-api', version: '2.13'
    compile 'com.cloudbees:groovy-cps:1.14'
    compile 'org.connectbot.jbcrypt:jbcrypt:1.0.0'
    compileOnly 'javax.servlet:javax.servlet-api:3.1.0'
    compile 'org.codehaus.groovy:groovy-all:2.4.12'
    testCompile 'junit:junit:4.12'
}
</code>```

When I run "gradle build" I get the following error:

```<code>> Task :compileGroovy FAILED
startup failed:
/home/user/myproject/SomeClass.groovy: 26: unable to resolve class org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
@ line 26, column 11.
        } catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException flowInterruptedException) {
            ^
1 error
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileGroovy'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 1s
1 actionable task: 1 executed
</code>```

It's as if it does not see "org.jenkinsci.plugins.workflow.steps.FlowInterruptedException" but I added workflow-step-api and it should find it.

What am I doing wrong? How to fix?

Thank you

答:
Apparently I needed to add ext jar. Here is my build file</p>

```<code>apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'java'
repositories {
    mavenCentral()
    maven {
        url 'https://repo.jenkins-ci.org/releases'
    }
    maven {
        url 'https://repo.jenkins-ci.org/public'
    }

}
sourceSets {
    main {
        groovy {
            srcDirs = ['src']
        }
    }
    test {
        groovy {
            srcDirs = ['test']
        }
    }
}
dependencies {
    compile group: 'org.jenkins-ci.main', name: 'jenkins-core', version: '2.76'
    compile group: 'org.jenkins-ci.plugins.workflow', name: 'workflow-step-api', version: '2.13', ext: 'jar'
    compile 'com.cloudbees:groovy-cps:1.14'
    compile 'org.codehaus.groovy:groovy-all:2.4.8'
    compileOnly 'javax.servlet:javax.servlet-api:3.1.0'
    testCompile 'junit:junit:4.12'
}
</code>```

Body:
I have the following build.gradle

apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'java'
repositories {
    mavenCentral()
    maven {
        url 'https://repo.jenkins-ci.org/releases'
    }
    maven {
        url 'https://repo.jenkins-ci.org/public'
    }
}
sourceSets {
    main {
        groovy {
            srcDirs = ['src']
        }
    }
    test {
        groovy {
            srcDirs = ['test']
        }
    }
}
dependencies {
    compile group: 'org.jenkins-ci.main', name: 'jenkins-core', version: '2.76'
    compile group: 'org.jenkins-ci.plugins.workflow', name: 'workflow-step-api', version: '2.13'
    compile 'com.cloudbees:groovy-cps:1.14'
    compile 'org.connectbot.jbcrypt:jbcrypt:1.0.0'
    compileOnly 'javax.servlet:javax.servlet-api:3.1.0'
    compile 'org.codehaus.groovy:groovy-all:2.4.12'
    testCompile 'junit:junit:4.12'
}

When I run "gradle build" I get the following error:

> Task :compileGroovy FAILED
startup failed:
/home/user/myproject/SomeClass.groovy: 26: unable to resolve class org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
@ line 26, column 11.
        } catch (org.jenkinsci.plugins.workflow.steps.FlowInterruptedException flowInterruptedException) {
            ^
1 error
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileGroovy'.
> Compilation failed; see the compiler error output for details.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
* Get more help at https://help.gradle.org
BUILD FAILED in 1s
1 actionable task: 1 executed

It's as if it does not see "org.jenkinsci.plugins.workflow.steps.FlowInterruptedException" but I added workflow-step-api and it should find it.

What am I doing wrong? How to fix?

Thank you

Body:
Apparently I needed to add ext jar. Here is my build file

apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'java'
repositories {
    mavenCentral()
    maven {
        url 'https://repo.jenkins-ci.org/releases'
    }
    maven {
        url 'https://repo.jenkins-ci.org/public'
    }

}
sourceSets {
    main {
        groovy {
            srcDirs = ['src']
        }
    }
    test {
        groovy {
            srcDirs = ['test']
        }
    }
}
dependencies {
    compile group: 'org.jenkins-ci.main', name: 'jenkins-core', version: '2.76'
    compile group: 'org.jenkins-ci.plugins.workflow', name: 'workflow-step-api', version: '2.13', ext: 'jar'
    compile 'com.cloudbees:groovy-cps:1.14'
    compile 'org.codehaus.groovy:groovy-all:2.4.8'
    compileOnly 'javax.servlet:javax.servlet-api:3.1.0'
    testCompile 'junit:junit:4.12'
}


问:
git ssh fails to access host but succeed when direct IP is used (Windows 10)
I am using git/bash in Windows 10 and try to clone a repository.
When I use the command: git clone username@hostname, I get:
ssh: Could not resolve hostname stbcmgit: Name or service not known

However, when I use a direct IP address instead of the hostname (git clone username@x.x.x.x), the access is successful and the clone starts.

Notes:

"known_hosts" file is located at c:\Users\myname\.ssh
The file is taken from my Linux account where everything works fine there.

The .ssh folder contains also the id_rsa and id_rsa.pub keys (copied also from Linux).

When I use 'ls $HOME/.ssh', I see these files listed.

Using Windows 10.

Thanks.

答:
You should check /etc/hosts and add such a line if it doesn't exist:

```<code>x.x.x.x hostname
</code>```

If the host's IP doesn't change, you can simplify the whole command by creating $HOME/.ssh/config like this

```<code>Host YourHost
    HostName x.x.x.x
    User username
    IdentityFile ~/.ssh/id_rsa
    PubKeyAuthentication yes
</code>```

Now you can run these commands:

```<code>git clone YourHost:repo
ssh YourHost
</code>```

Body:
You should check /etc/hosts and add such a line if it doesn't exist:

x.x.x.x hostname

If the host's IP doesn't change, you can simplify the whole command by creating $HOME/.ssh/config like this

Host YourHost
    HostName x.x.x.x
    User username
    IdentityFile ~/.ssh/id_rsa
    PubKeyAuthentication yes

Now you can run these commands:

git clone YourHost:repo
ssh YourHost


问:
how to obtain predictive posteriors in pystan?
I'm trying to move from using stan in R (I've mainly used the brms package) to pystan, but having trouble locating any methods in pystan that will give me predictive posterior distributions for new data. In R, I've been using brms::posterior_linpred() to do this. Does anyone know if this is possible in pystan?

If not, can it be bolted on without too much problem?

答: As far as I know, they are not any Python libraries that do what the brms and rstanarm R packages do, i.e. come with precompiled Stan models that allow users to draw from the predictive distribution in the high-level language. There are things like prophet and survivalstan but those are for a pretty niche set of models.


问:
How to use UNION while inserting in a table using SELECT clause from many tables in SQL Server 2000
I am using SQL Server 2000. I have multiple criterias which i have to use to extract different sets of records from mumtiple table in another  table. I am using

```<code>INSERT INTO T1(A,B)
(SELECT E,R FROM T2)
UNION
(SELECT Z,X FROM T3)
</code>```

Query analyzer is throwing error that while using UNION, you should use ORDER BY clause with SELECT. Even after doing that i m not able to union two different queries which are returing same columns in their select clause.

What is the right way to insert using SELECTS with UNIONS and ORDER BY.

答:
The pseudo is too cryptic (reduced?)
It is very unlikely to get 2 columns per cross join of 2 tables in each of the union components

```<code>INSERT INTO T1(A,B)
(SELECT * FROM E,R)
UNION
(SELECT * FROM Z,X)
</code>```

Note: If you have ANY order by clause at all, it must be at the end of the union

```<code>INSERT T1(A,B)
SELECT P,Q FROM E,R
UNION
SELECT R,S FROM Z,X
</code>```

@updated based on error text "Server: Msg 104, Level 15, State 1, Line 1 ORDER BY items must appear in the select list if the statement contains a UNION operator"

This occurs when you have a union that attempts to perform ORDER BY on a column that does not appear in the result.  Consider a normal ORDER BY involving non-selected columns

```<code>select top 10 name from syscolumns order by xtype
</code>```

The rows are consistent and the query can be satisfied.  However, if you did

```<code>select top 10 name from syscolumns where xtype > 50
union all
select top 10 name from syscolumns where xtype < 50
order by xtype
</code>```

EVEN IF xtype exists in both parts of the UNION, but the time it gets presented to ORDER BY (which works at the END over the entire result set), the column is not there.  You would have to rewrite it (if you didn't want to show xtype) as

```<code>select name from (
    select top 10 name, xtype from syscolumns where xtype > 50
    union all
    select top 10 name, xtype from syscolumns where xtype < 50
) x
order by xtype
</code>```

Hope that helps

Body:
I am using SQL Server 2000. I have multiple criterias which i have to use to extract different sets of records from mumtiple table in another  table. I am using

INSERT INTO T1(A,B)
(SELECT E,R FROM T2)
UNION
(SELECT Z,X FROM T3)

Query analyzer is throwing error that while using UNION, you should use ORDER BY clause with SELECT. Even after doing that i m not able to union two different queries which are returing same columns in their select clause.

What is the right way to insert using SELECTS with UNIONS and ORDER BY.

Body:
The pseudo is too cryptic (reduced?)
It is very unlikely to get 2 columns per cross join of 2 tables in each of the union components

INSERT INTO T1(A,B)
(SELECT * FROM E,R)
UNION
(SELECT * FROM Z,X)

Note: If you have ANY order by clause at all, it must be at the end of the union

INSERT T1(A,B)
SELECT P,Q FROM E,R
UNION
SELECT R,S FROM Z,X

@updated based on error text "Server: Msg 104, Level 15, State 1, Line 1 ORDER BY items must appear in the select list if the statement contains a UNION operator"

This occurs when you have a union that attempts to perform ORDER BY on a column that does not appear in the result.  Consider a normal ORDER BY involving non-selected columns

select top 10 name from syscolumns order by xtype

The rows are consistent and the query can be satisfied.  However, if you did

select top 10 name from syscolumns where xtype > 50
union all
select top 10 name from syscolumns where xtype < 50
order by xtype

EVEN IF xtype exists in both parts of the UNION, but the time it gets presented to ORDER BY (which works at the END over the entire result set), the column is not there.  You would have to rewrite it (if you didn't want to show xtype) as

select name from (
    select top 10 name, xtype from syscolumns where xtype > 50
    union all
    select top 10 name, xtype from syscolumns where xtype < 50
) x
order by xtype

Hope that helps


问:
rails remove file for public folder
I am trying to edit files in folder public but I don't know why whenever I make changes it is not showing.

I have created a file called test.html inside public folder. And I am calling it using javascript for that my code is :

```<code>  $("#click2").click(function(){
   console.log("click2");

  $('#content').load( 'test.html' );

   });
</code>```

I am making changes to my test.html file but it is not showing even when I delete the file it still show the content of that.  I want to make changes and want to see what should I do .

答:
The public folder should be used for storing never-changing assets, such as favicons or robots.txt files, as the results will be cached by browsers.

If you're set on doing this, try clearing your browser cache between changes.

Title: rails remove file for public folder

Body:
I am trying to edit files in folder public but I don't know why whenever I make changes it is not showing.

I have created a file called test.html inside public folder. And I am calling it using javascript for that my code is :

  $("#click2").click(function(){
   console.log("click2");

  $('#content').load( 'test.html' );

   });

I am making changes to my test.html file but it is not showing even when I delete the file it still show the content of that.  I want to make changes and want to see what should I do .


问:
Could not load file or assembly 'Antlr3.Runtime (1)' or one of its dependencies
I'm getting this error while trying to run my MVC4 project, it was working fine until last time on my other machines, but when I'm trying to run it from another machine it's giving me this error:

Could not load file or assembly 'Antlr3.Runtime (1)' or one of its
  dependencies. The located assembly's manifest definition does not
  match the assembly reference. (Exception from HRESULT: 0x80131040)

After reading about this here I've tried to do:

Install-Package Antlr3.Runtime -Pre

but it didn't help, any ideas?

答:
Solution for me was to go Tools > NuGet Package Manager > Manage Packages for Solution

Then click Antlr3 and ensure it was installed in:

The Startup Project

Any libraries using reflection

Any libraries calling the libraries that use reflection

In my case that was 4 Projects deep that needed it. Once that was done this issue was finally resolved.


问:
How to handle 404s in an observable request Angular
Problem i'm trying to fix:
I'm getting a lot of 404 not found in the console and I want to handle these.

I have these 2 methods in my angular code:

```<code>getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email);
}

isEmailAddressAvailable(email: string) {
    var user: User;
    var response = this.getUserByEmailAddress(email);
    response.subscribe(
       usr => user == usr,
       error => user == undefined);
  if (user === undefined) {
  return true;
  }
  else {
  return false;
  }
}
</code>```

This works as expected, when you call the end point if no user is found a 404 not found it returned.

What I am trying to do

I want to add a .catch() to the .get() request in getUserByEmailAddress()to handle these 404s and mask them from appearing in the console, however when i try to add it, I don't understand what i need to return for the observable, I've tried:

```<code>.catch(err => { return Observable.of(undefined)})
</code>```

but i don't think this is quite right.

Thanks for the help!

答:
I think the best solution will be http interceptor. Then you can check response of request an if it is 404 return Observable.empty()

https://angular.io/guide/http#logging

Body:
Problem i'm trying to fix:
I'm getting a lot of 404 not found in the console and I want to handle these.

I have these 2 methods in my angular code:

getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email);
}

isEmailAddressAvailable(email: string) {
    var user: User;
    var response = this.getUserByEmailAddress(email);
    response.subscribe(
       usr => user == usr,
       error => user == undefined);
  if (user === undefined) {
  return true;
  }
  else {
  return false;
  }
}

This works as expected, when you call the end point if no user is found a 404 not found it returned.

What I am trying to do

I want to add a .catch() to the .get() request in getUserByEmailAddress()to handle these 404s and mask them from appearing in the console, however when i try to add it, I don't understand what i need to return for the observable, I've tried:

.catch(err => { return Observable.of(undefined)})

but i don't think this is quite right.

Thanks for the help!


问:
Python Selenium - How to setup firefox remote webdriver? (gecko error)
Below is the current code I have been trying to use to run tests on a Firefox node I have set up.

```<code>def setUp(self):
    self.wd = webdriver.Remote(
        command_executor='http://10.0.1.226:4444/wd/hub',
        desired_capabilities= DesiredCapabilities.FIREFOX
    )
</code>```

I keep getting the error:

WebDriverException: Message: The path to the driver executable must be set by the webdriver.gecko.driver system property.

How do you fix this? I have looked online in other threads and cannot find any python syntax to resolve this problem, please help.

EDIT: I have set up the environment variable to the geckodriver and restarted my machine, the script still gives the error:

WebDriverException: Message: The path to the driver executable must be set by the webdriver.gecko.driver system property

Is the syntax above correct? Do I need to set up the capabilities to factor in the firefox marionette thing?

答:
Do you have the geckodriver path in your PATH?

You can add the path to the driver on Mac by typing the following into a terminal window:

```<code>export PATH=$PATH:/path/to/geckodriver
</code>```

On Windows you can search for View advanced system settings and then click on the button that says Environment Variables. Click on PATH > EDIT > NEW and add the path to geckodriver.

Body:
Below is the current code I have been trying to use to run tests on a Firefox node I have set up.

def setUp(self):
    self.wd = webdriver.Remote(
        command_executor='http://10.0.1.226:4444/wd/hub',
        desired_capabilities= DesiredCapabilities.FIREFOX
    )

I keep getting the error:

WebDriverException: Message: The path to the driver executable must be set by the webdriver.gecko.driver system property.

How do you fix this? I have looked online in other threads and cannot find any python syntax to resolve this problem, please help.

EDIT: I have set up the environment variable to the geckodriver and restarted my machine, the script still gives the error:

WebDriverException: Message: The path to the driver executable must be set by the webdriver.gecko.driver system property

Is the syntax above correct? Do I need to set up the capabilities to factor in the firefox marionette thing?

Body:
Do you have the geckodriver path in your PATH?

You can add the path to the driver on Mac by typing the following into a terminal window:

export PATH=$PATH:/path/to/geckodriver

On Windows you can search for View advanced system settings and then click on the button that says Environment Variables. Click on PATH > EDIT > NEW and add the path to geckodriver.


答:
```<code>divs  = $('.testimonial')
for(ind in divs){
  div = divs[ind];
  //do whatever you want
}
</code>```

Title: jQuery to loop through elements with the same class

Body:
I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?


问:
what is the most pythonic way to split a 2d array to arrays of each row?
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

```<code>a;b = foo()
</code>```

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

答:
You could just use list comprehensions, e.g.

```<code>(a,b)=([i[0] for i in mylist],[i[1] for i in mylist])
</code>```

To generalise you could use a comprehension within a comprehension:

```<code>(a,b,c,d,e)=([row[i] for row in mylist] for i in range(5))
</code>```

Body:
I have a function foo that returns an array with the shape (1000, 2)
how can I split it to two arrays a(1000) and b(1000)
I'm looking for something like this:

a;b = foo()

I'm looking for an answer that can easily generalize to the case in which the shape is (1000, 5) or so.

Body:
You could just use list comprehensions, e.g.

(a,b)=([i[0] for i in mylist],[i[1] for i in mylist])

To generalise you could use a comprehension within a comprehension:

(a,b,c,d,e)=([row[i] for row in mylist] for i in range(5))


问:
Iteration vs. range created via Union
The following code adds each value over 10 it founds in the sheet to the "Over10" range:

```<code>Sub IterateOver10()

Dim Over10 As Range

For Each cell In ActiveSheet.UsedRange.Cells
    If cell > 10 Then
        If Over10 Is Nothing then
            Set Over10 = cell
        Else
            Set Over10= Union(cell,Over10)
        End If
    End If
Next cell
</code>```

I want to iterate through each item in "Over10" with a loop and check if it exists in another range. The problem is that the following iteration:

```<code>For each cell2 in Over10
    ' check if exists in another range
next cell2
</code>```

won't work for a range declared this way because it seems to use the range from cell2 to (cell2 + the count of Over10) instead. Any suggestions for a workaround. Should I use arrays instead?

Thanks,
Bartek

答:
There are quite a few ways to do this. One of them is with nested loops, where you iterate through both of the collections (or ranges or arrays, as you wish):

```<code>Sub IterateOver10()

    Dim myCell          As Range
    Dim Over10          As Range
    Dim myCollection    As New Collection
    Dim myCollection2   As New Collection

    Dim iterator        As Variant
    Dim iterator2       As Variant

    For Each myCell In ActiveSheet.UsedRange
        If myCell > 10 Then
            myCollection.Add (myCell)
        End If
    Next myCell

    myCollection2.Add 15
    myCollection2.Add 16

    For Each iterator2 In myCollection2
        For Each iterator In myCollection
            If iterator = iterator2 Then
                Debug.Print iterator
            End If
        Next iterator
    Next iterator2

End Sub
</code>```

Thus, if your input looks like this at the beginning:

in your collection named myCollection you would have 12, 13, 14 and 15. Then in the myCollection2 you will find that 15 is in both collections and it will be printed on the immediate window.

Title: Iteration vs. range created via Union

Body:
The following code adds each value over 10 it founds in the sheet to the "Over10" range:

Sub IterateOver10()

Dim Over10 As Range

For Each cell In ActiveSheet.UsedRange.Cells
    If cell > 10 Then
        If Over10 Is Nothing then
            Set Over10 = cell
        Else
            Set Over10= Union(cell,Over10)
        End If
    End If
Next cell

I want to iterate through each item in "Over10" with a loop and check if it exists in another range. The problem is that the following iteration:

For each cell2 in Over10
    ' check if exists in another range
next cell2

won't work for a range declared this way because it seems to use the range from cell2 to (cell2 + the count of Over10) instead. Any suggestions for a workaround. Should I use arrays instead?

Thanks,
Bartek

Body:
There are quite a few ways to do this. One of them is with nested loops, where you iterate through both of the collections (or ranges or arrays, as you wish):

Sub IterateOver10()

    Dim myCell          As Range
    Dim Over10          As Range
    Dim myCollection    As New Collection
    Dim myCollection2   As New Collection

    Dim iterator        As Variant
    Dim iterator2       As Variant

    For Each myCell In ActiveSheet.UsedRange
        If myCell > 10 Then
            myCollection.Add (myCell)
        End If
    Next myCell

    myCollection2.Add 15
    myCollection2.Add 16

    For Each iterator2 In myCollection2
        For Each iterator In myCollection
            If iterator = iterator2 Then
                Debug.Print iterator
            End If
        Next iterator
    Next iterator2

End Sub

Thus, if your input looks like this at the beginning:

in your collection named myCollection you would have 12, 13, 14 and 15. Then in the myCollection2 you will find that 15 is in both collections and it will be printed on the immediate window.


问:
How do I integrate Plotly realtime updating graphs with React JS without rerender of component
I would like to use both React JS and plotly in my web app. I want plotly to graph realtime data, but I want to avoid a complete rerender of the graph everytime a new point is added. Plotly graphs have an update function that makes it so the entire graph isn't destroyed/rerendered.

So I have a few questions.
1. Is it possible to use react components to represent a plotly graph and have it update realtime without a full rerender of the graph?
2. If the above is not possible, is there a work around?

Thanks

答:
You can use shouldComponentUpdate to prevent your component from re-rendering when the data you use to update the plot changes. I'm currently doing exactly this with a canvas based project so it should work with plotly as well.

Edit: My shouldComponentUpdate looks like this, basically I only need to re-render the canvas if the size it's given changes not when the data changes.

```<code>  shouldComponentUpdate(nextProps) {
    if (this.props.height !== nextProps.height ||
       this.props.width !== nextProps.width) {
      return true;
    }

    return false;
  }
</code>```

Body:
You can use shouldComponentUpdate to prevent your component from re-rendering when the data you use to update the plot changes. I'm currently doing exactly this with a canvas based project so it should work with plotly as well.

Edit: My shouldComponentUpdate looks like this, basically I only need to re-render the canvas if the size it's given changes not when the data changes.

  shouldComponentUpdate(nextProps) {
    if (this.props.height !== nextProps.height ||
       this.props.width !== nextProps.width) {
      return true;
    }

    return false;
  }


问:
Asp.net getting label value from codebehind. for google maps coordinate
i can not get value of label in code behind. i'd like to save the coordinates from google map. can you help me to see what i'm missing?

HTML

```<code> <span>Location:</span>
    <input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />
    <div id="dvMap" style="width: 100%; height:300px;">
       <asp:Label ID="Label1" runat="server"></asp:Label>

          <asp:Label ID="Label2" runat="server"></asp:Label>

        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</code>```

Javascript

```<code><script type="text/javascript">
    google.maps.event.addDomListener(window, 'load', function () {
        var places = new google.maps.places.Autocomplete(document.getElementById('txtPlaces'));
        google.maps.event.addListener(places, 'place_changed', function () {
            var place = places.getPlace();
            var address = place.formatted_address;
            var latitude = place.geometry.location.lat();
            var longitude = place.geometry.location.lng();
            var mesg = "Address: " + address;
            mesg += "\nLatitude: " + latitude;
            mesg += "\nLongitude: " + longitude;
            document.getElementById('Label1').textContent = latitude;
            document.getElementById('Label2').textContent = longitude;

            var lat = document.getElementById('Label1').textContent;
            var lon = document.getElementById('Label2').textContent;
            var mapOptions = {
                center: new google.maps.LatLng(lat, lon),
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var infoWindow = new google.maps.InfoWindow();
            var latlngbounds = new google.maps.LatLngBounds();
            var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
            google.maps.event.addListener(map, 'click', function (e) {
                // alert("Latitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
            });
            alert(mesg);

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

CodeBehind

string example = Label1.Text; // or innerhtml or innertext..

答:
Changes in Labels, as well as in non-input elements e.g. divs, spans etc, won't be posted because of HTTP Post nature.

What I would do in your place is adding a hidden and set the value you want to be posted there. Just something like this:

```<code><input runat="server" ID="Label1Value" class="form-control" type="hidden" />
</code>```

Body:
i can not get value of label in code behind. i'd like to save the coordinates from google map. can you help me to see what i'm missing?

HTML

 Location:
    <input type="text" id="txtPlaces" style="width: 250px" placeholder="Enter a location" />

       <asp:Label ID="Label1" runat="server"></asp:Label>

          <asp:Label ID="Label2" runat="server"></asp:Label>

        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

Javascript

CodeBehind

string example = Label1.Text; // or innerhtml or innertext..

Body:
Changes in Labels, as well as in non-input elements e.g. divs, spans etc, won't be posted because of HTTP Post nature.

What I would do in your place is adding a hidden and set the value you want to be posted there. Just something like this:

<input runat="server" ID="Label1Value" class="form-control" type="hidden" />


问:
How to display a form inside another form like Visual Studio
How does Visual Studio and other similar programs display a form in their IDE?

Is it possible to achieve the same or a similar effect using C# or VB.NET?

Please see the picture below to get what I mean.

答: I believe what you want is a multiple document interface (MDI) see http://msdn.microsoft.com/en-us/library/ms973874.aspx for more info.</p>


问:
Django urls.reverse with argument
Stuck on this for a while:

in Django pytest I am trying to do

```<code>req = RequestFactory().get(reverse('app_name:app_view_name'))
</code>```

But I require the url to have '/[number]' at the end so that UpdateView will recognise the number and display appropriate form from model.

In the browser the links and form submission all work fine, but I am unable to use reverse() in testing. I have tried:

```<code>req = RequestFactory().get(reverse('app_name:app_view_name', args=[1]))
</code>```

and

```<code>req = RequestFactory().get(reverse('app_name:app_view_name'), kwargs=['pk'=1])
</code>```

but none of these work. I am simply trying to build the url with '/1' added at the end.

Any help much appreciated.

答:
It expects a dictionary, like you can find in the documentation:

```<code>RequestFactory().get(reverse('app_name:app_view_name'),
                     <b>{'pk': 1}</b>)</code>```

Title: Django urls.reverse with argument

Body:
Stuck on this for a while:

in Django pytest I am trying to do

req = RequestFactory().get(reverse('app_name:app_view_name'))

But I require the url to have '/[number]' at the end so that UpdateView will recognise the number and display appropriate form from model.

In the browser the links and form submission all work fine, but I am unable to use reverse() in testing. I have tried:

req = RequestFactory().get(reverse('app_name:app_view_name', args=[1]))

and

req = RequestFactory().get(reverse('app_name:app_view_name'), kwargs=['pk'=1])

but none of these work. I am simply trying to build the url with '/1' added at the end.

Any help much appreciated.

Body:
It expects a dictionary, like you can find in the documentation:

RequestFactory().get(reverse('app_name:app_view_name'),
                     {'pk': 1})


问:
Move-ADObject - input object cannot be found to any parameters for the command - error
Not exactly sure why I am getting this error - input object cannot be bound to any parameters for the command either because the commmand does not take pipeline input and its properties do not match any of the parameters that take pipeline input. Any assistance is appreciated

Code snippet below

```<code>$Session = New-PSSession -ComputerName DC1 -Credential $Cred
Import-Module ActiveDirectory -PSSession $Session
$comp = $env:COMPUTERNAME
if ($ComputerName -eq $null) {
Invoke-Command -Session $session  -ScriptBlock {$using:PC
}
if($comp.substring(5,3) -imatch "Dbs"){
Get-ADObject $PC |
Move-ADObject  -Targetpath "ou=Database,
dc=com,dc=company,dc=net"
Write-Host "Moved to Datbases"}

 }

Remove-PSSession -Session $Session
</code>```

答:
Have you tried getting the object explicitly?</p>

```<code>$Session = New-PSSession -ComputerName DC01 -Credential $Cred
Import-Module ActiveDirectory -PSSession $Session
$comp = $env:COMPUTERNAME
if($comp.substring(5,3) -imatch "Sys")
{
    $adObject = Get-ADObject -Filter {Name -eq $comp}
    Move-ADObject -Identity $adObject -Targetpath "ou=System Servers,ou=PRD,ou=Servers,dc=com,dc=myCompany,dc=net"
}
    elseif($comp.substring(5,3) -imatch "App")
{
</code>```

Body:
Not exactly sure why I am getting this error - input object cannot be bound to any parameters for the command either because the commmand does not take pipeline input and its properties do not match any of the parameters that take pipeline input. Any assistance is appreciated

Code snippet below

$Session = New-PSSession -ComputerName DC1 -Credential $Cred
Import-Module ActiveDirectory -PSSession $Session
$comp = $env:COMPUTERNAME
if ($ComputerName -eq $null) {
Invoke-Command -Session $session  -ScriptBlock {$using:PC
}
if($comp.substring(5,3) -imatch "Dbs"){
Get-ADObject $PC |
Move-ADObject  -Targetpath "ou=Database,
dc=com,dc=company,dc=net"
Write-Host "Moved to Datbases"}

 }

Remove-PSSession -Session $Session

Body:
Have you tried getting the object explicitly?

$Session = New-PSSession -ComputerName DC01 -Credential $Cred
Import-Module ActiveDirectory -PSSession $Session
$comp = $env:COMPUTERNAME
if($comp.substring(5,3) -imatch "Sys")
{
    $adObject = Get-ADObject -Filter {Name -eq $comp}
    Move-ADObject -Identity $adObject -Targetpath "ou=System Servers,ou=PRD,ou=Servers,dc=com,dc=myCompany,dc=net"
}
    elseif($comp.substring(5,3) -imatch "App")
{


问:
How and When to use subscribe?
Im very new to typescript.
I'm trying to understand the Observables but I'm kinda lost here.
The function below searches for videos on Youtube API v3.
Is it a good approach?
Is subscribing inside a function which will be called many times a good idea?
This function is called whenever user types something.

Should I have an unsubscribe somewhere?

```<code>searchVideos(searchbar: any): void{
  const typedValue: string = searchbar.srcElement.value;

   if(typedValue.length > 2){
     this.videosList = this.youtubeProvider.searchVideos(typedValue);
     this.videosList.subscribe(data => {
       if( data.length == 0  ){
         this.notFoundAnyVideo = true;
       }else{
         this.notFoundAnyVideo = false;
       }
     })
   }
}
</code>```

答:
It's a good question!

They are some ways to answer your question:

1/ you can debounce the action which call your function

Imagine, your action is triggered by a keyup in input field:

HTML

```<code><input type="text" (keyup)="onSearchKeyup(this.value, $event)">
</code>```

Component

```<code>export class MyComponent implements OnInt {

   onSearch$: Subject<string>

   ngOnInt(): void {
      this.onSearch$
          .debounceTime(500) //-> put your time here
          .subscribe(search => searchVideos(search)
   }

   onSearchKeyup(search: string, e: any) {
      this.onSearch$.next(search)
      e.preventDefault()
   }

}
</code>```

2/ you can cancel the observable with takeUntil

Component

```<code>export class MyComponent implements OnInt {

   onStopSearch$: Subject<void> = new Subject<void>();

   onSearchKeyup(search: string, e: any) {
      this.onStopSearch$.next()
      this.searchVideos(string)
      e.preventDefault()
   }

   private searchVideos(search: string): void{
      if(typedValue.length > 2){
         this.videosList = this.youtubeProvider.searchVideos(typedValue);
         this.videosList
             .takeUntil(this.onSearchStop$)
             .subscribe(data => {
                if( data.length == 0  ){
                   this.notFoundAnyVideo = true;
                }else{ this.notFoundAnyVideo = false; }
             })
      }
   }

}
</code>```

Of course you can combine 1 and 2

Why I use takeUntil to cancel my requests: https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87

Title: How and When to use subscribe?

Body:
Im very new to typescript.
I'm trying to understand the Observables but I'm kinda lost here.
The function below searches for videos on Youtube API v3.
Is it a good approach?
Is subscribing inside a function which will be called many times a good idea?
This function is called whenever user types something.

Should I have an unsubscribe somewhere?

searchVideos(searchbar: any): void{
  const typedValue: string = searchbar.srcElement.value;

   if(typedValue.length > 2){
     this.videosList = this.youtubeProvider.searchVideos(typedValue);
     this.videosList.subscribe(data => {
       if( data.length == 0  ){
         this.notFoundAnyVideo = true;
       }else{
         this.notFoundAnyVideo = false;
       }
     })
   }
}

Body:
It's a good question!

They are some ways to answer your question:

1/ you can debounce the action which call your function

Imagine, your action is triggered by a keyup in input field:

HTML

<input type="text" (keyup)="onSearchKeyup(this.value, $event)">

Component

export class MyComponent implements OnInt {

   onSearch$: Subject<string>

   ngOnInt(): void {
      this.onSearch$
          .debounceTime(500) //-> put your time here
          .subscribe(search => searchVideos(search)
   }

   onSearchKeyup(search: string, e: any) {
      this.onSearch$.next(search)
      e.preventDefault()
   }

}

2/ you can cancel the observable with takeUntil

Component

export class MyComponent implements OnInt {

   onStopSearch$: Subject<void> = new Subject<void>();

   onSearchKeyup(search: string, e: any) {
      this.onStopSearch$.next()
      this.searchVideos(string)
      e.preventDefault()
   }

   private searchVideos(search: string): void{
      if(typedValue.length > 2){
         this.videosList = this.youtubeProvider.searchVideos(typedValue);
         this.videosList
             .takeUntil(this.onSearchStop$)
             .subscribe(data => {
                if( data.length == 0  ){
                   this.notFoundAnyVideo = true;
                }else{ this.notFoundAnyVideo = false; }
             })
      }
   }

}

Of course you can combine 1 and 2

Why I use takeUntil to cancel my requests: https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87


问:
Add pickup locations custom field on checkout page and in WooCommerce data fields
I found the following solution in another answer to a similar question:
Add text to order summary based on a custom field value in WooCommerce. I have two pickup locations (and a third to be added next year only).

I managed to implement the code from the solution on my staging server but I have an issue with the INFO data because each location has different opening hours. So how do I make sure this difference gets added to the order data and email and display the correct hours for the location selected?

Here's what my code looks like:

```<code>    // WC CHECKOUT PAGE: Add pickup location seletion on checkout page
add_filter( 'woocommerce_checkout_fields' , 'custom_store_pickup_field');
function custom_store_pickup_field( $fields ) {
    $fields['billing']['store_pickup'] = array(
        'type'     => 'select',
        'id'       => 'store_pickup_val',
        'label'    => __('For pickup, select a pickup location (Optional)', 'woocommerce'),
        'required' => true,
        'class'    => array('store-pickup form-row-wide'),
        'options'  => array(
            ''=> 'select a pickup location',
            'option_1' => 'Crossroads Farmers’ Market',
            'option_2' => 'Market on Macleod',
            'option_3' => '',
        ),
        'clear'     => true,
    );
    return $fields;
}

//* Process the checkout
add_action('woocommerce_checkout_process',  'wps_select_checkout_field_process');
function wps_select_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( $_POST['store_pickup'] == "option_0" )
        wc_add_notice( '<strong>Please select a pickup location</strong>', 'error' );
}

// Add opening hours for each location
add_action( 'woocommerce_after_checkout_form', 'shop_opening_hours', 6 );
function shop_opening_hours() {
     ?>
    <script type="text/javascript">
        (function($){
            $('#store_pickup_val').change( function(){
                $( ".shop-collection" ).remove();
                if (this.value == 'option_0') {
                    $('#shipping_method_0_flat_rate1').prop('checked', true);
                } else if (this.value == 'option_1') {
                     $( "<p>Order can be picked up between 9am - 5pm on Friday-Sunday</p>" ).addClass("shop-collection").insertAfter( "#store_pickup_val" );
                     $('#shipping_method_0_local_pickup3').prop('checked', true);
                } else if (this.value == 'option_2') {
                    $( "<p>Order can be picked up between 9pm - 5pm on Thursday-Sunday</p>" ).addClass("shop-collection").insertAfter( "#store_pickup_val" );
                    $('#shipping_method_0_local_pickup3').prop('checked', true);
                }
                $('body').trigger('update_checkout');
            });
        })(jQuery);
    </script>
<?php
}

// Now save the pickup location data to the order meta
add_action( 'woocommerce_checkout_update_order_meta', 'store_pickup_field_update_order_meta', 10, 1 );
function store_pickup_field_update_order_meta( $order_id ) {

    // BELOW update the data
    if ( $_POST['store_pickup'] == 'option_1' )
        $data = array(
            'location' => 'Crossroads Farmers’ Market',
            'address' => '1235 26 Avenue SW<br> Calgary, Alberta<br> T2G 1R7'
        );
    elseif ( $_POST['store_pickup'] == 'option_2' )
        $data = array(
        'location' => 'Market on Macleod',
        'address' => '7711 Macleod Trail S<br> Calgary, Alberta<br> T2H 0M1'
    );

    $collect_info = 'Order can be picked up between 9:00am - 5:00pm on Friday-Sunday';

    if ( $_POST['store_pickup'] == 'option_1' || $_POST['store_pickup'] == 'option_2' ){
        // HTML
        $store_pickup = "<h3>Pickup Information</h3>
        <table class='pickup td' cellspacing='0' cellpadding='6'>
            <tr>
                <th>Location:</th>
                <td>".$data['location']."</td>
            </tr>
            <tr>
                <th><strong>Adress:</strong></th>
                <td>".$data['address']."</td>
            </tr>
            <tr>
                <th><strong>Info:</strong></th>
                <td>".$collect_info."</td>
            </tr>
        </table>";

        // Save pickup html data (front end)
        update_post_meta( $order_id, '_store_pickup_data', $store_pickup );
        // Save pickup location (backend)
        update_post_meta( $order_id, '_store_pickup_location', $data['location'] );
    }
}

// Display 'pickup location' on the order edit page (backend)
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'display_store_pickup_location_on_order_edit_pages', 10, 1 );
function display_store_pickup_location_on_order_edit_pages( $order ){
    $pickup_location = get_post_meta( $order->get_id(), '_store_pickup_location', true );
    if( ! empty( $pickup_location ) )
        echo '<p><strong>Store pickup location: </strong> ' . $pickup_location . '</p>';
}

// Display 'pickup html data' in "Order received" and "Order view" pages (frontend)
add_action( 'woocommerce_order_details_after_order_table', 'display_store_pickup_data_in_orders', 10 );
function display_store_pickup_data_in_orders( $order ) {
    $pickup_data = get_post_meta( $order->get_id(), '_store_pickup_data', true );
    if( ! empty( $pickup_data ) )
        echo $pickup_data;
}

// Display 'pickup html data' in Email notifications (frontend)
add_action( 'woocommerce_email_order_meta', 'display_store_pickup_data_in_emails', 10 );
function display_store_pickup_data_in_emails( $order ) {
    $pickup_data = get_post_meta( $order->get_id(), '_store_pickup_data', true );
    if( ! empty( $pickup_data ) ){
        // Email CSS style rules
        echo '<style>
        table.pickup{width: 100%; font-family: \'Helvetica Neue\', Helvetica, Roboto, Arial, sans-serif;
            color: #737373; border: 1px solid #e4e4e4;}
        table.pickup th, table.pickup td{text-align: left; border-top-width: 4px;
            color: #737373; border: 1px solid #e4e4e4; padding: 12px;}
        table.pickup td{text-align: left; border-top-width: 4px; color: #737373; border: 1px solid #e4e4e4; padding: 12px;}
        </style>';
        // Html data
        echo $pickup_data;
    }

}
</code>```

Any help would be greatly appreciated
Lyse

答:
Updated: You just forgot to add different "info" for each pickup location:

```<code>// Now save the pickup location data to the order meta
add_action( 'woocommerce_checkout_update_order_meta', 'store_pickup_field_update_order_meta', 10, 1 );
function store_pickup_field_update_order_meta( $order_id ) {
    // Only for chosen "option_1" and "option_2"
    if ( $_POST['store_pickup'] == 'option_1' || $_POST['store_pickup'] == 'option_2' ){

        // 1. Set the data in an array, conditionally on chosen option value

        $collect_info = __('Order can be picked up between ');
        if( $_POST['store_pickup'] == 'option_1' ){
            $data = array(
                'location' => __('Crossroads Farmers’ Market'),
                'address'  => __('1235 26 Avenue SW<br> Calgary, Alberta<br> T2G 1R7'),
                'info'     => $collect_info . __('9:00am - 5:00pm on Friday-Sunday')
            );
        } else {
            $data = array(
                'location' => __('Market on Macleod'),
                'address'  => __('7711 Macleod Trail S<br> Calgary, Alberta<br> T2H 0M1'),
                'info'     => $collect_info . __('9:00am - 5:00pm on Thursday-Sunday')
            );
        }

        // 2. Set the data in a formatted HTML string

        $data_html = "<h3>Pickup Information</h3>
        <table class='pickup td' cellspacing='0' cellpadding='6'>
            <tr>
                <th>Location:</th>
                <td>".$data['location']."</td>
            </tr>
            <tr>
                <th><strong>Adress:</strong></th>
                <td>".$data['address']."</td>
            </tr>
            <tr>
                <th><strong>Info:</strong></th>
                <td>".$data['info']."</td>
            </tr>
        </table><br>";

        // 3. Save the data to the Order meta data

        // Pickup html formated data
        update_post_meta( $order_id, '_store_pickup_data', $data_html );

        // Pickup location
        update_post_meta( $order_id, '_store_pickup_location', $data['location'] );
    }
}
</code>```

Also your jQuery code can be simplified a bit:

```<code>// Add opening hours for each location
add_action( 'woocommerce_after_checkout_form', 'shop_opening_hours', 6 );
function shop_opening_hours() {
     ?>
    <script type="text/javascript">
        (function($){
            $('#store_pickup_val').change( function(){
                $( ".shop-collection" ).remove();
                if (this.value == 'option_1') {
                    $( "<p>Order can be picked up between 9am - 5pm on Friday-Sunday</p>" ).addClass("shop-collection").insertAfter( "#store_pickup_val" );
                    $('#shipping_method_0_local_pickup3').prop('checked', true);
                } else if (this.value == 'option_2') {
                    $( "<p>Order can be picked up between 9pm - 5pm on Thursday-Sunday</p>" ).addClass("shop-collection").insertAfter( "#store_pickup_val" );
                    $('#shipping_method_0_local_pickup3').prop('checked', true);
                } else {
                    $('#shipping_method_0_flat_rate1').prop('checked', true);
                }
                $('body').trigger('update_checkout');
            });
        })(jQuery);
    </script>
<?php
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.You will get:

For "option_1" in Order received / view order pages | Email notifications

For "option_2" in Order received / view order pages | Email notifications

An advice:

In the first code function (at the end) instead of saving only the pickup location (non formatted data), you could save all the non formatted data in an array this way:

```<code> // Save all Pickup non formatted data array
 update_post_meta( $order_id, '_store_pickup', $data );
</code>```

So to access this data, you will simply use:

```<code> $data = get_post_meta( $order_id, '_store_pickup', true );

 $pickup_location = $data['location'];
 $pickup_address  = $data['address'];
 $pickup_info     = $data['info'];
</code>```

This way you are sure to save in the order an accessible non formatted complete pickup data.

In this case, this could replace:

```<code>$pickup_location = get_post_meta( $order->get_id(), '_store_pickup_location', true );
</code>```

Using instead:

```<code>$pickup_location = get_post_meta( $order->get_id(), '_store_pickup', true )['location'];
</code>```

So you could remove definitively Pickup location saving function…

Body:
I found the following solution in another answer to a similar question:
Add text to order summary based on a custom field value in WooCommerce. I have two pickup locations (and a third to be added next year only).

I managed to implement the code from the solution on my staging server but I have an issue with the INFO data because each location has different opening hours. So how do I make sure this difference gets added to the order data and email and display the correct hours for the location selected?

Here's what my code looks like:

    // WC CHECKOUT PAGE: Add pickup location seletion on checkout page
add_filter( 'woocommerce_checkout_fields' , 'custom_store_pickup_field');
function custom_store_pickup_field( $fields ) {
    $fields['billing']['store_pickup'] = array(
        'type'     => 'select',
        'id'       => 'store_pickup_val',
        'label'    => __('For pickup, select a pickup location (Optional)', 'woocommerce'),
        'required' => true,
        'class'    => array('store-pickup form-row-wide'),
        'options'  => array(
            ''=> 'select a pickup location',
            'option_1' => 'Crossroads Farmers’ Market',
            'option_2' => 'Market on Macleod',
            'option_3' => '',
        ),
        'clear'     => true,
    );
    return $fields;
}

//* Process the checkout
add_action('woocommerce_checkout_process',  'wps_select_checkout_field_process');
function wps_select_checkout_field_process() {
    // Check if set, if its not set add an error.
    if ( $_POST['store_pickup'] == "option_0" )
        wc_add_notice( 'Please select a pickup location', 'error' );
}

// Add opening hours for each location
add_action( 'woocommerce_after_checkout_form', 'shop_opening_hours', 6 );
function shop_opening_hours() {
     ?>

<?php
}

// Now save the pickup location data to the order meta
add_action( 'woocommerce_checkout_update_order_meta', 'store_pickup_field_update_order_meta', 10, 1 );
function store_pickup_field_update_order_meta( $order_id ) {

    // BELOW update the data
    if ( $_POST['store_pickup'] == 'option_1' )
        $data = array(
            'location' => 'Crossroads Farmers’ Market',
            'address' => '1235 26 Avenue SW
 Calgary, Alberta
 T2G 1R7'
        );
    elseif ( $_POST['store_pickup'] == 'option_2' )
        $data = array(
        'location' => 'Market on Macleod',
        'address' => '7711 Macleod Trail S
 Calgary, Alberta
 T2H 0M1'
    );

    $collect_info = 'Order can be picked up between 9:00am - 5:00pm on Friday-Sunday';

    if ( $_POST['store_pickup'] == 'option_1' || $_POST['store_pickup'] == 'option_2' ){
        // HTML
        $store_pickup = "
Pickup Information

                Location:
                ".$data['location']."

                Adress:
                ".$data['address']."

                Info:
                ".$collect_info."

";

        // Save pickup html data (front end)
        update_post_meta( $order_id, '_store_pickup_data', $store_pickup );
        // Save pickup location (backend)
        update_post_meta( $order_id, '_store_pickup_location', $data['location'] );
    }
}

// Display 'pickup location' on the order edit page (backend)
add_action( 'woocommerce_admin_order_data_after_shipping_address', 'display_store_pickup_location_on_order_edit_pages', 10, 1 );
function display_store_pickup_location_on_order_edit_pages( $order ){
    $pickup_location = get_post_meta( $order->get_id(), '_store_pickup_location', true );
    if( ! empty( $pickup_location ) )
        echo '
Store pickup location:  ' . $pickup_location . '
';
}

// Display 'pickup html data' in "Order received" and "Order view" pages (frontend)
add_action( 'woocommerce_order_details_after_order_table', 'display_store_pickup_data_in_orders', 10 );
function display_store_pickup_data_in_orders( $order ) {
    $pickup_data = get_post_meta( $order->get_id(), '_store_pickup_data', true );
    if( ! empty( $pickup_data ) )
        echo $pickup_data;
}

// Display 'pickup html data' in Email notifications (frontend)
add_action( 'woocommerce_email_order_meta', 'display_store_pickup_data_in_emails', 10 );
function display_store_pickup_data_in_emails( $order ) {
    $pickup_data = get_post_meta( $order->get_id(), '_store_pickup_data', true );
    if( ! empty( $pickup_data ) ){
        // Email CSS style rules
        echo '';
        // Html data
        echo $pickup_data;
    }

}

Any help would be greatly appreciated
Lyse

Body:
Updated: You just forgot to add different "info" for each pickup location:

// Now save the pickup location data to the order meta
add_action( 'woocommerce_checkout_update_order_meta', 'store_pickup_field_update_order_meta', 10, 1 );
function store_pickup_field_update_order_meta( $order_id ) {
    // Only for chosen "option_1" and "option_2"
    if ( $_POST['store_pickup'] == 'option_1' || $_POST['store_pickup'] == 'option_2' ){

        // 1. Set the data in an array, conditionally on chosen option value

        $collect_info = __('Order can be picked up between ');
        if( $_POST['store_pickup'] == 'option_1' ){
            $data = array(
                'location' => __('Crossroads Farmers’ Market'),
                'address'  => __('1235 26 Avenue SW<br> Calgary, Alberta<br> T2G 1R7'),
                'info'     => $collect_info . __('9:00am - 5:00pm on Friday-Sunday')
            );
        } else {
            $data = array(
                'location' => __('Market on Macleod'),
                'address'  => __('7711 Macleod Trail S<br> Calgary, Alberta<br> T2H 0M1'),
                'info'     => $collect_info . __('9:00am - 5:00pm on Thursday-Sunday')
            );
        }

        // 2. Set the data in a formatted HTML string

        $data_html = "<h3>Pickup Information</h3>
        <table class='pickup td' cellspacing='0' cellpadding='6'>
            <tr>
                <th>Location:</th>
                <td>".$data['location']."</td>
            </tr>
            <tr>
                <th><strong>Adress:</strong></th>
                <td>".$data['address']."</td>
            </tr>
            <tr>
                <th><strong>Info:</strong></th>
                <td>".$data['info']."</td>
            </tr>
        </table><br>";

        // 3. Save the data to the Order meta data

        // Pickup html formated data
        update_post_meta( $order_id, '_store_pickup_data', $data_html );

        // Pickup location
        update_post_meta( $order_id, '_store_pickup_location', $data['location'] );
    }
}

Also your jQuery code can be simplified a bit:

// Add opening hours for each location
add_action( 'woocommerce_after_checkout_form', 'shop_opening_hours', 6 );
function shop_opening_hours() {
     ?>
    <script type="text/javascript">
        (function($){
            $('#store_pickup_val').change( function(){
                $( ".shop-collection" ).remove();
                if (this.value == 'option_1') {
                    $( "<p>Order can be picked up between 9am - 5pm on Friday-Sunday</p>" ).addClass("shop-collection").insertAfter( "#store_pickup_val" );
                    $('#shipping_method_0_local_pickup3').prop('checked', true);
                } else if (this.value == 'option_2') {
                    $( "<p>Order can be picked up between 9pm - 5pm on Thursday-Sunday</p>" ).addClass("shop-collection").insertAfter( "#store_pickup_val" );
                    $('#shipping_method_0_local_pickup3').prop('checked', true);
                } else {
                    $('#shipping_method_0_flat_rate1').prop('checked', true);
                }
                $('body').trigger('update_checkout');
            });
        })(jQuery);
    </script>
<?php
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works.You will get:

For "option_1" in Order received / view order pages | Email notifications

For "option_2" in Order received / view order pages | Email notifications

An advice:

In the first code function (at the end) instead of saving only the pickup location (non formatted data), you could save all the non formatted data in an array this way:

 // Save all Pickup non formatted data array
 update_post_meta( $order_id, '_store_pickup', $data );

So to access this data, you will simply use:

 $data = get_post_meta( $order_id, '_store_pickup', true );

 $pickup_location = $data['location'];
 $pickup_address  = $data['address'];
 $pickup_info     = $data['info'];

This way you are sure to save in the order an accessible non formatted complete pickup data.

In this case, this could replace:

$pickup_location = get_post_meta( $order->get_id(), '_store_pickup_location', true );

Using instead:

$pickup_location = get_post_meta( $order->get_id(), '_store_pickup', true )['location'];

So you could remove definitively Pickup location saving function…


问:
Break <option> items in loop
I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    // var xhr = new XMLHttpRequest();
    // xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    // xhr.onreadystatechange = function() {
    //      if (xhr.readyState == 4 && xhr.status == 200) {
    //          var items = JSON.parse(xhr.responseText);
                var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
                var output = '<select>'
                for (var i in items) {
                    output += '<option>' + items[i].address + '</option>
'
                }
                output += '</select>'
                document.getElementById("replaceOption").innerHTML = output
    //      }
    // }
    // xhr.send();
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
    <script src="stations.js"></script>
    <title></title>
</head>
<body onload="addressList()">
    <div>
        <div id="addressDropdown">
            <form>
                <select>
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>
                <br>
                <input type="submit" value="Go" id="sumbit" href="#">
            </form>
        </div>
    </div>
</body>
</html></code>```

答:
document.addEventListener('DOMContentLoaded', function () {
  let selectEl = document.getElementById('select-el');

  let xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function (res) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      let items = JSON.parse(xhr.responseText);
      console.log(items);
      items.forEach(function (item) {
        let option = document.createElement('option');
        option.value = item.name;
        option.innerText = item.address;

        selectEl.appendChild(option);
      });
    }
  }

  xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
  xhr.send();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <script src="stations.js"></script>
  <title></title>
</head>

<body>
  <div>
    <div id="addressDropdown">
      <form>
        <select id="select-el"></select>
        <br/>
        <input type="submit" value="Go" id="sumbit" href="#" />
      </form>
    </div>
  </div>
</body>

</html></code>```

Title: Break <option> items in loop

Body:
I am trying to loop 100 values from an API into a dropdown list. When the function runs the page loads all 100 values but inserts them into the list on 1 line, rather than on 100 separate lines. I have tried adding a break tag to the loop but that didn't work.
How do you separate each item onto its own line?

// GET STATION NAMES AND PUT THEM INTO DROPDOWN LIST
function addressList() {
    // var xhr = new XMLHttpRequest();
    // xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
    // xhr.onreadystatechange = function() {
    //      if (xhr.readyState == 4 && xhr.status == 200) {
    //          var items = JSON.parse(xhr.responseText);
                var items = [{"address":"Smithfield North"},{"address":"Parnell Square North"},{"address":"Pearse Street"},{"address":"Excise Walk"},{"address":"Fitzwilliam Square West"},{"address":"St. James Hospital (Central)"},{"address":"Hanover Quay"},{"address":"Oliver Bond Street"},{"address":"Collins Barracks Museum"},{"address":"Brookfield Road"},{"address":"Clonmel Street"},{"address":"Mount Street Lower"},{"address":"Christchurch Place"},{"address":"Grantham Street"},{"address":"York Street East"},{"address":"Portobello Road"},{"address":"Parnell Street"},{"address":"Frederick Street South"},{"address":"Fownes Street Upper"},{"address":"Clarendon Row"},{"address":"Custom House"},{"address":"Benson Street"},{"address":"Fenian Street"},{"address":"South Dock Road"},{"address":"The Point"},{"address":"Lime Street"},{"address":"Kilmainham Gaol"},{"address":"Guild Street"},{"address":"Herbert Place"},{"address":"Western Way"},{"address":"Newman House"},{"address":"King Street North"},{"address":"Herbert Street"},{"address":"Earlsfort Terrace"},{"address":"Golden Lane"},{"address":"Deverell Place"},{"address":"John Street West"},{"address":"City Quay"},{"address":"Exchequer Street"},{"address":"Hatch Street"},{"address":"Charlemont Street"},{"address":"Hardwicke Place"},{"address":"Wolfe Tone Street"},{"address":"Francis Street"},{"address":"Greek Street"},{"address":"High Street"},{"address":"North Circular Road"},{"address":"Talbot Street"},{"address":"Sir Patrick's Dun"},{"address":"New Central Bank"},{"address":"Georges Quay"},{"address":"Mount Brown"},{"address":"Royal Hospital"},{"address":"Heuston Station (Central)"},{"address":"Townsend Street"},{"address":"Portobello Harbour"},{"address":"Custom House Quay"},{"address":"Molesworth Street"},{"address":"Kilmainham Lane"},{"address":"Market Street South"},{"address":"Kevin Street"},{"address":"Eccles Street East"},{"address":"Grand Canal Dock"},{"address":"Merrion Square East"},{"address":"York Street West"},{"address":"St. Stephen's Green South"},{"address":"Denmark Street Great"},{"address":"Heuston Station (Car Park)"},{"address":"St. Stephen's Green East"},{"address":"Eccles Street"},{"address":"Mater Hospital"},{"address":"Blessington Street"},{"address":"Merrion Square West"},{"address":"Convention Centre"},{"address":"Hardwicke Street"},{"address":"Smithfield"},{"address":"Dame Street"},{"address":"Sandwith Street"},{"address":"Princes Street / O'Connell Street"},{"address":"Grattan Street"},{"address":"St James Hospital (Luas)"},{"address":"Bolton Street"},{"address":"Strand Street Great"},{"address":"Barrow Street"},{"address":"Mountjoy Square West"},{"address":"Wilton Terrace"},{"address":"Leinster Street South"},{"address":"James Street"},{"address":"Parkgate Street"},{"address":"Heuston Bridge (South)"},{"address":"Cathal Brugha Street"},{"address":"Rothe Abbey"},{"address":"Upper Sherrard Street"},{"address":"Fitzwilliam Square East"},{"address":"Harcourt Terrace"},{"address":"Jervis Street"},{"address":"Ormond Quay Upper"},{"address":"Emmet Road"},{"address":"Heuston Bridge (North)"},{"address":"Blackhall Place"}];
                var output = '<select>'
                for (var i in items) {
                    output += '<option>' + items[i].address + '</option>
'
                }
                output += '</select>'
                document.getElementById("replaceOption").innerHTML = output
    //      }
    // }
    // xhr.send();
};

<!DOCTYPE html>

    <title></title>

            <form>
                <select>
                    <option id="addressList" value="select station" selected="selected">Select Station..</option>
                    <option id="replaceOption">0</option>
                </select>

                <input type="submit" value="Go" id="sumbit" href="#">
            </form>

Body:
document.addEventListener('DOMContentLoaded', function () {
  let selectEl = document.getElementById('select-el');

  let xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function (res) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      let items = JSON.parse(xhr.responseText);
      console.log(items);
      items.forEach(function (item) {
        let option = document.createElement('option');
        option.value = item.name;
        option.innerText = item.address;

        selectEl.appendChild(option);
      });
    }
  }

  xhr.open('GET', 'https://api.jcdecaux.com/vls/v1/stations?contract=Dublin&apiKey=xxxxxxxxxx');
  xhr.send();

});

<!DOCTYPE html>
<html>

<head>
  <script src="stations.js"></script>
  <title></title>
</head>

<body>
  <div>
    <div id="addressDropdown">
      <form>
        <select id="select-el"></select>
        <br/>
        <input type="submit" value="Go" id="sumbit" href="#" />
      </form>
    </div>
  </div>
</body>

</html>


问:
Impossible NPE being thrown (java)
In this example code a NullPointerException is being thrown on line 4.

```<code>1. private <O,T> void generate(Suggestion suggestion, GeneratorFactory<O, T> generatorFactory) {
2.     final Generator<O, T> generator = generatorFactory.getGenerator(suggestion);
3.     while (generator.hasNext()) {
4.         generator.doGenerate();
5.     }
6.     // post-generate stuff here
7. }
</code>```

It only happens occasionally, but it has happened a few times on a live server, so it's not some kind of "ghost" bug - it definitely needs fixing.

Stack trace:

```<code>java.lang.NullPointerException
    at package.SuggestionServiceImpl.generate(SuggestionServiceImpl.java:4)
</code>```

Code for GeneratoryFactory:

```<code>@Override
public synchronized Generator<O, T> getGenerator(final Suggestion suggestion) {
    Generator<O, T> generator = generators.get(suggestion.getId());
    if (generator == null) {
        generator = construct(suggestion); // calls `new Generator()`
        generators.put(suggestion.getId(), generator);
    }
    return generator;
}
</code>```

I'm confused by:

How come we don't get a NPE in the 'if' statement on line 3, if it's generator that's null?

How come the stack trace starts at line 4, and not from a line inside doGenerate() if that's where the exception is coming from? (The internals of doGenerate() are lengthy and complex - it is possible that an NPE starts here, but why no stack trace?)

Update:

As an experimental test, I deliberately threw a NPE inside doGenerate() [in dev environment] to compare the stack trace with the mystery live one. It does indeed have the anticipated extra stack frame.

```<code>java.lang.NullPointerException: DELIBERATE TEST EXCEPTION
    at package.Generator.doGenerate(Generator.java:71)
    at package.SuggestionServiceImpl.generate(SuggestionServiceImpl.java:4)
</code>```

The runtime JVM is:

```<code>java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Oracle JRockit(R) (build R28.1.4-7-144370-1.6.0_26-20110617-2130-linux-x86_64, compiled mode)
</code>```

答: I have encountered similar issue. It looks like JUnit (or JVM) truncated stacktrace in wrong way. Wrapping whole test method in try/catch and using Exception.printStackTrace() showed the real source of NPE instead of "impossible" location.</p>

Title: Impossible NPE being thrown (java)

Body:
In this example code a NullPointerException is being thrown on line 4.

1. private <O,T> void generate(Suggestion suggestion, GeneratorFactory<O, T> generatorFactory) {
2.     final Generator<O, T> generator = generatorFactory.getGenerator(suggestion);
3.     while (generator.hasNext()) {
4.         generator.doGenerate();
5.     }
6.     // post-generate stuff here
7. }

It only happens occasionally, but it has happened a few times on a live server, so it's not some kind of "ghost" bug - it definitely needs fixing.

Stack trace:

java.lang.NullPointerException
    at package.SuggestionServiceImpl.generate(SuggestionServiceImpl.java:4)

Code for GeneratoryFactory:

@Override
public synchronized Generator<O, T> getGenerator(final Suggestion suggestion) {
    Generator<O, T> generator = generators.get(suggestion.getId());
    if (generator == null) {
        generator = construct(suggestion); // calls `new Generator()`
        generators.put(suggestion.getId(), generator);
    }
    return generator;
}

I'm confused by:

How come we don't get a NPE in the 'if' statement on line 3, if it's generator that's null?

How come the stack trace starts at line 4, and not from a line inside doGenerate() if that's where the exception is coming from? (The internals of doGenerate() are lengthy and complex - it is possible that an NPE starts here, but why no stack trace?)

Update:

As an experimental test, I deliberately threw a NPE inside doGenerate() [in dev environment] to compare the stack trace with the mystery live one. It does indeed have the anticipated extra stack frame.

java.lang.NullPointerException: DELIBERATE TEST EXCEPTION
    at package.Generator.doGenerate(Generator.java:71)
    at package.SuggestionServiceImpl.generate(SuggestionServiceImpl.java:4)

The runtime JVM is:

java version "1.6.0_26"
Java(TM) SE Runtime Environment (build 1.6.0_26-b03)
Oracle JRockit(R) (build R28.1.4-7-144370-1.6.0_26-20110617-2130-linux-x86_64, compiled mode)


问:
disable all form elements inside div
is there a way to disable all fields (textarea/textfield/option/input/checkbox/submit etc) in a form by telling only the parent div name in jquery/javascript?</p>

答:
For me the accepted answer did not work as I had some asp net hidden fields which got disabled as well so I chose only to disable visible fields</p>

```<code>//just to save the list so we can enable fields later
var list = [];
$('#parent-selector').find(':input:visible:not([readonly][disabled]),button').each(function () {
    list.push('#' + this.id);
});

$(list.join(',')).attr('readonly', true);
</code>```

Title: disable all form elements inside div

Body:
For me the accepted answer did not work as I had some asp net hidden fields which got disabled as well so I chose only to disable visible fields

//just to save the list so we can enable fields later
var list = [];
$('#parent-selector').find(':input:visible:not([readonly][disabled]),button').each(function () {
    list.push('#' + this.id);
});

$(list.join(',')).attr('readonly', true);