答:
The issue is that you are not pausing the bounce animation which starts when the stroke animation ends.

Assing the bounce animation to a variable in order to pause it later when the user clicks.

// Declare the variable here to provide it with the right scope.
let bounceAnimation;

const cartIconAnimation = anime({
  // some options...

  complete: function() {
    bounceAnimation = anime({
      // your bounce options...
    });
  }
});
```

<p>Then you can modify the event listener this way:</p>

<pre class="lang-js prettyprint-override"><code>cartReplay.addEventListener('click', function() {
  bounceAnimation.pause()
  cartIconAnimation.restart()
});
</code>```

Try the snippet below.

const cartIcon = '.cart-icon';
let bounceAnimation;

const cartIconAnimation = anime({
  targets: `${cartIcon} path`,

  strokeDashoffset: {
    value: [anime.setDashoffset, 0],
    easing: 'easeInOutSine',
    duration: 1500,
    direction: 'alternate',
  },

  fill: {
    value: '#000',
    easing: 'linear',
    duration: 400,
    delay: 1500,
  },

  complete: function() {

   bounceAnimation = anime({
      targets: `${cartIcon} .arrow`,
      translateY: [-30, 0],
      duration: 700,
      easing: 'easeOutElastic',
      direction: 'alternate',
      loop: true
    });

  }

});

const cartReplay = document.querySelector('.cart-icon').nextElementSibling;

cartReplay.addEventListener('click', function() {
  bounceAnimation.pause()
  cartIconAnimation.restart()
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.icon {
  width: 100px;
  height: 100px;
  margin-top: 20px;
 }

 svg {
  width: 100%;
  height: 100%;
  overflow: visible;
 }

 button {
 margin-top: 20px;
 }</code>```

        <svg height="426pt" viewBox="-6 0 426 426.82755" width="426pt" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <path class="arrow" fill="#fff" stroke="#000" stroke-width="3" d="m207.859375 80.316406 35 30c.007813.007813.023437.015625.035156.023438.289063.246094.597657.464844.925781.660156.042969.027344.085938.054688.128907.078125.320312.179687.648437.335937.992187.464844l.160156.058593c.339844.121094.6875.210938 1.042969.277344l.15625.023438c.738281.128906 1.488281.128906 2.226563 0l.15625-.023438c.355468-.066406.703125-.15625 1.042968-.277344l.160157-.058593c.339843-.128907.671875-.285157.988281-.464844.046875-.023437.089844-.050781.132812-.078125.328126-.195312.636719-.414062.925782-.660156.011718-.007813.023437-.015625.035156-.023438l35-30c2.9375-2.519531 3.277344-6.9375.757812-9.871094-2.515624-2.9375-6.933593-3.277343-9.867187-.757812l-23.445313 20.09375v-82.78125c0-3.867188-3.132812-7-7-7-3.867187 0-7 3.132812-7 7v82.78125l-23.445312-20.09375c-2.933594-2.519531-7.351562-2.179688-9.871094.757812-2.515625 2.933594-2.175781 7.351563.761719 9.871094zm0 0" />
          <path class="cart" fill="#fff" stroke="#000" stroke-width="3" d="m407.414062 133.679688h-312l-3.277343-24.574219c-.007813-.054688-.015625-.109375-.023438-.167969-3.195312-20.703125-21.050781-35.957031-42-35.871094h-42.699219c-3.867187 0-7 3.132813-7 7 0 3.863282 3.132813 7 7 7h42.699219c14.019531-.058594 25.980469 10.128906 28.160157 23.980469l33.792968 253.425781c.007813.054688.015625.113282.023438.167969 3.195312 20.703125 21.050781 35.957031 42 35.875h5.875c2.578125 15.195313 15.742187 26.3125 31.152344 26.3125 15.414062 0 28.578124-11.117187 31.15625-26.3125h58.46875c2.707031 15.863281 16.902343 27.160156 32.96875 26.242187 16.070312-.921874 28.878906-13.765624 29.757812-29.835937s-10.457031-30.234375-26.328125-32.898437c-15.871094-2.667969-31.210937 7.015624-35.632813 22.492187h-60c-3.871093-13.574219-16.273437-22.933594-30.386718-22.933594-14.117188 0-26.519532 9.359375-30.390625 22.933594h-6.640625c-14.019532.058594-25.984375-10.128906-28.164063-23.980469l-10.183593-76.382812h218.40625c18.117187-.007813 34.242187-11.484375 40.179687-28.597656l39.703125-114.578126c.742188-2.140624.402344-4.507812-.910156-6.355468s-3.441406-2.945313-5.707032-2.941406zm-95.523437 243.90625c9.726563 0 17.613281 7.882812 17.613281 17.609374 0 9.726563-7.886718 17.613282-17.613281 17.613282s-17.609375-7.886719-17.609375-17.613282c.011719-9.722656 7.890625-17.597656 17.609375-17.609374zm-120.777344 0c9.726563 0 17.609375 7.882812 17.613281 17.609374 0 9.726563-7.886718 17.613282-17.613281 17.613282-9.726562 0-17.609375-7.886719-17.609375-17.613282.011719-9.722656 7.886719-17.597656 17.609375-17.609374zm169.988281-124.621094c-3.984374 11.480468-14.800781 19.179687-26.953124 19.183594h-220.273438l-16.601562-124.46875h300.300781zm0 0" />
          </svg>

<button class="icon-block__replay" type="button"> Replay </button>```

Title: Anime js animationg issues

Body:
I'm trying to animate an SVG icon with anime.js.

Here is my code:

const cartIcon = '.cart-icon';

const cartIconAnimation = anime({
  targets: `${cartIcon} path`,

  strokeDashoffset: {
    value: [anime.setDashoffset, 0],
    easing: 'easeInOutSine',
    duration: 1500,
    direction: 'alternate',
  },

  fill: {
    value: '#000',
    easing: 'linear',
    duration: 400,
    delay: 1500,
  },

  complete: function() {

   anime({
      targets: `${cartIcon} .arrow`,
      translateY: [-30, 0],
      duration: 700,
      easing: 'easeOutElastic',
      direction: 'alternate',
      loop: true
    });

  }

});

const cartReplay = document.querySelector('.cart-icon').nextElementSibling;

cartReplay.addEventListener('click', cartIconAnimation.restart);

.icon {
  width: 100px;
  height: 100px;
  margin-top: 20px;
 }

 svg {
  width: 100%;
  height: 100%;
  overflow: visible;
 }

 button {
 margin-top: 20px;
 }

        <svg height="426pt" viewBox="-6 0 426 426.82755" width="426pt" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <path class="arrow" fill="#fff" stroke="#000" stroke-width="3" d="m207.859375 80.316406 35 30c.007813.007813.023437.015625.035156.023438.289063.246094.597657.464844.925781.660156.042969.027344.085938.054688.128907.078125.320312.179687.648437.335937.992187.464844l.160156.058593c.339844.121094.6875.210938 1.042969.277344l.15625.023438c.738281.128906 1.488281.128906 2.226563 0l.15625-.023438c.355468-.066406.703125-.15625 1.042968-.277344l.160157-.058593c.339843-.128907.671875-.285157.988281-.464844.046875-.023437.089844-.050781.132812-.078125.328126-.195312.636719-.414062.925782-.660156.011718-.007813.023437-.015625.035156-.023438l35-30c2.9375-2.519531 3.277344-6.9375.757812-9.871094-2.515624-2.9375-6.933593-3.277343-9.867187-.757812l-23.445313 20.09375v-82.78125c0-3.867188-3.132812-7-7-7-3.867187 0-7 3.132812-7 7v82.78125l-23.445312-20.09375c-2.933594-2.519531-7.351562-2.179688-9.871094.757812-2.515625 2.933594-2.175781 7.351563.761719 9.871094zm0 0" />
          <path class="cart" fill="#fff" stroke="#000" stroke-width="3" d="m407.414062 133.679688h-312l-3.277343-24.574219c-.007813-.054688-.015625-.109375-.023438-.167969-3.195312-20.703125-21.050781-35.957031-42-35.871094h-42.699219c-3.867187 0-7 3.132813-7 7 0 3.863282 3.132813 7 7 7h42.699219c14.019531-.058594 25.980469 10.128906 28.160157 23.980469l33.792968 253.425781c.007813.054688.015625.113282.023438.167969 3.195312 20.703125 21.050781 35.957031 42 35.875h5.875c2.578125 15.195313 15.742187 26.3125 31.152344 26.3125 15.414062 0 28.578124-11.117187 31.15625-26.3125h58.46875c2.707031 15.863281 16.902343 27.160156 32.96875 26.242187 16.070312-.921874 28.878906-13.765624 29.757812-29.835937s-10.457031-30.234375-26.328125-32.898437c-15.871094-2.667969-31.210937 7.015624-35.632813 22.492187h-60c-3.871093-13.574219-16.273437-22.933594-30.386718-22.933594-14.117188 0-26.519532 9.359375-30.390625 22.933594h-6.640625c-14.019532.058594-25.984375-10.128906-28.164063-23.980469l-10.183593-76.382812h218.40625c18.117187-.007813 34.242187-11.484375 40.179687-28.597656l39.703125-114.578126c.742188-2.140624.402344-4.507812-.910156-6.355468s-3.441406-2.945313-5.707032-2.941406zm-95.523437 243.90625c9.726563 0 17.613281 7.882812 17.613281 17.609374 0 9.726563-7.886718 17.613282-17.613281 17.613282s-17.609375-7.886719-17.609375-17.613282c.011719-9.722656 7.890625-17.597656 17.609375-17.609374zm-120.777344 0c9.726563 0 17.609375 7.882812 17.613281 17.609374 0 9.726563-7.886718 17.613282-17.613281 17.613282-9.726562 0-17.609375-7.886719-17.609375-17.613282.011719-9.722656 7.886719-17.597656 17.609375-17.609374zm169.988281-124.621094c-3.984374 11.480468-14.800781 19.179687-26.953124 19.183594h-220.273438l-16.601562-124.46875h300.300781zm0 0" />
          </svg>

<button class="icon-block__replay" type="button"> Replay </button>

When animation works onload - everything is perfect. But when I click 'restart' button, there are 2 issues:

1) arrow part of icon must start animating only after line and fill animations complete, but it starts right at the beginning of animation along with line/fill animations;

2) when fill animation completes arrow makes strange movement to the top, and I don't know jow to fix it

