问:
How to create a method that gets the previous node using a Binary Search Tree in Java?
I am working on a method that gets the previous node using a binary search tree. Now I think I got this, however I am struggling with my if statements.

The instructions are the getPrevNode(BSTNode) method should find the node in the tree that comes before the parameter. And here is the algorithm that I am working with.

• If the node has a left child, move down the left subtree to get the max node

• Otherwise, if the node has a parent, we'll need to move up the tree as follows:

• If the node is a right child, return its parent

• If the node is a left child, move up the tree until you are a right child and return its
parent

• If you reach the root and are never a right child, then there is no previous node

Lets note that this is also a helper method. Therefore, here is my code that I have so far, following that algorithm.

```<code> private BSTNode<E> getPrevNode(BSTNode<E> node)
{
    if(node.left != null)
    {
        return getPrevNode(node.left);
    }
    else if(node.parent != null)
    {
        if(node == node.right)
        {
            return node.parent;
        }
        else if(node == node.left)
        {
            return node.parent;
        }
    }
    return getPrevNode(node);
}
</code>```

Now I know it's not accurate, but that's why I am asking. I will try to give out some information on this code but I will leave some methods out since I don't want it to be long.

```<code>public class BinarySearchTree<E extends Comparable<E>>
{
private BSTNode<E> root; // root of overall tree
private int numElements;
private BSTNode<E> first;
// post: constructs an empty search tree
public BinarySearchTree()
{
    this.root = null;
    this.numElements = 0;
}
private BSTNode<E> getPrevNode(BSTNode<E> node)
{
    if(node.left != null)
    {
        return getPrevNode(node.left);
    }
    else if(node.parent != null)
    {
        if(node == node.right)
        {
            return node.parent;
        }
        else if(node == node.left)
        {
            return node.parent;
        }
    }
    return getPrevNode(node);
}
 public class Iterator
{
    private BSTNode<E> currentNode;

    public Iterator()
    {
        currentNode = first;
    }

    public boolean hasNext()
    {
        return currentNode != null;
    }

    public E next()
    {
        E value = currentNode.data;
        currentNode = currentNode.next;
        return value;
    }
}
private static class BSTNode<E>
{
    public E data;
    public BSTNode<E> left;
    public BSTNode<E> right;
    public BSTNode<E> parent;
    public BSTNode<E> next;

    public BSTNode(E data)
    {
        this(data, null, null, null, null);
    }

    public BSTNode(E data, BSTNode<E> left, BSTNode<E> right, BSTNode<E> parent, BSTNode<E> next)
    {
        this.data = data;
        this.left = left;
        this.right = right;
        this.parent = parent;
        this.next = next;
    }
 }
}
</code>```

I hope this information is useful.

答:
Here's a solution with less code.</p>

```<code>private BSTNode<E> getPrevNode(BSTNode<E> node, int val) {
    if (node == null) return null;
    BSTNode<E> prev = null;
    while (node != null) {
       if (val < node.data) {
          prev = node;
          node = node.left;
       } else if (val > node.data) {
          prev = node;
          node = node.right;
       } else {
          break;
       }
    }
    return node != null ? prev : null;
}
</code>```

Body:
I am working on a method that gets the previous node using a binary search tree. Now I think I got this, however I am struggling with my if statements.

The instructions are the getPrevNode(BSTNode) method should find the node in the tree that comes before the parameter. And here is the algorithm that I am working with.

• If the node has a left child, move down the left subtree to get the max node

• Otherwise, if the node has a parent, we'll need to move up the tree as follows:

• If the node is a right child, return its parent

• If the node is a left child, move up the tree until you are a right child and return its
parent

• If you reach the root and are never a right child, then there is no previous node

Lets note that this is also a helper method. Therefore, here is my code that I have so far, following that algorithm.

 private BSTNode<E> getPrevNode(BSTNode<E> node)
{
    if(node.left != null)
    {
        return getPrevNode(node.left);
    }
    else if(node.parent != null)
    {
        if(node == node.right)
        {
            return node.parent;
        }
        else if(node == node.left)
        {
            return node.parent;
        }
    }
    return getPrevNode(node);
}

Now I know it's not accurate, but that's why I am asking. I will try to give out some information on this code but I will leave some methods out since I don't want it to be long.

public class BinarySearchTree<E extends Comparable<E>>
{
private BSTNode<E> root; // root of overall tree
private int numElements;
private BSTNode<E> first;
// post: constructs an empty search tree
public BinarySearchTree()
{
    this.root = null;
    this.numElements = 0;
}
private BSTNode<E> getPrevNode(BSTNode<E> node)
{
    if(node.left != null)
    {
        return getPrevNode(node.left);
    }
    else if(node.parent != null)
    {
        if(node == node.right)
        {
            return node.parent;
        }
        else if(node == node.left)
        {
            return node.parent;
        }
    }
    return getPrevNode(node);
}
 public class Iterator
{
    private BSTNode<E> currentNode;

    public Iterator()
    {
        currentNode = first;
    }

    public boolean hasNext()
    {
        return currentNode != null;
    }

    public E next()
    {
        E value = currentNode.data;
        currentNode = currentNode.next;
        return value;
    }
}
private static class BSTNode<E>
{
    public E data;
    public BSTNode<E> left;
    public BSTNode<E> right;
    public BSTNode<E> parent;
    public BSTNode<E> next;

    public BSTNode(E data)
    {
        this(data, null, null, null, null);
    }

    public BSTNode(E data, BSTNode<E> left, BSTNode<E> right, BSTNode<E> parent, BSTNode<E> next)
    {
        this.data = data;
        this.left = left;
        this.right = right;
        this.parent = parent;
        this.next = next;
    }
 }
}

I hope this information is useful.

Body:
Here's a solution with less code.

private BSTNode<E> getPrevNode(BSTNode<E> node, int val) {
    if (node == null) return null;
    BSTNode<E> prev = null;
    while (node != null) {
       if (val < node.data) {
          prev = node;
          node = node.left;
       } else if (val > node.data) {
          prev = node;
          node = node.right;
       } else {
          break;
       }
    }
    return node != null ? prev : null;
}


来源: stackexchange

问:
Dynamic creation of an array on the properties of an Angular object
I want to display the table automatically based on the entered data.

I want to add a value to every state line to the state object, e.g. state.Q0, state.Q1, state.Q2.

And I would like to give each cell automatically its own unique id

I've tried value = "{{state.Q {{q}}}} - An error pops up.

          <ng-container *ngFor="let header of stateColumn">

              {{header}}

          </ng-container>

       <ng-container *ngFor="let column of stateColumn;let colum=index">
          <ng-container *ngFor="let state of initTestTabelMT; let i=index">

                  <input type="text" value="{{state.Q1}}">  <-- HERE
                                            ============
                                    value="{{state.Q{{q}} }}" <-- Doesnt working
                                    value="{{state.Q}}{{q}}" <-- Doesnt working

          </ng-container>
        </ng-container>

```

<pre class="lang-js prettyprint-override"><code>this.stateColumn :
(6) ["0", "1", "2", "3", "4", "5"]
0: "0"
1: "1"
2: "2"
3: "3"
4: "4"
5: "5"
length: 6
</code>```

this.initTestTabelMT
(3) [{…}, {…}, {…}]
0: {Q0: "q0/a/P", Q1: "q1/a/P", Q2: "q2/a/P", Q3: "q3/a/P", Q4: "q5/A/#", …}
1: {Q0: "q0/a/P", Q1: "q1/a/P", Q2: "q2/a/P", Q3: "q3/a/P", Q4: "q5/A/#", …}
2: {Q0: "q0/a/P", Q1: "q1/a/P", Q2: "q2/a/P", Q3: "q3/a/P", Q4: "q5/A/#", …}
```

[1]: https://imgur.com/qaoeCxx - I expect

[2]: https://imgur.com/7Vg0y0T - I have this

答:
You can try these use keyvalue

```<code><table class="table">
  <thead>
    <tr>
      <ng-container *ngFor="let header of stateColumn">
        <th>
          <abbr title="State no.">{{header}}</abbr>
        </th>
      </ng-container>
    </tr>
  </thead>
<tbody>
  <ng-container >
    <tr *ngFor="let state of initTestTabelMT; let i=index">
      <td *ngFor="let s of state | keyvalue">
        <span [style.background-color]="getBackgroundColor()">
          <input type="text" value="{{s.value}}">
        </span>
      </td>
    </tr>
  </ng-container>
 </tbody>
