问:
How to save file with changed encoding without modifying its content in Powershell?
I have the following script:

Param (
    [Parameter(Mandatory=$true)]
    [String] $Source,
    [Parameter(Mandatory=$false)]
    [String] $Encoding = 'UTF8',
    [Parameter(Mandatory=$false)]
    [String] $Types= @('*.json', '*.ps1')
)

Get-ChildItem $Source\* -Recurse -Include $Types| ForEach-Object {
    $name = $_.Fullname
    try {
        $content = ($_ | Get-Content)
        $content | Out-File $name -Encoding $Encoding -Force | Out-Null
    } catch {
        Write-Error $_
    }
}

```

How should I change it to have only encoding of the files changed without appending an empty line at the end of the file (in case file hasn't an empty line) and without removing the ending line (if it has one). In other words, I just want to change encoding of files in some path without changing the content.

答:
I solved my problem here is changed script:

Param (
    [Parameter(Mandatory=$true)]
    [String] $Source,
    [Parameter(Mandatory=$false)]
    [String] $Encoding = 'UTF8',
    [Parameter(Mandatory=$false)]
    [String] $Types= @('*.json', '*.ps1')
)

Get-ChildItem $Source\* -Recurse -Include $Types| ForEach-Object {
    $name = $_.Fullname
    try {
        $content = ($_ | Get-Content -Raw)
        [IO.File]::WriteAllText($name, $content, [Text.Encoding]::$Encoding)
    } catch {
        Write-Error $_
    }
}
```

Body:
I have the following script:

Param (
    [Parameter(Mandatory=$true)]
    [String] $Source,
    [Parameter(Mandatory=$false)]
    [String] $Encoding = 'UTF8',
    [Parameter(Mandatory=$false)]
    [String] $Types= @('*.json', '*.ps1')
)

Get-ChildItem $Source\* -Recurse -Include $Types| ForEach-Object {
    $name = $_.Fullname
    try {
        $content = ($_ | Get-Content)
        $content | Out-File $name -Encoding $Encoding -Force | Out-Null
    } catch {
        Write-Error $_
    }
}