All the help will be very appreciated! Thank you!

Body:
The issue is that you are not pausing the bounce animation which starts when the stroke animation ends.

Assing the bounce animation to a variable in order to pause it later when the user clicks.

// Declare the variable here to provide it with the right scope.
let bounceAnimation;

const cartIconAnimation = anime({
  // some options...

  complete: function() {
    bounceAnimation = anime({
      // your bounce options...
    });
  }
});

Then you can modify the event listener this way:

cartReplay.addEventListener('click', function() {
  bounceAnimation.pause()
  cartIconAnimation.restart()
});

Try the snippet below.

const cartIcon = '.cart-icon';
let bounceAnimation;

const cartIconAnimation = anime({
  targets: `${cartIcon} path`,

  strokeDashoffset: {
    value: [anime.setDashoffset, 0],
    easing: 'easeInOutSine',
    duration: 1500,
    direction: 'alternate',
  },

  fill: {
    value: '#000',
    easing: 'linear',
    duration: 400,
    delay: 1500,
  },

  complete: function() {

   bounceAnimation = anime({
      targets: `${cartIcon} .arrow`,
      translateY: [-30, 0],
      duration: 700,
      easing: 'easeOutElastic',
      direction: 'alternate',
      loop: true
    });

  }

});

const cartReplay = document.querySelector('.cart-icon').nextElementSibling;

cartReplay.addEventListener('click', function() {
  bounceAnimation.pause()
  cartIconAnimation.restart()
});

.icon {
  width: 100px;
  height: 100px;
  margin-top: 20px;
 }

 svg {
  width: 100%;
  height: 100%;
  overflow: visible;
 }

 button {
 margin-top: 20px;
 }

<script src="https://cdn.jsdelivr.net/npm/animejs@3.1.0/lib/anime.min.js"></script>
<div class="cart-icon icon">
        <svg height="426pt" viewBox="-6 0 426 426.82755" width="426pt" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
          <path class="arrow" fill="#fff" stroke="#000" stroke-width="3" d="m207.859375 80.316406 35 30c.007813.007813.023437.015625.035156.023438.289063.246094.597657.464844.925781.660156.042969.027344.085938.054688.128907.078125.320312.179687.648437.335937.992187.464844l.160156.058593c.339844.121094.6875.210938 1.042969.277344l.15625.023438c.738281.128906 1.488281.128906 2.226563 0l.15625-.023438c.355468-.066406.703125-.15625 1.042968-.277344l.160157-.058593c.339843-.128907.671875-.285157.988281-.464844.046875-.023437.089844-.050781.132812-.078125.328126-.195312.636719-.414062.925782-.660156.011718-.007813.023437-.015625.035156-.023438l35-30c2.9375-2.519531 3.277344-6.9375.757812-9.871094-2.515624-2.9375-6.933593-3.277343-9.867187-.757812l-23.445313 20.09375v-82.78125c0-3.867188-3.132812-7-7-7-3.867187 0-7 3.132812-7 7v82.78125l-23.445312-20.09375c-2.933594-2.519531-7.351562-2.179688-9.871094.757812-2.515625 2.933594-2.175781 7.351563.761719 9.871094zm0 0" />
          <path class="cart" fill="#fff" stroke="#000" stroke-width="3" d="m407.414062 133.679688h-312l-3.277343-24.574219c-.007813-.054688-.015625-.109375-.023438-.167969-3.195312-20.703125-21.050781-35.957031-42-35.871094h-42.699219c-3.867187 0-7 3.132813-7 7 0 3.863282 3.132813 7 7 7h42.699219c14.019531-.058594 25.980469 10.128906 28.160157 23.980469l33.792968 253.425781c.007813.054688.015625.113282.023438.167969 3.195312 20.703125 21.050781 35.957031 42 35.875h5.875c2.578125 15.195313 15.742187 26.3125 31.152344 26.3125 15.414062 0 28.578124-11.117187 31.15625-26.3125h58.46875c2.707031 15.863281 16.902343 27.160156 32.96875 26.242187 16.070312-.921874 28.878906-13.765624 29.757812-29.835937s-10.457031-30.234375-26.328125-32.898437c-15.871094-2.667969-31.210937 7.015624-35.632813 22.492187h-60c-3.871093-13.574219-16.273437-22.933594-30.386718-22.933594-14.117188 0-26.519532 9.359375-30.390625 22.933594h-6.640625c-14.019532.058594-25.984375-10.128906-28.164063-23.980469l-10.183593-76.382812h218.40625c18.117187-.007813 34.242187-11.484375 40.179687-28.597656l39.703125-114.578126c.742188-2.140624.402344-4.507812-.910156-6.355468s-3.441406-2.945313-5.707032-2.941406zm-95.523437 243.90625c9.726563 0 17.613281 7.882812 17.613281 17.609374 0 9.726563-7.886718 17.613282-17.613281 17.613282s-17.609375-7.886719-17.609375-17.613282c.011719-9.722656 7.890625-17.597656 17.609375-17.609374zm-120.777344 0c9.726563 0 17.609375 7.882812 17.613281 17.609374 0 9.726563-7.886718 17.613282-17.613281 17.613282-9.726562 0-17.609375-7.886719-17.609375-17.613282.011719-9.722656 7.886719-17.597656 17.609375-17.609374zm169.988281-124.621094c-3.984374 11.480468-14.800781 19.179687-26.953124 19.183594h-220.273438l-16.601562-124.46875h300.300781zm0 0" />
          </svg>
</div>

<button class="icon-block__replay" type="button"> Replay </button>


来源: stackexchange

问:
How to return count of function calls between calls with the same input?
I'm trying to get the value of when was the last time function was called with the same input. If it's the first time, return -1. For example:

```<code>System.out.println(newNumber(1)); // returns -1
System.out.println(newNumber(2)); // returns -1
System.out.println(newNumber(3)); // returns -1
System.out.println(newNumber(1)); // returns 2
System.out.println(newNumber(2)); // returns 2
System.out.println(newNumber(1)); // returns 1
System.out.println(newNumber(4)); // returns -1
System.out.println(newNumber(1)); // returns 1
</code>```

Having really hard time finding the right way to start doing this. I'm pretty new to hash maps, and I think that's what you have to use?

答:
You can store the number of times a number appears in a map from the number to the number of times it appears. Note that this map will have to be a data member to retain the values beyond a single function call.

Map<Integer, Integer> map = new HashMap<>();
public int newNumber(int i) {
    Integer result = map.computeIfPresent(i, (k, v) -> v + 1);
    if (result == null) {
        map.put(i, 1);
        return -1;
    }
    return result;
}
```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get the value of when was the last time function was called with the same input. If it's the first time, return -1. For example:

System.out.println(newNumber(1)); // returns -1
System.out.println(newNumber(2)); // returns -1
System.out.println(newNumber(3)); // returns -1
System.out.println(newNumber(1)); // returns 2
System.out.println(newNumber(2)); // returns 2
System.out.println(newNumber(1)); // returns 1
System.out.println(newNumber(4)); // returns -1
System.out.println(newNumber(1)); // returns 1

Having really hard time finding the right way to start doing this. I'm pretty new to hash maps, and I think that's what you have to use?


问:
How do i determine the nth weekday of a given date in php
I am working on a calendar script where in i need to repeat a calendar event like
"Repeat on every 1st Tuesday of every month"

In the example above. How do you get the "1st"?

for example today is June 12,2009 this would mean it's "2nd Friday of June" How do i get the "2nd"?

Thanks in advance

ContentLicense: CC BY-SA 2.5

Body:
function dayOfWeek($d, $m, $y)
{
    static $t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
    $y -= $m < 3;
    return ($y + $y / 4 - $y / 100 + $y / 400 + $t[$m - 1] + $d) % 7;
}

// 30th August 2010
// 0: sunday - 6: saturday
echo dayOfWeek(30, 8, 2010);


问:
How can I compare the size of three arraylists in Java?
I have three ArrayLists, let's say a, b, and c, each of which contains some elements, and I want to compare their size to see if their sizes are equal, how can I do this? Is it like as follows:

if (a.size() == b.size() == c.size()) {

  // do-something

}
```

答:
tl;dr

Use this one-liner, or wrap this in a method to be called.

```<code>List
.of( listA , listB , listC )              // ⬅ Your list variables go here.
.stream()
.map( collection -> collection.size() )
.collect( Collectors.toSet() )
.size()
== 1                                      // Returns `true` if your lists are all the same size. Returns `false` if different sizes.
</code>```

Details

Set from a List of the lists’ sizes

Here is a one-liner.

```<code>if(
    new TreeSet< Integer > (
        List.of(
            listA.size() ,
            listB.size() ,
            listC.size()
        )
    )
    .size() == 1
)
{…}
</code>```

We collect the sizes of each of the lists, putting the sizes into a Set< Integer >. Sets eliminate duplicates. So after adding all the sizes, we should have a single value in the set.

For example, if all the lists are the same size, with a count of seven elements, then we end up with a single element set, [ 7 ]. On the other hand, if some of the lists had seven elements, and some had eight, then the resulting set of list sizes would have two elements [ 7 , 8 ] rather than one element.

Complete example

Here is a complete example.

```<code>package work.basil.example

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class ListSizes
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List listA = List.of( "Dog" , "Cat" , "Rabbit" );
        List listB = List.of( "Dog" , "Cat" , "Bird" );
        List listC = List.of( "Elephant" , "Giraffe" , "Hippo" );

        if(
            new TreeSet< Integer > (
                List.of(
                    listA.size() ,
                    listB.size() ,
                    listC.size()
                )
            )
            .size() == 1
        )
        { System.out.println( "Same size." ) ; }
        else
        { System.out.println( "Different sizes." ) ; }

    }
}
</code>```

See that code run live at IdeOne.com. You can fork that code within IdeOne.com to try deleting or adding items to any of the lists.

Same size.

By the way, you might notice how autoboxing has kicked-in, converting the int primitive returns by List::size into an Integer object to be passed into the List.of method call. I am a bit surprised that worked without needing to wrap the List::size calls in Integer.valueOf call.

