问:
The hash that jBCrypt generates isn't the same as that of server
My current code is this:

```<code>                    Class.forName("com.mysql.cj.jdbc.Driver");
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "");
                    String username = usernameBox.getText(), password = passwordBox.getText();
                    String pwHash = BCrypt.hashpw(password, BCrypt.gensalt(12));

                    PreparedStatement login = con.prepareStatement("SELECT * FROM core_members WHERE name=? AND members_pass_hash=?");
                    login.setString(1, username);
                    login.setString(2, pwHash);
                    ResultSet rs = login.executeQuery();
                    if(rs.next()){
                        // correct username and pass
                    } else {
                        // wrong username and pass
                    }
</code>```

When I tried replacing pwHash with the hash on the database it works, I am using Invision Community 4.4.10 for more context

答:
Your are using a random salt to generate a hash. Then you try to find a hash that matches it. Of course, you will find nothing.

Instead, you should use the same hash as you used for this username. Your steps should be briefly as follows:

Look up for an entry using username only.

If not found, exit.

Extract the salt from the found entry.

Calculate hash using given password and extracted salt.

Compare if the calculated hash equals to the hash in the found entry.

Body:
My current code is this:

                    Class.forName("com.mysql.cj.jdbc.Driver");
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "");
                    String username = usernameBox.getText(), password = passwordBox.getText();
                    String pwHash = BCrypt.hashpw(password, BCrypt.gensalt(12));

                    PreparedStatement login = con.prepareStatement("SELECT * FROM core_members WHERE name=? AND members_pass_hash=?");
                    login.setString(1, username);
                    login.setString(2, pwHash);
                    ResultSet rs = login.executeQuery();
                    if(rs.next()){
                        // correct username and pass
                    } else {
                        // wrong username and pass
                    }

When I tried replacing pwHash with the hash on the database it works, I am using Invision Community 4.4.10 for more context


来源: stackexchange

问:
Pandas count occurence of value in dictionary
Given a DF:

```<code>pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })
</code>```

How do i get a count of number of times "Closed" appears in the dict?

```<code>A  B    count
1 {..}  2
2 {..}  1
3 {..}  0
</code>```

I really don't know how to start on this to try

答:
Use an auxiliary function:</p>

```<code>def aux_func(x):

    week_days = x.keys()
    count=0
    for day in week_days:
        if x[day]=='Closed':
            count+=1

    return count

counts = [aux_func(c) for c in df.loc[:,'B'] ]

df['counts'] = counts
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Given a DF:

pd.DataFrame({"A":[1,2,3],
              "B": [{"Mon":"Closed", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Closed"},
                    {"Mon":"Open", "Tue":"Open", "Wed":"Open"}]
              })

How do i get a count of number of times "Closed" appears in the dict?

A  B    count
1 {..}  2
2 {..}  1
3 {..}  0

I really don't know how to start on this to try

Body:
Use an auxiliary function:

def aux_func(x):

    week_days = x.keys()
    count=0
    for day in week_days:
        if x[day]=='Closed':
            count+=1

    return count

counts = [aux_func(c) for c in df.loc[:,'B'] ]

df['counts'] = counts


问:
Error when installing Spinnaker on Kubernetes on prem cluster
I'm trying to install Spinnaker on a Kubernetes setup onprem.

Following instructions from https://www.spinnaker.io/setup/

Install and run Halyard as Docker on the Kubernetes master.

Run everything as root

mkdir ~/.hal  on Kubemaster. Created the service account as instrcuted in the site.

Copied the kubeconfig file from ./kube/config into ~/.hal/kubeconfig as it didnt work with docker -v option, there was some permission issue, so made it work this way

docker run halyard command -- all up and running fine.

Ran Bash and Inside halyard.

Now when I do these two things inside halyard

Point kubectl to the kubeconfig by export KUBECONFIG command

Enable kubernetes provider "hal config provider kubernetes enable"

The command gets executed sometimes successfully or it fails with this warning after timeout error

Getting object contents of versions.yml

Unexpected error comparing versions: com.netflix.spinnaker.halyard.core.error.v1.HalException: Could not load "versions.yml" from config bucket: www.googleapis.com.*

Even if it somehow manages to run successfully. When I run these,

```<code>CONTEXT=$(kubectl config current-context)

hal config provider kubernetes account add my-k8s-account --context $CONTEXT
</code>```

It fails with the same error as above.

Total weird stuff. Its intermittent. Does it have something to do with the kubeconfig file? Any pointers or help would be greatly appreciated.

Thanks.

答:
As noted in comments these kind of errors could result when there lack of network connectivity from inside the container.

As Vikram mentioned in his comment:

Yes, that was the problem. Azure support recommended installing a CNI plugin and it resolved the issue. So, it seems like inside of Azure VM without a Public IP, the CNI plugin is needed for a VM To connect to internet.

To configure CNI plugin on Azure platform use this guide.

Hope it helps.

Body:
I'm trying to install Spinnaker on a Kubernetes setup onprem.

Following instructions from https://www.spinnaker.io/setup/

Install and run Halyard as Docker on the Kubernetes master.

Run everything as root

mkdir ~/.hal  on Kubemaster. Created the service account as instrcuted in the site.

Copied the kubeconfig file from ./kube/config into ~/.hal/kubeconfig as it didnt work with docker -v option, there was some permission issue, so made it work this way

docker run halyard command -- all up and running fine.

Ran Bash and Inside halyard.

Now when I do these two things inside halyard

Point kubectl to the kubeconfig by export KUBECONFIG command

Enable kubernetes provider "hal config provider kubernetes enable"

The command gets executed sometimes successfully or it fails with this warning after timeout error

Getting object contents of versions.yml

Unexpected error comparing versions: com.netflix.spinnaker.halyard.core.error.v1.HalException: Could not load "versions.yml" from config bucket: www.googleapis.com.*

Even if it somehow manages to run successfully. When I run these,

CONTEXT=$(kubectl config current-context)

hal config provider kubernetes account add my-k8s-account --context $CONTEXT

It fails with the same error as above.

Total weird stuff. Its intermittent. Does it have something to do with the kubeconfig file? Any pointers or help would be greatly appreciated.

Thanks.


问:
How do i use my web server instead of localhost for a messaging chat app?
I got some code from a youtube tutorial explaining how to build a live chat app with jquery and php, using your localhost server (XAMPP) and it works nicely. Here's the link: https://www.youtube.com/watch?v=HOcFFJr2YdE

Problem:
My issue is when i attempt to recreate the same thing on my web server in cpanel in phpMyAdmin, the app doesn't work anymore, i'm pretty sure there's a problem with this line in the php file:
$db = new mysqli("localhost","root","","chat"); since i do not know what to fill in instead of localhost and root.

Here's my files:

chat.php

```<code>$db = new mysqli("localhost","root","","chat");
if($db->connect_error) {
    die("Connection failed:. $db->connect_error");
}

$result = array();
$message = isset($_POST['message']) ? $_POST['message'] : null;
$from = isset($_POST['from']) ? $_POST['from'] : null;

if(!empty($message) && !empty($from)) {
    $sql = "INSERT INTO `chat` (`message`,`from`) VALUE ('".$message."','".$from."')";
    $result['send_status'] = $db->query($sql);
}