How should I change it to have only encoding of the files changed without appending an empty line at the end of the file (in case file hasn't an empty line) and without removing the ending line (if it has one). In other words, I just want to change encoding of files in some path without changing the content.


来源: stackexchange

问:
Error when using LinkedIn's Share button
I'm attempting to add a LinkedIn Share button to our content-driven website. I've generated the embed code using the button builder, but whenever I try to actually use the button, I get a generic error:

There was a problem performing this action, please try again later.

It's been doing this for several days (since I first added the code), so I don't know if the error is on the LinkedIn side or mine. Is there any way to get a more specific error message? The code they provide is just a script tag that you paste in:

```<code><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/Share"></script>
</code>```

Unfortunately LinkedIn's "support" forums are limited to the various API's; there's nowhere available to submit a question regarding the build-a-button functionality. I'm hoping someone else has used this function and can point me in the right direction.

答:
If anyone is getting this error, and cannot figure out why, I recommend checking the URL of the page you're sharing with: LinkedIn Post Inspector.

So, for instance, if I were to check out how wikipedia.org looks when shared, I would visit and enter that URL, like so...

```<code>https://www.linkedin.com/post-inspector/inspect/https:%2F%2Fwww.wikipedia.org%2F
</code>```

And I see...

But there's a ton of information here, showing how everything is parsed, from the description to the title to the image selection for thumbnail display...

Warning: Add an og:image tag to the page to have control over the content's image on LinkedIn.

Title: Wikipedia

Type:  Article

Image: No image found

Description:   Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation.

Author:    No author found

Publish date:  6/1/2020, 6:39:59 AM

They even give you instructions on how to fix your page!  Hey, got some advice for Wikipedia.org here!

Provide a metadata tag for the og:image in the page's head section. For example:

<meta name="image" property="og:image" content="[Image URL here]">

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to add a LinkedIn Share button to our content-driven website. I've generated the embed code using the button builder, but whenever I try to actually use the button, I get a generic error:

There was a problem performing this action, please try again later.

It's been doing this for several days (since I first added the code), so I don't know if the error is on the LinkedIn side or mine. Is there any way to get a more specific error message? The code they provide is just a script tag that you paste in:

Unfortunately LinkedIn's "support" forums are limited to the various API's; there's nowhere available to submit a question regarding the build-a-button functionality. I'm hoping someone else has used this function and can point me in the right direction.

Body:
If anyone is getting this error, and cannot figure out why, I recommend checking the URL of the page you're sharing with: LinkedIn Post Inspector.

So, for instance, if I were to check out how wikipedia.org looks when shared, I would visit and enter that URL, like so...

https://www.linkedin.com/post-inspector/inspect/https:%2F%2Fwww.wikipedia.org%2F

And I see...

But there's a ton of information here, showing how everything is parsed, from the description to the title to the image selection for thumbnail display...

Warning: Add an og:image tag to the page to have control over the content's image on LinkedIn.

Title: Wikipedia

Type:  Article

Image: No image found

Description:   Wikipedia is a free online encyclopedia, created and edited by volunteers around the world and hosted by the Wikimedia Foundation.

Author:    No author found

Publish date:  6/1/2020, 6:39:59 AM

They even give you instructions on how to fix your page!  Hey, got some advice for Wikipedia.org here!

Provide a metadata tag for the og:image in the page's head section. For example:

<meta name="image" property="og:image" content="[Image URL here]">

ContentLicense: CC BY-SA 4.0


问:
Multithread performance
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

```<code>#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}
</code>```

答: for a scenario like this, by all means I'd prefer OpenMP #pragma parallel for, or simply use gcc -fopenmp -D_GLIBCXX_PARALLEL and (likely) get automatic parallelization...

Title: Multithread performance

Body:
I created very simple app to figure out how boost::thread works.
I found result of this test suprising.
4 threads of execution finish computation 2 times faster than 1 thread.
I expected 4x boost.
Another question is why 8 threads did not bring any performance boost?

I'm using boost 1.46.1 and VS2008. Full source code is below.
Program was run on Core i5 750 machine.

#include <iostream>
#include <vector>
#include <cmath>

#include <boost/thread.hpp>
#include <boost/timer.hpp>

typedef unsigned int uint;

struct Vector {
    float x, y, z;

    Vector() : x(0.f), y(0.f), z(0.f) {}

    float len() {
        return sqrtf(x*x + y*y + z*z);
    }

};

float norm(int a) {
    return float((a % 10) + 1) / 10.f;
}

void genVectors(std::vector<Vector>& examples) {
    srand(GetTickCount());

    for (uint i = 0; i < examples.size(); ++i) {
        examples[i].x = norm(rand());
        examples[i].y = norm(rand());
        examples[i].z = norm(rand());
    }

}

typedef std::vector<Vector> Data;
typedef Data::iterator DataIter;

typedef std::vector<float> Result;
typedef Result::iterator ResultIter;

struct Worker {
    Data   data;
    Result result;

    Worker(DataIter& dataStart,
           const DataIter& dataEnd,
           ResultIter& resultStart,
           const ResultIter& resultEnd) : data(dataStart, dataEnd), result(resultStart, resultEnd) {
        assert(data.size() == result.size());
    }

    void operator()() {
        DataIter di = data.begin();
        ResultIter ri = result.begin();

        const DataIter dend = data.end();

        for (; di != dend; ++di, ++ri) {
            *ri = di->len();
        }
    }
};

int main(int argc, char **argv) {
    const uint numThreads = 4;
    const uint seqLen = 13107200;

    std::vector<Vector> a;
    a.resize(seqLen);

    genVectors(a);

    std::vector<float> singleThreadResult(a.size());
    assert(a.size() == singleThreadResult.size());

    boost::timer singleThreadTimer;
    for (uint i = 0; i < a.size(); ++i) {
        singleThreadResult[i] = a[i].len();
    }
    double singleThreadTime = singleThreadTimer.elapsed();

    std::vector<float> multiThreadResult(a.size());

    Worker* workers[numThreads];
    for (uint i = 0; i < numThreads; ++i) {
        uint chunkSize = seqLen / numThreads;
        assert(numThreads * chunkSize == seqLen);

        workers[i] = new Worker(a.begin() + i*chunkSize,
                                a.begin() + (i+1)*chunkSize,
                                multiThreadResult.begin() + i*chunkSize,
                                multiThreadResult.begin() + (i+1)*chunkSize);
    }

    boost::timer multiThreadTimer;
    boost::thread_group threads;
    for (uint i = 0; i < numThreads; ++i) {
        threads.create_thread(boost::ref(*workers[i]));
    }
    threads.join_all();
    double multiThreadTime = multiThreadTimer.elapsed();

    using namespace std;
    cout << "Single thread time: " << singleThreadTime << endl;
    cout << numThreads << " threads time: " << multiThreadTime << endl;

    return 0;
}


问:
Set the value of second row to NULL MySQL
I have a very strange problem that I am not able to solve at the moment.
I have two tables. One table contains the IDs and the other table contains transactions.

Let's say IDs are like:

```<code>1
2
2
3
4
5
6
6
</code>```

and they are joined using the IDs. So what I want to do is if a transaction is there is the transaction table it should be recorded once for each id.

For Example if there is a transaction for ID = 6:

```<code>6 23
6 23
</code>```

23 is the transaction amount.

It should be shown as:

```<code>6 23
6 NULL
</code>```

答:
If I understand correctly, you just want the value once even when the ids are duplicated.  If so, you can use row_number():

```<code>select t1.id,
       (case when row_number() over (partition by t1.id order by t1.id) = 1
             then t.amount
        end)
from table1 t1 left join
     transactions t
     on t1.id = t.id;
</code>```

Body:
I have a very strange problem that I am not able to solve at the moment.
I have two tables. One table contains the IDs and the other table contains transactions.

Let's say IDs are like:

1
2
2
3
4
5
6
6

and they are joined using the IDs. So what I want to do is if a transaction is there is the transaction table it should be recorded once for each id.

For Example if there is a transaction for ID = 6:

6 23
6 23

23 is the transaction amount.

It should be shown as:

6 23
6 NULL

Body:
If I understand correctly, you just want the value once even when the ids are duplicated.  If so, you can use row_number():

select t1.id,
       (case when row_number() over (partition by t1.id order by t1.id) = 1
             then t.amount
        end)
from table1 t1 left join
     transactions t
     on t1.id = t.id;


问:
Get the Path of a .mp3 raw resource from URI
I'm trying to send an audio file to Dialogflow from an Android app.

In order to do that I need the Path of the audio file. According to the documentation, it goes like this:

```<code>val videouri: URI = URI.create("android.resource://$packageName/raw/tts")
val videopath: Path = Paths.get(videouri)
val inputAudio: ByteArray = Files.readAllBytes(videopath)
</code>```

However, on the second line, when obtaining the Path I get the following exception:

```<code>java.nio.file.filesystemnotfoundexception provider android.resource not installed
</code>```

The audio file is located in res > raw > tts.mp3

答:
Use Resources.openRawResource() with the resource ID, which is R.raw.filename.
See https://developer.android.com/guide/topics/resources/providing-resources

Body:
I'm trying to send an audio file to Dialogflow from an Android app.

In order to do that I need the Path of the audio file. According to the documentation, it goes like this:

val videouri: URI = URI.create("android.resource://$packageName/raw/tts")
val videopath: Path = Paths.get(videouri)
val inputAudio: ByteArray = Files.readAllBytes(videopath)

However, on the second line, when obtaining the Path I get the following exception:

java.nio.file.filesystemnotfoundexception provider android.resource not installed

The audio file is located in res > raw > tts.mp3


问:
Python rotating the elements inside subarrays
I am trying to create two subarrays in given order, in this case i have two integers a and b a represents the value of the subarrays range, and b represents how many times it needs to be rotated.

I created the subarrays like this;

```<code>def reorder(a,b):
   return [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]
</code>```

Imagine a is 10 and b is 1 the output is:

```<code>[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
</code>```

But how can i reverse each subarrays b times?

The output that i want;

```<code>[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]
</code>```

答:
You can use indexing as well. Like so:

```<code>def reorder(a, b):
  tmp = [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]
  tmp[0] = tmp[0][-b:] + tmp[0][:-b]
  tmp[1] = tmp[1][-b:] + tmp[1][:-b]
  return tmp

reorder(10, 1)
</code>```

Output:

```<code>[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]
</code>```

Edit

For the edge case where b is greater than a/2. Use the modulo as such:

```<code>def reorder(a, b):
  sz = a//2
  r = b%sz
  tmp = [[i for i in range(0, sz)]] + [[f for f in range(sz, a)]]
  tmp[0] = tmp[0][-r:] + tmp[0][:-r]
  tmp[1] = tmp[1][-r:] + tmp[1][:-r]
  return tmp

reorder(10, 7)

[[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]
</code>```

This can be done for in Maurice Meyer's answer (best so far) as well.

Body:
I am trying to create two subarrays in given order, in this case i have two integers a and b a represents the value of the subarrays range, and b represents how many times it needs to be rotated.

I created the subarrays like this;

def reorder(a,b):
   return [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]

Imagine a is 10 and b is 1 the output is:

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

But how can i reverse each subarrays b times?

The output that i want;

[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]

Body:
You can use indexing as well. Like so:

def reorder(a, b):
  tmp = [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]
  tmp[0] = tmp[0][-b:] + tmp[0][:-b]
  tmp[1] = tmp[1][-b:] + tmp[1][:-b]
  return tmp

reorder(10, 1)

Output:

[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]

Edit

For the edge case where b is greater than a/2. Use the modulo as such:

def reorder(a, b):
  sz = a//2
  r = b%sz
  tmp = [[i for i in range(0, sz)]] + [[f for f in range(sz, a)]]
  tmp[0] = tmp[0][-r:] + tmp[0][:-r]
  tmp[1] = tmp[1][-r:] + tmp[1][:-r]
  return tmp

reorder(10, 7)

[[3, 4, 0, 1, 2], [8, 9, 5, 6, 7]]

This can be done for in Maurice Meyer's answer (best so far) as well.


问:
Getting horizontal scroll in mobile when close the menu
I am using anime.js and displaying the menu on mobile. I am getting a horizontal scroll on mobile.

I added display:none so that my menu will hide and when user click on the menu then I am adding the display block using the script but the issue is, after closing the menu I am still getting the scroll

Script adding the class

```<code> $('html').addClass('noscroll');
</code>```

and added below css

```<code> html.noscroll {
    overflow: hidden;
}
</code>```

So that scroll will hide. Then also I am getting an issue if I close the menu.

Would you help me out with this issue?

I am using the below code.

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}</code>```

Open

close

Home

About

contact

```