Make a method, passing your collections whose sizes need comparing

We could put this code in a method. Use the varargs feature of Java, you would pass any number of Collection objects. Their sizes would then be compared.

```<code>Boolean sameSize ( Collection... arguments )
{
    List < Integer > sizes = new ArrayList <>( arguments.length );
    for ( Collection collection : arguments )
    {
        sizes.add( collection.size() );
    }
    return ( new TreeSet < Integer >( sizes ).size() == 1 );
}
</code>```

Let's try using the method.

```<code>List listA = List.of( "Dog" , "Cat" );
List listB = List.of( "Dog" , "Cat" , "Bird" );
List listC = List.of( "Elephant" , "Giraffe" , "Hippo" );

Boolean sameSize = this.sameSize( listA , listB , listC );
System.out.println( "sameSize = " + sameSize );
</code>```

See that code run live at IdeOne.com.

Stream & lambda

We could shorten that method by using stream and lambda syntax.

```<code>Boolean sameSize ( Collection... arguments )
{
    List< Integer > sizes = Arrays.stream( arguments ).map( collection -> collection.size() ).collect( Collectors.toList());
    return ( new TreeSet < Integer >( sizes ).size() == 1 );
}
</code>```

We could even shorten it to a one-liner.

```<code>Boolean sameSize ( Collection... arguments )
{
    return (
            new TreeSet < Integer >(
                    Arrays
                    .stream( arguments )
                    .map( collection -> collection.size() )
                    .collect( Collectors.toList() )
            ).size() == 1
    );
}
</code>```

Which means we could also use this one-liner directly, without putting in a named method. And doing so would make it a bit easier to pass our list arguments, as we no longer need to call size() on each list as we did in the code at top of this Answer.

```<code>Boolean sameSize = new TreeSet < Integer >(
        List
                .of( listA , listB , listC )  // ⬅ Your list variables go here.
                .stream()
                .map( collection -> collection.size() )
                .collect( Collectors.toList() )
).size() == 1;
</code>```

We could simplify further by using a Collector that makes a Set. No need to make a list and feed that into the constructor of a Set. The stream & lambda can feed our size results directly into a set.

```<code>Boolean sameSize =
        List
                .of( listA , listB , listC )  // ⬅ Your list variables go here.
                .stream()
                .map( collection -> collection.size() )
                .collect( Collectors.toSet() )
                .size() == 1;
</code>```

Body:
tl;dr

Use this one-liner, or wrap this in a method to be called.

List
.of( listA , listB , listC )              // ⬅ Your list variables go here.
.stream()
.map( collection -> collection.size() )
.collect( Collectors.toSet() )
.size()
== 1                                      // Returns `true` if your lists are all the same size. Returns `false` if different sizes.

Details

Set from a List of the lists’ sizes

Here is a one-liner.

if(
    new TreeSet< Integer > (
        List.of(
            listA.size() ,
            listB.size() ,
            listC.size()
        )
    )
    .size() == 1
)
{…}

We collect the sizes of each of the lists, putting the sizes into a Set< Integer >. Sets eliminate duplicates. So after adding all the sizes, we should have a single value in the set.

For example, if all the lists are the same size, with a count of seven elements, then we end up with a single element set, [ 7 ]. On the other hand, if some of the lists had seven elements, and some had eight, then the resulting set of list sizes would have two elements [ 7 , 8 ] rather than one element.

Complete example

Here is a complete example.

package work.basil.example

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class ListSizes
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List listA = List.of( "Dog" , "Cat" , "Rabbit" );
        List listB = List.of( "Dog" , "Cat" , "Bird" );
        List listC = List.of( "Elephant" , "Giraffe" , "Hippo" );

        if(
            new TreeSet< Integer > (
                List.of(
                    listA.size() ,
                    listB.size() ,
                    listC.size()
                )
            )
            .size() == 1
        )
        { System.out.println( "Same size." ) ; }
        else
        { System.out.println( "Different sizes." ) ; }

    }
}

See that code run live at IdeOne.com. You can fork that code within IdeOne.com to try deleting or adding items to any of the lists.

Same size.

By the way, you might notice how autoboxing has kicked-in, converting the int primitive returns by List::size into an Integer object to be passed into the List.of method call. I am a bit surprised that worked without needing to wrap the List::size calls in Integer.valueOf call.

Make a method, passing your collections whose sizes need comparing

We could put this code in a method. Use the varargs feature of Java, you would pass any number of Collection objects. Their sizes would then be compared.

Boolean sameSize ( Collection... arguments )
{
    List < Integer > sizes = new ArrayList <>( arguments.length );
    for ( Collection collection : arguments )
    {
        sizes.add( collection.size() );
    }
    return ( new TreeSet < Integer >( sizes ).size() == 1 );
}

Let's try using the method.

List listA = List.of( "Dog" , "Cat" );
List listB = List.of( "Dog" , "Cat" , "Bird" );
List listC = List.of( "Elephant" , "Giraffe" , "Hippo" );

Boolean sameSize = this.sameSize( listA , listB , listC );
System.out.println( "sameSize = " + sameSize );

See that code run live at IdeOne.com.

Stream & lambda

We could shorten that method by using stream and lambda syntax.

Boolean sameSize ( Collection... arguments )
{
    List< Integer > sizes = Arrays.stream( arguments ).map( collection -> collection.size() ).collect( Collectors.toList());
    return ( new TreeSet < Integer >( sizes ).size() == 1 );
}

We could even shorten it to a one-liner.

Boolean sameSize ( Collection... arguments )
{
    return (
            new TreeSet < Integer >(
                    Arrays
                    .stream( arguments )
                    .map( collection -> collection.size() )
                    .collect( Collectors.toList() )
            ).size() == 1
    );
}

Which means we could also use this one-liner directly, without putting in a named method. And doing so would make it a bit easier to pass our list arguments, as we no longer need to call size() on each list as we did in the code at top of this Answer.

Boolean sameSize = new TreeSet < Integer >(
        List
                .of( listA , listB , listC )  // ⬅ Your list variables go here.
                .stream()
                .map( collection -> collection.size() )
                .collect( Collectors.toList() )
).size() == 1;

We could simplify further by using a Collector that makes a Set. No need to make a list and feed that into the constructor of a Set. The stream & lambda can feed our size results directly into a set.

Boolean sameSize =
        List
                .of( listA , listB , listC )  // ⬅ Your list variables go here.
                .stream()
                .map( collection -> collection.size() )
                .collect( Collectors.toSet() )
                .size() == 1;


问:
Mapping A simple XSD userdefined simple type to A .net class
I have a XSD I generated using xsd.exe and then created a class off the the xsd.  Everything worked great but some of the elements have common business rules.  For example all of the amounts in our xml are expressed without the decimal so 3.94$ becomes 394.  I have created a xml simple type to represent all of the attributes that are defined in this way, but haven't figured out how to map the xsd type to a .net class that can handle the business logic of how the data has to be stored in the xml.  I have created complex types before but not simple types that are used in attributes can some one point me in the right directory

A very Simplified XML snip it

```<code><Check amt="356" >
   <LNItem amt="123" />
   <LNItem amt="223" />
</Check>
</code>```

I would like a class like the following.

```<code>[XmlType(Check)]
public
{
    AmtType Amt {get;set}

}
</code>```

答:
You'd have to do something like this:

```<code>partial class Check
{
    internal const decimal ScaleFactor = 0.01m;

    private decimal amount;

    [XmlAttribute("Amt")]
    public decimal XmlAmount
    {
        get { return decimal.Round(amount / ScaleFactor); }
        set { amount = value * ScaleFactor; }
    }

    [XmlIgnore]
    public decimal Amount
    {
        get { return amount; }
        set { amount = value; }
    }
}
</code>```

Note that dividing a decimal by a scale factor less than zero is significant: it removes the decimal places from the decimal representation, while multiplying by its reciprocal will not.  In other words:

```<code>Console.WriteLine(3.94m / 0.01m); // prints "394"
Console.WriteLine(3.94m * 100m);  // prints "394.00"
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a XSD I generated using xsd.exe and then created a class off the the xsd.  Everything worked great but some of the elements have common business rules.  For example all of the amounts in our xml are expressed without the decimal so 3.94$ becomes 394.  I have created a xml simple type to represent all of the attributes that are defined in this way, but haven't figured out how to map the xsd type to a .net class that can handle the business logic of how the data has to be stored in the xml.  I have created complex types before but not simple types that are used in attributes can some one point me in the right directory

A very Simplified XML snip it

<Check amt="356" >
   <LNItem amt="123" />
   <LNItem amt="223" />
</Check>

I would like a class like the following.

[XmlType(Check)]
public
{
    AmtType Amt {get;set}

}

Body:
You'd have to do something like this:

partial class Check
{
    internal const decimal ScaleFactor = 0.01m;

    private decimal amount;

    [XmlAttribute("Amt")]
    public decimal XmlAmount
    {
        get { return decimal.Round(amount / ScaleFactor); }
        set { amount = value * ScaleFactor; }
    }

    [XmlIgnore]
    public decimal Amount
    {
        get { return amount; }
        set { amount = value; }
    }
}

Note that dividing a decimal by a scale factor less than zero is significant: it removes the decimal places from the decimal representation, while multiplying by its reciprocal will not.  In other words:

Console.WriteLine(3.94m / 0.01m); // prints "394"
Console.WriteLine(3.94m * 100m);  // prints "394.00"


问:
Why HATEOAS starts creating issue for spring-boot version >= 2.2.x during startup with Swagger 2.x?
I moved my project from spring-boot 2.1.9 to 2.2.0.

While starting the project, I am facing the below error messages.

```<code>Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry<org.springframework.hateoas.client.LinkDiscoverer, org.springframework.http.MediaType>' available: expected single matching bean but found 17: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,syntheticModelProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,apiListingScannerPluginRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'linkDiscoverers' defined in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]: Unsatisfied dependency expressed through method 'linkDiscoverers' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry<org.springframework.hateoas.client.LinkDiscoverer, org.springframework.http.MediaType>' available: expected single matching bean but found 17: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,syntheticModelProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,apiListingScannerPluginRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration
required a single bean, but 17 were found:
- modelBuilderPluginRegistry: defined in null
- modelPropertyBuilderPluginRegistry: defined in null
- typeNameProviderPluginRegistry: defined in null
- syntheticModelProviderPluginRegistry: defined in null
- documentationPluginRegistry: defined in null
- apiListingBuilderPluginRegistry: defined in null
- operationBuilderPluginRegistry: defined in null
- parameterBuilderPluginRegistry: defined in null
- expandedParameterBuilderPluginRegistry: defined in null
- resourceGroupingStrategyRegistry: defined in null
- operationModelsProviderPluginRegistry: defined in null
- defaultsProviderPluginRegistry: defined in null
- pathDecoratorRegistry: defined in null
- apiListingScannerPluginRegistry: defined in null
- relProviderPluginRegistry: defined by method 'relProviderPluginRegistry' in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]
- linkDiscovererRegistry: defined in null
- entityLinksPluginRegistry: defined by method 'entityLinksPluginRegistry' in class path resource [org/springframework/hateoas/config/WebMvcEntityLinksConfiguration.class]
</code>```

What could have caused this issue ?

Note: I am not using HATEOAS in my pom.xml file.

pom.xml

```<code><properties>
    <java.version>1.8</java.version>
    <swagger-springfox.version>2.9.2</swagger-springfox.version>
    <sonar.jacoco.execPath>${project.basedir}/target/jacoco.exec</sonar.jacoco.execPath>
    <jasypt-spring-boot-starter>2.1.1</jasypt-spring-boot-starter>
    <logbook-spring-boot-starter>1.13.0</logbook-spring-boot-starter>
    <assertj-swagger>0.8.1</assertj-swagger>
    <jacoco-version>0.8.4</jacoco-version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-spring-web</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-core</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