</table>
</code>```

Here is a Stackblitz example

ContentLicense: CC BY-SA 4.0

Body:
I want to display the table automatically based on the entered data.

I want to add a value to every state line to the state object, e.g. state.Q0, state.Q1, state.Q2.

And I would like to give each cell automatically its own unique id

I've tried value = "{{state.Q {{q}}}} - An error pops up.

          <ng-container *ngFor="let header of stateColumn">

              {{header}}

          </ng-container>

       <ng-container *ngFor="let column of stateColumn;let colum=index">
          <ng-container *ngFor="let state of initTestTabelMT; let i=index">

                  <input type="text" value="{{state.Q1}}">  <-- HERE
                                            ============
                                    value="{{state.Q{{q}} }}" <-- Doesnt working
                                    value="{{state.Q}}{{q}}" <-- Doesnt working

          </ng-container>
        </ng-container>

this.stateColumn :
(6) ["0", "1", "2", "3", "4", "5"]
0: "0"
1: "1"
2: "2"
3: "3"
4: "4"
5: "5"
length: 6

this.initTestTabelMT
(3) [{…}, {…}, {…}]
0: {Q0: "q0/a/P", Q1: "q1/a/P", Q2: "q2/a/P", Q3: "q3/a/P", Q4: "q5/A/#", …}
1: {Q0: "q0/a/P", Q1: "q1/a/P", Q2: "q2/a/P", Q3: "q3/a/P", Q4: "q5/A/#", …}
2: {Q0: "q0/a/P", Q1: "q1/a/P", Q2: "q2/a/P", Q3: "q3/a/P", Q4: "q5/A/#", …}

[1]: https://imgur.com/qaoeCxx - I expect

[2]: https://imgur.com/7Vg0y0T - I have this

Body:
You can try these use keyvalue

<table class="table">
  <thead>
    <tr>
      <ng-container *ngFor="let header of stateColumn">
        <th>
          <abbr title="State no.">{{header}}</abbr>
        </th>
      </ng-container>
    </tr>
  </thead>
<tbody>
  <ng-container >
    <tr *ngFor="let state of initTestTabelMT; let i=index">
      <td *ngFor="let s of state | keyvalue">
        <span [style.background-color]="getBackgroundColor()">
          <input type="text" value="{{s.value}}">
        </span>
      </td>
    </tr>
  </ng-container>
 </tbody>
</table>

Here is a Stackblitz example


问:
remove ? char from my url for use custom api
I'm using Guzzle 6 with custom api, I would like to change the URL
from
http://my.domain.com/test?key1=5&key2=ABC
to this
http://my.domain.com/test/key1=5&key2=ABC

How can I remove the "?" char between url and first parameter

```<code>$endpoint = "http://my.domain.com/test";
$client = new \GuzzleHttp\Client();
$key1= 5;
$key2= ABC;

$response = $client->request('GET', $endpoint, ['query' => [
    'key1' => $key1,
    'kei2' => $key2

]]);
</code>```

答:
You can split URL into parts and put it together in the custom order.</p>

```<code>$expectedUrl = 'http://my.domain.com/test/key1=5&key2=ABC';

$urlParts = parse_url('http://my.domain.com/test?key1=5&key2=ABC');
$resultUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '/' . $urlParts['query'];

var_dump(
    $resultUrl === $expectedUrl
);
</code>```

Body:
I'm using Guzzle 6 with custom api, I would like to change the URL
from
http://my.domain.com/test?key1=5&key2=ABC
to this
http://my.domain.com/test/key1=5&key2=ABC

How can I remove the "?" char between url and first parameter

$endpoint = "http://my.domain.com/test";
$client = new \GuzzleHttp\Client();
$key1= 5;
$key2= ABC;

$response = $client->request('GET', $endpoint, ['query' => [
    'key1' => $key1,
    'kei2' => $key2

]]);

Body:
You can split URL into parts and put it together in the custom order.

$expectedUrl = 'http://my.domain.com/test/key1=5&key2=ABC';

$urlParts = parse_url('http://my.domain.com/test?key1=5&key2=ABC');
$resultUrl = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'] . '/' . $urlParts['query'];

var_dump(
    $resultUrl === $expectedUrl
);


问:
Processing large arrays in PowerShell
I am having a difficult time understanding the most efficient to process large datasets/arrays in PowerShell. I have arrays that have several million items that I need to process and group. This list is always different in size meaning it could be 3.5 million items or 10 million items.

Example: 3.5 million items they group by "4's" like the following:

Items 0,1,2,3 Group together 4,5,6,7 Group Together and so on.

I have tried processing the array using a single thread by looping through the list and assigning to a pscustomobject which works it just takes 45-50+ minutes to complete.

I have also attempted to break up the array into smaller arrays but that causes the process to run even longer.

$i=0
$d_array = @()
$item_array # Large dataset

While ($i -lt $item_array.length){

    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++

    $items = [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    $d_array += $items

}
```

I would imagine if I applied a job scheduler that would allow me to run the multiple jobs would cut the process time down by a significant amount, but I wanted to get others takes on a quick effective way to tackle this.

答:
If you are working with large data, using C# is also effective.</p>

```<code>Add-Type -TypeDefinition @"
using System.Collections.Generic;

public static class Test
{
    public static List<object> Convert(object[] src)
    {
        var result = new List<object>();
        for(var i = 0; i <= src.Length - 4; i+=4)
        {
            result.Add( new {
                field1 = "Test",
                field2 = "Test",
                field3 = src[i + 0],
                field4 = src[i + 1],
                field5 = src[i + 2],
                field6 = src[i + 3]
            });
        }
        return result;
    }
}
"@

$item_array = 1..10000000
$result = [Test]::Convert($item_array)
</code>```

Title: Processing large arrays in PowerShell

Body:
I am having a difficult time understanding the most efficient to process large datasets/arrays in PowerShell. I have arrays that have several million items that I need to process and group. This list is always different in size meaning it could be 3.5 million items or 10 million items.

Example: 3.5 million items they group by "4's" like the following:

Items 0,1,2,3 Group together 4,5,6,7 Group Together and so on.

I have tried processing the array using a single thread by looping through the list and assigning to a pscustomobject which works it just takes 45-50+ minutes to complete.

I have also attempted to break up the array into smaller arrays but that causes the process to run even longer.

$i=0
$d_array = @()
$item_array # Large dataset

While ($i -lt $item_array.length){

    $o = "Test"
    $oo = "Test"
    $n = $item_array[$i];$i++
    $id = $item_array[$i];$i++
    $ir = $item_array[$i];$i++
    $cs = $item_array[$i];$i++

    $items = [PSCustomObject]@{
        'field1' = $o
        'field2' = $oo
        'field3' = $n
        'field4' = $id
        'field5' = $ir
        'field6'= $cs
    }
    $d_array += $items

}

I would imagine if I applied a job scheduler that would allow me to run the multiple jobs would cut the process time down by a significant amount, but I wanted to get others takes on a quick effective way to tackle this.

Body:
If you are working with large data, using C# is also effective.

Add-Type -TypeDefinition @"
using System.Collections.Generic;

public static class Test
{
    public static List<object> Convert(object[] src)
    {
        var result = new List<object>();
        for(var i = 0; i <= src.Length - 4; i+=4)
        {
            result.Add( new {
                field1 = "Test",
                field2 = "Test",
                field3 = src[i + 0],
                field4 = src[i + 1],
                field5 = src[i + 2],
                field6 = src[i + 3]
            });
        }
        return result;
    }
}
"@

$item_array = 1..10000000
$result = [Test]::Convert($item_array)


问:
How does Xcode know which profile the application belongs to?
I have been wondering about how does xcode link the provisioning profile to a particular application.

For example, I install profile named 'myprofile' in the organizer and go to the project name 'newapp' and say build and go.

The application 'newapp' is installed fine on the iphone but how do i know if there is a link between 'newapp' and 'myprofile'.

What happens if i change my app name and again say build and go?

This is what i do:

 1. Login to my account.

 2. Create a new app id: 'first'

 3. Use existing device: 'myiphone'

 4. enter the profile name: 'myprofile', download it

 5. install it inside organizer. (Till this point no application is assigned to the profile)

 6. Now go to my project: 'newapp' just say build and go and app runs on the device.

I never selected a profile and said assign the app to this profile so...
How can i say that 'myprofile' is tied to 'newapp'?

Thanks

答: You can manually set which profile an app will use in the build settings (under "Code Signing Identity"). The default for this is automatic which will match based on your app identifier (com.example.appname).</p>

ContentLicense: CC BY-SA 3.0


问:
Color clustered features based on clustered point counts
I'm developing an app using Xamarin.iOS and Mapbox iOS SDK (Naxam.Mapbox.iOS NuGet package here.
And i'm following this example in MapBox iOS SDK website: https://docs.mapbox.com/ios/maps/examples/clustering/.

And i'm having problems converting this part of code to C#:

```<code>// Color clustered features based on clustered point counts.
let stops = [
    20: UIColor.lightGray,
    50: UIColor.orange,
    100: UIColor.red,
    200: UIColor.purple
]
</code>```

And:

```<code>circlesLayer.circleColor = NSExpression(format: "mgl_step:from:stops:(point_count, %@, %@)", UIColor.lightGray, stops)
</code>```

I'm able to set an unique color to the cluster if i do it like this:

```<code>circlesLayer.CircleColor = NSExpression.FromConstant(FromObject(UIColor.Green));
</code>```

But i'm not managing to do it if i follow the example, in it, the Expression format takes 3 Parameters: string, UiColor, Array

But in C# NSExpression.FromConstant, takes at max 2 params: string and a NSObject[], so i created this: (to match the array "stops" in the examle)

```<code>NSDictionary[] stops = new NSDictionary[]
{
    new NSDictionary(new NSNumber(0), FromObject(UIColor.Green)),
    new NSDictionary(new NSNumber(20), FromObject(UIColor.Blue)),
    new NSDictionary(new NSNumber(100), FromObject(UIColor.Red))
};
</code>```

But it no success, what should i be doing instead?

答:
You can use NSExpression.FromFormat(string format, NSObject [] parameters) for this purpose.

Something like this:

```<code>circlesLayer.CircleColor = NSExpression.FromFormat ("mgl_step:from:stops:(point_count, %@, %@)", stops)
</code>```