答:
You're thinking right direction - overflow would solve the problem. But in your code, I can't see where you're adding overflow.

One of the solutions would be to add a static overflow for X-axis to whole body:

```<code>body {
    overflow-x: hidden;
}
</code>```

Another solution, as you said, add it when necessary using JS.

```<code>function menuClose() {
  $('.menu-background').hide(300);
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}
</code>```

Body:
I am using anime.js and displaying the menu on mobile. I am getting a horizontal scroll on mobile.

I added display:none so that my menu will hide and when user click on the menu then I am adding the display block using the script but the issue is, after closing the menu I am still getting the scroll

Script adding the class

 $('html').addClass('noscroll');

and added below css

 html.noscroll {
    overflow: hidden;
}

So that scroll will hide. Then also I am getting an issue if I close the menu.

Would you help me out with this issue?

I am using the below code.

function menuOpen() {
  $('.menu-background').css('display', 'block');
  anime({
    targets: '.menu-background',
    translateX: ['100vw', 0],
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });

}
$('.menu-trigger').on('click', function() {
  menuOpen();
});

function menuClose() {
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}

// trigger menu animation on icon click
$('.menu-icon-close').on('click', function() {
  menuClose();
});

.menu-trigger,
.menu-icon-close {
  display: none;
}

@media all and (max-width: 768px) {
  .menu-trigger,
  .menu-icon-close {
    display: block;
  }
  .menu-background {
    position: absolute;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: #04dcff;
    display: none;
  }
  .menu-background {
    transform: translateX(100vw);
  }
}

Open

close

Home

About

contact

Body:
You're thinking right direction - overflow would solve the problem. But in your code, I can't see where you're adding overflow.

One of the solutions would be to add a static overflow for X-axis to whole body:

body {
    overflow-x: hidden;
}

Another solution, as you said, add it when necessary using JS.

function menuClose() {
  $('.menu-background').hide(300);
  anime({
    targets: '.menu-background',
    translateX: [0, '100vw'],
    delay: 300,
    duration: 1300,
    easing: 'cubicBezier(0.44, -0.01, 0.08, 0.99)'
  });
}


问:
why stack() doesn't create accessor in d3.js?
enter image description here

```<code>var layers = d3.stack()
                        .keys(keys)
                        (payment);

                console.log("layer",layers);
</code>```

from this code i get layer console like this it return y0 value as 0 , y1 value as NaN [added in above image].

var keys = ["Cash", "Credit card", "Debit card", "Bank Transfer", "Online Payment", "TDS Payment", "Payment gateway", "Cheque"];
enter image description here

My original data from response is payment from above image i add that response .
any one help me  out find a mistake .

答: Make sure Data should be manipulate before executing stacked area chart , i made a mistake in data manipulate that's why I didn't get accessor .</p>

Body:
enter image description here

var layers = d3.stack()
                        .keys(keys)
                        (payment);

                console.log("layer",layers);

from this code i get layer console like this it return y0 value as 0 , y1 value as NaN [added in above image].

var keys = ["Cash", "Credit card", "Debit card", "Bank Transfer", "Online Payment", "TDS Payment", "Payment gateway", "Cheque"];
enter image description here

My original data from response is payment from above image i add that response .
any one help me  out find a mistake .


问:
Can't push the data to array in Firestore + React Hooks
I want to collect the UIDs to the Array fields in Firestore. Successfully fetched each user data, however, I can't list.

contactArray: {"0": "xxxxxxxxxxxx", "1": "yyyyyyyyyyyy"}

User data can be retrieved, but the problem cannot be displayed as a list. I could push it, but it disappears for some reason.

The warning:

Expected to return a value in arrow function

useEffect

```<code>const [contactList, setContactList] = useState([])

useEffect(() => {
  if (currentUserUid) {
    firestore.doc(`users/${currentUserUid}`).get().then(userSnapshot => {
      const { contactUidList } = userSnapshot.data()
      return contactUidList
    })
      .then((contactUidList) => {
        contactUidList.map((contactUid) => {
          firestore.doc(`users/${contactUid}`)
            .onSnapshot(userQuerySnapshot => {
              contactList.push(userQuerySnapshot.data())
              setContactList(contactList)
            })
        })
      })
  }
}, [currentUserUid, contactList])
</code>```

View

```<code>  return (
    <ul>
      {contactList.map((contact, idx) => {
          return(<p>{contact.name}</p>)
       ))
  )
</code>```

答:
Data is loaded from Firestore (and most cloud APIs) asynchronously. For that reason you'll need to keep contactList in the state, and update it there. When you do that, React knows to update the UI when the results come back from the database (or are updated).

So something like:

```<code>const [contactList, setContactList] = useState(0);
useEffect(() => {
  if (currentUserUid) {
    firestore.doc(`users/${currentUserUid}`).get().then(userSnapshot => {
      const { contactArray } = userSnapshot.data()
      return contactArray
    })
      .then((contactArray) => {
        contactUidList.map((contactUid) => {
          firestore.doc(`users/${contactUid}`)
            .onSnapshot(userQuerySnapshot => {
              contactList.push(userQuerySnapshot.data())
              setContactList(contactList)
            })
        })
      })
  }
}, [currentUserUid, contactList])
</code>```

Body:
I want to collect the UIDs to the Array fields in Firestore. Successfully fetched each user data, however, I can't list.

contactArray: {"0": "xxxxxxxxxxxx", "1": "yyyyyyyyyyyy"}

User data can be retrieved, but the problem cannot be displayed as a list. I could push it, but it disappears for some reason.

The warning:

Expected to return a value in arrow function

useEffect

const [contactList, setContactList] = useState([])

useEffect(() => {
  if (currentUserUid) {
    firestore.doc(`users/${currentUserUid}`).get().then(userSnapshot => {
      const { contactUidList } = userSnapshot.data()
      return contactUidList
    })
      .then((contactUidList) => {
        contactUidList.map((contactUid) => {
          firestore.doc(`users/${contactUid}`)
            .onSnapshot(userQuerySnapshot => {
              contactList.push(userQuerySnapshot.data())
              setContactList(contactList)
            })
        })
      })
  }
}, [currentUserUid, contactList])