</code>```

答:
Resolved it, it was happening due to integration when Swagger + HATEOAS was used with Spring Boot 2.2.4.RELEASE

```<code>package com.company.springbootworks.swagger;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.hateoas.client.LinkDiscoverer;
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.hateoas.mediatype.collectionjson.CollectionJsonLinkDiscoverer;
import org.springframework.http.ResponseEntity;
import org.springframework.plugin.core.SimplePluginRegistry;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.DocExpansion;
import springfox.documentation.swagger.web.ModelRendering;
import springfox.documentation.swagger.web.OperationsSorter;
import springfox.documentation.swagger.web.TagsSorter;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public LinkDiscoverers discoverers() {
        List<LinkDiscoverer> plugins = new ArrayList<>();
        plugins.add(new CollectionJsonLinkDiscoverer());
        return new LinkDiscoverers(SimplePluginRegistry.create(plugins));

    }

    @Bean
    public Docket eDesignApi(SwaggerConfigProperties swaggerConfigProperties) {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo(swaggerConfigProperties))
                .enable(Boolean.valueOf(swaggerConfigProperties.getEnabled())).select()
                .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build().pathMapping("/")
                .directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(Boolean.valueOf(swaggerConfigProperties.getUseDefaultResponseMessages()))
                .enableUrlTemplating(Boolean.valueOf(swaggerConfigProperties.getEnableUrlTemplating()));
    }

    @Bean
    UiConfiguration uiConfig(SwaggerConfigProperties swaggerConfigProperties) {
        return UiConfigurationBuilder.builder().deepLinking(Boolean.valueOf(swaggerConfigProperties.getDeepLinking()))
                .displayOperationId(Boolean.valueOf(swaggerConfigProperties.getDisplayOperationId()))
                .defaultModelsExpandDepth(Integer.valueOf(swaggerConfigProperties.getDefaultModelsExpandDepth()))
                .defaultModelExpandDepth(Integer.valueOf(swaggerConfigProperties.getDefaultModelExpandDepth()))
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(Boolean.valueOf(swaggerConfigProperties.getDisplayRequestDuration()))
                .docExpansion(DocExpansion.NONE).filter(Boolean.valueOf(swaggerConfigProperties.getFilter()))
                .maxDisplayedTags(Integer.valueOf(swaggerConfigProperties.getMaxDisplayedTags()))
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(Boolean.valueOf(swaggerConfigProperties.getShowExtensions()))
                .tagsSorter(TagsSorter.ALPHA).supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
                .validatorUrl(null).build();
    }

    private ApiInfo apiInfo(SwaggerConfigProperties swaggerConfigProperties) {
        return new ApiInfoBuilder().title(swaggerConfigProperties.getTitle())
                .description(swaggerConfigProperties.getDescription()).version(swaggerConfigProperties.getApiVersion())
                .build();
    }
}
</code>```

and below are the swagger dependencies

```<code><properties>
    <java.version>1.8</java.version>
    <swagger.version>2.9.2</swagger.version>
    <swagger-annotations.version>1.5.21</swagger-annotations.version>
    <swagger-models.version>1.5.21</swagger-models.version>
    <spring-plugin.version>2.0.0.BUILD-SNAPSHOT</spring-plugin.version>