Where stops is what you had above with the dictionary.

Body:
I'm developing an app using Xamarin.iOS and Mapbox iOS SDK (Naxam.Mapbox.iOS NuGet package here.
And i'm following this example in MapBox iOS SDK website: https://docs.mapbox.com/ios/maps/examples/clustering/.

And i'm having problems converting this part of code to C#:

// Color clustered features based on clustered point counts.
let stops = [
    20: UIColor.lightGray,
    50: UIColor.orange,
    100: UIColor.red,
    200: UIColor.purple
]

And:

circlesLayer.circleColor = NSExpression(format: "mgl_step:from:stops:(point_count, %@, %@)", UIColor.lightGray, stops)

I'm able to set an unique color to the cluster if i do it like this:

circlesLayer.CircleColor = NSExpression.FromConstant(FromObject(UIColor.Green));

But i'm not managing to do it if i follow the example, in it, the Expression format takes 3 Parameters: string, UiColor, Array

But in C# NSExpression.FromConstant, takes at max 2 params: string and a NSObject[], so i created this: (to match the array "stops" in the examle)

NSDictionary[] stops = new NSDictionary[]
{
    new NSDictionary(new NSNumber(0), FromObject(UIColor.Green)),
    new NSDictionary(new NSNumber(20), FromObject(UIColor.Blue)),
    new NSDictionary(new NSNumber(100), FromObject(UIColor.Red))
};

But it no success, what should i be doing instead?

Body:
You can use NSExpression.FromFormat(string format, NSObject [] parameters) for this purpose.

Something like this:

circlesLayer.CircleColor = NSExpression.FromFormat ("mgl_step:from:stops:(point_count, %@, %@)", stops)

Where stops is what you had above with the dictionary.


问:
How to select letters from a string until predefined point?
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

```<code>vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end
</code>```

答:
```<code>consonants << letter until vowels.include?(letter)
</code>```

will just end up pushing the same consonant over and over again (an infinite loop).

How I would do this, is reduce using `break.

I recommend reading up on these if you're unfamiliar

https://apidock.com/ruby/Enumerable/reduce

How to break out from a ruby block?

```<code># better to make this a constant
Vowels = ["a", "e", "i", "o", "u"]

def letters_before_first_vowel(string)
  string.chars.reduce([]) do |result, char|
    break result if Vowels.include?(char)
    result + [char]
  end.join
end

puts letters_before_first_vowel("truck")
# => "tr"
</code>```

Body:
I would like to extract all consonants in a string before the first vowel, ideally without using regex. If I have the word truck for example I would like to extract the "tr", for "street" I would like to extract "str".

I tried the following but received the error wrong number of arguments (given 0, expected 1) for the execution of the block in vowels.

Can someone explain where the error is or suggest an easier way to do this?

vowels = ["a", "e", "i", "o", "u"]

def vowels(words)
  letters = words.split("")
  consonants = []
  letters.each do |letter|
    consonants << letter until vowels.include?(letter)
  end
  consonants
end

Body:
consonants << letter until vowels.include?(letter)

will just end up pushing the same consonant over and over again (an infinite loop).

How I would do this, is reduce using `break.

I recommend reading up on these if you're unfamiliar

https://apidock.com/ruby/Enumerable/reduce

How to break out from a ruby block?

# better to make this a constant
Vowels = ["a", "e", "i", "o", "u"]

def letters_before_first_vowel(string)
  string.chars.reduce([]) do |result, char|
    break result if Vowels.include?(char)
    result + [char]
  end.join
end

puts letters_before_first_vowel("truck")
# => "tr"


问:
This BackgroundWorker states that it doesn't report progress
Where is my mistake? I think everything is fine but still I see this exception:

Exception {"This BackgroundWorker states that it doesn't report
  progress. Modify WorkerReportsProgress to state that it does report
  progress."}.Exception wasthrown in
  _worker.ReportProgress((int)(progressPercentage*100)).

Can somebody recommend me a ftp server with rich data for test download and upload?

Here is my code:

```<code>    this._worker = new BackgroundWorker();

    this._worker.WorkerSupportsCancellation = true;
    this._worker.WorkerSupportsCancellation = true;

    this._worker.ProgressChanged += backgroundWorker1_ProgressChanged;
    this._worker.DoWork += backgroundWorker1_DoWork;

using (FileStream fs = new    FileStream(Path.Combine(this._ftpInfo.SaveDirectory, this._ftpInfo.FileName), FileMode.CreateNew, FileAccess.Write))
                    {

                byte[] buffer = new byte[1024];
                    int len;
                    int byteTotal = 0;

                    while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        await fs.WriteAsync(buffer, 0, len);
                        byteTotal += len;
                        double index = (double)(byteTotal);
                        double total = (double)buffer.Length;
                        double progressPercentage = (index / total);
                        _worker.ReportProgress((int)(progressPercentage*100));

                    }
                    fs.Close();
</code>```

答:
You have this line twice:

```<code>this._worker.WorkerSupportsCancellation = true;
</code>```

One of those was probably supposed to be:

```<code>this._worker.WorkerReportsProgress = true;
</code>```

On a side note, consider using Task.Run with IProgress<T> instead of BackgroundWorker. The resulting code will be shorter and more type-safe.

Body:
Where is my mistake? I think everything is fine but still I see this exception:

Exception {"This BackgroundWorker states that it doesn't report
  progress. Modify WorkerReportsProgress to state that it does report
  progress."}.Exception wasthrown in
  _worker.ReportProgress((int)(progressPercentage*100)).

Can somebody recommend me a ftp server with rich data for test download and upload?

Here is my code:

    this._worker = new BackgroundWorker();

    this._worker.WorkerSupportsCancellation = true;
    this._worker.WorkerSupportsCancellation = true;

    this._worker.ProgressChanged += backgroundWorker1_ProgressChanged;
    this._worker.DoWork += backgroundWorker1_DoWork;

using (FileStream fs = new    FileStream(Path.Combine(this._ftpInfo.SaveDirectory, this._ftpInfo.FileName), FileMode.CreateNew, FileAccess.Write))
                    {

                byte[] buffer = new byte[1024];
                    int len;
                    int byteTotal = 0;

                    while ((len = stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        await fs.WriteAsync(buffer, 0, len);
                        byteTotal += len;
                        double index = (double)(byteTotal);
                        double total = (double)buffer.Length;
                        double progressPercentage = (index / total);
                        _worker.ReportProgress((int)(progressPercentage*100));

                    }
                    fs.Close();

Body:
You have this line twice:

this._worker.WorkerSupportsCancellation = true;

One of those was probably supposed to be:

this._worker.WorkerReportsProgress = true;

On a side note, consider using Task.Run with IProgress<T> instead of BackgroundWorker. The resulting code will be shorter and more type-safe.


问:
Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."
Important notice:

If you register for testing, go to your profile settings and to your interests add delete profile.

Trying to login with Facebook to my website:

I get the following error:

URL Blocked: This redirect failed because the redirect URI is not
  whitelisted in the app’s Client OAuth Settings. Make sure Client and
  Web OAuth Login are on and add all your app domains as Valid OAuth
  Redirect URIs.

My settings (Basics) in Facebook are:

App Domains: openstrategynetwork.com

Site URL for website: http://openstrategynetwork.com/

In the advanced tab, Valid OAuth redirect URIs is set to:

http://openstrategynetwork.com/_oauth/facebook?close

App is public.

More settings (Advanced) here:

App key and secret are correct. I'm using Meteor and its accounts packages.

答:
Ok First of all this is a very clear error message. Just look at this many devs miss this including my self. Have a look at the screen shot here please.

Under Products > Facebook Login > Settings

or just go to this url here (Replace YOUR_APP_ID with your app id lol):

```<code>https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/settings/
</code>```

If you are working on localhost:3000 Make sure you have https://localhost:3000/auth/facebook/callback

Ofcourse you don't have to have the status live (Green Switch on top right corner) but in my case, I am deploying to heroku now and will soon replace localhost:3000 with https://myapp.herokuapp.com/auth/facebook/callback

Of course I will update the urls in Settings/Basic & Settings/Advanced and also add a privacy policy url in the basic section.

I am assuming that you have properly configured initializers/devise.rb  if you are using devise and you have the proper facebook gem 'omniauth-facebook', '~> 4.0' gem installed and gem 'omniauth', '~> 1.6', and you have the necessary columns in your users table such as uid, image, and provider. That's it.

Body:
Ok First of all this is a very clear error message. Just look at this many devs miss this including my self. Have a look at the screen shot here please.

Under Products > Facebook Login > Settings

or just go to this url here (Replace YOUR_APP_ID with your app id lol):

https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/settings/

If you are working on localhost:3000 Make sure you have https://localhost:3000/auth/facebook/callback

Ofcourse you don't have to have the status live (Green Switch on top right corner) but in my case, I am deploying to heroku now and will soon replace localhost:3000 with https://myapp.herokuapp.com/auth/facebook/callback

Of course I will update the urls in Settings/Basic & Settings/Advanced and also add a privacy policy url in the basic section.

I am assuming that you have properly configured initializers/devise.rb  if you are using devise and you have the proper facebook gem 'omniauth-facebook', '~> 4.0' gem installed and gem 'omniauth', '~> 1.6', and you have the necessary columns in your users table such as uid, image, and provider. That's it.


问:
How to get Dataframe with associated Zip codes from Lat and Long in python?
I am trying to reverse Geocode and get the zip codes.
I have a table / dataframe that has 400,000 lat and long and I would like to get the zip code by parsing the lat,long.

Below is the sample dataframe

```<code>data = {'Site 1': '31.336968, -109.560959',
        'Site 2': '31.347745, -108.229963',
        'Site 3': '32.277621, -107.734724',
        'Site 4': '31.655494, -106.420484',
        'Site 5': '30.295053, -104.014528'}
</code>```

My code:

```<code>import geopandas as gpd
from shapely.geometry import Point
gdf_locations = gpd.read_file('/Users/admin/Downloads/tl_2016_us_zcta510/tl_2016_us_zcta510.shp')
</code>```

I downloaded the tl_2016_us_zcta510.shp file from here.

This is where I am getting stuck. One solution that I tried was to convert it to NUMPY array and pass the value. But that seems extremely slow.
I would like to do it as a dataframe using lambda and get the results quickly.

What I tried:

```<code>               [Longitude]    [Latitude]
x = np.array((-73.986946106, 40.284328461))
x_pnt = Point(x)
filter = gdf_locations['geometry'].contains(x_pnt)
print(gdf_locations.loc[filter, 'GEOID10'])
</code>```

While this is giving me what I want, it is extremely slow.
How can I make it faster and as a recursive function?
Any help is appreciated. Thank you.

P.S: I have seen many blog posts and read stuff on this subject, but none seems to address it for large scale real-time implementation.

Edits:
I am specifically looking to get a dataframe with following structure:

```<code> data = {'Site 1': '31.336968, -109.560959', 94108,
            'Site 2': '31.347745, -108.229963', 60616,
            'Site 3': '32.277621, -107.734724', 78654,
            'Site 4': '31.655494, -106.420484', 78090,
            'Site 5': '30.295053, -104.014528', 78901}
</code>```

I understand how to convert lat long to Zip, what I'm not able to do is get a dataframe. Hope this makes it more clear.

答:
I haven't used geopandas very much, but I would try using scipy's cKDTree. It should be very fast for the amount of data you have. The only thing is that it works for point to point lookups, so you'd have to use the centroids of the polygons from the zip code dataset.

For example, transforming the centroids, which are Shapely points, to a numpy array:

```<code>centroids = gdf_locations.centroid

# transform shapely points to np array
point_array = []
for centroid in centroids:
    point_array.append([centroid.x, centroid.y])
point_array = np.array(point_array)
</code>```

```<code>print(point_array[0])
>>> array([-83.61511443,  41.31279856])
</code>```

To make sure it was going to be a quick lookup I create 400,000 random coordinates:

```<code>random_lat_long = np.random.randn(400000, 2) * 80
</code>```

```<code>print(random_lat_long)
>>> array([ -8.37429385, -23.19458311])
</code>```

Now for the closest point:

```<code>distance, index = spatial.cKDTree(point_array).query(random_lat_long)
</code>```

On my computer using %%timeit in Jupyter this took about 1.7 seconds.

And finally, grabbing the zip codes from the dataframe:

```<code>zip_codes = gdf_locations.loc[index, 'GEOID10']
</code>```

Edit:
To get the latitude and longitude as part of the result:

Pull out data and convert types:

```<code>lats_lons_zips = gdf_locations.loc[index, ['INTPTLAT10', 'INTPTLON10', 'GEOID10']]
# keep the zip code as an str to preserve leading zeros
lats_lons_zips = lats_lons_zips.astype({"INTPTLAT10": float, "INTPTLON10": float, "GEOID10": str})
</code>```

Change index to "Site XX":

```<code>new_index = ["Site " + str(i) for i in range(len(lats_lons_zips))]
lats_lons_zips.index = new_index
</code>```

Finally, get results:

```<code>print(lats_lons_zips.iloc[0:4].to_dict(orient="index"))
</code>```

```<code>{ 'Site 0': { 'GEOID10': '00824',
              'INTPTLAT10': 17.7445568,
              'INTPTLON10': -64.6829328},
  'Site 1': { 'GEOID10': '96916',
              'INTPTLAT10': 13.2603723,
              'INTPTLON10': 144.7006789},
  'Site 2': { 'GEOID10': '96916',
              'INTPTLAT10': 13.2603723,
              'INTPTLON10': 144.7006789},
  'Site 3': { 'GEOID10': '04741',
              'INTPTLAT10': 47.453712,
              'INTPTLON10': -69.2229208}}
</code>```

Body:
I am trying to reverse Geocode and get the zip codes.
I have a table / dataframe that has 400,000 lat and long and I would like to get the zip code by parsing the lat,long.

Below is the sample dataframe

data = {'Site 1': '31.336968, -109.560959',
        'Site 2': '31.347745, -108.229963',
        'Site 3': '32.277621, -107.734724',
        'Site 4': '31.655494, -106.420484',
        'Site 5': '30.295053, -104.014528'}

My code:

import geopandas as gpd
from shapely.geometry import Point
gdf_locations = gpd.read_file('/Users/admin/Downloads/tl_2016_us_zcta510/tl_2016_us_zcta510.shp')

I downloaded the tl_2016_us_zcta510.shp file from here.

This is where I am getting stuck. One solution that I tried was to convert it to NUMPY array and pass the value. But that seems extremely slow.
I would like to do it as a dataframe using lambda and get the results quickly.

What I tried:

               [Longitude]    [Latitude]
x = np.array((-73.986946106, 40.284328461))
x_pnt = Point(x)
filter = gdf_locations['geometry'].contains(x_pnt)
print(gdf_locations.loc[filter, 'GEOID10'])

While this is giving me what I want, it is extremely slow.
How can I make it faster and as a recursive function?
Any help is appreciated. Thank you.

P.S: I have seen many blog posts and read stuff on this subject, but none seems to address it for large scale real-time implementation.

Edits:
I am specifically looking to get a dataframe with following structure:

 data = {'Site 1': '31.336968, -109.560959', 94108,
            'Site 2': '31.347745, -108.229963', 60616,
            'Site 3': '32.277621, -107.734724', 78654,
            'Site 4': '31.655494, -106.420484', 78090,
            'Site 5': '30.295053, -104.014528', 78901}

I understand how to convert lat long to Zip, what I'm not able to do is get a dataframe. Hope this makes it more clear.

Body:
I haven't used geopandas very much, but I would try using scipy's cKDTree. It should be very fast for the amount of data you have. The only thing is that it works for point to point lookups, so you'd have to use the centroids of the polygons from the zip code dataset.

For example, transforming the centroids, which are Shapely points, to a numpy array:

centroids = gdf_locations.centroid

# transform shapely points to np array
point_array = []
for centroid in centroids:
    point_array.append([centroid.x, centroid.y])
point_array = np.array(point_array)

print(point_array[0])
>>> array([-83.61511443,  41.31279856])

To make sure it was going to be a quick lookup I create 400,000 random coordinates:

random_lat_long = np.random.randn(400000, 2) * 80

print(random_lat_long)
>>> array([ -8.37429385, -23.19458311])

Now for the closest point:

distance, index = spatial.cKDTree(point_array).query(random_lat_long)

On my computer using %%timeit in Jupyter this took about 1.7 seconds.

And finally, grabbing the zip codes from the dataframe:

zip_codes = gdf_locations.loc[index, 'GEOID10']

Edit:
To get the latitude and longitude as part of the result:

Pull out data and convert types:

lats_lons_zips = gdf_locations.loc[index, ['INTPTLAT10', 'INTPTLON10', 'GEOID10']]
# keep the zip code as an str to preserve leading zeros
lats_lons_zips = lats_lons_zips.astype({"INTPTLAT10": float, "INTPTLON10": float, "GEOID10": str})

Change index to "Site XX":

new_index = ["Site " + str(i) for i in range(len(lats_lons_zips))]
lats_lons_zips.index = new_index

Finally, get results:

print(lats_lons_zips.iloc[0:4].to_dict(orient="index"))

{ 'Site 0': { 'GEOID10': '00824',
              'INTPTLAT10': 17.7445568,
              'INTPTLON10': -64.6829328},
  'Site 1': { 'GEOID10': '96916',
              'INTPTLAT10': 13.2603723,
              'INTPTLON10': 144.7006789},
  'Site 2': { 'GEOID10': '96916',
              'INTPTLAT10': 13.2603723,
              'INTPTLON10': 144.7006789},
  'Site 3': { 'GEOID10': '04741',
              'INTPTLAT10': 47.453712,
              'INTPTLON10': -69.2229208}}


问:
"Error: Server Error. socket hang up" whenever I do "firebase deploy --only hosting, database, storage"
I am currently working with Firebase using its hosting, functions, storage, database. After setting up all the firebase.json correctly, whenever I try to deploy those to the my project on firebase, this error keeps occuring.

firebase.json is in a good condition.
I simply followed the instructions provided by firebase docs.
I tried to uninstall and reinstall the 'firebase-tools' npm for my CLI.
I have all checked the answers across the stackoverflow, but it seems that there is no correct answer.

```<code>firebase login
firebase list
firebase use 'myprojectid'
firebase deploy --only database, functions, storage, hosting
</code>```

I expect it to work properly so that all things get deloyed.
But I got this "socket hang up"error.

答:
I opened the issue on "firebase-tools" GitHub repo. Thanks to "thechenky", I caught the clue to solve this problem. The problem was ".firebaserc" settings. The configuration was not correct for my project as following:

```<code>{
  "projects": {
    "default": "gobot-a5af4",
    "dev": "gobot-a5af4",
    "prod": "gobot-3e82e",
    "mu": "gobot-multiuser"
  }
}
</code>```

So, whenever I deploy my functions, storage, database, and hosting, I unconsciously implied wrong projectID by "default".
You can check the link: https://github.com/firebase/firebase-tools/issues/1309

Body:
I am currently working with Firebase using its hosting, functions, storage, database. After setting up all the firebase.json correctly, whenever I try to deploy those to the my project on firebase, this error keeps occuring.

firebase.json is in a good condition.
I simply followed the instructions provided by firebase docs.
I tried to uninstall and reinstall the 'firebase-tools' npm for my CLI.
I have all checked the answers across the stackoverflow, but it seems that there is no correct answer.

firebase login
firebase list
firebase use 'myprojectid'
firebase deploy --only database, functions, storage, hosting

I expect it to work properly so that all things get deloyed.
But I got this "socket hang up"error.

Body:
I opened the issue on "firebase-tools" GitHub repo. Thanks to "thechenky", I caught the clue to solve this problem. The problem was ".firebaserc" settings. The configuration was not correct for my project as following:

{
  "projects": {
    "default": "gobot-a5af4",
    "dev": "gobot-a5af4",
    "prod": "gobot-3e82e",
    "mu": "gobot-multiuser"
  }
}

So, whenever I deploy my functions, storage, database, and hosting, I unconsciously implied wrong projectID by "default".
You can check the link: https://github.com/firebase/firebase-tools/issues/1309


问:
array return index from another array
suppose we have this two array. in some condition, I want to return the index of a second array.

```<code>let a = [1, 2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 , 12]
let b = [0, 1, 2, 3 , 4 , 5, 6 , 7 , 8, 9, 10, 11]

if (a[2]) ? return b[2] : return null
</code>```

why I need this? because I have a month number of the year that starts from 0 to 11. but I need to turn this 1 12 for storing in my database.
sry about the title of this question if someone has a better title I would be glad about changing it.

答:
You could calculate the value by adding 11 and get the remainder value with 12.

function getZeroBasedMonth(n) {
    return (n + 11) % 12;
}

console.log(getZeroBasedMonth(1));
console.log(getZeroBasedMonth(12));```
</div>
</div>
</p>

<p>For the getting the opposite, just add one.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getMonth(n) {
    return n + 1;
}

console.log(getMonth(0));
console.log(getMonth(11));</code>```

Title: array return index from another array

Body:
suppose we have this two array. in some condition, I want to return the index of a second array.

let a = [1, 2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 , 12]
let b = [0, 1, 2, 3 , 4 , 5, 6 , 7 , 8, 9, 10, 11]

if (a[2]) ? return b[2] : return null

why I need this? because I have a month number of the year that starts from 0 to 11. but I need to turn this 1 12 for storing in my database.
sry about the title of this question if someone has a better title I would be glad about changing it.

Body:
You could calculate the value by adding 11 and get the remainder value with 12.

function getZeroBasedMonth(n) {
    return (n + 11) % 12;
}

console.log(getZeroBasedMonth(1));
console.log(getZeroBasedMonth(12));

For the getting the opposite, just add one.

function getMonth(n) {
    return n + 1;
}

console.log(getMonth(0));
console.log(getMonth(11));


问:
why there is no return value rather gives null
why does the return value in this function gives None
rather i think it should return count

output - None

```<code>def longestChain(num,count):
    if num==1:
        return count
    elif num%2==0:
        num = num/2
        count+=1
        longestChain(num,count)
    elif num%2==1:
        num =3*num+1
        count+=1
        longestChain(num,count)

print(longestChain(13,1))
</code>```

CORRECTED  ONE

```<code>def longestChain(num,count):
    if num==1:
        return count
    elif num%2==0:
        num = num/2
        count+=1
        return longestChain(num,count)
    elif num%2==1:
        num =3*num+1
        count+=1
        return longestChain(num,count)

print(longestChain(13,1))
</code>```

答: You're only returning a value in case num==1. In the other cases, you are doing a recursive call, but you forgot to return a value there.

Body:
why does the return value in this function gives None
rather i think it should return count

output - None

def longestChain(num,count):
    if num==1:
        return count
    elif num%2==0:
        num = num/2
        count+=1
        longestChain(num,count)
    elif num%2==1:
        num =3*num+1
        count+=1
        longestChain(num,count)

print(longestChain(13,1))

CORRECTED  ONE

def longestChain(num,count):
    if num==1:
        return count
    elif num%2==0:
        num = num/2
        count+=1
        return longestChain(num,count)
    elif num%2==1:
        num =3*num+1
        count+=1
        return longestChain(num,count)

print(longestChain(13,1))


问:
Sort spring @Beans by method level @Order annotation
My library has to deal with multiple beans (interceptors) that are specified in arbitrary order (because they are spread over multiple configuration files).
Before I can apply them I have to sort them by their priority. I use AnnotationAwareOrderComparator.sort(beans) for that. This works well as long as the @Order annotation is added on the class level of that interceptor.
But it does not work when I try to use it in @Configuration classes on @Bean methods:

```<code>@Configuration
public class Config {

    @Bean
    @Order(1)
    public ServerInterceptor exceptionTranslatingServerInterceptor() {
        return ...;
    }

    @Bean
    @Order(2)
    public ServerInterceptor authenticatingServerInterceptor() {
        return ...;
    }

    @Bean
    @Order(3)
    public ServerInterceptor authorizationCheckingServerInterceptor() {
        return ...
    }

}
</code>```

But if I add a test like this:

```<code>@Test
void testOrderingOfTheDefaultInterceptors() {
    List<ServerInterceptor> expected = new ArrayList<>();
    expected.add(applicationContext.getBean(ExceptionTranslatingServerInterceptor.class));
    expected.add(applicationContext.getBean(AuthenticatingServerInterceptor.class));
    expected.add(applicationContext.getBean(AuthorizationCheckingServerInterceptor.class));

    List<ServerInterceptor> actual = new ArrayList<>(this.registry.getServerInterceptors());
    assertEquals(expected, actual); // Accidentally passes
    // System.out.println(actual);

    Collections.shuffle(actual);
    AnnotationAwareOrderComparator.sort(actual);
    assertEquals(expected, actual); // Fails
    // System.out.println(actual);
}
</code>```

Then the test will fail.
From my debugging I know that AnnotationAwareOrderComparator.findOrder(Object) always returns null (unspecified) for the order of those beans. Probably because the bean instances aren't proxied and thus neither implement order nor have the order annotation on their class level. Is there a BeanPostProcessor or an config option that I have to enable?

How do I tell spring to either preserve the annotated order or use the application context's bean definitions to sort the beans appropriately?

答:
For your test case to work you need to use Ordered interface instead of the annotation.
Lets examine the source code of AnnotationAwareOrderComparator. Notice that you are passing directly the objects to the sort method. The  AnnotationAwareOrderComparator is using the findOrder upon the pased objects in order to find one of the three artifacts @Priority annotation @Order annotation or @Ordered interface. In your case you are passing the interceptor instances so the if check for Methidf and for Class will return false. You will hit the last if method: if (obj != null)

in which case it will just check you object clas for @Order annotation which will be null in your case. Effectivly your test case is just wrong. Notice though that your testcase will behave as expected if you implement Ordered interface.

```<code>public static void sort(List list) {
        if (list.size() > 1) {
            Collections.sort(list, INSTANCE);
        }
    }

protected Integer findOrder(Object obj) {
        // Check for regular Ordered interface
        Integer order = super.findOrder(obj);
        if (order != null) {
            return order;
        }

        // Check for @Order and @Priority on various kinds of elements
        if (obj instanceof Class) {
            return OrderUtils.getOrder((Class) obj);
        }
        else if (obj instanceof Method) {
            Order ann = AnnotationUtils.findAnnotation((Method) obj, Order.class);
            if (ann != null) {
                return ann.value();
            }
        }
        else if (obj instanceof AnnotatedElement) {
            Order ann = AnnotationUtils.getAnnotation((AnnotatedElement) obj, Order.class);
            if (ann != null) {
                return ann.value();
            }
        }
        else if (obj != null) {
            return OrderUtils.getOrder(obj.getClass());
        }

        return null;
    }
</code>```

Body:
My library has to deal with multiple beans (interceptors) that are specified in arbitrary order (because they are spread over multiple configuration files).
Before I can apply them I have to sort them by their priority. I use AnnotationAwareOrderComparator.sort(beans) for that. This works well as long as the @Order annotation is added on the class level of that interceptor.
But it does not work when I try to use it in @Configuration classes on @Bean methods:

@Configuration
public class Config {

    @Bean
    @Order(1)
    public ServerInterceptor exceptionTranslatingServerInterceptor() {
        return ...;
    }

    @Bean
    @Order(2)
    public ServerInterceptor authenticatingServerInterceptor() {
        return ...;
    }

    @Bean
    @Order(3)
    public ServerInterceptor authorizationCheckingServerInterceptor() {
        return ...
    }

}

But if I add a test like this:

@Test
void testOrderingOfTheDefaultInterceptors() {
    List<ServerInterceptor> expected = new ArrayList<>();
    expected.add(applicationContext.getBean(ExceptionTranslatingServerInterceptor.class));
    expected.add(applicationContext.getBean(AuthenticatingServerInterceptor.class));
    expected.add(applicationContext.getBean(AuthorizationCheckingServerInterceptor.class));

    List<ServerInterceptor> actual = new ArrayList<>(this.registry.getServerInterceptors());
    assertEquals(expected, actual); // Accidentally passes
    // System.out.println(actual);

    Collections.shuffle(actual);
    AnnotationAwareOrderComparator.sort(actual);
    assertEquals(expected, actual); // Fails
    // System.out.println(actual);
}

Then the test will fail.
From my debugging I know that AnnotationAwareOrderComparator.findOrder(Object) always returns null (unspecified) for the order of those beans. Probably because the bean instances aren't proxied and thus neither implement order nor have the order annotation on their class level. Is there a BeanPostProcessor or an config option that I have to enable?

How do I tell spring to either preserve the annotated order or use the application context's bean definitions to sort the beans appropriately?

Body:
For your test case to work you need to use Ordered interface instead of the annotation.
Lets examine the source code of AnnotationAwareOrderComparator. Notice that you are passing directly the objects to the sort method. The  AnnotationAwareOrderComparator is using the findOrder upon the pased objects in order to find one of the three artifacts @Priority annotation @Order annotation or @Ordered interface. In your case you are passing the interceptor instances so the if check for Methidf and for Class will return false. You will hit the last if method: if (obj != null)

in which case it will just check you object clas for @Order annotation which will be null in your case. Effectivly your test case is just wrong. Notice though that your testcase will behave as expected if you implement Ordered interface.

public static void sort(List list) {
        if (list.size() > 1) {
            Collections.sort(list, INSTANCE);
        }
    }

protected Integer findOrder(Object obj) {
        // Check for regular Ordered interface
        Integer order = super.findOrder(obj);
        if (order != null) {
            return order;
        }

        // Check for @Order and @Priority on various kinds of elements
        if (obj instanceof Class) {
            return OrderUtils.getOrder((Class) obj);
        }
        else if (obj instanceof Method) {
            Order ann = AnnotationUtils.findAnnotation((Method) obj, Order.class);
            if (ann != null) {
                return ann.value();
            }
        }
        else if (obj instanceof AnnotatedElement) {
            Order ann = AnnotationUtils.getAnnotation((AnnotatedElement) obj, Order.class);
            if (ann != null) {
                return ann.value();
            }
        }
        else if (obj != null) {
            return OrderUtils.getOrder(obj.getClass());
        }

        return null;
    }


问:
Using AtomicInteger and CountDownLatch to generate one instance
I have a class which I want to have only one instance. However, I don't want multiple threads to call getInstance(). So I have coded it in the following way

```<code>public class SomeService implements Provider<String, Claims>{

    private SomeService(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // single instance
    private static SomeService instance = null;

    private String a;
    private static AtomicInteger initialized = new AtomicInteger();
    private static CountDownLatch latch = new CountDownLatch(1);
    private String b;
    private String c;

    public static SomeService getInstance(String a, String b, String c) {
       if ( initialized.incrementAndGet() == 1) {
           instance = new SomeService(a, b, c);
           latch.countDown();
       } else {
           try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       }
       return instance;

    }

    // Other implementation code

    }
</code>```

My intention (as well as understanding about this) is that:

When a thread calls getInstance it will atomically increment and check whehther it's desired value.

If not, it will wait for the other thread to open the latch which means initialization is in progress.

It would be helpful if someone helps me correct my mistakes. Seems to me that I can probably just do synchronized(someLockObject) {} block but I was wondering if this makes sense at all.

答:
I guess the design is fundamentally wrong here. what I believe I should be doing is

1) Put more abstraction layer and ensure that a builder pattern is used.

2) When my service needs to serve, it can use the initialization properties to determine what builder to use and then do that job.

3) If possible, I can also combine it with a factory.

Don't know if the above makes sense, but this removes the need for antipattern or "Singleton".

Body:
I have a class which I want to have only one instance. However, I don't want multiple threads to call getInstance(). So I have coded it in the following way

public class SomeService implements Provider<String, Claims>{

    private SomeService(String a, String b, String c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    // single instance
    private static SomeService instance = null;

    private String a;
    private static AtomicInteger initialized = new AtomicInteger();
    private static CountDownLatch latch = new CountDownLatch(1);
    private String b;
    private String c;

    public static SomeService getInstance(String a, String b, String c) {
       if ( initialized.incrementAndGet() == 1) {
           instance = new SomeService(a, b, c);
           latch.countDown();
       } else {
           try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
       }
       return instance;

    }

    // Other implementation code

    }

My intention (as well as understanding about this) is that:

When a thread calls getInstance it will atomically increment and check whehther it's desired value.

If not, it will wait for the other thread to open the latch which means initialization is in progress.

It would be helpful if someone helps me correct my mistakes. Seems to me that I can probably just do synchronized(someLockObject) {} block but I was wondering if this makes sense at all.


问:
How to properly use connections and transactions in a FOR loop?
EDIT: I get the ERROR that my connection is already closed

I just started working with some databases and connections. I didn't understand exactly how they worked and wrote an absolute monstrosity. If anybody can fix this code i'll be really grateful, as i have no clue what to do. Thanks.
PS. The variables show how much i'm close to losing my mind
PPS. I tried to make the code look nicer but stack overflow just won't let me

```<code>        povezava = new SqlConnection(izdvor);

        povezava.Open();

        SqlTransaction mTrans = povezava.BeginTransaction();
        poizvedba = new SqlCommand("SELECT COUNT(id) FROM Tekme", povezava);
        poizvedba.Transaction = mTrans;
        int Tekma = (int)poizvedba.ExecuteScalar();

            poizvedba.CommandType = CommandType.Text;
        poizvedba.ExecuteNonQuery();
        mTrans.Commit();
        povezava.Close();
        for (int i = 0; i < Tekma; i++)
        {
            if (i < Tekma)
            {
                string dab1 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                lol1 = new SqlConnection(dab1);

                povezava.Open();

                SqlTransaction fTrans = lol1.BeginTransaction();
                test1 = new SqlCommand("SELECT Datum FROM Tekme WHERE id = " + i + "", lol1);
                test1.Transaction = mTrans;
                string Datum = test1.ExecuteScalar().ToString();
                string Datum1 = DateTime.Now.ToString("M/d/yyyy");
                int a = i;

                test1.CommandType = CommandType.Text;
                test1.ExecuteNonQuery();
                fTrans.Commit();
                lol1.Close();
                if (DateTime.Parse(Datum) <= DateTime.Parse(Datum1))
                {
                    string dab2 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                    lol2 = new SqlConnection(dab2);
                    povezava.Open();

                    SqlTransaction kTrans = lol2.BeginTransaction();
                    test2 = new SqlCommand("SELECT Ura FROM Tekme WHERE id = " + i + "", lol2);
                    test2.Transaction = mTrans;
                    int Ura = (int)test2.ExecuteScalar();

                    DateTime dt = DateTime.Now;
                    int hour = dt.Hour;

                    test2.CommandType = CommandType.Text;
                    test2.ExecuteNonQuery();
                    kTrans.Commit();
                    lol2.Close();
                    if (Ura < hour)
                    {
                        string dab3 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                        lol3 = new SqlConnection(dab3);
                        povezava.Open();

                        SqlTransaction yTrans = lol3.BeginTransaction();
                        test3 = new SqlCommand("SELECT Minuta FROM Tekme WHERE id = " + i + "", lol3);
                        test3.Transaction = mTrans;
                        int Minuta = (int)test3.ExecuteScalar();

                        DateTime ft = DateTime.Now;
                        int minute = ft.Minute;

                        test3.CommandType = CommandType.Text;
                        test3.ExecuteNonQuery();
                        yTrans.Commit();
                        lol3.Close();
                        if (Minuta < minute)
                        {
                            string dab4 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                            lol4 = new SqlConnection(dab4);
                            povezava.Open();

                            SqlTransaction xTrans = povezava.BeginTransaction();
                            test4 = new SqlCommand("UPDATE Uporabniki SET idPaketa = @Kdaj WHERE id = " + i + "", povezava);
                            test4.Transaction = mTrans;
                            test4.Parameters.Add(new SqlParameter("@Kdaj", "Prihodnost"));

                            test4.CommandType = CommandType.Text;
                            test4.ExecuteNonQuery();
                            xTrans.Commit();
                            lol4.Close();
                            a = 0;
                        }
</code>```

答:
The best I can tell, you keep opening the povenza connection with povezava.Open(); when  believe you actually mean:

```<code>...
lol1.Open()
...
lol2.Open()
...
lol3.Open()
...
lol4.Open()
...
</code>```

Because you are starting transactions without actually opening the connections.

Also, in general it's not a good practice to be opening and closing database connections in a loop, as this can get out of control quickly and impact performance of your database. It's better to consolidate beforehand or process afterwards and perform a single operation if possible.

Body:
EDIT: I get the ERROR that my connection is already closed

I just started working with some databases and connections. I didn't understand exactly how they worked and wrote an absolute monstrosity. If anybody can fix this code i'll be really grateful, as i have no clue what to do. Thanks.
PS. The variables show how much i'm close to losing my mind
PPS. I tried to make the code look nicer but stack overflow just won't let me

        povezava = new SqlConnection(izdvor);

        povezava.Open();

        SqlTransaction mTrans = povezava.BeginTransaction();
        poizvedba = new SqlCommand("SELECT COUNT(id) FROM Tekme", povezava);
        poizvedba.Transaction = mTrans;
        int Tekma = (int)poizvedba.ExecuteScalar();

            poizvedba.CommandType = CommandType.Text;
        poizvedba.ExecuteNonQuery();
        mTrans.Commit();
        povezava.Close();
        for (int i = 0; i < Tekma; i++)
        {
            if (i < Tekma)
            {
                string dab1 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                lol1 = new SqlConnection(dab1);

                povezava.Open();

                SqlTransaction fTrans = lol1.BeginTransaction();
                test1 = new SqlCommand("SELECT Datum FROM Tekme WHERE id = " + i + "", lol1);
                test1.Transaction = mTrans;
                string Datum = test1.ExecuteScalar().ToString();
                string Datum1 = DateTime.Now.ToString("M/d/yyyy");
                int a = i;

                test1.CommandType = CommandType.Text;
                test1.ExecuteNonQuery();
                fTrans.Commit();
                lol1.Close();
                if (DateTime.Parse(Datum) <= DateTime.Parse(Datum1))
                {
                    string dab2 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                    lol2 = new SqlConnection(dab2);
                    povezava.Open();

                    SqlTransaction kTrans = lol2.BeginTransaction();
                    test2 = new SqlCommand("SELECT Ura FROM Tekme WHERE id = " + i + "", lol2);
                    test2.Transaction = mTrans;
                    int Ura = (int)test2.ExecuteScalar();

                    DateTime dt = DateTime.Now;
                    int hour = dt.Hour;

                    test2.CommandType = CommandType.Text;
                    test2.ExecuteNonQuery();
                    kTrans.Commit();
                    lol2.Close();
                    if (Ura < hour)
                    {
                        string dab3 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                        lol3 = new SqlConnection(dab3);
                        povezava.Open();

                        SqlTransaction yTrans = lol3.BeginTransaction();
                        test3 = new SqlCommand("SELECT Minuta FROM Tekme WHERE id = " + i + "", lol3);
                        test3.Transaction = mTrans;
                        int Minuta = (int)test3.ExecuteScalar();

                        DateTime ft = DateTime.Now;
                        int minute = ft.Minute;

                        test3.CommandType = CommandType.Text;
                        test3.ExecuteNonQuery();
                        yTrans.Commit();
                        lol3.Close();
                        if (Minuta < minute)
                        {
                            string dab4 = @"Data Source=dd\sqlexpress;Initial catalog=Grubelnik2_3DR;user ID=arduino;Password=arduino";
                            lol4 = new SqlConnection(dab4);
                            povezava.Open();

                            SqlTransaction xTrans = povezava.BeginTransaction();
                            test4 = new SqlCommand("UPDATE Uporabniki SET idPaketa = @Kdaj WHERE id = " + i + "", povezava);
                            test4.Transaction = mTrans;
                            test4.Parameters.Add(new SqlParameter("@Kdaj", "Prihodnost"));

                            test4.CommandType = CommandType.Text;
                            test4.ExecuteNonQuery();
                            xTrans.Commit();
                            lol4.Close();
                            a = 0;
                        }

Body:
The best I can tell, you keep opening the povenza connection with povezava.Open(); when  believe you actually mean:

...
lol1.Open()
...
lol2.Open()
...
lol3.Open()
...
lol4.Open()
...

Because you are starting transactions without actually opening the connections.

Also, in general it's not a good practice to be opening and closing database connections in a loop, as this can get out of control quickly and impact performance of your database. It's better to consolidate beforehand or process afterwards and perform a single operation if possible.


问:
Pattern matches bug
I have found a bug in Android when calling static method.

Pattern.matches(String pattern, String value)

Here is the bug details:

let parameter pattern = "^[a-zA-Z0-9]([\\-a-zA-Z0-9_\\u4e00-\\u9fa5]*)+";

let value to be a long string containing symbol "@" (in the end will crash almost every time), for example "Abcjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj@";

call Pattern.matches(pattern, value);

This method get stuck and do not return anything.

if input string is short like "Abc@", it's fine and return false.

if input a short string like "Abc@", then continue to make the string longer like "Abc@jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj@, it's fine and return false.

In my application, when I do this in an EditText and click a Button to excute Pattern.mathes (pattern, value).UI will not response and application will crash then.

I found this bug at work when I want to filtering user's input, then I write a simple test case in my own application to recurrent this bug (see btnTestInput () method), here is my application code.

This is mainActivity XML:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.tyouter.timecat.ui.activity.MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edtTestInputFilter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="none" />

    <Button
        android:id="@+id/btnTestInput"
        android:text="@string/activity_main_test_input_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

This is mainActivity.class:

```<code>@EActivity(R.layout.activity_main)
@OptionsMenu(R.menu.menu_main)
public class MainActivity extends BaseActivity {

    @ViewById
    EditText edtTestInputFilter;

    @ViewById
    Button btnTestInput;

    @Bean
    MainController controller;

    MainAdapter adapter;

    @AfterViews
    void init() {
        TimeCatApplication.BUS.register(this);
    }

    @OptionsItem
    void menuSettings() {

    }

    @OptionsItem
    void menuAbout() {
        controller.onMenuAboutClicked(this);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEventMainThread(TestEventBusEvent event) {
        T.showLong(this, getResources().getString(R.string.test_event_success));
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews(Bundle savedInstance) {

    }

    @Override
    protected void loadData() {

    }

    @Click
    void btnTestInput() {
        if (InputFilter.projectNameMatches(getTest())) {
            T.showLong(this, "pass");
        }else {
            T.showLong(this, "fail");
        }
    }

    private String getTest() {
        return edtTestInputFilter.getText().toString();
    }
}
</code>```

Here is InputFilter.class:

```<code>public class InputFilter {
    static String mProjectName = "^[a-zA-Z0-9]([\\-a-zA-Z0-9_\\u4e00-\\u9fa5]*)+";

    public static boolean matches(String pattern, String value) {
        return Pattern.matches(pattern, value);
    }

    public static boolean projectNameMatches(String projectName) {
        return matches(mProjectName, projectName);
    }
}
</code>```

My Java version: 1.8.0_51.

My Android build tools and sdk:23.0.1 23.

答:
This is no bug, it is catastrophic backtracking. You have nested quantifiers in your pattern. Change it to

```<code>String pattern = "[a-zA-Z0-9][-a-zA-Z0-9_\\u4e00-\\u9fa5]*";
</code>```

You do not need the first ^ in the pattern as you use it inside matches method that requires the entire string to match the pattern.

Title: Pattern matches bug

Body:
I have found a bug in Android when calling static method.

Pattern.matches(String pattern, String value)

Here is the bug details:

let parameter pattern = "^[a-zA-Z0-9]([\\-a-zA-Z0-9_\\u4e00-\\u9fa5]*)+";

let value to be a long string containing symbol "@" (in the end will crash almost every time), for example "Abcjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj@";

call Pattern.matches(pattern, value);

This method get stuck and do not return anything.

if input string is short like "Abc@", it's fine and return false.

if input a short string like "Abc@", then continue to make the string longer like "Abc@jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj@, it's fine and return false.

In my application, when I do this in an EditText and click a Button to excute Pattern.mathes (pattern, value).UI will not response and application will crash then.

I found this bug at work when I want to filtering user's input, then I write a simple test case in my own application to recurrent this bug (see btnTestInput () method), here is my application code.

This is mainActivity XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.tyouter.timecat.ui.activity.MainActivity"
    android:orientation="vertical">

    <EditText
        android:id="@+id/edtTestInputFilter"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="none" />

    <Button
        android:id="@+id/btnTestInput"
        android:text="@string/activity_main_test_input_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

This is mainActivity.class:

@EActivity(R.layout.activity_main)
@OptionsMenu(R.menu.menu_main)
public class MainActivity extends BaseActivity {

    @ViewById
    EditText edtTestInputFilter;

    @ViewById
    Button btnTestInput;

    @Bean
    MainController controller;

    MainAdapter adapter;

    @AfterViews
    void init() {
        TimeCatApplication.BUS.register(this);
    }

    @OptionsItem
    void menuSettings() {

    }

    @OptionsItem
    void menuAbout() {
        controller.onMenuAboutClicked(this);
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEventMainThread(TestEventBusEvent event) {
        T.showLong(this, getResources().getString(R.string.test_event_success));
    }

    @Override
    protected void initVariables() {

    }

    @Override
    protected void initViews(Bundle savedInstance) {

    }

    @Override
    protected void loadData() {

    }

    @Click
    void btnTestInput() {
        if (InputFilter.projectNameMatches(getTest())) {
            T.showLong(this, "pass");
        }else {
            T.showLong(this, "fail");
        }
    }

    private String getTest() {
        return edtTestInputFilter.getText().toString();
    }
}

Here is InputFilter.class:

public class InputFilter {
    static String mProjectName = "^[a-zA-Z0-9]([\\-a-zA-Z0-9_\\u4e00-\\u9fa5]*)+";

    public static boolean matches(String pattern, String value) {
        return Pattern.matches(pattern, value);
    }

    public static boolean projectNameMatches(String projectName) {
        return matches(mProjectName, projectName);
    }
}

My Java version: 1.8.0_51.

My Android build tools and sdk:23.0.1 23.

Body:
This is no bug, it is catastrophic backtracking. You have nested quantifiers in your pattern. Change it to

String pattern = "[a-zA-Z0-9][-a-zA-Z0-9_\\u4e00-\\u9fa5]*";

You do not need the first ^ in the pattern as you use it inside matches method that requires the entire string to match the pattern.


问:
Warshall algorithm idea and possible improvement
Warshall's algorithm for computing the transitive closure of a digraph typically takes the following form (from Warshall algorithm idea and improvement):

```<code>ALGORITHM Warshall(A[1..n, 1..n])
    //ImplementsWarshall’s algorithm for computing the transitive closure
    //Input: The adjacency matrix A of a digraph with n vertices
    //Output: The transitive closure of the digraph
    R(0) ←A
    for k←1 to n do
        for i ←1 to n do
            for j ←1 to n do
                R(k)[i, j ]←R(k−1)[i, j ] or (R(k−1)[i, k] and R(k−1)[k, j])
    return R(n)
</code>```

But we could speed up the above implementation by noticing that there is no update if |i-j| <= k, so we can skip running the update in that case.

Am I missing something? Does this kind of improvement not impact the runtime? (I haven't taken the time yet to calculate the runtime for that version.)

答:
What you're missing is that |i - j| is not related to the distance between i and j.

What Warshal's Algorithm does at iteration k is to determine if there exists a path between the vertex labeled i and the vertex labeled j using only vertices among {1, ..., k} as intermediates. Hence, R(k)[i,j] should equal to 1 if any one of the following two conditions holds:

R(k-1)[i,j] = 1. That is, there exists a path between vertex i and vertex j using only vertices among {1, ..., k-1} as intermediates.

R(k−1)[i, k] and R(k−1)[k, j]. That is, there exists a path from vertex i to vertex k and there exists a path from vertex k to vertex j, each using only vertices among {1, ..., k-1} as intermediates.

The values of i or j (and |i-j| for that matter) have nothing to do with the distances between vertex i and vertex j. They're arbitrary labels serving as identifiers for the vertices.

Body:
Warshall's algorithm for computing the transitive closure of a digraph typically takes the following form (from Warshall algorithm idea and improvement):

ALGORITHM Warshall(A[1..n, 1..n])
    //ImplementsWarshall’s algorithm for computing the transitive closure
    //Input: The adjacency matrix A of a digraph with n vertices
    //Output: The transitive closure of the digraph
    R(0) ←A
    for k←1 to n do
        for i ←1 to n do
            for j ←1 to n do
                R(k)[i, j ]←R(k−1)[i, j ] or (R(k−1)[i, k] and R(k−1)[k, j])
    return R(n)

But we could speed up the above implementation by noticing that there is no update if |i-j| <= k, so we can skip running the update in that case.

Am I missing something? Does this kind of improvement not impact the runtime? (I haven't taken the time yet to calculate the runtime for that version.)


问:
Deploying asp.net core self-contained web app to Ubuntu. Database name empty when present in appsettings.json
I just set up a LAMP server VM on Digital Ocean. OS is Ubuntu 18.04 x64. MySQL is 5.7.23. I also have a published to a local folder asp.net core web application, which I have set to Ubuntu 18.04-x64. I copied the files from the local folder to var/MyApp on the server and set chmod +x on the executable file. I also changed the MySql root password and created a database named limboworld. My application is set to run all migrations on startup. However when I start it with ./catchme.bg I get the following output with an error shown below.

I tried changing the MySql password and also the connection string from:

```<code>"catchmebgContextConnection": "Server=localhost;Database=limboworld;User=root;Password=limboworld;"
</code>```

to

```<code>"catchmebgContextConnection": "Server=localhost;Database=limboworld;Uid=root;Pwd=limboworld;"

</code>```

```<code>info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.1.11-servicing-32099 initialized 'catchmebgContext' using provider 'Pomelo.EntityFrameworkCore.MySql' with options: MaxPoolSize=128 ServerVersion 5.7.24 MySql
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database '' on server 'localhost'.
MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost'
   ...
Application startup exception: MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost'
   at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 356
   at MySql.Data.MySqlClient.MySqlConnection.CreateSessionAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 442
   at MySql.Data.MySqlClient.MySqlConnection.OpenAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 175
   at MySql.Data.MySqlClient.MySqlConnection.Open() in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 161
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, Func`2 verifySucceeded, TState state)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at catchme.bg.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, catchmebgContext db1, CatchmeContext db2) in C:\Users\Ivan\Source\repos\catchme.bg\catchme.bg\catchme.bg\Startup.cs:line 84
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6]
      Application startup exception
MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost'
   at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 356
   at MySql.Data.MySqlClient.MySqlConnection.CreateSessionAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 442
   at MySql.Data.MySqlClient.MySqlConnection.OpenAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 175
   at MySql.Data.MySqlClient.MySqlConnection.Open() in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 161
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, Func`2 verifySucceeded, TState state)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at catchme.bg.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, catchmebgContext db1, CatchmeContext db2) in C:\Users\Ivan\Source\repos\catchme.bg\catchme.bg\catchme.bg\Startup.cs:line 84
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: /var/MyApp
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
</code>```

I would like to connect to the database on application startup and run the migrations. However because of the above error it doesn't work.

Any ideas would be very helpful!

答:
It turned out MySql 5.7 uses a plugin named 'auth_socket', which enables the root user to login to mysql with no password.

This line sets a password 'test' for the root account:

```<code>ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';
</code>```

After setting the password in the appsettings.json and appsettings.production.json files, everything worked correctly!

Here is the link, that I used to fix the problem:

https://www.percona.com/blog/2016/03/16/change-user-password-in-mysql-5-7-with-plugin-auth_socket/

Thank you all for looking at my question!

Body:
I just set up a LAMP server VM on Digital Ocean. OS is Ubuntu 18.04 x64. MySQL is 5.7.23. I also have a published to a local folder asp.net core web application, which I have set to Ubuntu 18.04-x64. I copied the files from the local folder to var/MyApp on the server and set chmod +x on the executable file. I also changed the MySql root password and created a database named limboworld. My application is set to run all migrations on startup. However when I start it with ./catchme.bg I get the following output with an error shown below.

I tried changing the MySql password and also the connection string from:

"catchmebgContextConnection": "Server=localhost;Database=limboworld;User=root;Password=limboworld;"

to

"catchmebgContextConnection": "Server=localhost;Database=limboworld;Uid=root;Pwd=limboworld;"

info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using '/root/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
      Entity Framework Core 2.1.11-servicing-32099 initialized 'catchmebgContext' using provider 'Pomelo.EntityFrameworkCore.MySql' with options: MaxPoolSize=128 ServerVersion 5.7.24 MySql
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database '' on server 'localhost'.
MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost'
   ...
Application startup exception: MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost'
   at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 356
   at MySql.Data.MySqlClient.MySqlConnection.CreateSessionAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 442
   at MySql.Data.MySqlClient.MySqlConnection.OpenAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 175
   at MySql.Data.MySqlClient.MySqlConnection.Open() in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 161
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, Func`2 verifySucceeded, TState state)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at catchme.bg.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, catchmebgContext db1, CatchmeContext db2) in C:\Users\Ivan\Source\repos\catchme.bg\catchme.bg\catchme.bg\Startup.cs:line 84
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
crit: Microsoft.AspNetCore.Hosting.Internal.WebHost[6]
      Application startup exception
MySql.Data.MySqlClient.MySqlException (0x80004005): Access denied for user 'root'@'localhost'
   at MySqlConnector.Core.ServerSession.ConnectAsync(ConnectionSettings cs, ILoadBalancer loadBalancer, IOBehavior ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\Core\ServerSession.cs:line 356
   at MySql.Data.MySqlClient.MySqlConnection.CreateSessionAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 442
   at MySql.Data.MySqlClient.MySqlConnection.OpenAsync(Nullable`1 ioBehavior, CancellationToken cancellationToken) in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 175
   at MySql.Data.MySqlClient.MySqlConnection.Open() in C:\projects\mysqlconnector\src\MySqlConnector\MySql.Data.MySqlClient\MySqlConnection.cs:line 161
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, Func`2 verifySucceeded, TState state)
   at Pomelo.EntityFrameworkCore.MySql.Storage.Internal.MySqlDatabaseCreator.Exists(Boolean retryOnNotExists)
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at catchme.bg.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, catchmebgContext db1, CatchmeContext db2) in C:\Users\Ivan\Source\repos\catchme.bg\catchme.bg\catchme.bg\Startup.cs:line 84
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
Hosting environment: Production
Content root path: /var/MyApp
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

I would like to connect to the database on application startup and run the migrations. However because of the above error it doesn't work.

Any ideas would be very helpful!

Body:
It turned out MySql 5.7 uses a plugin named 'auth_socket', which enables the root user to login to mysql with no password.

This line sets a password 'test' for the root account:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';

After setting the password in the appsettings.json and appsettings.production.json files, everything worked correctly!

Here is the link, that I used to fix the problem:

https://www.percona.com/blog/2016/03/16/change-user-password-in-mysql-5-7-with-plugin-auth_socket/

Thank you all for looking at my question!