View

  return (

      {contactList.map((contact, idx) => {
          return(
{contact.name}
)
       ))
  )

Body:
Data is loaded from Firestore (and most cloud APIs) asynchronously. For that reason you'll need to keep contactList in the state, and update it there. When you do that, React knows to update the UI when the results come back from the database (or are updated).

So something like:

const [contactList, setContactList] = useState(0);
useEffect(() => {
  if (currentUserUid) {
    firestore.doc(`users/${currentUserUid}`).get().then(userSnapshot => {
      const { contactArray } = userSnapshot.data()
      return contactArray
    })
      .then((contactArray) => {
        contactUidList.map((contactUid) => {
          firestore.doc(`users/${contactUid}`)
            .onSnapshot(userQuerySnapshot => {
              contactList.push(userQuerySnapshot.data())
              setContactList(contactList)
            })
        })
      })
  }
}, [currentUserUid, contactList])


问:
How to get url from Google Spreadsheet cell with Google Apps Script?
I've got a google spreadsheet copied from excel ANd I have some problem with that.
This is my document https://docs.google.com/spreadsheets/d/1Ok_phu5OXtvKHLj3MLa7N3WV2qBdMWRz8dLHnTqjHrc/edit?usp=sharing

This is my code

```<code>function myFunction() {
  cel = SpreadsheetApp.getActiveSpreadsheet().getActiveCell()
  Logger.log(cel.getFormula())
  Logger.log(cel.getValue())
}
</code>```

And this is my log:

```<code>[16-10-05 13:39:59:628 EEST]
[16-10-05 13:39:59:629 EEST] RU: VTB Arena - Park and Hotel
</code>```

And I need to get an URL (https://na3.salesforce.com/0065000000a1b8p) How can I do that?

答:
Here's a workaround I used to get links from cells.  Apparently when you use ctrl+K to add links they are added as rich text rather than as formulas.  I used the function below in a google sheet to turn these rich text fields with links into html.  If there is a link in the field then it returns the html code for the link.  If there isn't a link then it simply returns the text passed in.  Of course this could be done more elegantly ... I used lots of variables to make it easier to follow what was going on.

```<code>//get link from a cell given by A1 notation
function getHtmlfromRichTextRange(theRange){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(theRange);
  var cell = range;
  var cellValue = cell.getRichTextValue();
  var cellText = cell.getValue();
  var theThing = cellValue.getLinkUrl();

  if (theThing == null){
    return cellText;
  } else {
    return '<a href="'+theThing+'">'+cellText+'</a>';
  }
}
</code>```

In a spreadsheet you could do something like (see image 1):

In cell A1, enter "a link to apple"

With cell A1 highlighted, press ctrl+k to add the hyperlink to http://www.apple.com

In cell B1, enter A1

In Cell C1, enter the formula =getHtmlfromRichTextRange(B1)

As a result, you should see the value

a link to apple in cell C1

A couple of things I noticed when working with this example in this way:

If the function in C1 returned just the url and not the url with some String text around it, then Google sheets turned C1 into RichText, too.  Since I was using this to create html emails, I had the function return the HTML code for the link.

I could have simplified and passed the String "A1" in quotes the function.  I was trying to find a way to have the formula in C1 update when the richtext link in A1 was updated.  My thought was that if A1 changed (e.g. the URL changed), then the result of the function in C1 would automatically update.  It doesn't.  I didn't pursue it.  What is written above did the trick for me.

This code worked if the link was all the text in the cell.  If the cell had some text in it that had the hyperlink and some text that did not (e.g. the hyperlink was only part of the text in the cell) then this code returned it as plain text and not as a URL.

I used the function as-is in AppScript to loop over a range that contained links.  Inside the loop I passed the function the A1 notation of the cells, some of which had links.  It worked beautifully and saved me loads of time!

I'm sure there's an easier way.  I typically find that after doing it the harder way and thus don't need to do it anymore.

Body:
I've got a google spreadsheet copied from excel ANd I have some problem with that.
This is my document https://docs.google.com/spreadsheets/d/1Ok_phu5OXtvKHLj3MLa7N3WV2qBdMWRz8dLHnTqjHrc/edit?usp=sharing

This is my code

function myFunction() {
  cel = SpreadsheetApp.getActiveSpreadsheet().getActiveCell()
  Logger.log(cel.getFormula())
  Logger.log(cel.getValue())
}

And this is my log:

[16-10-05 13:39:59:628 EEST]
[16-10-05 13:39:59:629 EEST] RU: VTB Arena - Park and Hotel

And I need to get an URL (https://na3.salesforce.com/0065000000a1b8p) How can I do that?

Body:
Here's a workaround I used to get links from cells.  Apparently when you use ctrl+K to add links they are added as rich text rather than as formulas.  I used the function below in a google sheet to turn these rich text fields with links into html.  If there is a link in the field then it returns the html code for the link.  If there isn't a link then it simply returns the text passed in.  Of course this could be done more elegantly ... I used lots of variables to make it easier to follow what was going on.

//get link from a cell given by A1 notation
function getHtmlfromRichTextRange(theRange){
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  var range = sheet.getRange(theRange);
  var cell = range;
  var cellValue = cell.getRichTextValue();
  var cellText = cell.getValue();
  var theThing = cellValue.getLinkUrl();

  if (theThing == null){
    return cellText;
  } else {
    return '<a href="'+theThing+'">'+cellText+'</a>';
  }
}

In a spreadsheet you could do something like (see image 1):

In cell A1, enter "a link to apple"

With cell A1 highlighted, press ctrl+k to add the hyperlink to http://www.apple.com

In cell B1, enter A1

In Cell C1, enter the formula =getHtmlfromRichTextRange(B1)

As a result, you should see the value

<a href="http://www.apple.com/">a link to apple</a> in cell C1

A couple of things I noticed when working with this example in this way:

If the function in C1 returned just the url and not the url with some String text around it, then Google sheets turned C1 into RichText, too.  Since I was using this to create html emails, I had the function return the HTML code for the link.

I could have simplified and passed the String "A1" in quotes the function.  I was trying to find a way to have the formula in C1 update when the richtext link in A1 was updated.  My thought was that if A1 changed (e.g. the URL changed), then the result of the function in C1 would automatically update.  It doesn't.  I didn't pursue it.  What is written above did the trick for me.

This code worked if the link was all the text in the cell.  If the cell had some text in it that had the hyperlink and some text that did not (e.g. the hyperlink was only part of the text in the cell) then this code returned it as plain text and not as a URL.

I used the function as-is in AppScript to loop over a range that contained links.  Inside the loop I passed the function the A1 notation of the cells, some of which had links.  It worked beautifully and saved me loads of time!

I'm sure there's an easier way.  I typically find that after doing it the harder way and thus don't need to do it anymore.


问:
Jmeter report giving errors with distributed mode but errors don`t appear in result tree
I am running my test in distributed mode from the GUI.  I have some 20,000 users and two vitual machines have more than 4 VPCUs and 80 Gg memory.  I can`t see any stress on any of the machines, neither the slaves or masters, nor the server under test and I could hardly see any error in the GUI.  However, in the report, I am having the following errors:

Non HTTP response code: javax.net.ssl.SSLException/Non HTTP response
  message: Couldn't kickstart handshaking

Non HTTP response code: javax.net.ssl.SSLException/Non HTTP response
  message: readHandshakeRecord

Non HTTP response code: javax.net.ssl.SSLException/Non HTTP response
  message: Connection reset

The errors are only 0.05%

Can anyone help me what these errors mean and how can I correct them.

答:
You are not seeing the error in GUI because i.e. View Results Tree listener shows only 500 last results, it is controllable by view.results.tree.max_results JMeter Property and if you add the next line to user.properties file:

```<code>view.results.tree.max_results=0
</code>```

next time you run JMeter you will see each and every request in the View Results Tree listener.

Be informed that GUI mode should be used for tests development and debugging, execution should happen in command-line non-GUI mode

For Couldn't kickstart handshaking and readHandshakeRecord  - you can get some troubleshooting information by enabling debug logging for SSL, it can be done by adding the next line to system.properties file:

```<code>javax.net.debug=ssl
</code>```

For Connection reset - see JMeterSocketClosed wiki article

If you have access to your application logs - check them for any suspicious entries

More information:

Apache JMeter Properties Reference

Apache JMeter Properties Customization Guide

Body:
You are not seeing the error in GUI because i.e. View Results Tree listener shows only 500 last results, it is controllable by view.results.tree.max_results JMeter Property and if you add the next line to user.properties file:

view.results.tree.max_results=0

next time you run JMeter you will see each and every request in the View Results Tree listener.

Be informed that GUI mode should be used for tests development and debugging, execution should happen in command-line non-GUI mode

For Couldn't kickstart handshaking and readHandshakeRecord  - you can get some troubleshooting information by enabling debug logging for SSL, it can be done by adding the next line to system.properties file:

javax.net.debug=ssl

For Connection reset - see JMeterSocketClosed wiki article

If you have access to your application logs - check them for any suspicious entries

More information:

Apache JMeter Properties Reference

Apache JMeter Properties Customization Guide


问:
Nodejs Mysql connection best practice
What is the best practice when we want to create MySql connection in nodejs.

Create a global connection and use it for all queries

Open a new connection for each query and close it after the query is done.

答:
Define Global connection variable and use it in the whole project.</p>

```<code>

// only use when you have not setup app.set('con',con);
// global.con;

dbConnection = () => {

  // MYSQL database connection start
  let con = mysql.createPool('database Config obj here');

  // if you want use global.con variable
  // con = mysql.createPool(databaseConfig);

  con.getConnection((err) => {
    if (err) {
      //- The server close the connection.
      if (err.code === "PROTOCOL_CONNECTION_LOST") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Connection in closing
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_QUIT") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Fatal error : connection variable must be recreated
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Error because a connection is already being established
      else if (err.code === "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Anything else
      else {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      setTimeout(dbConnection, 5000);
    } else {

      // you can also set the con varibale by calling below set method or else use global.con ;
      app.set('con', con);

      // rest of the code will goes here
    }
  });
}

dbConnection();

let con = app.get('con');
// => will have connection varibale here

</code>```

Title: Nodejs Mysql connection best practice

Body:
Define Global connection variable and use it in the whole project.

// only use when you have not setup app.set('con',con);
// global.con;

dbConnection = () => {

  // MYSQL database connection start
  let con = mysql.createPool('database Config obj here');

  // if you want use global.con variable
  // con = mysql.createPool(databaseConfig);

  con.getConnection((err) => {
    if (err) {
      //- The server close the connection.
      if (err.code === "PROTOCOL_CONNECTION_LOST") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Connection in closing
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_QUIT") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Fatal error : connection variable must be recreated
      else if (err.code === "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Error because a connection is already being established
      else if (err.code === "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE") {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      //- Anything else
      else {
        console.error("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
      }

      setTimeout(dbConnection, 5000);
    } else {

      // you can also set the con varibale by calling below set method or else use global.con ;
      app.set('con', con);

      // rest of the code will goes here
    }
  });
}

dbConnection();

let con = app.get('con');
// => will have connection varibale here


问:
How do I print the index of the maximum and minimum values?
The following code prints the maximum and minimum value. How do I go about printing the index of those values rather than the values themselves?</p>

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

int main()
{
    int arr1[100];
    int i, mx, mn, n;

       printf("Input the number of elements to be stored in the array :");
       scanf("%d",&n);

       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
            {
          printf("element - %d : ",i);
          scanf("%d",&arr1[i]);
        }

    mx = arr1[0];
    mn = arr1[0];

    for(i=1; i<n; i++)
    {
        if(arr1[i]>mx)
        {
            mx = arr1[i];
        }

        if(arr1[i]<mn)
        {
            mn = arr1[i];
        }
    }
    printf("Maximum element is : %d\n", mx);
    printf("Minimum element is : %d\n\n", mn);

    return 0;
}
</code>```

答:
Simply save the index when you're updating mx respectively mn:

```<code>int max_index = 0;
int min_index = 0;

// ...

    if(arr1[i]>mx)
    {
        mx = arr1[i];
        max_index = i;
    }

    if(arr1[i]<mn)
    {
        mn = arr1[i];
        min_index = i;
    }
</code>```

Body:
The following code prints the maximum and minimum value. How do I go about printing the index of those values rather than the values themselves?

#include <stdio.h>

int main()
{
    int arr1[100];
    int i, mx, mn, n;

       printf("Input the number of elements to be stored in the array :");
       scanf("%d",&n);

       printf("Input %d elements in the array :\n",n);
       for(i=0;i<n;i++)
            {
          printf("element - %d : ",i);
          scanf("%d",&arr1[i]);
        }

    mx = arr1[0];
    mn = arr1[0];

    for(i=1; i<n; i++)
    {
        if(arr1[i]>mx)
        {
            mx = arr1[i];
        }

        if(arr1[i]<mn)
        {
            mn = arr1[i];
        }
    }
    printf("Maximum element is : %d\n", mx);
    printf("Minimum element is : %d\n\n", mn);

    return 0;
}

Body:
Simply save the index when you're updating mx respectively mn:

int max_index = 0;
int min_index = 0;

// ...

    if(arr1[i]>mx)
    {
        mx = arr1[i];
        max_index = i;
    }

    if(arr1[i]<mn)
    {
        mn = arr1[i];
        min_index = i;
    }


问:
Insert 2 values into MySQL, and then stop said values appearing again
I have a script, its supposed to insert a vote (either -1 or +1) to a MySQL value, it does this fine, but it's also supposed to insert the ID of the item they have just voted on, into another table, in array format, to the user who has just voted, so that it doesn't appear again for that user.

1) I don't know how to stop the values appearing again
2) It's not sending the id of the website

The code:

```<code>    $sql = "SELECT * FROM webmash ORDER BY RAND() LIMIT 1";
    $result = mysql_query($sql) or print ("Can't select entry from table webmash.<br />" . $sql . "<br />" . mysql_error());

    while($row = mysql_fetch_array($result)) {
    $name = stripslashes($row['name']);
    $description = stripslashes($row['description']);
    $link =($row['link']);
    $votes = ($row['votes']);
    $id = $row['id'];
    }

    $sql2 = "SELECT * FROM webmashusers";
    $result2 = mysql_query($sql) or print ("Can't select entry from table webmashusers.<br />" . $sql . "<br />" . mysql_error());

    while($row = mysql_fetch_array($result2)) {
    $username = stripslashes($row['username']);
    $likes = ($row['likes']);
    $dislikes = ($row['dislikes']);
    }

    if(isset($_POST['like'])) {
    $votes += 1;
    $sql = "UPDATE webmash SET votes = $votes WHERE id = ".$_POST['id'];
    mysql_query($sql);

    $sqllikes = array (serialize($id));
    $sql2 = "INSERT '$sqllikes' INTO webmashusers (likes) WHERE 'username' = '$376770'";
    mysql_query($sql2);
    }

    if(isset($_POST['dislike'])) {
    $votes -= 1;
    $sql = "UPDATE webmash SET votes = $votes WHERE id = ".$_POST['id'];
    mysql_query($sql);

    $sqldislikes = array (serialize($id));
    $sql2 = "INSERT '$sqldislikes' INTO webmashusers (dislikes) WHERE 'username' = '$376770'";
    mysql_query($sql2);

    }
</code>```

EDIT: $376770 is my username cookie.

答:
Saving serialized arrays in mysql isn't a good way.

Anyway I think you have a couple of errors starting with:

```<code> $sqllikes = array (serialize($id));
</code>```

basically you are serializing a simple int ?

$id is previsouly setted to = $row['id'];

That makes 0 sense.

You should store just the int of the ID in a single column and maybe to avoid duplicate insert you can make it UNIQUE with the other key.

Body:
I have a script, its supposed to insert a vote (either -1 or +1) to a MySQL value, it does this fine, but it's also supposed to insert the ID of the item they have just voted on, into another table, in array format, to the user who has just voted, so that it doesn't appear again for that user.

1) I don't know how to stop the values appearing again
2) It's not sending the id of the website

The code:

    $sql = "SELECT * FROM webmash ORDER BY RAND() LIMIT 1";
    $result = mysql_query($sql) or print ("Can't select entry from table webmash.
" . $sql . "
" . mysql_error());

    while($row = mysql_fetch_array($result)) {
    $name = stripslashes($row['name']);
    $description = stripslashes($row['description']);
    $link =($row['link']);
    $votes = ($row['votes']);
    $id = $row['id'];
    }

    $sql2 = "SELECT * FROM webmashusers";
    $result2 = mysql_query($sql) or print ("Can't select entry from table webmashusers.
" . $sql . "
" . mysql_error());

    while($row = mysql_fetch_array($result2)) {
    $username = stripslashes($row['username']);
    $likes = ($row['likes']);
    $dislikes = ($row['dislikes']);
    }

    if(isset($_POST['like'])) {
    $votes += 1;
    $sql = "UPDATE webmash SET votes = $votes WHERE id = ".$_POST['id'];
    mysql_query($sql);

    $sqllikes = array (serialize($id));
    $sql2 = "INSERT '$sqllikes' INTO webmashusers (likes) WHERE 'username' = '$376770'";
    mysql_query($sql2);
    }

    if(isset($_POST['dislike'])) {
    $votes -= 1;
    $sql = "UPDATE webmash SET votes = $votes WHERE id = ".$_POST['id'];
    mysql_query($sql);

    $sqldislikes = array (serialize($id));
    $sql2 = "INSERT '$sqldislikes' INTO webmashusers (dislikes) WHERE 'username' = '$376770'";
    mysql_query($sql2);

    }

EDIT: $376770 is my username cookie.

Body:
Saving serialized arrays in mysql isn't a good way.

Anyway I think you have a couple of errors starting with:

 $sqllikes = array (serialize($id));

basically you are serializing a simple int ?

$id is previsouly setted to = $row['id'];

That makes 0 sense.

You should store just the int of the ID in a single column and maybe to avoid duplicate insert you can make it UNIQUE with the other key.


问:
Calculate sum, avg, max and min
I have the following table on SQL:

If you notice on the column 'timeroperador' there are duplicated values
I would like to have a procedure to find these duplicated values,calculate and return the avg, max, min and sum of the column 'timertempo'. is that possible? I know that I can do it like this:

```<code>select avg(timertempo) from tempo where timeroperador = 'Nonato'
</code>```

and so on, by informing the names. But I don't want to keep informing the names. is there a way to do that?

答:
To get the avg, max, min, and sum for groups with multiple entries you can use GROUP BY and HAVING. For example:

```<code>select
  timeroperador,
  avg(timertempo),
  max(timertempo),
  min(timertempo),
  sum(timertempo)
from tempo
group by timeroperador
having count(*) > 1
</code>```

Title: Calculate sum, avg, max and min

Body:
I have the following table on SQL:

If you notice on the column 'timeroperador' there are duplicated values
I would like to have a procedure to find these duplicated values,calculate and return the avg, max, min and sum of the column 'timertempo'. is that possible? I know that I can do it like this:

select avg(timertempo) from tempo where timeroperador = 'Nonato'

and so on, by informing the names. But I don't want to keep informing the names. is there a way to do that?

Body:
To get the avg, max, min, and sum for groups with multiple entries you can use GROUP BY and HAVING. For example:

select
  timeroperador,
  avg(timertempo),
  max(timertempo),
  min(timertempo),
  sum(timertempo)
from tempo
group by timeroperador
having count(*) > 1


答:
If applicable I'd suggest using deque.
I'd expect it to be faster that list.

import collections
def reorder(a,b):
   tmp = [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]

   for i in range(len(tmp)):
     tmp[i] = collections.deque(tmp[i])

     # rotates to right for positive numbers
     tmp[i].rotate(b)

print d
>>> deque([3, 4, 5, 1, 2])
```

Title: Python rotating the elements inside subarrays

Body:
I am trying to create two subarrays in given order, in this case i have two integers a and b a represents the value of the subarrays range, and b represents how many times it needs to be rotated.

I created the subarrays like this;

def reorder(a,b):
   return [[i for i in range(0, a//2)]] + [[f for f in range(a//2, a)]]

Imagine a is 10 and b is 1 the output is:

[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]

But how can i reverse each subarrays b times?

The output that i want;

[[4, 0, 1, 2, 3], [9, 5, 6, 7, 8]]


问:
import vue-awesome icons error while jest testing with nuxt on node 13.9.0
I have followed the instructions on https://github.com/Justineo/vue-awesome

in my jest.config.js I add the following

transformIgnorePatterns: [
    '/node_modules(?![\\\\/]vue-awesome[\\\\/])/'
]
```

<p>my nuxt.config.js</p>

<pre class="lang-js prettyprint-override"><code>build: {
  transpile: [/^vue-awesome/] // enable font-awesome integration.
},
</code>```

The icons work just fine when I'm running the dev box, but I get the following when I run yarn test:

[path/to/project]/node_modules/vue-awesome/icons/building.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
                                                                                ^^^^^^

    SyntaxError: Cannot use import statement outside a module
```

<p>explicitly, the issue seems to be something to do with how babel reads (or overlooks) the imports above the Icon component import.  So, for example, given the <code>building.js</code> in the error log above, here is how the import looks in the vuejs file:</p>

```
```

答:
It looks like I have to explicitly mock the component and its imports at the top of the file (below the imports)

the following works for my test.

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import { AxiosSpy, MockNuxt } from 'jest-nuxt-helper'
import index from '@/pages/courses/index'

// MOCKS:
jest.mock('vue-awesome/icons/building', () => '')
jest.mock('vue-awesome/components/Icon', () => '

')

...
```

Body:
I have followed the instructions on https://github.com/Justineo/vue-awesome

in my jest.config.js I add the following

transformIgnorePatterns: [
    '/node_modules(?![\\\\/]vue-awesome[\\\\/])/'
]

my nuxt.config.js

build: {
  transpile: [/^vue-awesome/] // enable font-awesome integration.
},

The icons work just fine when I'm running the dev box, but I get the following when I run yarn test:

[path/to/project]/node_modules/vue-awesome/icons/building.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
                                                                                ^^^^^^

    SyntaxError: Cannot use import statement outside a module

explicitly, the issue seems to be something to do with how babel reads (or overlooks) the imports above the Icon component import.  So, for example, given the building.js in the error log above, here is how the import looks in the vuejs file:

Body:
It looks like I have to explicitly mock the component and its imports at the top of the file (below the imports)

the following works for my test.

import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import { AxiosSpy, MockNuxt } from 'jest-nuxt-helper'
import index from '@/pages/courses/index'

// MOCKS:
jest.mock('vue-awesome/icons/building', () => '')
jest.mock('vue-awesome/components/Icon', () => '<div></div>')

...


问:
Draw path between two points using Google Maps Android API v2
Google changed its map API for Android and introduced API V2. The previous codes for drawing path are not working with API V2.

I have managed to draw a path with API V2. I had searched a lot for the solution but did not find any answer. So I am sharing its answer.

答:
Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

```<code>public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }

        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}
</code>```

GetPathFromLocation.java

```<code>public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}
</code>```

DirectionPointListener

```<code>public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}
</code>```

Now draw path using below code in your Activity

```<code>private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }
</code>```

OutPut

Body:
Try below solution to draw path with animation and also get time and distance between two points.

DirectionHelper.java

public class DirectionHelper {

    public List<List<HashMap<String, String>>> parse(JSONObject jObject) {

        List<List<HashMap<String, String>>> routes = new ArrayList<>();
        JSONArray jRoutes;
        JSONArray jLegs;
        JSONArray jSteps;
        JSONObject jDistance = null;
        JSONObject jDuration = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for (int i = 0; i < jRoutes.length(); i++) {
                jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<>();

                /** Traversing all legs */
                for (int j = 0; j < jLegs.length(); j++) {

                    /** Getting distance from the json data */
                    jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
                    HashMap<String, String> hmDistance = new HashMap<String, String>();
                    hmDistance.put("distance", jDistance.getString("text"));

                    /** Getting duration from the json data */
                    jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
                    HashMap<String, String> hmDuration = new HashMap<String, String>();
                    hmDuration.put("duration", jDuration.getString("text"));

                    /** Adding distance object to the path */
                    path.add(hmDistance);

                    /** Adding duration object to the path */
                    path.add(hmDuration);

                    jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for (int k = 0; k < jSteps.length(); k++) {
                        String polyline = "";
                        polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for (int l = 0; l < list.size(); l++) {
                            HashMap<String, String> hm = new HashMap<>();
                            hm.put("lat", Double.toString((list.get(l)).latitude));
                            hm.put("lng", Double.toString((list.get(l)).longitude));
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
        }

        return routes;
    }

    //Method to decode polyline points
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

GetPathFromLocation.java

public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {

    private Context context;
    private String TAG = "GetPathFromLocation";
    private LatLng source, destination;
    private ArrayList<LatLng> wayPoint;
    private GoogleMap mMap;
    private boolean animatePath, repeatDrawingPath;
    private DirectionPointListener resultCallback;
    private ProgressDialog progressDialog;

    //https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
    //https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/

    public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
        this.context = context;
        this.source = source;
        this.destination = destination;
        this.wayPoint = wayPoint;
        this.mMap = mMap;
        this.animatePath = animatePath;
        this.repeatDrawingPath = repeatDrawingPath;
        this.resultCallback = resultCallback;
    }

    synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {

        String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
                + source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
        for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
            if (centerPoint == 0) {
                url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            } else {
                url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
            }
        }
        url = url + "&key=" + context.getResources().getString(R.string.google_api_key);

        return url;
    }

    public int getRandomColor() {
        Random rnd = new Random();
        return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Please wait...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... url) {

        String data;

        try {
            InputStream inputStream = null;
            HttpURLConnection connection = null;
            try {
                URL directionUrl = new URL(getUrl(source, destination, wayPoint));
                connection = (HttpURLConnection) directionUrl.openConnection();
                connection.connect();
                inputStream = connection.getInputStream();

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer stringBuffer = new StringBuffer();

                String line = "";
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }

                data = stringBuffer.toString();
                bufferedReader.close();

            } catch (Exception e) {
                Log.e(TAG, "Exception : " + e.toString());
                return null;
            } finally {
                inputStream.close();
                connection.disconnect();
            }
            Log.e(TAG, "Background Task data : " + data);

            //Second AsyncTask

            JSONObject jsonObject;
            List<List<HashMap<String, String>>> routes = null;

            try {
                jsonObject = new JSONObject(data);
                // Starts parsing data
                DirectionHelper helper = new DirectionHelper();
                routes = helper.parse(jsonObject);
                Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);

                return routes;

            } catch (Exception e) {
                Log.e(TAG, "Exception in Executing Routes : " + e.toString());
                return null;
            }

        } catch (Exception e) {
            Log.e(TAG, "Background Task Exception : " + e.toString());
            return null;
        }
    }

    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        super.onPostExecute(result);

        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

        ArrayList<LatLng> points;
        PolylineOptions lineOptions = null;
        String distance = "";
        String duration = "";

        // Traversing through all the routes
        for (int i = 0; i < result.size(); i++) {
            points = new ArrayList<>();
            lineOptions = new PolylineOptions();

            // Fetching i-th route
            List<HashMap<String, String>> path = result.get(i);

            // Fetching all the points in i-th route
            for (int j = 0; j < path.size(); j++) {
                HashMap<String, String> point = path.get(j);

                if (j == 0) {    // Get distance from the list
                    distance = (String) point.get("distance");
                    continue;
                } else if (j == 1) { // Get duration from the list
                    duration = (String) point.get("duration");
                    continue;
                }

                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);

                points.add(position);
            }

            // Adding all the points in the route to LineOptions
            lineOptions.addAll(points);
            lineOptions.width(8);
            lineOptions.color(Color.RED);
            //lineOptions.color(getRandomColor());

            if (animatePath) {
                final ArrayList<LatLng> finalPoints = points;
                ((AppCompatActivity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        PolylineOptions polylineOptions;
                        final Polyline greyPolyLine, blackPolyline;
                        final ValueAnimator polylineAnimator;

                        LatLngBounds.Builder builder = new LatLngBounds.Builder();
                        for (LatLng latLng : finalPoints) {
                            builder.include(latLng);
                        }
                        polylineOptions = new PolylineOptions();
                        polylineOptions.color(Color.RED);
                        polylineOptions.width(8);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.jointType(ROUND);
                        polylineOptions.addAll(finalPoints);
                        greyPolyLine = mMap.addPolyline(polylineOptions);

                        polylineOptions = new PolylineOptions();
                        polylineOptions.width(8);
                        polylineOptions.color(Color.WHITE);
                        polylineOptions.startCap(new SquareCap());
                        polylineOptions.endCap(new SquareCap());
                        polylineOptions.zIndex(5f);
                        polylineOptions.jointType(ROUND);

                        blackPolyline = mMap.addPolyline(polylineOptions);
                        polylineAnimator = ValueAnimator.ofInt(0, 100);
                        polylineAnimator.setDuration(5000);
                        polylineAnimator.setInterpolator(new LinearInterpolator());
                        polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                                List<LatLng> points = greyPolyLine.getPoints();
                                int percentValue = (int) valueAnimator.getAnimatedValue();
                                int size = points.size();
                                int newPoints = (int) (size * (percentValue / 100.0f));
                                List<LatLng> p = points.subList(0, newPoints);
                                blackPolyline.setPoints(p);
                            }
                        });

                        polylineAnimator.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {
                                if (repeatDrawingPath) {
                                    List<LatLng> greyLatLng = greyPolyLine.getPoints();
                                    if (greyLatLng != null) {
                                        greyLatLng.clear();

                                    }
                                    polylineAnimator.start();
                                }
                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {
                                polylineAnimator.cancel();
                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {
                            }
                        });
                        polylineAnimator.start();
                    }
                });
            }

            Log.e(TAG, "PolylineOptions Decoded");
        }

        // Drawing polyline in the Google Map for the i-th route
        if (resultCallback != null && lineOptions != null)
            resultCallback.onPath(lineOptions, distance, duration);
    }
}

DirectionPointListener

public interface DirectionPointListener {
    public void onPath(PolylineOptions polyLine,String distance,String duration);
}

Now draw path using below code in your Activity

private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;

mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

@Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                LatLngBounds.Builder builder = new LatLngBounds.Builder();

                /*Add Source Marker*/
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.position(source);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                mMap.addMarker(markerOptions);
                builder.include(source);

                /*Add Destination Marker*/
                markerOptions = new MarkerOptions();
                markerOptions.position(destination);
                markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
                mMap.addMarker(markerOptions);
                builder.include(destination);

                LatLngBounds bounds = builder.build();

                int width = mapFragment.getView().getMeasuredWidth();
                int height = mapFragment.getView().getMeasuredHeight();
                int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen

                CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);

                mMap.animateCamera(cu);

                new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
                    @Override
                    public void onPath(PolylineOptions polyLine, String distance, String duration) {
                        mMap.addPolyline(polyLine);
                        Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);

                        binding.txtDistance.setText(String.format(" %s", distance));
                        binding.txtDuration.setText(String.format(" %s", duration));
                    }
                }).execute();
            }
        });
    }