</properties>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>${swagger-annotations.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>${swagger-models.version}</version>
</dependency>
</code>```

Body:
I moved my project from spring-boot 2.1.9 to 2.2.0.

While starting the project, I am facing the below error messages.

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry<org.springframework.hateoas.client.LinkDiscoverer, org.springframework.http.MediaType>' available: expected single matching bean but found 17: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,syntheticModelProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,apiListingScannerPluginRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'linkDiscoverers' defined in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]: Unsatisfied dependency expressed through method 'linkDiscoverers' parameter 0; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.springframework.plugin.core.PluginRegistry<org.springframework.hateoas.client.LinkDiscoverer, org.springframework.http.MediaType>' available: expected single matching bean but found 17: modelBuilderPluginRegistry,modelPropertyBuilderPluginRegistry,typeNameProviderPluginRegistry,syntheticModelProviderPluginRegistry,documentationPluginRegistry,apiListingBuilderPluginRegistry,operationBuilderPluginRegistry,parameterBuilderPluginRegistry,expandedParameterBuilderPluginRegistry,resourceGroupingStrategyRegistry,operationModelsProviderPluginRegistry,defaultsProviderPluginRegistry,pathDecoratorRegistry,apiListingScannerPluginRegistry,relProviderPluginRegistry,linkDiscovererRegistry,entityLinksPluginRegistry

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of method linkDiscoverers in org.springframework.hateoas.config.HateoasConfiguration
required a single bean, but 17 were found:
- modelBuilderPluginRegistry: defined in null
- modelPropertyBuilderPluginRegistry: defined in null
- typeNameProviderPluginRegistry: defined in null
- syntheticModelProviderPluginRegistry: defined in null
- documentationPluginRegistry: defined in null
- apiListingBuilderPluginRegistry: defined in null
- operationBuilderPluginRegistry: defined in null
- parameterBuilderPluginRegistry: defined in null
- expandedParameterBuilderPluginRegistry: defined in null
- resourceGroupingStrategyRegistry: defined in null
- operationModelsProviderPluginRegistry: defined in null
- defaultsProviderPluginRegistry: defined in null
- pathDecoratorRegistry: defined in null
- apiListingScannerPluginRegistry: defined in null
- relProviderPluginRegistry: defined by method 'relProviderPluginRegistry' in class path resource [org/springframework/hateoas/config/HateoasConfiguration.class]
- linkDiscovererRegistry: defined in null
- entityLinksPluginRegistry: defined by method 'entityLinksPluginRegistry' in class path resource [org/springframework/hateoas/config/WebMvcEntityLinksConfiguration.class]

What could have caused this issue ?

Note: I am not using HATEOAS in my pom.xml file.

pom.xml

<properties>
    <java.version>1.8</java.version>
    <swagger-springfox.version>2.9.2</swagger-springfox.version>
    <sonar.jacoco.execPath>${project.basedir}/target/jacoco.exec</sonar.jacoco.execPath>
    <jasypt-spring-boot-starter>2.1.1</jasypt-spring-boot-starter>
    <logbook-spring-boot-starter>1.13.0</logbook-spring-boot-starter>
    <assertj-swagger>0.8.1</assertj-swagger>
    <jacoco-version>0.8.4</jacoco-version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-spring-web</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-core</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-data-rest</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-bean-validators</artifactId>
        <version>${swagger-springfox.version}</version>
    </dependency>

Body:
Resolved it, it was happening due to integration when Swagger + HATEOAS was used with Spring Boot 2.2.4.RELEASE

package com.company.springbootworks.swagger;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.hateoas.client.LinkDiscoverer;
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.hateoas.mediatype.collectionjson.CollectionJsonLinkDiscoverer;
import org.springframework.http.ResponseEntity;
import org.springframework.plugin.core.SimplePluginRegistry;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.DocExpansion;
import springfox.documentation.swagger.web.ModelRendering;
import springfox.documentation.swagger.web.OperationsSorter;
import springfox.documentation.swagger.web.TagsSorter;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public LinkDiscoverers discoverers() {
        List<LinkDiscoverer> plugins = new ArrayList<>();
        plugins.add(new CollectionJsonLinkDiscoverer());
        return new LinkDiscoverers(SimplePluginRegistry.create(plugins));

    }

    @Bean
    public Docket eDesignApi(SwaggerConfigProperties swaggerConfigProperties) {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo(swaggerConfigProperties))
                .enable(Boolean.valueOf(swaggerConfigProperties.getEnabled())).select()
                .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build().pathMapping("/")
                .directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class)
                .useDefaultResponseMessages(Boolean.valueOf(swaggerConfigProperties.getUseDefaultResponseMessages()))
                .enableUrlTemplating(Boolean.valueOf(swaggerConfigProperties.getEnableUrlTemplating()));
    }

    @Bean
    UiConfiguration uiConfig(SwaggerConfigProperties swaggerConfigProperties) {
        return UiConfigurationBuilder.builder().deepLinking(Boolean.valueOf(swaggerConfigProperties.getDeepLinking()))
                .displayOperationId(Boolean.valueOf(swaggerConfigProperties.getDisplayOperationId()))
                .defaultModelsExpandDepth(Integer.valueOf(swaggerConfigProperties.getDefaultModelsExpandDepth()))
                .defaultModelExpandDepth(Integer.valueOf(swaggerConfigProperties.getDefaultModelExpandDepth()))
                .defaultModelRendering(ModelRendering.EXAMPLE)
                .displayRequestDuration(Boolean.valueOf(swaggerConfigProperties.getDisplayRequestDuration()))
                .docExpansion(DocExpansion.NONE).filter(Boolean.valueOf(swaggerConfigProperties.getFilter()))
                .maxDisplayedTags(Integer.valueOf(swaggerConfigProperties.getMaxDisplayedTags()))
                .operationsSorter(OperationsSorter.ALPHA)
                .showExtensions(Boolean.valueOf(swaggerConfigProperties.getShowExtensions()))
                .tagsSorter(TagsSorter.ALPHA).supportedSubmitMethods(UiConfiguration.Constants.DEFAULT_SUBMIT_METHODS)
                .validatorUrl(null).build();
    }

    private ApiInfo apiInfo(SwaggerConfigProperties swaggerConfigProperties) {
        return new ApiInfoBuilder().title(swaggerConfigProperties.getTitle())
                .description(swaggerConfigProperties.getDescription()).version(swaggerConfigProperties.getApiVersion())
                .build();
    }
}

and below are the swagger dependencies

<properties>
    <java.version>1.8</java.version>
    <swagger.version>2.9.2</swagger.version>
    <swagger-annotations.version>1.5.21</swagger-annotations.version>
    <swagger-models.version>1.5.21</swagger-models.version>
    <spring-plugin.version>2.0.0.BUILD-SNAPSHOT</spring-plugin.version>
</properties>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>${swagger.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-annotations</artifactId>
    <version>${swagger-annotations.version}</version>
</dependency>
<dependency>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-models</artifactId>
    <version>${swagger-models.version}</version>
</dependency>


问:
Running external JS within a PHP webpage
I have created a PHP version of my webpage, and it finds my external css just fine.  However, I cannot get it to load the external JS code and I can't figure out why that is.  I am using WinSCP to connect to a server.

I know that PHP is server-side, and technically, the JS is also on the server right?  In my code, I link the css down to the root folder, and it comes back in the PHP version of the webpage.  But JS won't.  I have searched for quite some time on how to make this work, and perhaps it doesn't.

```<code><?php
 $path = $_SERVER['DOCUMENT_ROOT'];
 $header= $path."/includes/header.php";
 include ($header);
 $menu= $path."/includes/menu.php";
 include ($menu);
 $footer= $path."/includes/footer.php";
 include ($footer);

?>
<html>
    <head>
        <title>My Profile</title>
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="../css/mycss.css" rel="stylesheet" type="text/css"/>
        <script src="../js/myjs.js" type="text/javascript"></script>

    </head>

</code>```

答:
It should be working. Load the php script in a browser. Right click, Inspectand go to Console. (But I guess you should know how to go to the console already.)

If it mention anything about a 404, the file doesn't exist or you're not putting the correct url in the src="".

If it's not, please comment the error in the console. If there isn't any, the script was loaded, but you don't realize it somehow.

Edit: Also, maybe your mime type is wrong, if the above doesn't work, try replacing type="text/javascript" to type="application/javascript".

Body:
I have created a PHP version of my webpage, and it finds my external css just fine.  However, I cannot get it to load the external JS code and I can't figure out why that is.  I am using WinSCP to connect to a server.

I know that PHP is server-side, and technically, the JS is also on the server right?  In my code, I link the css down to the root folder, and it comes back in the PHP version of the webpage.  But JS won't.  I have searched for quite some time on how to make this work, and perhaps it doesn't.

<?php
 $path = $_SERVER['DOCUMENT_ROOT'];
 $header= $path."/includes/header.php";
 include ($header);
 $menu= $path."/includes/menu.php";
 include ($menu);
 $footer= $path."/includes/footer.php";
 include ($footer);

?>

        <title>My Profile</title>
        <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="../css/mycss.css" rel="stylesheet" type="text/css"/>


问:
Perl array vs list
I have two data structures in Perl:

An array:

```<code>my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}
</code>```

Giving me the following output:

```<code>1
2
3
</code>```

And a list:

```<code>my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}
</code>```

Giving the following output:

```<code>ARRAY(0x9c90818)
</code>```

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

答:
If you want more clarification, see the relevant documentation.

You could try and do some things for illustration purposes:

```<code>#!perl -lw # -l appends a \n to each print, -w enables warnings
use strict;
my $aryref = [1 .. 5];
print for $aryref;    # Prints the stringified reference - not what you want
print for @$aryref;   # Dereferencing it lets you access the array
my @ary = $aryref;    # Probably not what you want
print for @ary;       # Stringified reference again
print for @{$ary[0]}; # Dereference the first array element (which holds the ref)
</code>```

Title: Perl array vs list

Body:
I have two data structures in Perl:

An array:

my @array2 = ( "1", "2", "3");

for $elem (@array2) {
    print $elem."\n";
}

Giving me the following output:

1
2
3

And a list:

my @array = [ "1", "2", "3"];

for $elem (@array) {
    print $elem."\n";
}

Giving the following output:

ARRAY(0x9c90818)

Obviously, I'd like to iterate over the elements in both cases, but why does the second solution give me only the reference to this array?

Body:
If you want more clarification, see the relevant documentation.

You could try and do some things for illustration purposes:

#!perl -lw # -l appends a \n to each print, -w enables warnings
use strict;
my $aryref = [1 .. 5];
print for $aryref;    # Prints the stringified reference - not what you want
print for @$aryref;   # Dereferencing it lets you access the array
my @ary = $aryref;    # Probably not what you want
print for @ary;       # Stringified reference again
print for @{$ary[0]}; # Dereference the first array element (which holds the ref)


问:
My access VBA code for creating excel files with data connections works on the first file then always fails at random points
I have written some code in Access to copy an excel template file, perform some refresh and simple transsformations on the copy, save, and then move to the next file.  Initially i could create multiple files by looping through a list but kept getting odd errors on random lines during subsequent iterations.  I've avoided Active anything as that seems to be problematic, but still the code fails on the second iteration.  Mostly its on the Connection.Refresh but sometimes it is other lines such as "Method Rows of object Global failed".  I'm fairly experienced on this.  I also tried setting all my vba excel objects to nothing at the end of each loop but that didnt help.  Code below.  Any ideas gratefully recieved:</p>

```<code>Sub CreateFilesIndividual()

     Dim mw As Variant
     Dim ccount As Integer
     Dim rs As Recordset
     Dim i As Integer

     Set rs = CurrentDb.OpenRecordset("SELECT CM1920 as CM from Comm1920 order by rscount desc", dbOpenSnapshot)
     If rs.RecordCount = 0 Then
         MsgBox "No Commissioners Codes available - exiting"
         Exit Sub
     End If

     For i = 1 To rs.RecordCount
         CreateFile rs("CM")
     Next

End Sub

Sub CreateFile(commCode)

     Dim templateloc As String
     Dim fileloc As String
     Dim Xl As Excel.Application
     Dim wb As Excel.Workbook
     Dim ws As Excel.Worksheet
     Dim ws2 As Excel.Worksheet
     Dim ws3 As Excel.Worksheet
     Dim ws4 As Excel.Worksheet

     templateloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\Proposal template CCGs 2021 v2.6.xlsm"
     fileloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\test\Proposal CCGs 1920 v2.6 " & commCode & ".xlsm"

     FileCopy templateloc, fileloc
    '
     Set Xl = CreateObject("Excel.Application")
     Set wb = Xl.Workbooks.Open(fileloc)
     Set ws = wb.Sheets("Commissioner Summary")
     ws.Unprotect
     ws.Cells(2, 4) = commCode.Value
     Debug.Print ws.Cells(2, 4).Value & " - " & commCode.Value
     wb.Connections("Update1").Refresh
     Set ws2 = wb.Sheets("Contract Category Detail")
     ws2.Range("A:AM").Copy

     Set ws3 = wb.Sheets("CC detail")
     ws3.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
     ws3.Range("A1").PasteSpecial Paste:=xlPasteFormats
     ws3.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws3.Range("AG3").FormulaR1C1 = "=ROUND(RC[-2]+RC[-1],0)"
    Dim myrange As Integer
    myrange = ws3.Range("A" & Rows.Count).End(xlUp).Row
    ws3.Range("AG3:AG" & myrange).FillDown

    ws3.Range("AL3").FormulaR1C1 = "=RC[-5]*RC34"
    ws3.Range("AL3:AL" & myrange).FillDown
    ws3.Range("A:AM").Copy

    Set ws4 = wb.Sheets("Contract_Category_detail")
    ws4.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    ws4.Range("A1").PasteSpecial Paste:=xlPasteFormats
    ws4.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws2.Delete
    ws3.Delete

    wb.Save
    wb.Close

    'Clean up
    Xl.Quit
    Set ws = Nothing
    Set ws2 = Nothing
    Set ws3 = Nothing
    Set ws4 = Nothing
    Set wb = Nothing
    Set Xl = Nothing