//print messages
$start = isset($_GET['start']) ? intval($_GET['start']) : 0;
$items = $db->query("SELECT * FROM `chat` WHERE `id` >" . $start);
while($row = $items->fetch_assoc()){
    $result['items'][] = $row;
}

$db->close();

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

echo json_encode($result);
</code>```

index.html

```<code><body>
    <div id="messages"></div>
    <form>
    <input type="text" id="message" autocomplete="off" autofocus placeholder="Type message">
    <input type="submit" value="Send">
    </form>
</body>
</code>```

index.js

```<code>var from = null;
var start = 0;
var url = 'http://localhost/chat.php';

$(document).ready(function() {

from = prompt('Please enter your name');

$('form').submit(function(e) {
    $.post(url, {
        message: $('#message').val(),
        from: from
    });
    $('#message').val('');

    return false;
});

setInterval(function() {
    load();
},500)

});

function load() {
    $.get(url + '?start=' + start, function(result) {
        if(result.items) {
            result.items.forEach(item => {
            start = item.id;
            $('#messages').append(renderMessage(item));
            });
            $('#messages').animate({scrollTop: $('#messages')[0].scrollHeight});
        }

    });

}

function renderMessage(item) {
        let time = new Date(item.created);
        time = `${time.getHours()}:${time.getMinutes() < 10 ? '0' : }       ${time.getMinutes()}`;
        return `<div class="msg"><p>${item.from}</p>${item.message}<span>${time</span></div>`;
}
</code>```

Remeber it works on localhost server but not on my web server, so has nothing to do with any html or js code per say but probably with linking the correct server or path or something similar.

答:
In Cpanel - create a database user (and password) and a new database for your app.  Use these instead.

mysqli_connect('localhost', $username, $password, $database);

As far as your second error - first and foremost - the server cannot find the page /chat/chat.php (file does not exist under this directory).  /chat.php loads, but the db connection properties are wrong.

Ensure that the chat.php file you are targeting is under the following directory
WEBROOT/web.

Your jquery error is actually at root from the css3-animate-it package you are using.  Disable it until you have figured out your connection / chat error.

Body:
I got some code from a youtube tutorial explaining how to build a live chat app with jquery and php, using your localhost server (XAMPP) and it works nicely. Here's the link: https://www.youtube.com/watch?v=HOcFFJr2YdE

Problem:
My issue is when i attempt to recreate the same thing on my web server in cpanel in phpMyAdmin, the app doesn't work anymore, i'm pretty sure there's a problem with this line in the php file:
$db = new mysqli("localhost","root","","chat"); since i do not know what to fill in instead of localhost and root.

Here's my files:

chat.php

$db = new mysqli("localhost","root","","chat");
if($db->connect_error) {
    die("Connection failed:. $db->connect_error");
}

$result = array();
$message = isset($_POST['message']) ? $_POST['message'] : null;
$from = isset($_POST['from']) ? $_POST['from'] : null;

if(!empty($message) && !empty($from)) {
    $sql = "INSERT INTO `chat` (`message`,`from`) VALUE ('".$message."','".$from."')";
    $result['send_status'] = $db->query($sql);
}

//print messages
$start = isset($_GET['start']) ? intval($_GET['start']) : 0;
$items = $db->query("SELECT * FROM `chat` WHERE `id` >" . $start);
while($row = $items->fetch_assoc()){
    $result['items'][] = $row;
}

$db->close();

header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

echo json_encode($result);

index.html

    <form>
    <input type="text" id="message" autocomplete="off" autofocus placeholder="Type message">
    <input type="submit" value="Send">
    </form>

index.js

var from = null;
var start = 0;
var url = 'http://localhost/chat.php';

$(document).ready(function() {

from = prompt('Please enter your name');

$('form').submit(function(e) {
    $.post(url, {
        message: $('#message').val(),
        from: from
    });
    $('#message').val('');

    return false;
});

setInterval(function() {
    load();
},500)

});

function load() {
    $.get(url + '?start=' + start, function(result) {
        if(result.items) {
            result.items.forEach(item => {
            start = item.id;
            $('#messages').append(renderMessage(item));
            });
            $('#messages').animate({scrollTop: $('#messages')[0].scrollHeight});
        }

    });

}

function renderMessage(item) {
        let time = new Date(item.created);
        time = `${time.getHours()}:${time.getMinutes() < 10 ? '0' : }       ${time.getMinutes()}`;
        return `<div class="msg"><p>${item.from}</p>${item.message}<span>${time</span></div>`;
}

Remeber it works on localhost server but not on my web server, so has nothing to do with any html or js code per say but probably with linking the correct server or path or something similar.


问:
Hide character with jQuery inside a span with a class
I've looked for the solution to this but nothing seems to be working.

I have an SKU within a span with a class of "sku". Some of the SKUs have periods before the SKU to allow for adding more than one product with the same SKU.

I'd like to hide the periods when the SKU is displayed though.

This is my code:

..THESKU

And this is the jQuery I am using:

```<code><script>
    $('span.sku').html($('span.sku').html().replace('.',''));
</script>
</code>```

Is the right, or am I missing something? Thanks.

答:
Your code will only replace one dot '.'. You can use regex to remove all the dots instead:

```<code>const skus = $('span.sku');

$('span.sku').each(function() {
  const text = $(this).html();
  const cleaned = text.replace(/\./g,'');
  $(this).html(cleaned);
})
</code>```

Hope this helps!

EDIT: Updated as suggested by @Taplar

Body:
I've looked for the solution to this but nothing seems to be working.

I have an SKU within a span with a class of "sku". Some of the SKUs have periods before the SKU to allow for adding more than one product with the same SKU.

I'd like to hide the periods when the SKU is displayed though.

This is my code:

..THESKU

And this is the jQuery I am using:

Is the right, or am I missing something? Thanks.

Body:
Your code will only replace one dot '.'. You can use regex to remove all the dots instead:

const skus = $('span.sku');

$('span.sku').each(function() {
  const text = $(this).html();
  const cleaned = text.replace(/\./g,'');
  $(this).html(cleaned);
})

Hope this helps!

EDIT: Updated as suggested by @Taplar


问:
A private key for specified extension already exists. Reuse that key or delete it first
Im trying to add a new extension for google chrome.(im new to this).

I keep getting the error message "A Private key for specified extension already exists. Reuse that key or delete it first".

```<code>{
   "manifest_version": 2,
   "description": "test",

   "name": "test",
   "version": "2.1",

   "content_scripts": [
 {
      "matches": ["*://www.google.com*"],
    "js": ["script.js"]

   }

  ]
}
</code>```

答: In the root folder where your extension is located, there is a <code>.pem</code> file. Simply delete it. </p>

Body:
Im trying to add a new extension for google chrome.(im new to this).

I keep getting the error message "A Private key for specified extension already exists. Reuse that key or delete it first".

{
   "manifest_version": 2,
   "description": "test",

   "name": "test",
   "version": "2.1",

   "content_scripts": [
 {
      "matches": ["*://www.google.com*"],
    "js": ["script.js"]

   }

  ]
}

Body: In the root folder where your extension is located, there is a .pem file. Simply delete it.


问:
How to create complex anagram using Streams
I have a task

```<code>Write an application that reverses all the words of input text:

E.g. "abcd efgh" => "dcba hgfe"

All non-letter symbols should stay on the same places:

E.g. "a1bcd efg!h" => "d1cba hgf!e"
</code>```

and it is successfully solved using core java. The core method is as follows:

private String reverseSeparateWord(String word) {

        char sentencePart[] = new char[word.length()];
        sentencePart = word.toCharArray();

        int firstIndex = 0;
        int lastIndex = sentencePart.length - 1;

        for (int i = 0; i < sentencePart.length; i++) {

            char symbolToBeSwapped = sentencePart[lastIndex];

            if (firstIndex < lastIndex) {

                if (!Character.isLetter(sentencePart[firstIndex])) {
                    firstIndex++;

                } else {
                    if (!Character.isLetter(symbolToBeSwapped)) {
                        lastIndex--;
                        symbolToBeSwapped = sentencePart[lastIndex];

                    } else {
                        sentencePart[lastIndex] = sentencePart[firstIndex];
                        sentencePart[firstIndex] = symbolToBeSwapped;

                        firstIndex++;
                        lastIndex--;

                        symbolToBeSwapped = sentencePart[lastIndex];
                    }
                }
            }
        }
        return new String(sentencePart);
    }

```

Now I sould solve this task using Streams and it is where I'm struggling.
I will appreciate any thoughts.

答:
There is some solution but it does not look too clean:

```<code>String input = "abc1cdef |efghk| klm**mnops";

String result = Arrays.stream(input.split("(?<=[^A-Za-z])")) // split by non-letter delimiter and include delimiter
                .map(s -> {
                    int d = s.matches("[A-Za-z]*[^A-Za-z]$") ? 1 : 0; // check for the last non-letter symbol
                    List<Character> list = s.substring(0, s.length() - d).chars().mapToObj(c -> (char) c).collect(Collectors.toList()); // convert word to list of chars
                    Collections.shuffle(list);
                    return list.stream().map(String::valueOf).collect(Collectors.joining()) + s.substring(s.length() - d);
                })
                .collect(Collectors.joining());
System.out.println(result);
</code>```

Example output:

```<code>cab1dfec |gfhek| klm**ompns
bac1fecd |ehgkf| mlk**smonp
etc.
</code>```

Update
A bit cleaner solution with shuffling the char array in a separate method:

```<code>private static String shuffle(char[] s) {
    Random random = new Random();
    IntStream.range(0, s.length - 1 - (Character.isLetter(s.length - 1) ? 0 : 1))
                .forEach(i -> {
                        int r = i+1+random.nextInt(s.length - i - 1 - (Character.isLetter(s[s.length - 1]) ? 0 : 1));
                        char c = s[i];
                        s[i] = s[r];
                        s[r] = c;
                });
    return new String(s);
}

// ------------
String input = "abcd1cdefg |efghk| klm**mnops";
String result = Arrays.stream(input.split("(?<=[^A-Za-z])"))
                .map(s -> Test.shuffle(s.toCharArray()))
                .collect(Collectors.joining());
// outputs
cdba1fgdec |ghfke| mkl**ompns
bdac1gfdce |hkefg| mkl**ompns
etc.
</code>```

Body:
I have a task

Write an application that reverses all the words of input text:

E.g. "abcd efgh" => "dcba hgfe"

All non-letter symbols should stay on the same places:

E.g. "a1bcd efg!h" => "d1cba hgf!e"

and it is successfully solved using core java. The core method is as follows:

private String reverseSeparateWord(String word) {

        char sentencePart[] = new char[word.length()];
        sentencePart = word.toCharArray();

        int firstIndex = 0;
        int lastIndex = sentencePart.length - 1;

        for (int i = 0; i < sentencePart.length; i++) {

            char symbolToBeSwapped = sentencePart[lastIndex];

            if (firstIndex < lastIndex) {

                if (!Character.isLetter(sentencePart[firstIndex])) {
                    firstIndex++;

                } else {
                    if (!Character.isLetter(symbolToBeSwapped)) {
                        lastIndex--;
                        symbolToBeSwapped = sentencePart[lastIndex];

                    } else {
                        sentencePart[lastIndex] = sentencePart[firstIndex];
                        sentencePart[firstIndex] = symbolToBeSwapped;

                        firstIndex++;
                        lastIndex--;

                        symbolToBeSwapped = sentencePart[lastIndex];
                    }
                }
            }
        }
        return new String(sentencePart);
    }

Now I sould solve this task using Streams and it is where I'm struggling.
I will appreciate any thoughts.

Body:
There is some solution but it does not look too clean:

String input = "abc1cdef |efghk| klm**mnops";

String result = Arrays.stream(input.split("(?<=[^A-Za-z])")) // split by non-letter delimiter and include delimiter
                .map(s -> {
                    int d = s.matches("[A-Za-z]*[^A-Za-z]$") ? 1 : 0; // check for the last non-letter symbol
                    List<Character> list = s.substring(0, s.length() - d).chars().mapToObj(c -> (char) c).collect(Collectors.toList()); // convert word to list of chars
                    Collections.shuffle(list);
                    return list.stream().map(String::valueOf).collect(Collectors.joining()) + s.substring(s.length() - d);
                })
                .collect(Collectors.joining());
System.out.println(result);

Example output:

cab1dfec |gfhek| klm**ompns
bac1fecd |ehgkf| mlk**smonp
etc.

Update
A bit cleaner solution with shuffling the char array in a separate method:

private static String shuffle(char[] s) {
    Random random = new Random();
    IntStream.range(0, s.length - 1 - (Character.isLetter(s.length - 1) ? 0 : 1))
                .forEach(i -> {
                        int r = i+1+random.nextInt(s.length - i - 1 - (Character.isLetter(s[s.length - 1]) ? 0 : 1));
                        char c = s[i];
                        s[i] = s[r];
                        s[r] = c;
                });
    return new String(s);
}

// ------------
String input = "abcd1cdefg |efghk| klm**mnops";
String result = Arrays.stream(input.split("(?<=[^A-Za-z])"))
                .map(s -> Test.shuffle(s.toCharArray()))
                .collect(Collectors.joining());
// outputs
cdba1fgdec |ghfke| mkl**ompns
bdac1gfdce |hkefg| mkl**ompns
etc.


问:
how can you don't replace a value in an array when you are replacing the value with nothing in python?
```<code>import sympy as sp
import math
import re

a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z = sp.symbols('a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z')

formula = input('')
unknown_values = int(input('how many unknown values?: '))

unknown_array = []
values = []

for i in range(unknown_values):
    unknown_name = input('unknown value: ')
    unknown_array += [unknown_name]

for i in range(len(unknown_array)):
    values += [input('Enter the value of ' + unknown_array[i] + ': ')]

for word in unknown_array:
    formula = formula.replace(word, values[unknown_array.index(word)])

formula = re.split(r'[=|<|>|<=|>=|==]', formula)[0:2]
split_a = sympify(formula[0])
split_b = sympify(formula[1])
split_c = simplify(split_a - split_b)
result = sp.solve(split_c, x)

for w in result:
    print(w.evalf())
</code>```

input: a*x**2 + b*x + c = 0

how many unknown values?: 3

unknown value: a

unknown value: b

unknown value: c

Enter the value of a: 1

Enter the value of b: 5

Enter the value of c: 6

-3.00000000000000

-2.00000000000000

this is how my code works. But when I put the values in 'unknown_array', i need to put only a,b,c and not x because it's the one I need to find. I would like to put also x in 'unknown_array' and in 'values' nothing (just press enter). The problem is that if I put nothing, then, when it will replace the values, it will just eliminate x. So I would like that in every value that I just press enter, it won't replace that value and put that value here: result = sp.solve(split_c, ...); instead of the 3 points and so solve for that value. While if there are multiple values, it will solve them one at a time and print every result.

答:
You are doing things with strings that you don't have to but if you want to reinvent the wheel that is always a way to learn so I won't try change the code. But as for how to solve for something other than x you need to identify what variable is left. You could do that by having the user identify what they are going to supply values for and then just don't say that you are solving for x:

```<code>sp.solve(split_c) instead of sp.solve(split_c, x)
</code>```

This will return a dictionary with the solved value.

Otherwise, if you have an expression like a*x+b and they say there are 3 unknowns and they want to "press return" on the one they want to solve for then when it comes to substituting in values, just skip that one during replacement (or replace it with the corresponding symbol):

```<code>for word in unknown_array:
    i = unknown_array.index(word)
    formula = formula.replace(word, values[i] or unknown_array[i])
</code>```

And then, again, don't pass x to solve -- solve will work it out if there is one symbol left.

Body:
import sympy as sp
import math
import re

a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z = sp.symbols('a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z')

formula = input('')
unknown_values = int(input('how many unknown values?: '))

unknown_array = []
values = []

for i in range(unknown_values):
    unknown_name = input('unknown value: ')
    unknown_array += [unknown_name]

for i in range(len(unknown_array)):
    values += [input('Enter the value of ' + unknown_array[i] + ': ')]

for word in unknown_array:
    formula = formula.replace(word, values[unknown_array.index(word)])

formula = re.split(r'[=|<|>|<=|>=|==]', formula)[0:2]
split_a = sympify(formula[0])
split_b = sympify(formula[1])
split_c = simplify(split_a - split_b)
result = sp.solve(split_c, x)

for w in result:
    print(w.evalf())

input: a*x**2 + b*x + c = 0

how many unknown values?: 3

unknown value: a

unknown value: b

unknown value: c

Enter the value of a: 1

Enter the value of b: 5

Enter the value of c: 6

-3.00000000000000

-2.00000000000000

this is how my code works. But when I put the values in 'unknown_array', i need to put only a,b,c and not x because it's the one I need to find. I would like to put also x in 'unknown_array' and in 'values' nothing (just press enter). The problem is that if I put nothing, then, when it will replace the values, it will just eliminate x. So I would like that in every value that I just press enter, it won't replace that value and put that value here: result = sp.solve(split_c, ...); instead of the 3 points and so solve for that value. While if there are multiple values, it will solve them one at a time and print every result.

Body:
You are doing things with strings that you don't have to but if you want to reinvent the wheel that is always a way to learn so I won't try change the code. But as for how to solve for something other than x you need to identify what variable is left. You could do that by having the user identify what they are going to supply values for and then just don't say that you are solving for x:

sp.solve(split_c) instead of sp.solve(split_c, x)

This will return a dictionary with the solved value.

Otherwise, if you have an expression like a*x+b and they say there are 3 unknowns and they want to "press return" on the one they want to solve for then when it comes to substituting in values, just skip that one during replacement (or replace it with the corresponding symbol):

for word in unknown_array:
    i = unknown_array.index(word)
    formula = formula.replace(word, values[i] or unknown_array[i])

And then, again, don't pass x to solve -- solve will work it out if there is one symbol left.


问:
Unable to load class 'kotlin.coroutines.Continuation'
This error keeps happening every once in a while in my Kotlin projects. I tried several Kotlin versions (1.3.41, 1.3.60, 1.3.72) but this seems to come up on any version and in various projects. Once it starts happening, I can't build any project.

Full error message:

Unable to load class 'kotlin.coroutines.Continuation'.
  Possible causes for this unexpected error include:
  Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

Re-download dependencies and sync project (requires network)

The state of a Gradle build process (daemon) may be corrupt.
   Stopping all Gradle daemons may solve this problem.

Stop Gradle build processes (requires restart)

Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.

In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

I have tried all the suggestions and none of it helped. When I click
"Re-download dependencies and sync project (requires network)", it says

Clicking "Stop Gradle build processes (requires restart)" restarts Intellij but doesn't help.

Closing Intellij and killing Java processes didn't help either.

答:
While none of the linked suggestions in the error popup worked, running 'clean' gradle task manually did do the trick!

```<code>./gradlew clean
</code>```

The error still comes up every once in a while but can be reliably fixed by running gradle clean.

Body:
While none of the linked suggestions in the error popup worked, running 'clean' gradle task manually did do the trick!

./gradlew clean

The error still comes up every once in a while but can be reliably fixed by running gradle clean.


问:
Android Random string generated from int
Basically Im trying to generate a random string when the page loads up. The problem is I dont know how to make the created random integer as a variable for my switch case. Can anyone modify my code and help me?

CODE

```<code>import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ask_2 extends Activity {

TextView ActivityNumber;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ask2);

    ChooseActivity();
}

private void ChooseActivity() {
    Random myRandom = new Random();
    TextView textGenerateNumber = (TextView) findViewById(R.id.generatenumber);
    textGenerateNumber.setText(String.valueOf(myRandom.nextInt(2)));
    TextView textGenerateDesc = (TextView) findViewById(R.id.generatedesc);
    switch (myRandom) {
    case 0:
        textGenerateDesc.setText("Hello0");
        break;
    case 1:
        textGenerateDesc.setText("Hello1");
        break;
    case 2:
        textGenerateDesc.setText("Hello2");
        break;
    }

}
}
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Activity " />
<TextView android:id="@+id/generatenumber"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="Number" />
<TextView android:id="@+id/generatedesc" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Description" />

</LinearLayout>
</code>```

答:
You shouldn't switch on random, you should first get an int:

```<code>Random rand = new Random();
int myRandom = rand.nextInt() % 3;
</code>```

or, as you implemented it

```<code>Random myRandom = new Random();
//...
switch(myRandom.nextInt() %3) {
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Basically Im trying to generate a random string when the page loads up. The problem is I dont know how to make the created random integer as a variable for my switch case. Can anyone modify my code and help me?

CODE

import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ask_2 extends Activity {

TextView ActivityNumber;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ask2);

    ChooseActivity();
}

private void ChooseActivity() {
    Random myRandom = new Random();
    TextView textGenerateNumber = (TextView) findViewById(R.id.generatenumber);
    textGenerateNumber.setText(String.valueOf(myRandom.nextInt(2)));
    TextView textGenerateDesc = (TextView) findViewById(R.id.generatedesc);
    switch (myRandom) {
    case 0:
        textGenerateDesc.setText("Hello0");
        break;
    case 1:
        textGenerateDesc.setText("Hello1");
        break;
    case 2:
        textGenerateDesc.setText("Hello2");
        break;
    }

}
}

XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical">
<TextView android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Activity " />
<TextView android:id="@+id/generatenumber"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="Number" />
<TextView android:id="@+id/generatedesc" android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="Description" />

</LinearLayout>

Body:
You shouldn't switch on random, you should first get an int:

Random rand = new Random();
int myRandom = rand.nextInt() % 3;

or, as you implemented it

Random myRandom = new Random();
//...
switch(myRandom.nextInt() %3) {


问:
Understanding a modified variant of Sieve of Eratosthenes algorithm
I came across this algorithm on a coding site (There was no author's information) which counts all prime numbers less than a given limit. It looks very similar to SoE algorithm but it is different in the way it counts the primes:

```<code>public int countPrimes(int n) {
    if (n < 3) return 0;
    boolean[] s = new boolean[n];
    int c = n / 2;
    for (int i = 3; i < Math.sqrt(n); i += 2) {
        if (s[i]) continue;
        for (int j = i * i; j < n; j += 2 * i) {
            if (!s[j]) {
                c--;
                s[j] = true;
            }
        }
    }
    return c;
}
</code>```

It sets the initial count to half the limit then decrement it, but I can not seem to understand why does this work. Can anyone please explain?

答:
The count is initialized to n/2 because all even numbers (except 2) are not primes.
And then the loop below can start checking from multiples of 3.
If a new non-prime is found (!s[j]), the count of primes (c) is decreased.</p>

Body:
I came across this algorithm on a coding site (There was no author's information) which counts all prime numbers less than a given limit. It looks very similar to SoE algorithm but it is different in the way it counts the primes:

public int countPrimes(int n) {
    if (n < 3) return 0;
    boolean[] s = new boolean[n];
    int c = n / 2;
    for (int i = 3; i < Math.sqrt(n); i += 2) {
        if (s[i]) continue;
        for (int j = i * i; j < n; j += 2 * i) {
            if (!s[j]) {
                c--;
                s[j] = true;
            }
        }
    }
    return c;
}

It sets the initial count to half the limit then decrement it, but I can not seem to understand why does this work. Can anyone please explain?


问:
Does LinkedIn Share API support escaped fragment URL's (hasbang url)
Using the customized URL method is it possible to share a URL that implements the Escaped Fragment protocol?

For example a url in the following format:

```<code>https://www.example.com/#!/my-angularjs-page
</code>```

So far from my experience, LinkedIn always removes the hashtag thus only retaining the domain name part of the URL:

```<code>https://www.example.com/
</code>```

And therefore only the homepage is being shared.

References:

https://developer.linkedin.com/docs/share-on-linkedin

答:
You need to escape the characters, whenever you want to use #, &, ?, and a few other reserved characters as the value of a GET parameter in a URL.  It's called URL-encoding.  The standard LinkedIn format is...

```<code>https://www.linkedin.com/sharing/share-offsite/?url={url}
</code>```

So, for your site, notice how I am doing the encoding of these special characters...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.example.com%2F%23!%2Fmy-angularjs-page
</code>```

# becomes %23.  Afterall, how is the browser supposed to know that # there is for the URL you are sharing, or for the LinkedIn page itself?  It needs to be able to distinguish, and it does that with encoding.

More Info: Official LinkedIn Share Documentation

Body:
Using the customized URL method is it possible to share a URL that implements the Escaped Fragment protocol?

For example a url in the following format:

https://www.example.com/#!/my-angularjs-page

So far from my experience, LinkedIn always removes the hashtag thus only retaining the domain name part of the URL:

https://www.example.com/

And therefore only the homepage is being shared.

References:

https://developer.linkedin.com/docs/share-on-linkedin

Body:
You need to escape the characters, whenever you want to use #, &, ?, and a few other reserved characters as the value of a GET parameter in a URL.  It's called URL-encoding.  The standard LinkedIn format is...

https://www.linkedin.com/sharing/share-offsite/?url={url}

So, for your site, notice how I am doing the encoding of these special characters...

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.example.com%2F%23!%2Fmy-angularjs-page

# becomes %23.  Afterall, how is the browser supposed to know that # there is for the URL you are sharing, or for the LinkedIn page itself?  It needs to be able to distinguish, and it does that with encoding.

More Info: Official LinkedIn Share Documentation


问:
Do Ignite support logback for distributed compute？
I try to use spring boot (2.1.0.RELEASE) to run ignite.compute. As spring boot + lombok use logback as default, the following codes always throw exceptions (2020-05-28 07:00:48.979  WARN 8460 --- [        p2p-#49] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback). The result (28) could be returned. Seems we see log4j and log4j2 on official website. Does ignite support logback?

pom.xml

```<code>    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.ignite</groupId>
            <artifactId>ignite-core</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ignite</groupId>
            <artifactId>ignite-spring</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</code>```

default-config.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="igniteCfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="clientMode" value="true"/>
        <property name="peerClassLoadingEnabled" value="true"/>
        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="localPort" value="48500"/>
                <property name="localPortRange" value="20"/>
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
                        <property name="addresses">
                            <list>
                                <value>127.0.0.1:48500..48520</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
        <property name="communicationSpi">
            <bean class="org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi">
                <property name="localPort" value="48100"/>
            </bean>
        </property>
    </bean>
</beans>
</code>```

java code:

```<code>@Configuration
@ImportResource(locations={"classpath:default-config.xml"})
public class IgniteConfig {

    @Bean
    public Ignite ignite(IgniteConfiguration igniteConfiguration) {
        Ignite ignite = Ignition.start(igniteConfiguration);
        Ignition.setClientMode(true);
        return ignite;
    }
}

@Slf4j
@RestController
public class WebController {

    @Autowired
    private Ignite ignite;

    @GetMapping("/compute")
    public void compute() {
        Collection<IgniteCallable<Integer>> calls = new ArrayList<>();

        // Iterate through all the words in the sentence and create Callable jobs.
        for (final String word : "Count characters using callable".split(" "))
            calls.add(word::length);

        // Execute collection of Callables on the grid.
        Collection<Integer> res = ignite.compute().call(calls);

        // Add up all the results.
        int sum = res.stream().mapToInt(Integer::intValue).sum();

        log.info("Total number of characters is '" + sum + "'.");
    }
}
</code>```

Exception:

```<code>2020-05-28 07:00:48.786  INFO 8460 --- [nio-8080-exec-1] o.a.i.i.m.d.GridDeploymentLocalStore     : Class locally deployed: class com.sonic.sample.springboot.controller.WebController
2020-05-28 07:00:48.890  WARN 8460 --- [        p2p-#49] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback

java.lang.ClassNotFoundException: ch.qos.logback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_121]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_121]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_121]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_121]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processResourceRequest(GridDeploymentCommunication.java:216) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processDeploymentRequest(GridDeploymentCommunication.java:152) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.access$000(GridDeploymentCommunication.java:55) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication$1.onMessage(GridDeploymentCommunication.java:88) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1843) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.access$5100(GridIoManager.java:229) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager$8.run(GridIoManager.java:1325) [ignite-core-2.8.0.jar:2.8.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

2020-05-28 07:00:49.000  WARN 8460 --- [        p2p-#50] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback

java.lang.ClassNotFoundException: ch.qos.logback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_121]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_121]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_121]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_121]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processResourceRequest(GridDeploymentCommunication.java:216) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processDeploymentRequest(GridDeploymentCommunication.java:152) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.access$000(GridDeploymentCommunication.java:55) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication$1.onMessage(GridDeploymentCommunication.java:88) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1843) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.access$5100(GridIoManager.java:229) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager$8.run(GridIoManager.java:1325) [ignite-core-2.8.0.jar:2.8.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

2020-05-28 07:00:49.000  WARN 8460 --- [        p2p-#50] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback

java.lang.ClassNotFoundException: ch.qos.logback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_121]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_121]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_121]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_121]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processResourceRequest(GridDeploymentCommunication.java:216) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processDeploymentRequest(GridDeploymentCommunication.java:152) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.access$000(GridDeploymentCommunication.java:55) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication$1.onMessage(GridDeploymentCommunication.java:88) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1843) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.access$5100(GridIoManager.java:229) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager$8.run(GridIoManager.java:1325) [ignite-core-2.8.0.jar:2.8.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

2020-05-28 07:00:49.025  INFO 8460 --- [nio-8080-exec-1] c.s.s.s.controller.WebController         : Total number of characters is '28'.
</code>```

答:
I'm not really sure why the entire logback would not peer class load (I will check that), BUT

I don't recommend relying on it, instead adding your dependencies' JARs to your server node classpath. I did that by issuing

```<code>~/ignite_demo% mvn dependency:copy-dependencies
... Maven downloads dependencies ...
~/ignite_demo% cp -R target/dependency ~/apache-ignite-2.8.0-bin/libs
</code>```

After that, I have restarted my server node, it was able to see dependencies' JARs and http://localhost:8080/compute worked just fine.

Body:
I try to use spring boot (2.1.0.RELEASE) to run ignite.compute. As spring boot + lombok use logback as default, the following codes always throw exceptions (2020-05-28 07:00:48.979  WARN 8460 --- [        p2p-#49] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback). The result (28) could be returned. Seems we see log4j and log4j2 on official website. Does ignite support logback?

pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.ignite</groupId>
            <artifactId>ignite-core</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.ignite</groupId>
            <artifactId>ignite-spring</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

default-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="igniteCfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="clientMode" value="true"/>
        <property name="peerClassLoadingEnabled" value="true"/>
        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="localPort" value="48500"/>
                <property name="localPortRange" value="20"/>
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
                        <property name="addresses">
                            <list>
                                <value>127.0.0.1:48500..48520</value>
                            </list>
                        </property>
                    </bean>
                </property>
            </bean>
        </property>
        <property name="communicationSpi">
            <bean class="org.apache.ignite.spi.communication.tcp.TcpCommunicationSpi">
                <property name="localPort" value="48100"/>
            </bean>
        </property>
    </bean>
</beans>

java code:

@Configuration
@ImportResource(locations={"classpath:default-config.xml"})
public class IgniteConfig {

    @Bean
    public Ignite ignite(IgniteConfiguration igniteConfiguration) {
        Ignite ignite = Ignition.start(igniteConfiguration);
        Ignition.setClientMode(true);
        return ignite;
    }
}

@Slf4j
@RestController
public class WebController {

    @Autowired
    private Ignite ignite;

    @GetMapping("/compute")
    public void compute() {
        Collection<IgniteCallable<Integer>> calls = new ArrayList<>();

        // Iterate through all the words in the sentence and create Callable jobs.
        for (final String word : "Count characters using callable".split(" "))
            calls.add(word::length);

        // Execute collection of Callables on the grid.
        Collection<Integer> res = ignite.compute().call(calls);

        // Add up all the results.
        int sum = res.stream().mapToInt(Integer::intValue).sum();

        log.info("Total number of characters is '" + sum + "'.");
    }
}

Exception:

2020-05-28 07:00:48.786  INFO 8460 --- [nio-8080-exec-1] o.a.i.i.m.d.GridDeploymentLocalStore     : Class locally deployed: class com.sonic.sample.springboot.controller.WebController
2020-05-28 07:00:48.890  WARN 8460 --- [        p2p-#49] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback

java.lang.ClassNotFoundException: ch.qos.logback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_121]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_121]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_121]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_121]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processResourceRequest(GridDeploymentCommunication.java:216) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processDeploymentRequest(GridDeploymentCommunication.java:152) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.access$000(GridDeploymentCommunication.java:55) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication$1.onMessage(GridDeploymentCommunication.java:88) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1843) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.access$5100(GridIoManager.java:229) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager$8.run(GridIoManager.java:1325) [ignite-core-2.8.0.jar:2.8.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

2020-05-28 07:00:49.000  WARN 8460 --- [        p2p-#50] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback

java.lang.ClassNotFoundException: ch.qos.logback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_121]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_121]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_121]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_121]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processResourceRequest(GridDeploymentCommunication.java:216) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processDeploymentRequest(GridDeploymentCommunication.java:152) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.access$000(GridDeploymentCommunication.java:55) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication$1.onMessage(GridDeploymentCommunication.java:88) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1843) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.access$5100(GridIoManager.java:229) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager$8.run(GridIoManager.java:1325) [ignite-core-2.8.0.jar:2.8.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

2020-05-28 07:00:49.000  WARN 8460 --- [        p2p-#50] o.a.i.i.m.d.GridDeploymentCommunication  : Failed to resolve class: ch.qos.logback

java.lang.ClassNotFoundException: ch.qos.logback
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_121]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_121]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_121]
    at java.lang.Class.forName0(Native Method) ~[na:1.8.0_121]
    at java.lang.Class.forName(Class.java:348) ~[na:1.8.0_121]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processResourceRequest(GridDeploymentCommunication.java:216) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.processDeploymentRequest(GridDeploymentCommunication.java:152) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication.access$000(GridDeploymentCommunication.java:55) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.deployment.GridDeploymentCommunication$1.onMessage(GridDeploymentCommunication.java:88) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1843) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager.access$5100(GridIoManager.java:229) [ignite-core-2.8.0.jar:2.8.0]
    at org.apache.ignite.internal.managers.communication.GridIoManager$8.run(GridIoManager.java:1325) [ignite-core-2.8.0.jar:2.8.0]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_121]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_121]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_121]

2020-05-28 07:00:49.025  INFO 8460 --- [nio-8080-exec-1] c.s.s.s.controller.WebController         : Total number of characters is '28'.

Body:
I'm not really sure why the entire logback would not peer class load (I will check that), BUT

I don't recommend relying on it, instead adding your dependencies' JARs to your server node classpath. I did that by issuing

~/ignite_demo% mvn dependency:copy-dependencies
... Maven downloads dependencies ...
~/ignite_demo% cp -R target/dependency ~/apache-ignite-2.8.0-bin/libs

After that, I have restarted my server node, it was able to see dependencies' JARs and http://localhost:8080/compute worked just fine.


问:
Laravel/Passport scope issue
Hi stackoverflow developers.

I'm facing an issue with Laravel/Passport scopes. An error occurs when i use a route with scope middleware.

```<code>{
"message": "in_array() expects parameter 2 to be array, null given",
"exception": "ErrorException",
"file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
"line": 95,
"trace": [
    {
        "function": "handleError",
        "class": "Illuminate\Foundation\Bootstrap\HandleExceptions",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
        "line": 95,
        "function": "in_array"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\HasApiTokens.php",
        "line": 54,
        "function": "can",
        "class": "Laravel\Passport\Token",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Http\Middleware\CheckForAnyScope.php",
        "line": 27,
        "function": "tokenCan",
        "class": "App\User",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Laravel\Passport\Http\Middleware\CheckForAnyScope",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php",
        "line": 41,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\SubstituteBindings",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php",
        "line": 59,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\ThrottleRequests",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php",
        "line": 44,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Auth\Middleware\Authenticate",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 687,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 662,
        "function": "runRouteWithinStack",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 628,
        "function": "runRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 617,
        "function": "dispatchToRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 165,
        "function": "dispatch",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 128,
        "function": "Illuminate\Foundation\Http\{closure}",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php",
        "line": 27,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php",
        "line": 63,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fruitcake\laravel-cors\src\HandleCors.php",
        "line": 37,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fruitcake\Cors\HandleCors",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fideloper\proxy\src\TrustProxies.php",
        "line": 57,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fideloper\Proxy\TrustProxies",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 140,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 109,
        "function": "sendRequestThroughRouter",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\public\index.php",
        "line": 55,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\server.php",
        "line": 21,
        "function": "require_once"
    }
]
</code>```

My Route is:

```<code>Route::middleware(["auth:api", "scope:Administrator"])->post('atts/languages', 'AttribsController@createLanguage');
</code>```

Scopes definition in AuthServiceProvider:

```<code>public function boot()
{
    $this->registerPolicies();
    Passport::routes();
    Passport::tokensExpireIn(now()->addCentury());
    Passport::tokensCan([
        'Administrator' => 'Administrator',
        'Moderator' => 'Moderator',
        'Journalist' => 'Journalist',
        'Client' => 'Client'
    ]);
    Passport::setDefaultScope(['Client']);
}
</code>```

Token affectation in AuthController:

```<code> $token = $user->createToken('app', ['Administrator'])->accessToken;

    $user->token = $token;

    return response()->json($user);
</code>```

Any solution for this?

And thanks.

Environment: Windows 10 OS, Laravel 7.13, Passport 9.2, PHP 7.2, Database MySQL.

Update:
AuthController.php

```<code><?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller{
public function signup(Request $request){
$request->validate([
    'email' => 'required|string|unique:users|email',
    'password' => 'required|string',
    "username" => 'required|string|unique:users',
    'name' => 'required|string',
    'typeId' => 'required|int',
    'lName' => 'required|string',
]);

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type_id = $request->typeId;
$user->lName = $request->lName;
$user->username = $request->username;
$user->photo = $request->photo;
$user->phone = $request->phone;
$user->address = $request->adr;
$user->bio = $request->bio;

$user->save();

$user = User::with(['type'])->find($user->id);

$token = $user->createToken('app', [$user->type->name])->accessToken;

$user->token = $token;

return response()->json($user);
}

public function login(){
if (!Auth::attempt(['email' => request('email'), "password" =>>request('password')]))
    return response()->json(['message' => 'not acceptable'], Response::HTTP_NOT_ACCEPTABLE);

$user = request()->user();

$user->token = $user->createToken('app', [$user->type->name])->accessToken;

return response()->json($user);
}

public function logout(){
request()->user()->token()->revoke();
return response()->json(['message' => 'goodbye']);
}
}
</code>```

答:
Use Route Like This:

```<code>Route::post('atts/languages', 'AttribsController@createLanguage')->middleware(["auth:api", "scope:Administrator"]);
</code>```

Kernel.php in $routeMiddleware

```<code>'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,
</code>```

Use use Laravel\Passport\Passport; in AuthServiceProvider

Make Sure You are following all of this.

Title: Laravel/Passport scope issue

Body:
Hi stackoverflow developers.

I'm facing an issue with Laravel/Passport scopes. An error occurs when i use a route with scope middleware.

{
"message": "in_array() expects parameter 2 to be array, null given",
"exception": "ErrorException",
"file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
"line": 95,
"trace": [
    {
        "function": "handleError",
        "class": "Illuminate\Foundation\Bootstrap\HandleExceptions",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Token.php",
        "line": 95,
        "function": "in_array"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\HasApiTokens.php",
        "line": 54,
        "function": "can",
        "class": "Laravel\Passport\Token",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\passport\src\Http\Middleware\CheckForAnyScope.php",
        "line": 27,
        "function": "tokenCan",
        "class": "App\User",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Laravel\Passport\Http\Middleware\CheckForAnyScope",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php",
        "line": 41,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\SubstituteBindings",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php",
        "line": 59,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Routing\Middleware\ThrottleRequests",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php",
        "line": 44,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Auth\Middleware\Authenticate",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 687,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 662,
        "function": "runRouteWithinStack",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 628,
        "function": "runRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
        "line": 617,
        "function": "dispatchToRoute",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 165,
        "function": "dispatch",
        "class": "Illuminate\Routing\Router",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 128,
        "function": "Illuminate\Foundation\Http\{closure}",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
        "line": 21,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php",
        "line": 27,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php",
        "line": 63,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fruitcake\laravel-cors\src\HandleCors.php",
        "line": 37,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fruitcake\Cors\HandleCors",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\fideloper\proxy\src\TrustProxies.php",
        "line": 57,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 167,
        "function": "handle",
        "class": "Fideloper\Proxy\TrustProxies",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
        "line": 103,
        "function": "Illuminate\Pipeline\{closure}",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 140,
        "function": "then",
        "class": "Illuminate\Pipeline\Pipeline",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
        "line": 109,
        "function": "sendRequestThroughRouter",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\public\index.php",
        "line": 55,
        "function": "handle",
        "class": "Illuminate\Foundation\Http\Kernel",
        "type": "->"
    },
    {
        "file": "C:\Users\amir\PhpstormProjects\baobab_back\server.php",
        "line": 21,
        "function": "require_once"
    }
]

My Route is:

Route::middleware(["auth:api", "scope:Administrator"])->post('atts/languages', 'AttribsController@createLanguage');

Scopes definition in AuthServiceProvider:

public function boot()
{
    $this->registerPolicies();
    Passport::routes();
    Passport::tokensExpireIn(now()->addCentury());
    Passport::tokensCan([
        'Administrator' => 'Administrator',
        'Moderator' => 'Moderator',
        'Journalist' => 'Journalist',
        'Client' => 'Client'
    ]);
    Passport::setDefaultScope(['Client']);
}

Token affectation in AuthController:

 $token = $user->createToken('app', ['Administrator'])->accessToken;

    $user->token = $token;

    return response()->json($user);

Any solution for this?

And thanks.

Environment: Windows 10 OS, Laravel 7.13, Passport 9.2, PHP 7.2, Database MySQL.

Update:
AuthController.php

<?php
namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller{
public function signup(Request $request){
$request->validate([
    'email' => 'required|string|unique:users|email',
    'password' => 'required|string',
    "username" => 'required|string|unique:users',
    'name' => 'required|string',
    'typeId' => 'required|int',
    'lName' => 'required|string',
]);

$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type_id = $request->typeId;
$user->lName = $request->lName;
$user->username = $request->username;
$user->photo = $request->photo;
$user->phone = $request->phone;
$user->address = $request->adr;
$user->bio = $request->bio;

$user->save();

$user = User::with(['type'])->find($user->id);

$token = $user->createToken('app', [$user->type->name])->accessToken;

$user->token = $token;

return response()->json($user);
}

public function login(){
if (!Auth::attempt(['email' => request('email'), "password" =>>request('password')]))
    return response()->json(['message' => 'not acceptable'], Response::HTTP_NOT_ACCEPTABLE);

$user = request()->user();

$user->token = $user->createToken('app', [$user->type->name])->accessToken;

return response()->json($user);
}

public function logout(){
request()->user()->token()->revoke();
return response()->json(['message' => 'goodbye']);
}
}

Body:
Use Route Like This:

Route::post('atts/languages', 'AttribsController@createLanguage')->middleware(["auth:api", "scope:Administrator"]);

Kernel.php in $routeMiddleware

'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

Use use Laravel\Passport\Passport; in AuthServiceProvider

Make Sure You are following all of this.


问:
response.status code is Undefined while using an API
While using an API I am getting undefined rather then the status code like 200 or 404.

```<code>app.get('/', function(req, res){

    const url = ''; //The API key

    https.get(url, function(response){

        console.log(response.statuscode);
    });
    res.send('App is running');
});
</code>```

答:
it should be :  response.statusCode

```<code>const req = https.request(options, (response) => {
  console.log('statusCode:', response.statusCode);
});
</code>```

Body:
While using an API I am getting undefined rather then the status code like 200 or 404.

app.get('/', function(req, res){

    const url = ''; //The API key

    https.get(url, function(response){

        console.log(response.statuscode);
    });
    res.send('App is running');
});

Body:
it should be :  response.statusCode

const req = https.request(options, (response) => {
  console.log('statusCode:', response.statusCode);
});


答:
First of all, the boolean array s represents SoE.

The first loop iterates odd numbers from 3 to sqrt(n) (Because all even except 2 is not prime).
At the 6th line, If i is already in the s, continue to next odd number. If not, add all multiple of i that is less or equal to n to s in the second loop.

In addition, the second loop starts from i*i because all multiple of i smaller than i*i are already checked in prior loops.

Title: Understanding a modified variant of Sieve of Eratosthenes algorithm


问:
free country, city database for sql server
have anyone used this before, i need free country, city, IP database for sqlserver</p>

答:
If you need to find the location of the current user based on their IP address, then you could try the Google Geolocation API, in particular google.loader.ClientLocation.

Check out the Google API docs for more info:
http://code.google.com/apis/ajax/documentation/#ClientLocation

OwnerDisplayName: StoneHeart

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: cxfx


问:
Remove repetition from if-else statement
I have written an if...else statement which uses an array myArr and a string myStr as follows:

```<code>If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If
</code>```

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

答:
You can decompose the statements like this:</p>

```<code>If myArr.Length > 0 Then
    If myArr(0) = "-1" Then
       'Do stuff
    Else
       'Do sstuff
    End If
Else
    If myyStr= "xyz" Then
        'Do stuff
    End If
End If
</code>```

Body:
I have written an if...else statement which uses an array myArr and a string myStr as follows:

If myArr.Length > 0 AndAlso myArr(0) = "-1" Then
  'Do stuff 1
ElseIf myStr= "xyz" Then
  'Do stuff 2
ElseIf myArr.Length > 0 Then
  'Do Stuff 3
Else
  'Do Nothing
End If

It works exactly as I need. But It looks really confusing, mostly because the array length is checked twice. There must be a clearer way to write it, but I can't think of one.

Just to clarify.... the order that each statement is executed is crucial. i.e. Stuff 1 has priority over stuff 2, which has priority over stuff 3.

Body:
You can decompose the statements like this:

If myArr.Length > 0 Then
    If myArr(0) = "-1" Then
       'Do stuff
    Else
       'Do sstuff
    End If
Else
    If myyStr= "xyz" Then
        'Do stuff
    End If
End If


问:
Writing a normal python code into function called computepay()
How can I write the following program to prompt the user for hours and rate per hour using input to compute gross pay in a function called computepay() and use the function to do the computation. I want the function to return a value. In short, I want function to do it for me so that I can reduce the manual work from my side. Any help would be appreciated. Thanks.</p>

```<code>
sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result

if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

</code>```

答:
Your code works fine.

quit() # Commenting this line out will yield different result

Yes, if you don't exit, the program continues how ever it can.

I modified my answer to incorporate your request in the comments. Here I use a recursive to retry getting the argument if float() fails:

```<code>def compute_pay(hours, rate) :
        """ Comute pay for given hours and rate per hour """
        if hours > 40:
                reg = rate  * hours
                otp = (hours - 40.0) * (rate * 0.5)
                return reg + otp
        else:
                return hours * rate

def get_argument(arg_name):
    """ Recursively tries to get arguments """
    try:
        # attempt to float the input
        return float(input(f"Enter {arg_name}:"))
    except ValueError:
        # retry if failed
        print("Error, please enter numeric input...")
        return get_argument(arg_name)

# your program is launched here: python3 this_program.py
if __name__=="__main__":
        # get the arguments, retrying recursively
        hours_worked, hourly_rate = get_argument('hours'), get_argument('rate')

        # compute the pay
        pay = compute_pay(hours_worked, hourly_rate)

        # output
        print(f"Pay: {pay}")

        # exit gracefully: 0 means "all good"
        exit(0)
</code>```

Body:
How can I write the following program to prompt the user for hours and rate per hour using input to compute gross pay in a function called computepay() and use the function to do the computation. I want the function to return a value. In short, I want function to do it for me so that I can reduce the manual work from my side. Any help would be appreciated. Thanks.

sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result

if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
Your code works fine.

quit() # Commenting this line out will yield different result

Yes, if you don't exit, the program continues how ever it can.

I modified my answer to incorporate your request in the comments. Here I use a recursive to retry getting the argument if float() fails:

def compute_pay(hours, rate) :
        """ Comute pay for given hours and rate per hour """
        if hours > 40:
                reg = rate  * hours
                otp = (hours - 40.0) * (rate * 0.5)
                return reg + otp
        else:
                return hours * rate

def get_argument(arg_name):
    """ Recursively tries to get arguments """
    try:
        # attempt to float the input
        return float(input(f"Enter {arg_name}:"))
    except ValueError:
        # retry if failed
        print("Error, please enter numeric input...")
        return get_argument(arg_name)

# your program is launched here: python3 this_program.py
if __name__=="__main__":
        # get the arguments, retrying recursively
        hours_worked, hourly_rate = get_argument('hours'), get_argument('rate')

        # compute the pay
        pay = compute_pay(hours_worked, hourly_rate)

        # output
        print(f"Pay: {pay}")

        # exit gracefully: 0 means "all good"
        exit(0)


问:
Deno allow all permissions
I often find myself typing at least two or three permission options when playing with Deno:

deno run --allow-net --allow-read --allow-env app.ts
```

There's a way to escape explicit permissions.

答:
You could use denon https://deno.land/x/denon, is a tool like nodemon. An awesome thing about this is that includes a denon.json where you can add the attribute "allow": as an array and add the flags you want.

```<code>"allow": ["net", "read", "write"]
</code>```

and then in the terminal run the script for start your application

```<code>denon start yourapp.ts
</code>```

This will run:

```<code>deno run --allow-net --allow-read --allow-write yourapp.ts
</code>```

Now, when you make a change and save, it will run it again.

It has other cool attributes to add like the "unstable": true. Give it a try and read the README from denon for more information.

Title: Deno allow all permissions

Body:
I often find myself typing at least two or three permission options when playing with Deno:

deno run --allow-net --allow-read --allow-env app.ts

There's a way to escape explicit permissions.

Body:
You could use denon https://deno.land/x/denon, is a tool like nodemon. An awesome thing about this is that includes a denon.json where you can add the attribute "allow": as an array and add the flags you want.

"allow": ["net", "read", "write"]

and then in the terminal run the script for start your application

denon start yourapp.ts

This will run:

deno run --allow-net --allow-read --allow-write yourapp.ts

Now, when you make a change and save, it will run it again.

It has other cool attributes to add like the "unstable": true. Give it a try and read the README from denon for more information.