OutPut


问:
Pass this to child Function
This function should get some data out of a MySQL database:

function getXXX() {
  this.output = []
  con.connect(function(err) {
    if (err) throw err
    con.query('SELECT * FROM `XXX`', function(err, result) {
      if (err) throw err
      this.output = result
    })
  })
  return this.output
}
console.log(getXXX())
```

how do i pass this to the child function because right now it returns []?

(I basically want a function that returns the values from the database)

答:
In your current implementation, getXXX returns before con.query executes the callback which you pass as its second parameter.

One way to get the result back to the context in which you call getXXX, without having to worry about passing this around, would be to return a Promise:

```<code>function getXXX() {
  return new Promise(function(resolve, reject){
    con.connect(function(err) {
      if (err) {
        reject(err)
        return // return early to prevent further execution below
      }
      con.query('SELECT * FROM `XXX`', function(err, result) {
        if (err) {
          reject(err)
          return // return early to prevent further execution below
        }
        resolve(result)
      })
    })
  })
}

// getXXX now returns a promise so you can use .then and .catch
getXXX().then(data => {
  // work with your data here
}).catch(err => {
  // handle the error
})
</code>```

You may want to read up on asynchronous patterns in javascript, this is a good resource to start: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises

Title: Pass this to child Function

Body:
This function should get some data out of a MySQL database:

function getXXX() {
  this.output = []
  con.connect(function(err) {
    if (err) throw err
    con.query('SELECT * FROM `XXX`', function(err, result) {
      if (err) throw err
      this.output = result
    })
  })
  return this.output
}
console.log(getXXX())

how do i pass this to the child function because right now it returns []?

(I basically want a function that returns the values from the database)

Body:
In your current implementation, getXXX returns before con.query executes the callback which you pass as its second parameter.

One way to get the result back to the context in which you call getXXX, without having to worry about passing this around, would be to return a Promise:

function getXXX() {
  return new Promise(function(resolve, reject){
    con.connect(function(err) {
      if (err) {
        reject(err)
        return // return early to prevent further execution below
      }
      con.query('SELECT * FROM `XXX`', function(err, result) {
        if (err) {
          reject(err)
          return // return early to prevent further execution below
        }
        resolve(result)
      })
    })
  })
}

// getXXX now returns a promise so you can use .then and .catch
getXXX().then(data => {
  // work with your data here
}).catch(err => {
  // handle the error
})

You may want to read up on asynchronous patterns in javascript, this is a good resource to start: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises


问:
python how to skip symlinks when checking folders
I made a script with python that creates placeholders in all empty directories so that they wont get deleted.

The problem with that is: it detects symlinks which I do not want to happen.

and I am getting error like: PermissionError: [Errno 13] Permission denied: 'system/d/'

code:

```<code>#!/usr/bin/env python3