End Sub
</code>```

答: Just curious...when was the last time you rebooted your machine.  It's been a while since I've done anything major with VBA, but as I recall, sometimes I would get weird, and inexplicable, errors just like you described.  I traced the errors to control breaks; when you stop VBA code by simultaneously hitting Ctrl+Break keys.  After a while, the control breaks would build up, and it would cause all kinds of bizarre issues.  Simply rebooting the machine fixed everything.  Try that and feed back with your findings.</p>

Body:
I have written some code in Access to copy an excel template file, perform some refresh and simple transsformations on the copy, save, and then move to the next file.  Initially i could create multiple files by looping through a list but kept getting odd errors on random lines during subsequent iterations.  I've avoided Active anything as that seems to be problematic, but still the code fails on the second iteration.  Mostly its on the Connection.Refresh but sometimes it is other lines such as "Method Rows of object Global failed".  I'm fairly experienced on this.  I also tried setting all my vba excel objects to nothing at the end of each loop but that didnt help.  Code below.  Any ideas gratefully recieved:

Sub CreateFilesIndividual()

     Dim mw As Variant
     Dim ccount As Integer
     Dim rs As Recordset
     Dim i As Integer

     Set rs = CurrentDb.OpenRecordset("SELECT CM1920 as CM from Comm1920 order by rscount desc", dbOpenSnapshot)
     If rs.RecordCount = 0 Then
         MsgBox "No Commissioners Codes available - exiting"
         Exit Sub
     End If

     For i = 1 To rs.RecordCount
         CreateFile rs("CM")
     Next

End Sub

Sub CreateFile(commCode)

     Dim templateloc As String
     Dim fileloc As String
     Dim Xl As Excel.Application
     Dim wb As Excel.Workbook
     Dim ws As Excel.Worksheet
     Dim ws2 As Excel.Worksheet
     Dim ws3 As Excel.Worksheet
     Dim ws4 As Excel.Worksheet

     templateloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\Proposal template CCGs 2021 v2.6.xlsm"
     fileloc = "\\gstt.local\Users\01\MWaring\Documents\Bespoke Report Requests\Contracts automation\test\Proposal CCGs 1920 v2.6 " & commCode & ".xlsm"

     FileCopy templateloc, fileloc
    '
     Set Xl = CreateObject("Excel.Application")
     Set wb = Xl.Workbooks.Open(fileloc)
     Set ws = wb.Sheets("Commissioner Summary")
     ws.Unprotect
     ws.Cells(2, 4) = commCode.Value
     Debug.Print ws.Cells(2, 4).Value & " - " & commCode.Value
     wb.Connections("Update1").Refresh
     Set ws2 = wb.Sheets("Contract Category Detail")
     ws2.Range("A:AM").Copy

     Set ws3 = wb.Sheets("CC detail")
     ws3.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
     ws3.Range("A1").PasteSpecial Paste:=xlPasteFormats
     ws3.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws3.Range("AG3").FormulaR1C1 = "=ROUND(RC[-2]+RC[-1],0)"
    Dim myrange As Integer
    myrange = ws3.Range("A" & Rows.Count).End(xlUp).Row
    ws3.Range("AG3:AG" & myrange).FillDown

    ws3.Range("AL3").FormulaR1C1 = "=RC[-5]*RC34"
    ws3.Range("AL3:AL" & myrange).FillDown
    ws3.Range("A:AM").Copy

    Set ws4 = wb.Sheets("Contract_Category_detail")
    ws4.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
    ws4.Range("A1").PasteSpecial Paste:=xlPasteFormats
    ws4.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False

    ws2.Delete
    ws3.Delete

    wb.Save
    wb.Close

    'Clean up
    Xl.Quit
    Set ws = Nothing
    Set ws2 = Nothing
    Set ws3 = Nothing
    Set ws4 = Nothing
    Set wb = Nothing
    Set Xl = Nothing

End Sub


问:
React setState with arrays , how to auto create an array id without construct
I'm trying to setState from firebase which respond from node and create  with google-maps-react like this

{maskprop.map(({ ................. }, index) => (
          <Marker
            onClick={this.onMarkerClick}
            name={name}
            position={{lat, lng}}
            key={index}
          />
))}
```

<p>So i want to save the result in a state array.</p>

<p>The response data which i get from node:</p>

<pre class="lang-json prettyprint-override"><code>    {
    "2303240013": {
        "address": "臺中市西區民權路105號",
        "county": "臺中市",
        "location": {
            "lat": 120.675929,
            "lng": 24.141144
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市中西區衛生所",
        "phone": "04 -22223811",
        "town": "西區",
        "updated": ""
    },
    "2317020010": {
        "address": "臺中市東區信義街142號",
        "county": "臺中市",
        "location": {
            "lat": 120.687798,
            "lng": 24.13337
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市東區衛生所",
        "phone": "04 -22834121",
        "town": "東區",
        "updated": ""
    }
}
</code>```

and i want to setState like below

    0:
    address: "address1"
    county: "county1"
    location: {lat: 120.888455, lng: 24.173788}
    mask_adult: 0
    mask_child: 100
    name: "name1"
    phone: "phone1"
    town: "town1"
    updated: "2020/02/14 22:59:03"
    1:
    address: "address2"
    county: "county2"
    location: {lat: 120.888455, lng: 24.173788}
    mask_adult: 0
    mask_child: 100
    name: "name2"
    phone: "phone2"
    town: "town2"
    updated: "2020/02/14 22:59:03"
```

<p>This is my code now, it can only get the last state which i set for <code>maskprop</code>.
Can someone introduce the way to create index for the arrays?</p>

<pre class="lang-js prettyprint-override"><code>async getfirebasedata(){
    const response = await axios.post(
      'http://127.0.0.1:9000/hello',
      { county: '臺中市' },
      { headers: { 'Content-Type': 'application/json' } }
    )
    //console.log(response.data);
    var getdata = response.data;
    var item;
    for(item in getdata){
      //console.log(getdata[item].address);
      this.setState({
        maskprop:[
        {
          address: getdata[item].address,
          county: getdata[item].county,
          location: getdata[item].location,
          mask_adult: getdata[item].mask_adult,
          mask_child: getdata[item].mask_child,
          name: getdata[item].name,
          phone: getdata[item].phone,
          town: getdata[item].town,
          updated: getdata[item].updated,
        }],
      })
    }

    console.log(this.state.maskprop);
  }
</code>```

Or any other ways to create multiple  ?

答:
Use Object.keys and .map() to convert the object to array,

const data = {
    "2303240013": {
        "address": "臺中市西區民權路105號",
        "county": "臺中市",
        "location": {
            "lat": 120.675929,
            "lng": 24.141144
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市中西區衛生所",
        "phone": "04 -22223811",
        "town": "西區",
        "updated": ""
    },
    "2317020010": {
        "address": "臺中市東區信義街142號",
        "county": "臺中市",
        "location": {
            "lat": 120.687798,
            "lng": 24.13337
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市東區衛生所",
        "phone": "04 -22834121",
        "town": "東區",
        "updated": ""
    }
}

const array = Object.keys(data).map(key => data[key]);

console.log(array)```
</div>
</div>
</p>

```async getfirebasedata() {
  const response = await axios.post(
    "http://127.0.0.1:9000/hello",
    { county: "臺中市" },
    { headers: { "Content-Type": "application/json" } }
  );
  //console.log(response.data);
  const getData = response.data;
  const data = Object.keys(getData).map(key => getData[key]);

  this.setState({
    maskprop: data
  }, () => console.log(this.state.maskprop));
}
```

Body:
I'm trying to setState from firebase which respond from node and create  with google-maps-react like this

{maskprop.map(({ ................. }, index) => (
          <Marker
            onClick={this.onMarkerClick}
            name={name}
            position={{lat, lng}}
            key={index}
          />
))}

So i want to save the result in a state array.

The response data which i get from node:

    {
    "2303240013": {
        "address": "臺中市西區民權路105號",
        "county": "臺中市",
        "location": {
            "lat": 120.675929,
            "lng": 24.141144
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市中西區衛生所",
        "phone": "04 -22223811",
        "town": "西區",
        "updated": ""
    },
    "2317020010": {
        "address": "臺中市東區信義街142號",
        "county": "臺中市",
        "location": {
            "lat": 120.687798,
            "lng": 24.13337
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市東區衛生所",
        "phone": "04 -22834121",
        "town": "東區",
        "updated": ""
    }
}

and i want to setState like below

    0:
    address: "address1"
    county: "county1"
    location: {lat: 120.888455, lng: 24.173788}
    mask_adult: 0
    mask_child: 100
    name: "name1"
    phone: "phone1"
    town: "town1"
    updated: "2020/02/14 22:59:03"
    1:
    address: "address2"
    county: "county2"
    location: {lat: 120.888455, lng: 24.173788}
    mask_adult: 0
    mask_child: 100
    name: "name2"
    phone: "phone2"
    town: "town2"
    updated: "2020/02/14 22:59:03"

This is my code now, it can only get the last state which i set for maskprop.
Can someone introduce the way to create index for the arrays?

async getfirebasedata(){
    const response = await axios.post(
      'http://127.0.0.1:9000/hello',
      { county: '臺中市' },
      { headers: { 'Content-Type': 'application/json' } }
    )
    //console.log(response.data);
    var getdata = response.data;
    var item;
    for(item in getdata){
      //console.log(getdata[item].address);
      this.setState({
        maskprop:[
        {
          address: getdata[item].address,
          county: getdata[item].county,
          location: getdata[item].location,
          mask_adult: getdata[item].mask_adult,
          mask_child: getdata[item].mask_child,
          name: getdata[item].name,
          phone: getdata[item].phone,
          town: getdata[item].town,
          updated: getdata[item].updated,
        }],
      })
    }

    console.log(this.state.maskprop);
  }

Or any other ways to create multiple  ?

Body:
Use Object.keys and .map() to convert the object to array,

const data = {
    "2303240013": {
        "address": "臺中市西區民權路105號",
        "county": "臺中市",
        "location": {
            "lat": 120.675929,
            "lng": 24.141144
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市中西區衛生所",
        "phone": "04 -22223811",
        "town": "西區",
        "updated": ""
    },
    "2317020010": {
        "address": "臺中市東區信義街142號",
        "county": "臺中市",
        "location": {
            "lat": 120.687798,
            "lng": 24.13337
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市東區衛生所",
        "phone": "04 -22834121",
        "town": "東區",
        "updated": ""
    }
}

const array = Object.keys(data).map(key => data[key]);

console.log(array)

async getfirebasedata() {
  const response = await axios.post(
    "http://127.0.0.1:9000/hello",
    { county: "臺中市" },
    { headers: { "Content-Type": "application/json" } }
  );
  //console.log(response.data);
  const getData = response.data;
  const data = Object.keys(getData).map(key => getData[key]);

  this.setState({
    maskprop: data
  }, () => console.log(this.state.maskprop));
}


问:
Sending a 301/302 redirect from a Python CGI script
I keep finding answers on how to read a redirect from an HTTP client response out of Python, but I can't figure out how to send a 301 or 302 redirect back to the client.  Seems this should work, but I always get a 200 response before the body:

```<code>print("Content-Type: text/html; charset=UTF-8\n")
print("HTTP/1.1 301 Moved Permanently")
print("Location:", "https://www.google.com/")
</code>```

The equivalent PHP code would simply be:

```<code>// Redirect the browser to Google
header("Location: https://www.google.com/", true, 301);
</code>```

答:
In it's simplest form, with no external libraries, you can simply output straight HTTP:

```<code>print('''Status: 301 Redirect
Location: {url}
Content-Type: text/html

Moved permanently to <a href="{url}">{url}</a>
'''.format(url='https://www.google.com/'))
</code>```

If you are using a library or framework there are likely better approaches.

Body:
I keep finding answers on how to read a redirect from an HTTP client response out of Python, but I can't figure out how to send a 301 or 302 redirect back to the client.  Seems this should work, but I always get a 200 response before the body:

print("Content-Type: text/html; charset=UTF-8\n")
print("HTTP/1.1 301 Moved Permanently")
print("Location:", "https://www.google.com/")

The equivalent PHP code would simply be:

// Redirect the browser to Google
header("Location: https://www.google.com/", true, 301);

Body:
In it's simplest form, with no external libraries, you can simply output straight HTTP:

print('''Status: 301 Redirect
Location: {url}
Content-Type: text/html

Moved permanently to <a href="{url}">{url}</a>
'''.format(url='https://www.google.com/'))

If you are using a library or framework there are likely better approaches.


问:
How to connect to arduino and view services within android app?
I am currently using an Arduino Nano 33 BLE to calculate an angle measurement from an IMU and add these values to a Bluetooth characteristic within a service. I create the service and characteristic using the ArduinoBLE library:

```<code>BLEService angleService("1826");
BLEFloatCharacteristic rollBLE("2A57", BLERead | BLENotify);
</code>```

Within my setup, I set the device's name, service, and characteristic. I initially write a value of 0 to the characteristic:

```<code>BLE.setLocalName("acsAssist");
BLE.setAdvertisedService(angleService);
angleService.addCharacteristic(rollBLE);
BLE.addService(angleService);
rollBLE.writeValue(0);
BLE.advertise();
</code>```

Within my loop, after I perform my calculation, I change the value of the characteristic accordingly:

```<code>rollBLE.writeValue(posiRoll);            // posiRoll is my calculation
</code>```

When I use a third party app like nrfConnect on my Android device, I am able to find my device and connect to it. The service and characteristic I defined is present and the value is changing as expected:

Here is the output from the nrfConnect app

Now, I am attempting to manually connect to this device within the Android app that I'm building so that I can display this changing value on the screen for the user to see. I include all of the following permissions in my Manifest:

```<code><uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</code>```

I begin by checking that the device the user is using has a bluetooth adapter, and that it is on:

```<code>        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {                     // Bluetooth not supported
            Toast.makeText(getActivity(), "This device does not support Bluetooth! Use a Bluetooth enabled device.", Toast.LENGTH_LONG).show();
        }

        if (!bluetoothAdapter.isEnabled()) {                // If adapter is not enabled, request to enable it from within the app
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }

        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }

</code>```

Since I know the MAC address of the arduino, I try to get the device using that MAC address. When I do this, I am able to view attributes such as the device name and address. However, when I try to view the UUIDs of the arduino, I receive 'null'. The followning code:

```<code>BluetoothDevice arduino = bluetoothAdapter.getRemoteDevice("E5:A5:53:32:BD:7C");
Log.i("DEVICES", String.valueOf(arduino.getName()));
Log.i("DEVICES", String.valueOf(arduino.getAddress()));
Log.i("DEVICES", String.valueOf(arduino.getUuids()));
</code>```

produces the resulting output in the logcat:

```<code>02-11 12:09:02.862 29503-29503/com.seniorproject.acsAssistApp I/DEVICES: acsAssist
02-11 12:09:02.862 29503-29503/com.seniorproject.acsAssistApp I/DEVICES: E5:A5:53:32:BD:7C
02-11 12:09:02.868 29503-29503/com.seniorproject.acsAssistApp I/DEVICES: null
</code>```

I have been trying to figure out how to connect my app to the arduino and view the services that I created, but I am at a loss for how to do that. All the guides, Q&As, and documentation I have tried to find related to this has left me feeling hopeless and confused. Any guidance on how to do this would be greatly appreciated.

PS: I apologize if my formatting for this submission is poor. This is my very first time submitting a question on Stack Overflow. I am also a completely new beginner with Arduino and Android Development.

答:
I have discovered the answer to my difficulties. I was over-complicating the situation; instead I have decided to take advantage of the GATT properties of my implementation. First,  I get the adapter and the arduino via MAC address.

```<code>BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice arduino = bluetoothAdapter.getRemoteDevice("E5:A5:53:32:BD:7C");
</code>```

When I am ready, I connect to the arduino:

```<code>arduino.connectGatt(this.getActivity(), true, gattCallback);
</code>```

I implement my GATT callback:

```<code> private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            final TextView instructionText = getView().findViewById(R.id.instructionText);
            Log.i("DEVICES", "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i("DEVICES", "STATE_CONNECTED");
                    instructionText.setText("Connected. Select Exercise");
                    gatt.discoverServices();
                    break;

                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.i("DEVICES", "STATE_DISCONNECTED");
                    instructionText.setText("acsAssist Disconnected");
                    break;

                case BluetoothProfile.STATE_CONNECTING:
                    Log.i("DEVICES", "CONNECTING");
                    instructionText.setText("Connecting to acsAssist...");
                    break;

                default:
                    Log.i("DEVICES", "STATE_OTHER");
                    instructionText.setText("acsAssist Disconnected");
            }
        }
</code>```

I perform my desired actions for service discovery:

```<code>        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i("DEVICES", "Services Found");
                for (BluetoothGattService service: gatt.getServices()) {
                    Log.i("DEVICES", service.getUuid().toString());
                }
                for (BluetoothGattCharacteristic characteristic: gatt.getService(UUID.fromString("00001826-0000-1000-8000-00805f9b34fb")).getCharacteristics()) {
                    gatt.setCharacteristicNotification(characteristic, true);
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
//                    descriptor.setValue(true ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[]{0x00, 0x00});
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

                    gatt.writeDescriptor(descriptor);
                }
            }
        }
</code>```

And I implement my reading of the characteristic, specifically so that I can monitor it as it is being changed via onCharacteristicChanged

```<code>  @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            //super.onCharacteristicRead(gatt, characteristic, status);
            //gatt.setCharacteristicNotification(characteristic, true);
            Float tester = characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_SFLOAT,1);
            Log.i("UUID", String.valueOf(tester));
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            TextView instructionText = getView().findViewById(R.id.instructionText);
            instructionText.setText(String.valueOf(characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_SFLOAT,1)));

        }
</code>```

Body:
I am currently using an Arduino Nano 33 BLE to calculate an angle measurement from an IMU and add these values to a Bluetooth characteristic within a service. I create the service and characteristic using the ArduinoBLE library:

BLEService angleService("1826");
BLEFloatCharacteristic rollBLE("2A57", BLERead | BLENotify);

Within my setup, I set the device's name, service, and characteristic. I initially write a value of 0 to the characteristic:

BLE.setLocalName("acsAssist");
BLE.setAdvertisedService(angleService);
angleService.addCharacteristic(rollBLE);
BLE.addService(angleService);
rollBLE.writeValue(0);
BLE.advertise();

Within my loop, after I perform my calculation, I change the value of the characteristic accordingly:

rollBLE.writeValue(posiRoll);            // posiRoll is my calculation

When I use a third party app like nrfConnect on my Android device, I am able to find my device and connect to it. The service and characteristic I defined is present and the value is changing as expected:

Here is the output from the nrfConnect app

Now, I am attempting to manually connect to this device within the Android app that I'm building so that I can display this changing value on the screen for the user to see. I include all of the following permissions in my Manifest:

<uses-feature android:name="android.hardware.bluetooth" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I begin by checking that the device the user is using has a bluetooth adapter, and that it is on:

        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {                     // Bluetooth not supported
            Toast.makeText(getActivity(), "This device does not support Bluetooth! Use a Bluetooth enabled device.", Toast.LENGTH_LONG).show();
        }

        if (!bluetoothAdapter.isEnabled()) {                // If adapter is not enabled, request to enable it from within the app
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }

        if (bluetoothAdapter.isDiscovering()) {
            bluetoothAdapter.cancelDiscovery();
        }

Since I know the MAC address of the arduino, I try to get the device using that MAC address. When I do this, I am able to view attributes such as the device name and address. However, when I try to view the UUIDs of the arduino, I receive 'null'. The followning code:

BluetoothDevice arduino = bluetoothAdapter.getRemoteDevice("E5:A5:53:32:BD:7C");
Log.i("DEVICES", String.valueOf(arduino.getName()));
Log.i("DEVICES", String.valueOf(arduino.getAddress()));
Log.i("DEVICES", String.valueOf(arduino.getUuids()));

produces the resulting output in the logcat:

02-11 12:09:02.862 29503-29503/com.seniorproject.acsAssistApp I/DEVICES: acsAssist
02-11 12:09:02.862 29503-29503/com.seniorproject.acsAssistApp I/DEVICES: E5:A5:53:32:BD:7C
02-11 12:09:02.868 29503-29503/com.seniorproject.acsAssistApp I/DEVICES: null

I have been trying to figure out how to connect my app to the arduino and view the services that I created, but I am at a loss for how to do that. All the guides, Q&As, and documentation I have tried to find related to this has left me feeling hopeless and confused. Any guidance on how to do this would be greatly appreciated.

PS: I apologize if my formatting for this submission is poor. This is my very first time submitting a question on Stack Overflow. I am also a completely new beginner with Arduino and Android Development.

Body:
I have discovered the answer to my difficulties. I was over-complicating the situation; instead I have decided to take advantage of the GATT properties of my implementation. First,  I get the adapter and the arduino via MAC address.

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice arduino = bluetoothAdapter.getRemoteDevice("E5:A5:53:32:BD:7C");

When I am ready, I connect to the arduino:

arduino.connectGatt(this.getActivity(), true, gattCallback);

I implement my GATT callback:

 private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            final TextView instructionText = getView().findViewById(R.id.instructionText);
            Log.i("DEVICES", "Status: " + status);
            switch (newState) {
                case BluetoothProfile.STATE_CONNECTED:
                    Log.i("DEVICES", "STATE_CONNECTED");
                    instructionText.setText("Connected. Select Exercise");
                    gatt.discoverServices();
                    break;

                case BluetoothProfile.STATE_DISCONNECTED:
                    Log.i("DEVICES", "STATE_DISCONNECTED");
                    instructionText.setText("acsAssist Disconnected");
                    break;

                case BluetoothProfile.STATE_CONNECTING:
                    Log.i("DEVICES", "CONNECTING");
                    instructionText.setText("Connecting to acsAssist...");
                    break;

                default:
                    Log.i("DEVICES", "STATE_OTHER");
                    instructionText.setText("acsAssist Disconnected");
            }
        }

I perform my desired actions for service discovery:

        @Override
        // New services discovered
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.i("DEVICES", "Services Found");
                for (BluetoothGattService service: gatt.getServices()) {
                    Log.i("DEVICES", service.getUuid().toString());
                }
                for (BluetoothGattCharacteristic characteristic: gatt.getService(UUID.fromString("00001826-0000-1000-8000-00805f9b34fb")).getCharacteristics()) {
                    gatt.setCharacteristicNotification(characteristic, true);
                    BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
//                    descriptor.setValue(true ? BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE : new byte[]{0x00, 0x00});
                    descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);

                    gatt.writeDescriptor(descriptor);
                }
            }
        }

And I implement my reading of the characteristic, specifically so that I can monitor it as it is being changed via onCharacteristicChanged

  @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            //super.onCharacteristicRead(gatt, characteristic, status);
            //gatt.setCharacteristicNotification(characteristic, true);
            Float tester = characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_SFLOAT,1);
            Log.i("UUID", String.valueOf(tester));
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            TextView instructionText = getView().findViewById(R.id.instructionText);
            instructionText.setText(String.valueOf(characteristic.getFloatValue(BluetoothGattCharacteristic.FORMAT_SFLOAT,1)));

        }