import os, glob

dirs = []
paths = ["system", "vendor"]
for path in paths:
    dirs.append(glob.glob(path + '/**/', recursive=True))

for dir in dirs:
    for dir1 in dir:
        if len(os.listdir(dir1)) == 0:
            open(dir1, '.PLACEHOLDER').close()
        else: continue
</code>```

How do i ignore symlinks

答:
Use os.walk instead of glob, as in:

```<code>dirs.append(list(os.walk(path, followlinks=False)))
</code>```

( Please note that according to the documentation, the default for followLinks is False - so you can omit this argument. )

Body:
I made a script with python that creates placeholders in all empty directories so that they wont get deleted.

The problem with that is: it detects symlinks which I do not want to happen.

and I am getting error like: PermissionError: [Errno 13] Permission denied: 'system/d/'

code:

#!/usr/bin/env python3

import os, glob

dirs = []
paths = ["system", "vendor"]
for path in paths:
    dirs.append(glob.glob(path + '/**/', recursive=True))

for dir in dirs:
    for dir1 in dir:
        if len(os.listdir(dir1)) == 0:
            open(dir1, '.PLACEHOLDER').close()
        else: continue

How do i ignore symlinks

Body:
Use os.walk instead of glob, as in:

dirs.append(list(os.walk(path, followlinks=False)))

( Please note that according to the documentation, the default for followLinks is False - so you can omit this argument. )


问:
How to Add Java Method Timer for Redirect in ZK
Hello fellow developer,i've getting problem to set the Timer method on ZK,default the method in my .zul page is:

```<code><timer id="timer" delay="1000" repeats="false"
onTimer="response.sendRedirect('./Login.zul')" />
</code>```

but the code is error(i think beacuse ('./Login.zul'),if i try (\"./Login.zul\"),still show error),i try to build in my controller page like this:

```<code>     private Timer timer=new Timer( 1000 );

    public OTPController() {

        timer.setRepeats( true );
        timer.setAttribute( "onTimer","response.sendRedirect(\"./Login.zul\")", Timer.COMPONENT_SCOPE );

        timer.start();
}
</code>```

but nothing happen..:(

anybody can help me?

maybe i have to create java script method or something like that?
iam still trying to find the answer,ive read the ZK Docs but nothing can help..

Thanks for your attention and sorry for my bad english :D

答:
You can try the following example,</p>

```<code><timer id="timer" delay="1000" repeats="false"
    onTimer='Executions.sendRedirect("./Login.zul")' />
</code>```

Body:
Hello fellow developer,i've getting problem to set the Timer method on ZK,default the method in my .zul page is:

<timer id="timer" delay="1000" repeats="false"
onTimer="response.sendRedirect('./Login.zul')" />

but the code is error(i think beacuse ('./Login.zul'),if i try (\"./Login.zul\"),still show error),i try to build in my controller page like this:

     private Timer timer=new Timer( 1000 );

    public OTPController() {

        timer.setRepeats( true );
        timer.setAttribute( "onTimer","response.sendRedirect(\"./Login.zul\")", Timer.COMPONENT_SCOPE );

        timer.start();
}

but nothing happen..:(

anybody can help me?

maybe i have to create java script method or something like that?
iam still trying to find the answer,ive read the ZK Docs but nothing can help..

Thanks for your attention and sorry for my bad english :D

Body:
You can try the following example,

<timer id="timer" delay="1000" repeats="false"
    onTimer='Executions.sendRedirect("./Login.zul")' />