问:
can not start android studio Internal Error. Please report to https://code.google.com/p/android/issues
When I start Android Studio this problem was happened. I tried to re-install android studio, restart window, but It didn't work</p>

```<code>java.io.FileNotFoundException: C:\Users\sev_user\.AndroidStudio2.3\system\port (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at com.intellij.openapi.util.io.FileUtil.writeToFile(FileUtil.java:1285)
    at com.intellij.openapi.util.io.FileUtil.writeToFile(FileUtil.java:1279)
    at com.intellij.openapi.util.io.FileUtil.writeToFile(FileUtil.java:1264)
    at com.intellij.idea.SocketLock.lambda$lock$1(SocketLock.java:156)
    at com.intellij.idea.SocketLock.underLocks(SocketLock.java:180)
    at com.intellij.idea.SocketLock.lock(SocketLock.java:129)
    at com.intellij.idea.StartupUtil.lockSystemFolders(StartupUtil.java:296)
    at com.intellij.idea.StartupUtil.prepareAndStart(StartupUtil.java:124)
    at com.intellij.idea.MainImpl.start(MainImpl.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.ide.plugins.PluginManager.lambda$start$0(PluginManager.java:91)
    at java.lang.Thread.run(Thread.java:745)
</code>```

答:
happened to me too,
solved it by Installing newer version of Java JDK.

Hope it works for you too :)

Body:
When I start Android Studio this problem was happened. I tried to re-install android studio, restart window, but It didn't work

java.io.FileNotFoundException: C:\Users\sev_user\.AndroidStudio2.3\system\port (Access is denied)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at com.intellij.openapi.util.io.FileUtil.writeToFile(FileUtil.java:1285)
    at com.intellij.openapi.util.io.FileUtil.writeToFile(FileUtil.java:1279)
    at com.intellij.openapi.util.io.FileUtil.writeToFile(FileUtil.java:1264)
    at com.intellij.idea.SocketLock.lambda$lock$1(SocketLock.java:156)
    at com.intellij.idea.SocketLock.underLocks(SocketLock.java:180)
    at com.intellij.idea.SocketLock.lock(SocketLock.java:129)
    at com.intellij.idea.StartupUtil.lockSystemFolders(StartupUtil.java:296)
    at com.intellij.idea.StartupUtil.prepareAndStart(StartupUtil.java:124)
    at com.intellij.idea.MainImpl.start(MainImpl.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.ide.plugins.PluginManager.lambda$start$0(PluginManager.java:91)
    at java.lang.Thread.run(Thread.java:745)


问:
React set className by conditions dynamic
I have a map function which should dynamic show classNames.
In this function i want to set the className dynamic.
I tried to set the className also without the

$

But dosen't also not work

```<code>this.state.antwort.map((item,key) =>
  <Col md={2} key={key} className={' ${item.gender == "Female" ? karteFemale : karteMann}' } >

...

)    }
</code>```

But i got the error, that the classNames are undefined.
So how can i set the classes flexible ?

答:
@Nifiro's post was spot on!

You can also use the clsx package in the future if you want some complicated behavior and classnames.

Body:
I have a map function which should dynamic show classNames.
In this function i want to set the className dynamic.
I tried to set the className also without the

$

But dosen't also not work

this.state.antwort.map((item,key) =>
  <Col md={2} key={key} className={' ${item.gender == "Female" ? karteFemale : karteMann}' } >

...

)    }

But i got the error, that the classNames are undefined.
So how can i set the classes flexible ?


问:
How do I execute a bash script in Terminal?
I have a bash script like:

```<code>#!/bin/bash

echo Hello world!
</code>```

How do I execute this in Terminal?

答:
And yet one more way

```<code>. /path/to/script
</code>```

What is the meaning of the dot?

Body:
I have a bash script like:

#!/bin/bash

echo Hello world!

How do I execute this in Terminal?

Body:
And yet one more way

. /path/to/script

What is the meaning of the dot?


答:
Just iterate through an object and turn in into an array, but I should notice that object is not a flat structure, so index will be created in arbitrary sequence.

const apiData = {
    "2303240013": {
        "address": "臺中市西區民權路105號",
        "county": "臺中市",
        "location": {
            "lat": 120.675929,
            "lng": 24.141144
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市中西區衛生所",
        "phone": "04 -22223811",
        "town": "西區",
        "updated": ""
    },
    "2317020010": {
        "address": "臺中市東區信義街142號",
        "county": "臺中市",
        "location": {
            "lat": 120.687798,
            "lng": 24.13337
        },
        "mask_adult": 0,
        "mask_child": 0,
        "name": "臺中市東區衛生所",
        "phone": "04 -22834121",
        "town": "東區",
        "updated": ""
    }
}

const parseApiData = data => {
  return Object.keys(data).map(key => data[key])
}

console.log(parseApiData(apiData))```

Title: React setState with arrays , how to auto create an array id without construct


问:
Verifying if data exists in my Table using TClientDataSet in Delphi
I am trying to verify if [specific] data exists in my table using TClientDataSet. I

Is there a way that I can do this in TClientDataSet?

I am avoiding to use query for some reason here.

答:
The following shows how to check whether a TClientDataSet contains any data and how to find whether it contains a record with a field having a specific value (or a record containg a combination of values in multiple fields)

```<code>procedure TForm1.FormCreate(Sender: TObject);
var
  i : Integer;
  Field : TField;
  S : String;
begin

  //  Create 2 fields in the CDS

  Field := TIntegerField.Create(Self);
  Field.FieldName := 'ID';
  Field.FieldKind := fkData;
  Field.DataSet := CDS1;

  Field := TStringField.Create(Self);
  Field.FieldName := 'Name';
  Field.Size := 40;
  Field.FieldKind := fkData;
  Field.DataSet := CDS1;

  //  Next, set up the CDS; it will be empty initially
  CDS1.CreateDataSet;

  if CDS1.IsEmpty then
    ShowMessage('Is empty - no data')
  else
    ShowMessage('Something went wrong');

  CDS1.IndexFieldNames := 'Name;ID';
  CDS1.InsertRecord([1, 'One']);
  CDS1.InsertRecord([2, 'Two']);
  CDS1.InsertRecord([3, 'Three']);

  ShowMessage('DataSet now contains ' + IntToStr(CDS1.RecordCount) + ' records');

  S := 'Two';
  if CDS1.Locate('Name', S, []) then
    ShowMessage('Found record with Name = ' + S)
  else
    ShowMessage('Failed to find record with Name = ' + S);

  //  Following shows how to use Locate on more than one field
  //  Note: to use VarArrayOf, you need Variants in your uses list
  if CDS1.Locate('ID;Name', VarArrayOf([1, 'one']), [loCaseInsensitive])  then
    ShowMessage('Found record by multiple criteria');
end;
</code>```

Note that setting the IndexFieldNames to 'Name;ID' is to speed up the Locate operation if there are a lot of records.

Body:
The following shows how to check whether a TClientDataSet contains any data and how to find whether it contains a record with a field having a specific value (or a record containg a combination of values in multiple fields)

procedure TForm1.FormCreate(Sender: TObject);
var
  i : Integer;
  Field : TField;
  S : String;
begin

  //  Create 2 fields in the CDS

  Field := TIntegerField.Create(Self);
  Field.FieldName := 'ID';
  Field.FieldKind := fkData;
  Field.DataSet := CDS1;

  Field := TStringField.Create(Self);
  Field.FieldName := 'Name';
  Field.Size := 40;
  Field.FieldKind := fkData;
  Field.DataSet := CDS1;

  //  Next, set up the CDS; it will be empty initially
  CDS1.CreateDataSet;

  if CDS1.IsEmpty then
    ShowMessage('Is empty - no data')
  else
    ShowMessage('Something went wrong');

  CDS1.IndexFieldNames := 'Name;ID';
  CDS1.InsertRecord([1, 'One']);
  CDS1.InsertRecord([2, 'Two']);
  CDS1.InsertRecord([3, 'Three']);

  ShowMessage('DataSet now contains ' + IntToStr(CDS1.RecordCount) + ' records');

  S := 'Two';
  if CDS1.Locate('Name', S, []) then
    ShowMessage('Found record with Name = ' + S)
  else
    ShowMessage('Failed to find record with Name = ' + S);

  //  Following shows how to use Locate on more than one field
  //  Note: to use VarArrayOf, you need Variants in your uses list
  if CDS1.Locate('ID;Name', VarArrayOf([1, 'one']), [loCaseInsensitive])  then
    ShowMessage('Found record by multiple criteria');
end;

Note that setting the IndexFieldNames to 'Name;ID' is to speed up the Locate operation if there are a lot of records.