问:
Count decimal numbers in a string using the standard library
I have white-space separeted integers inside a string, e.g.:

```<code>std::string s = "1 2 33 444 0 5";
</code>```

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

答:
Are the integers guaranteed to each be separated by a single whitespace character (without there being leading or trailing whitespace)?

If so, then you just need to add 1 to the number of whitespace chars in the string itself, accounting for the empty string being a special case.

```<code>#include <algorithm>

size_t intCount(const std::string& s) {
  if (s.size() == 0) {
    return 0;
  }

  return std::count(s.begin(), s.end(), ‘ ‘) + 1;
}
</code>```

Body:
I have white-space separeted integers inside a string, e.g.:

std::string s = "1 2 33 444 0 5";

The string is well-formed: just white-space separated numbers without any letters, new-lines, etc.

How to count the number of integers in the above string in an STL way? I am looking for something "short" that will use e.g. iterators or <algorithm>.

Body:
Are the integers guaranteed to each be separated by a single whitespace character (without there being leading or trailing whitespace)?

If so, then you just need to add 1 to the number of whitespace chars in the string itself, accounting for the empty string being a special case.

#include <algorithm>

size_t intCount(const std::string& s) {
  if (s.size() == 0) {
    return 0;
  }

  return std::count(s.begin(), s.end(), ‘ ‘) + 1;
}


来源: stackexchange

问:
mac safari vs iphone safari
works on safari/firefox/chrome/opera for mac + pc. But not for safari iPhone. "error occurred" is the message which is better than nothing but not very helpful.
Is there a quick way to determine the cause of the problem? The website itself is svg + a lot of javascript/jquery. It also uses

```<code>eval()
</code>```

which may also be the reason of failure.

Erroneous website is here, and code is in svn on code.google.com

答:
I assume the problem is with google.load(). Apparently on certain browsers, the order of includes might not be that you would expect, therefore your plugin and other code would fail to load/execute.

I suggest you use the direct link to the Google CDN for your scripts:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>
</code>```

Alternatively you can attach a function to google.setOnLoadCallback() and use jQuery's $.getScript() in there as discussed in this thread, but the above is a lot cleaner solution.

ContentLicense: CC BY-SA 3.0

Title: mac safari vs iphone safari

Body:
works on safari/firefox/chrome/opera for mac + pc. But not for safari iPhone. "error occurred" is the message which is better than nothing but not very helpful.
Is there a quick way to determine the cause of the problem? The website itself is svg + a lot of javascript/jquery. It also uses

eval()

which may also be the reason of failure.

Erroneous website is here, and code is in svn on code.google.com

Body:
I assume the problem is with google.load(). Apparently on certain browsers, the order of includes might not be that you would expect, therefore your plugin and other code would fail to load/execute.

I suggest you use the direct link to the Google CDN for your scripts:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js" type="text/javascript"></script>

Alternatively you can attach a function to google.setOnLoadCallback() and use jQuery's $.getScript() in there as discussed in this thread, but the above is a lot cleaner solution.


问:
SELECTION SORT USING POINTERS AND FUNCTIONS IN C
```<code>#include<stdio.h>
void functt(int *,int );
int main {
int n;
scanf("%d",&n);
printf("Enter the elements of the array");
int i;
int arr[n];
int *ptr;
ptr=arr;
for (i=0;i<n;i++)
{
    scanf("%d",(p+i));
}
printf("The array elemets are as follows");
for (i=0;i<n;i++)
{
    printf("%d",*(p+i));
}
void functt(arr,n);
return 0;
}

void functt(int *,int n)
{
    int i,j,min;
    for (i=0;i<n;i++)
    {
        min=i;

        for (j=i+1;j<n;j++)
        {
            if(*(p+min)>*(p+j))
            {
                min=j;
            }

        }
    int temp=*(p+min);
    *(p+min)=*(p+j);
    *(p+j)=temp;
}
</code>```

ERRORS:
 https://i.stack.imgur.com/T2iLq.png

Can't run this code due to these errors
PROGRAM IS TO USE SELECTION SORT VIA POINTERS AND FUNCTIONS.
LOGIC SEEMS TO BE CORRECT I THINK BUT IT GIVES SOME ERRORS AS IN THE PNG ATTACHED ABOVE.

答:
I write this solution in order to dilver some important tips for C programming and any other language.

The code must me readable, this can be achieved with functions and giving them ameaningful names.

Functions shouldnt be long and complicated (seperate the logic) let each function do 1 task.

Always check parameters (those who comes from the outside of your application like user inputs or any other API users).

Checking and validating function arguments affect performance! when there is no need to check we dont check. e.g. we must check the return value of system call malloc(), because if we fail to allocate we dont want to crash the whole program!

Use size_t when you are talking about sizes which >= 0 !

Use const (you can protect the address and the value of the parameter) in function decleration and let the compiler helps you enforcing language rules and your own rules!

Think performance (just if you need, but C was borned for performance :-)), accessing arrays like pointers with the derefernce operator, astrisc or star * is more faster than operator subscribt []

Good luck. C is one of the most eligant and powerful language that ever made!

The Code Snippet

```<code>enter code here
#include <stdio.h>
#include <stdlib.h>
/*swap two int varibles*/
void f_swap(int* lhs, int* rhs)
{
    int temp = *rhs;
    *rhs = *lhs;
    *lhs = temp;
}
/*status enum*/
typedef enum E_STAT {
    success_status = 0x0,
    allocation_failed = 0x1,
    invalid_user_inputs = 0x2,
    /*... you can add if you want/need*/
    failure_status
}E_STAT;

const char* f_status_to_str(E_STAT stat)
{
    static const char* STATUS_MSG[4] = {
                             "success_status",
                             "allocation_failure",
                             "invalid_user_inputs",
                             "failure_status" };

    return STATUS_MSG[stat];
}

void f_fill_array(int* p_ret_arr, size_t arr_size)
{
    printf("Enter the elements of the array below:\n");
    for (size_t i = 0; i < arr_size; ++i)
    {
        /*scanf("%d", &p_ret_arr[i]);*/ /*or we can take them in the form next line*/
        printf("Enter the -%lu- element:", i);
        scanf("%d", (p_ret_arr + i));
        //puts("");
    }
}

void f_sel_sort(int* const p_arr, size_t arr_size)
{
    size_t i, j, min_idx;

    /* One by one move boundary of unsorted subarray  */
    for (i = 0; i < arr_size - 1; i++)
    {
        /* Find the minimum element in unsorted array  */
        min_idx = i;
        for (j = i + 1; j < arr_size; ++j)
        {
            if (p_arr[j] < p_arr[min_idx])
            {
                min_idx = j;
            }
        }

        /*Swap the found minimum element with the first element  */
        f_swap(&p_arr[min_idx], &p_arr[i]);
    }
}

void f_print_array(const int* const p_arr, size_t arr_size)
{
    for (size_t j = 0; j < arr_size; ++j)
    {
        printf("%d ", *(p_arr + j));
    }
}

/*allocate new int array on the heap (dyn allocation)*/
int* f_allocate(size_t arr_size)
{
    int* p_ret = NULL;
    return (p_ret=(int*)malloc(sizeof(int) * arr_size));
}

E_STAT f_get_arr(int** p_ret_arr, size_t* arr_size)
{
    E_STAT stat;

    printf("Please enter array size below:\n");
    scanf("%lu", arr_size);
    /*recomended to check the arr_size and do some limiting on this variable if you wish*/

    *p_ret_arr = f_allocate(*arr_size);
    if (!(*p_ret_arr))
    {
        stat = allocation_failed;
        return stat;
    }

    f_fill_array(*p_ret_arr, *arr_size);
    stat = success_status;
    return stat;
}

int main(int argc, char* argv[])
{
    size_t arr_size = 0;
    int* arr = NULL;
    E_STAT stat;

    stat = f_get_arr(&arr, &arr_size);
    if (stat != success_status)
    {
        printf("Error: %s\n", f_status_to_str(stat));
        abort();
    }

    f_sel_sort(arr, arr_size);
    printf("Sorted array elements:\n");
    f_print_array(arr, arr_size);

    return 0;
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
#include<stdio.h>
void functt(int *,int );
int main {
int n;
scanf("%d",&n);
printf("Enter the elements of the array");
int i;
int arr[n];
int *ptr;
ptr=arr;
for (i=0;i<n;i++)
{
    scanf("%d",(p+i));
}
printf("The array elemets are as follows");
for (i=0;i<n;i++)
{
    printf("%d",*(p+i));
}
void functt(arr,n);
return 0;
}

void functt(int *,int n)
{
    int i,j,min;
    for (i=0;i<n;i++)
    {
        min=i;

        for (j=i+1;j<n;j++)
        {
            if(*(p+min)>*(p+j))
            {
                min=j;
            }

        }
    int temp=*(p+min);
    *(p+min)=*(p+j);
    *(p+j)=temp;
}

ERRORS:
 https://i.stack.imgur.com/T2iLq.png

Can't run this code due to these errors
PROGRAM IS TO USE SELECTION SORT VIA POINTERS AND FUNCTIONS.
LOGIC SEEMS TO BE CORRECT I THINK BUT IT GIVES SOME ERRORS AS IN THE PNG ATTACHED ABOVE.

Body:
I write this solution in order to dilver some important tips for C programming and any other language.

The code must me readable, this can be achieved with functions and giving them ameaningful names.

Functions shouldnt be long and complicated (seperate the logic) let each function do 1 task.

Always check parameters (those who comes from the outside of your application like user inputs or any other API users).

Checking and validating function arguments affect performance! when there is no need to check we dont check. e.g. we must check the return value of system call malloc(), because if we fail to allocate we dont want to crash the whole program!

Use size_t when you are talking about sizes which >= 0 !

Use const (you can protect the address and the value of the parameter) in function decleration and let the compiler helps you enforcing language rules and your own rules!

Think performance (just if you need, but C was borned for performance :-)), accessing arrays like pointers with the derefernce operator, astrisc or star * is more faster than operator subscribt []

Good luck. C is one of the most eligant and powerful language that ever made!

The Code Snippet

enter code here
#include <stdio.h>
#include <stdlib.h>
/*swap two int varibles*/
void f_swap(int* lhs, int* rhs)
{
    int temp = *rhs;
    *rhs = *lhs;
    *lhs = temp;
}
/*status enum*/
typedef enum E_STAT {
    success_status = 0x0,
    allocation_failed = 0x1,
    invalid_user_inputs = 0x2,
    /*... you can add if you want/need*/
    failure_status
}E_STAT;

const char* f_status_to_str(E_STAT stat)
{
    static const char* STATUS_MSG[4] = {
                             "success_status",
                             "allocation_failure",
                             "invalid_user_inputs",
                             "failure_status" };

    return STATUS_MSG[stat];
}

void f_fill_array(int* p_ret_arr, size_t arr_size)
{
    printf("Enter the elements of the array below:\n");
    for (size_t i = 0; i < arr_size; ++i)
    {
        /*scanf("%d", &p_ret_arr[i]);*/ /*or we can take them in the form next line*/
        printf("Enter the -%lu- element:", i);
        scanf("%d", (p_ret_arr + i));
        //puts("");
    }
}

void f_sel_sort(int* const p_arr, size_t arr_size)
{
    size_t i, j, min_idx;

    /* One by one move boundary of unsorted subarray  */
    for (i = 0; i < arr_size - 1; i++)
    {
        /* Find the minimum element in unsorted array  */
        min_idx = i;
        for (j = i + 1; j < arr_size; ++j)
        {
            if (p_arr[j] < p_arr[min_idx])
            {
                min_idx = j;
            }
        }

        /*Swap the found minimum element with the first element  */
        f_swap(&p_arr[min_idx], &p_arr[i]);
    }
}

void f_print_array(const int* const p_arr, size_t arr_size)
{
    for (size_t j = 0; j < arr_size; ++j)
    {
        printf("%d ", *(p_arr + j));
    }
}

/*allocate new int array on the heap (dyn allocation)*/
int* f_allocate(size_t arr_size)
{
    int* p_ret = NULL;
    return (p_ret=(int*)malloc(sizeof(int) * arr_size));
}

E_STAT f_get_arr(int** p_ret_arr, size_t* arr_size)
{
    E_STAT stat;

    printf("Please enter array size below:\n");
    scanf("%lu", arr_size);
    /*recomended to check the arr_size and do some limiting on this variable if you wish*/

    *p_ret_arr = f_allocate(*arr_size);
    if (!(*p_ret_arr))
    {
        stat = allocation_failed;
        return stat;
    }

    f_fill_array(*p_ret_arr, *arr_size);
    stat = success_status;
    return stat;
}

int main(int argc, char* argv[])
{
    size_t arr_size = 0;
    int* arr = NULL;
    E_STAT stat;

    stat = f_get_arr(&arr, &arr_size);
    if (stat != success_status)
    {
        printf("Error: %s\n", f_status_to_str(stat));
        abort();
    }

    f_sel_sort(arr, arr_size);
    printf("Sorted array elements:\n");
    f_print_array(arr, arr_size);

    return 0;
}


问:
Convert a Pandas DataFrame to a specific dictionary format
I have a dataframe:

```<code>Name   Fruit    Fruit-Low   Fruit-High
Joe    Apple     8.12       8.74
Joe    Pear      3.54       6.24
Jess   Orange    5.36       8.24
Jess   Apple     5.45       8.44
</code>```

I am trying to convert the dataframe into a specific dictionary format such as:

```<code>dictionary = {Joe: {Apple: (8.12, 8.74), Pear: (3.54, 6.24)}, Jess: {Orange: (5.36, 8.24), Apple: (5.45, 8.44)}}
</code>```

Is there a pay to specify this format when converting the dataframe? I have tried the to_dict() command but continue to not be able to bring in all the rows as I am trying.

Any help would be greatly appreciated! Thanks in advance.

答: Perhaps this Stack Overflow thread could help. Your main directions should DataFrame.to_dict documentation</p>

Body:
I have a dataframe:

Name   Fruit    Fruit-Low   Fruit-High
Joe    Apple     8.12       8.74
Joe    Pear      3.54       6.24
Jess   Orange    5.36       8.24
Jess   Apple     5.45       8.44

I am trying to convert the dataframe into a specific dictionary format such as:

dictionary = {Joe: {Apple: (8.12, 8.74), Pear: (3.54, 6.24)}, Jess: {Orange: (5.36, 8.24), Apple: (5.45, 8.44)}}

Is there a pay to specify this format when converting the dataframe? I have tried the to_dict() command but continue to not be able to bring in all the rows as I am trying.

Any help would be greatly appreciated! Thanks in advance.


答:
I think a possible solution would be something like this, although I'm sure it's not the pandorable way. of solving this:

```<code>def to_dict(df):
    result = {}
    for index, row in df.iterrows():
        entry = result.get(row['Name'])
        if entry == None:
            entry = {}
        entry[row['Fruit']] = (row['Fruit-Low'], row['Fruit-High'])
    return result
</code>```

This assumes that each fruit is unique per name. If that assumption is wrong, the solution would overwrite the previous entry.

Title: Convert a Pandas DataFrame to a specific dictionary format

Body:
I think a possible solution would be something like this, although I'm sure it's not the pandorable way. of solving this:

def to_dict(df):
    result = {}
    for index, row in df.iterrows():
        entry = result.get(row['Name'])
        if entry == None:
            entry = {}
        entry[row['Fruit']] = (row['Fruit-Low'], row['Fruit-High'])
    return result

This assumes that each fruit is unique per name. If that assumption is wrong, the solution would overwrite the previous entry.


问:
Doing a sum of specific values of an array in java
good afternoon, practicing exercises I am having a problem, which I already identified, but I have not managed to solve, it must be something simple that I do not see, this is what the exercise asks for:

Write a program that reads an array of ints and an integer number n. The program must sum all the array elements greater than n.

Input data format

The first line contains the size of an array.
The second line contains elements of the array separated by spaces.
The third line contains the number n.

Output data format

Only a single number representing the sum.

Sample Input 1:

5

5 8 11 2 10

8

Sample Output 1:

21

This is my code that I have so far:

```<code> public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    int[] array = new int[size];
    int sum = 0;

    int n = in.nextInt();

    for (int i = 0; i < array.length; i++) {
        array[i] = in.nextInt();
            if (array[i] > n) {
                sum += array[i];
            }
    }
    System.out.println(sum);
}
</code>```

I identify that my program prints 37 and not 21, because it is not comparing the number well, since it asks me for the value of n in the second line that I enter and it should be after it has the elements of the arrangement, I would like them to help me, try placing if, for, and did not reach the solution.

I really appreciate your time and help, thanks.

答:
Order of operations is wrong. First you read array's size, then number n, and then read the array. Run this code, read the comments and compare to your code:

```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    // read array size
    int size = in.nextInt();
    int[] array = new int[size];
    int sum = 0;

    // read elements of array
    for (int i = 0; i < array.length; i++) {
        array[i] = in.nextInt();
    }

    // and only now read the number n
    int n = in.nextInt();

    // now that we have all data, we can calculate the sum
    for (int value : array) {
        if (value > n) {
            sum += value;
        }
    }
    System.out.println(sum);
}
</code>```

Body:
good afternoon, practicing exercises I am having a problem, which I already identified, but I have not managed to solve, it must be something simple that I do not see, this is what the exercise asks for:

Write a program that reads an array of ints and an integer number n. The program must sum all the array elements greater than n.

Input data format

The first line contains the size of an array.
The second line contains elements of the array separated by spaces.
The third line contains the number n.

Output data format

Only a single number representing the sum.

Sample Input 1:

5

5 8 11 2 10

8

Sample Output 1:

21

This is my code that I have so far:

 public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    int[] array = new int[size];
    int sum = 0;

    int n = in.nextInt();

    for (int i = 0; i < array.length; i++) {
        array[i] = in.nextInt();
            if (array[i] > n) {
                sum += array[i];
            }
    }
    System.out.println(sum);
}

I identify that my program prints 37 and not 21, because it is not comparing the number well, since it asks me for the value of n in the second line that I enter and it should be after it has the elements of the arrangement, I would like them to help me, try placing if, for, and did not reach the solution.

I really appreciate your time and help, thanks.

Body:
Order of operations is wrong. First you read array's size, then number n, and then read the array. Run this code, read the comments and compare to your code:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    // read array size
    int size = in.nextInt();
    int[] array = new int[size];
    int sum = 0;

    // read elements of array
    for (int i = 0; i < array.length; i++) {
        array[i] = in.nextInt();
    }

    // and only now read the number n
    int n = in.nextInt();

    // now that we have all data, we can calculate the sum
    for (int value : array) {
        if (value > n) {
            sum += value;
        }
    }
    System.out.println(sum);
}


问:
ViewModel.setLookAtData() does not animate if using only bounds
I am attempting to zoom into a clicked shape or group of shapes. The actual move works, but the property to tell it to animate does not.

```<code>map.getViewModel().setLookAtData({
   bounds: boundingBox
}, true);
</code>```

This does move and zoom correctly but without animation. If I add a specific zoom level it animates as expected, but part of what I need it to figure out is the zoom level for me.

I can probably fake it if I can work out any reliable way to calculate what the zoom level should be manually, but that is less than ideal. For what ever reason, using only bounds breaks the feature that allows animation. Any work around for this?

答:
Possible Workaround:  seems to work if you pass the bounds centroid:</p>

```<code>let data = {bounds: bounds, position: bounds.getCenter() };
map.getViewModel().setLookAtData(data, opt_animate);
</code>```

Body:
I am attempting to zoom into a clicked shape or group of shapes. The actual move works, but the property to tell it to animate does not.

map.getViewModel().setLookAtData({
   bounds: boundingBox
}, true);

This does move and zoom correctly but without animation. If I add a specific zoom level it animates as expected, but part of what I need it to figure out is the zoom level for me.

I can probably fake it if I can work out any reliable way to calculate what the zoom level should be manually, but that is less than ideal. For what ever reason, using only bounds breaks the feature that allows animation. Any work around for this?

Body:
Possible Workaround:  seems to work if you pass the bounds centroid:

let data = {bounds: bounds, position: bounds.getCenter() };
map.getViewModel().setLookAtData(data, opt_animate);


问:
MySQL join is scanning the table rather than using the index
I have following tables:

SHOW CREATE TABLE access_token_status;

```<code>CREATE TABLE `access_token_status` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` varchar(10) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `status` (`status`),
  KEY `idx_access_token_status_status_lookup_2` (`status`,`id`),
  KEY `idx_access_token_status_status_lookup_1` (`id`,`status`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
</code>```

and

SHOW CREATE TABLE user;

```<code>CREATE TABLE `user` (
  `id` varchar(17) NOT NULL,
  `short_lived_access_token_status_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_user_status_lookup_1` (`id`,`short_lived_access_token_status_id`),
  KEY `idx_user_status_lookup_2` (`short_lived_access_token_status_id`,`id`),
  KEY `ix_user_short_lived_access_token_status_id` (`short_lived_access_token_status_id`),
  CONSTRAINT `user_ibfk_1` FOREIGN KEY (`short_lived_access_token_status_id`) REFERENCES `access_token_status` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
</code>```

and

SHOW CREATE TABLE account;

```<code>CREATE TABLE `account` (
  `id` varchar(17) NOT NULL,
  `user_id` varchar(17) NOT NULL,
  `track` tinyint(1) NOT NULL,
  `estimated_time_to_regain_access` int(11) NOT NULL,
  `media_list_fetched_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_account_next_fetch_lookup` (`user_id`,`estimated_time_to_regain_access`,`track`,`media_list_fetched_at`),
  CONSTRAINT `account_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
  CONSTRAINT `account_chk_1` CHECK ((`track` in (0,1)))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
</code>```

When I try to explain the following query

```<code>explain select a.*
        from account a
        inner join user u
        on a.user_id = u.id
        inner  join access_token_status as s
        on u.short_lived_access_token_status_id = s.id and s.status = 'valid'
        where
            u.short_lived_access_token_status_id = 3
            and a.estimated_time_to_regain_access = 0
            and a.track = true
            and a.media_list_fetched_at > '2020-05-30 12:31:01'
        limit 1
        for update of a SKIP LOCKED
</code>```

I get this output:

```<code># id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'SIMPLE', 's', NULL, 'const', 'PRIMARY,status,idx_access_token_status_status_lookup_2,idx_access_token_status_status_lookup_1', 'PRIMARY', '4', 'const', '1', '100.00', NULL
'1', 'SIMPLE', 'a', NULL, 'index', 'idx_account_next_fetch_lookup', 'idx_account_next_fetch_lookup', '80', NULL, '2', '50.00', 'Using where; Using index'
'1', 'SIMPLE', 'u', NULL, 'eq_ref', 'PRIMARY,idx_user_status_lookup_1,idx_user_status_lookup_2,ix_user_short_lived_access_token_status_id', 'PRIMARY', '70', 'media_meta.a.user_id', '1', '100.00', 'Using where'
</code>```

It seems like indexes are not being used for some tables. This is an issue for my case as the scanned rows get locked and other queries will skip them (due to SKIP LOCKED which is required to make sure queries are not blocked on each other)

I'm not sure what index I'm missing or if I need to change something in the query

答:
In your query you use "u.short_lived_access_token_status_id = 3", so the join with "s" looks either impossible (if s.status for s.id = 3 is NOT "valid") or superfluous (if it is). Unless you are fetching some other columns from s.

Let us now see where "u" is used:

```<code>on a.user_id = u.id
...
    on u.short_lived_access_token_status_id = ...
</code>```

So you are using a main selection criterion based on u.short_lived_access_token_status_id = 3, and from this you need to get u.id. So your idx_user_status_lookup_2 ought to work as a covering index.

Why doesn't it? Possibly because the table is so small that it doesn't matter very much, or because the join with S is interfering with the optimizer (you'll note that the table u is evaluated third).

If at all possible, try removing the join with s and see what happens.

Body:
I have following tables:

SHOW CREATE TABLE access_token_status;

CREATE TABLE `access_token_status` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `status` varchar(10) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `status` (`status`),
  KEY `idx_access_token_status_status_lookup_2` (`status`,`id`),
  KEY `idx_access_token_status_status_lookup_1` (`id`,`status`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

and

SHOW CREATE TABLE user;

CREATE TABLE `user` (
  `id` varchar(17) NOT NULL,
  `short_lived_access_token_status_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_user_status_lookup_1` (`id`,`short_lived_access_token_status_id`),
  KEY `idx_user_status_lookup_2` (`short_lived_access_token_status_id`,`id`),
  KEY `ix_user_short_lived_access_token_status_id` (`short_lived_access_token_status_id`),
  CONSTRAINT `user_ibfk_1` FOREIGN KEY (`short_lived_access_token_status_id`) REFERENCES `access_token_status` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

and

SHOW CREATE TABLE account;

CREATE TABLE `account` (
  `id` varchar(17) NOT NULL,
  `user_id` varchar(17) NOT NULL,
  `track` tinyint(1) NOT NULL,
  `estimated_time_to_regain_access` int(11) NOT NULL,
  `media_list_fetched_at` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_account_next_fetch_lookup` (`user_id`,`estimated_time_to_regain_access`,`track`,`media_list_fetched_at`),
  CONSTRAINT `account_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
  CONSTRAINT `account_chk_1` CHECK ((`track` in (0,1)))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

When I try to explain the following query

explain select a.*
        from account a
        inner join user u
        on a.user_id = u.id
        inner  join access_token_status as s
        on u.short_lived_access_token_status_id = s.id and s.status = 'valid'
        where
            u.short_lived_access_token_status_id = 3
            and a.estimated_time_to_regain_access = 0
            and a.track = true
            and a.media_list_fetched_at > '2020-05-30 12:31:01'
        limit 1
        for update of a SKIP LOCKED

I get this output:

# id, select_type, table, partitions, type, possible_keys, key, key_len, ref, rows, filtered, Extra
'1', 'SIMPLE', 's', NULL, 'const', 'PRIMARY,status,idx_access_token_status_status_lookup_2,idx_access_token_status_status_lookup_1', 'PRIMARY', '4', 'const', '1', '100.00', NULL
'1', 'SIMPLE', 'a', NULL, 'index', 'idx_account_next_fetch_lookup', 'idx_account_next_fetch_lookup', '80', NULL, '2', '50.00', 'Using where; Using index'
'1', 'SIMPLE', 'u', NULL, 'eq_ref', 'PRIMARY,idx_user_status_lookup_1,idx_user_status_lookup_2,ix_user_short_lived_access_token_status_id', 'PRIMARY', '70', 'media_meta.a.user_id', '1', '100.00', 'Using where'

It seems like indexes are not being used for some tables. This is an issue for my case as the scanned rows get locked and other queries will skip them (due to SKIP LOCKED which is required to make sure queries are not blocked on each other)

I'm not sure what index I'm missing or if I need to change something in the query

Body:
In your query you use "u.short_lived_access_token_status_id = 3", so the join with "s" looks either impossible (if s.status for s.id = 3 is NOT "valid") or superfluous (if it is). Unless you are fetching some other columns from s.

Let us now see where "u" is used:

on a.user_id = u.id
...
    on u.short_lived_access_token_status_id = ...

So you are using a main selection criterion based on u.short_lived_access_token_status_id = 3, and from this you need to get u.id. So your idx_user_status_lookup_2 ought to work as a covering index.

Why doesn't it? Possibly because the table is so small that it doesn't matter very much, or because the join with S is interfering with the optimizer (you'll note that the table u is evaluated third).

If at all possible, try removing the join with s and see what happens.


问:
What is the complexity(Big O) of this algorithm?
I have an array of n numbers from 0 to n-1.

```<code>int func(Integer[]array){
    int res = 0;
    for (int x = 0; x < array.length; x++) {
        for (int y = x; y > Math.max(x - 1000, 0) ; y--) {
            res = res + array[y];
        }
    }
    return res;
}
</code>```

O(n), O(n^2), O(n^1/5), O(log n)

I think it's O(n^2). I'm right?

答:
It seems that Paul's comment is correct. The inner loop only runs at constant time. Therefore, the time complexity is just O(N) for the outer loop. </p>

<p>The algorithm also runs at constant memory O(1). </p>

Body:
I have an array of n numbers from 0 to n-1.

int func(Integer[]array){
    int res = 0;
    for (int x = 0; x < array.length; x++) {
        for (int y = x; y > Math.max(x - 1000, 0) ; y--) {
            res = res + array[y];
        }
    }
    return res;
}

O(n), O(n^2), O(n^1/5), O(log n)

I think it's O(n^2). I'm right?

Body:
It seems that Paul's comment is correct. The inner loop only runs at constant time. Therefore, the time complexity is just O(N) for the outer loop.

The algorithm also runs at constant memory O(1).


问:
Task 'assembleRelease' not found in root project 'android'
I'm using Reactnative 0.54.0 and react-native-cli 2.0.1 along side gradle 4.8.1

I have created a react-native project using create-react-native-app myProjectName

When I created the project, it doesn't include android and ios folders, so I added them manually.

I also installed gradle using choco and then created a wrapper for it using gradle wrapper --gradle-version 4.8.1 --distribution-type all

so I am developing react-native using microsoft vsCode and then see my application in action using Genymotion emulator, everything is fine

now, I want to generate the final Signed APK for play store, I'm using this guide provided by react-native

https://facebook.github.io/react-native/docs/signed-apk-android.html

When I want to run gradlew assembleRelease I get this error

```<code>C:\myApp\android>gradlew assembleRelease

FAILURE: Build failed with an exception.

* What went wrong:
Task 'assembleRelease' not found in root project 'android'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s
</code>```

what's wrong with assembleRelease? what should I do?

to add more info, I have to say that when I want to build this project in VSTS (TFS Online) I get this error

```<code>2018-07-17T16:20:14.9268702Z ##[error]Error: Not found wrapperScript: D:\a\1\s\gradlew
</code>```

Any clue is appriciated
Thanks

Update:
as @philipp asked, this is the list of tasks that gradlew have listed and assembleRelease is not one one them!!!! what's the reason?

```<code>C:\myApp\Android>gradlew tasks

> Task :tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'android'.
components - Displays the components produced by root project 'android'. [incubating]
dependencies - Displays all dependencies declared in root project 'android'.
dependencyInsight - Displays the insight into a specific dependency in root project 'android'.
dependentComponents - Displays the dependent components of components in root project 'android'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'android'. [incubating]
projects - Displays the sub-projects of root project 'android'.
properties - Displays the properties of root project 'android'.
tasks - Displays the tasks runnable from root project 'android'.

To see all tasks and more detail, run gradlew tasks --all

To see more detail about a task, run gradlew help --task <task>

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed
</code>```

and this is myApp\android**build.gradle**

```<code>project.ext.react = [
    bundleInStaging: true
]
task wrapper(type: Wrapper) {
    gradleVersion = '4.8.1'
}
android {
    defaultConfig {
        applicationId "com.sunkime.client"
    }
    signingConfigs {
        staging {
            keyAlias = "staging"
            storeFile = file("my-release-key.keystore")
            keyPassword = "qwert%$#@!"
            storePassword = "qwert%$#@!"
        }
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword qwert%$#@!
                keyAlias qwert%$#@!
                keyPassword qwert%$#@!
            }
        }
    }
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }
        staging {
            applicationIdSuffix ".staging"
            signingConfig signingConfigs.staging
            minifyEnabled true
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }

        release {
            applicationIdSuffix ".release"
            signingConfig signingConfigs.release
            minifyEnabled true
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
}
</code>```

I also used gradlew clean and no difference

答:
Make sure you are not finding the android environment variables

Run the command on the mac like this to load the variables

```<code>source ~/.bash_profile
</code>```

Body:
I'm using Reactnative 0.54.0 and react-native-cli 2.0.1 along side gradle 4.8.1

I have created a react-native project using create-react-native-app myProjectName

When I created the project, it doesn't include android and ios folders, so I added them manually.

I also installed gradle using choco and then created a wrapper for it using gradle wrapper --gradle-version 4.8.1 --distribution-type all

so I am developing react-native using microsoft vsCode and then see my application in action using Genymotion emulator, everything is fine

now, I want to generate the final Signed APK for play store, I'm using this guide provided by react-native

https://facebook.github.io/react-native/docs/signed-apk-android.html

When I want to run gradlew assembleRelease I get this error

C:\myApp\android>gradlew assembleRelease

FAILURE: Build failed with an exception.

* What went wrong:
Task 'assembleRelease' not found in root project 'android'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 4s

what's wrong with assembleRelease? what should I do?

to add more info, I have to say that when I want to build this project in VSTS (TFS Online) I get this error

2018-07-17T16:20:14.9268702Z ##[error]Error: Not found wrapperScript: D:\a\1\s\gradlew

Any clue is appriciated
Thanks

Update:
as @philipp asked, this is the list of tasks that gradlew have listed and assembleRelease is not one one them!!!! what's the reason?

C:\myApp\Android>gradlew tasks

> Task :tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'android'.
components - Displays the components produced by root project 'android'. [incubating]
dependencies - Displays all dependencies declared in root project 'android'.
dependencyInsight - Displays the insight into a specific dependency in root project 'android'.
dependentComponents - Displays the dependent components of components in root project 'android'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'android'. [incubating]
projects - Displays the sub-projects of root project 'android'.
properties - Displays the properties of root project 'android'.
tasks - Displays the tasks runnable from root project 'android'.

To see all tasks and more detail, run gradlew tasks --all

To see more detail about a task, run gradlew help --task <task>

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

and this is myApp\android**build.gradle**

project.ext.react = [
    bundleInStaging: true
]
task wrapper(type: Wrapper) {
    gradleVersion = '4.8.1'
}
android {
    defaultConfig {
        applicationId "com.sunkime.client"
    }
    signingConfigs {
        staging {
            keyAlias = "staging"
            storeFile = file("my-release-key.keystore")
            keyPassword = "qwert%$#@!"
            storePassword = "qwert%$#@!"
        }
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword qwert%$#@!
                keyAlias qwert%$#@!
                keyPassword qwert%$#@!
            }
        }
    }
    buildTypes {
        debug {
            applicationIdSuffix ".debug"
        }
        staging {
            applicationIdSuffix ".staging"
            signingConfig signingConfigs.staging
            minifyEnabled true
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }

        release {
            applicationIdSuffix ".release"
            signingConfig signingConfigs.release
            minifyEnabled true
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
}

I also used gradlew clean and no difference

Body:
Make sure you are not finding the android environment variables

Run the command on the mac like this to load the variables

source ~/.bash_profile


问:
Is a std::function member variable of the class type allowed (incomplete type)?
I am wondering if this is fine to do, it compiles fine for me but I am not sure if it actually is ok:

```<code>class Foo {
  std::function<Foo(Foo& f)> my_function;
};
</code>```

The function my_function takes a Foo reference and returns a Foo. It is a member variable inside Foo, and usually these incomplete types are not allowed. For example:

```<code>class Foo {
   std::vector<Foo> foos;
};
</code>```

Would not work I don't think (a benefit of boost is that it does work for boost::container::vector).

答:
Per the Standard, this appears to be fine.

[res.on.functions]/2 says:

[...] [The] effects are undefined in the following cases:

[...]

If an incomplete type ([basic.types]) is used as a template argument when instantiating a template component or evaluating a concept, unless specifically allowed for that component.

But while a class type is incomplete within the immediate body of that class, a function type derived from that class type is not incomplete (since a function type is not an object type), much as a pointer to an incomplete class type is not an incomplete type.
There are also no requirements within [func.wrap] that R or Args in std::function<R(Args...)> should be complete types.

More or less, this is equivalent to having a class data member of type Foo(*)(Foo&) (pointer to function), which is also fine.

You will need to be careful not to call the std::function data member within the immediate body of your class (e.g. in a data member initializer). (This is because a function call expression that returns an class prvalue will at some point require a temporary materialization conversion, which requires the class to be complete.) Calling it within member functions is fine, since Foo will be complete by that point, even for member functions defined inline.

Body:
I am wondering if this is fine to do, it compiles fine for me but I am not sure if it actually is ok:

class Foo {
  std::function<Foo(Foo& f)> my_function;
};

The function my_function takes a Foo reference and returns a Foo. It is a member variable inside Foo, and usually these incomplete types are not allowed. For example:

class Foo {
   std::vector<Foo> foos;
};

Would not work I don't think (a benefit of boost is that it does work for boost::container::vector).


问:
Re-Rendering Angular component
I have the below stackblitz whenever I change the value of the boolean var I want the component to be rerendered how can I achieve that?

https://stackblitz.com/edit/angular-ivy-8rwqba?file=src/app/app.component.html

答:
Use [checked] instead of [value] :

<input type="checkbox" [checked]="test1"/>test1 - {{test1}}
<input type="checkbox" [checked]="test2"/>test2 - {{test2}}```

Title: Re-Rendering Angular component


问:
the getter 'text' was called on null flutter
I have this error in my Flutter app:

NoSuchMethodError: The getter 'text' was called on null.
  Receiver: null
  Tried calling: text
  See also:
  https://flutter.dev/docs/testing/errors

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(
    NewApp()
  );
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           TextField(
            controller: textController,
          ),
          Text(
            textController.text
          )
         ],
       )
    );
  }
}
</code>```

答:
You are getting the error because textController is not yet instantiated, hence its value is null. You can make the property call null-aware to skip the error:

```<code>textController?.text
</code>```

you'll get other errors though. After fixing the other errors the app will work but I doubt it does what you want.

Body:
I have this error in my Flutter app:

NoSuchMethodError: The getter 'text' was called on null.
  Receiver: null
  Tried calling: text
  See also:
  https://flutter.dev/docs/testing/errors

import 'package:flutter/material.dart';

void main() {
  runApp(
    NewApp()
  );
}

class NewApp extends StatefulWidget {
  NewApp({Key key}) : super(key: key);

  @override
  _NewAppState createState() => _NewAppState();
}

class _NewAppState extends State<NewApp> {
  TextEditingController textController;

  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           TextField(
            controller: textController,
          ),
          Text(
            textController.text
          )
         ],
       )
    );
  }
}

Body:
You are getting the error because textController is not yet instantiated, hence its value is null. You can make the property call null-aware to skip the error:

textController?.text

you'll get other errors though. After fixing the other errors the app will work but I doubt it does what you want.


问:
How can I multiply together every nth cell in a row to get the product?
I want to calculate the product of the investment returns (compound interest), which in this instance would give a return of 162%:

Additional stock return data will be added in future, so I need a formula that compounds every nth (2nd) value. I am able to sum the cells using:
=SUMIF(ARRAYFORMULA(MOD((COLUMN(A2:H2)-COLUMN(A2)+1),2)),0,A2:H2)

However I cannot find an equivalent 'PRODUCTIF' function and have not been able to make a formula that works. Writing the formula out long hand would be:
=B2*D2*F2*H2

答:
Product formula should be like Sum formula but putting 1 for odd columns:

```<code>=ArrayFormula(PRODUCT(IF(MOD(COLUMN(A2:H2)-COLUMN(A2)+1,2),1,A2:H2)))
</code>```

Body:
Product formula should be like Sum formula but putting 1 for odd columns:

=ArrayFormula(PRODUCT(IF(MOD(COLUMN(A2:H2)-COLUMN(A2)+1,2),1,A2:H2)))


问:
Discord.js - ReferenceError: member is not defined
I am having issues with this, i am trying to add a role called Simon Says Player, can anyone help??</p>

```<code>bot.on('message', message => {

    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
        case 'join':

            let person = message.guild.member

            if (!person) {
                return message.reply('Couldn`t find the user!');
            }

            let mainRole = (role => role.name === "Simon Says Player");

            member.addRole(mainRole.id);

            message.channel.send('Successfully Entered The Game!!')

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

答:
member is in fact undefined, you did not state the intended function but from what I can see you're trying to give a role to the member that sent the join command.

bot.on('message', message => {

  let args = message.content.substring(PREFIX.length).split(" ");

  switch (args[0]) {
    case 'join':

      let person = message.guild.member

      if (!person) {
        return message.reply('Couldn`t find the user!');
      }

      let mainRole = message.guild.roles.cache.find(role => role.name === "Simon Says Player");

      message.member.roles.add(mainRole.id);

      message.channel.send('Successfully Entered The Game!!')

      break;
  }
})
```

Body:
I am having issues with this, i am trying to add a role called Simon Says Player, can anyone help??

bot.on('message', message => {

    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
        case 'join':

            let person = message.guild.member

            if (!person) {
                return message.reply('Couldn`t find the user!');
            }

            let mainRole = (role => role.name === "Simon Says Player");

            member.addRole(mainRole.id);

            message.channel.send('Successfully Entered The Game!!')

            break;
    }
})


问:
ASP.NET Core API Authentication with JWT breaks built-in authentication for website
I'm working on an ASP.NET Core project that has a website as well as an API. I need the API to be secured by some means, so I implemented JWT authentication. This worked as expected, and the API is only accessible by calls made with a valid token.

The problem is, the built-in login functionality on the website no longer works.
This is the code I added to Startup.cs:

```<code>services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

</code>```

If I remove this code, the built-in login feature works as usual, but the API no longer works.

Is there a way I can make the JWT authentication only apply to the API controllers? Or is there a way I can make the built-in authentication use JWT?

答:
I had the same problem and resolved it (using Asp.Net Core 3.0).

You can add more than one Authentication schema to your project with code like this.

```<code>// Read the token generation data...
var token = Configuration.GetSection("JwtTokenData").Get<JwtTokenData>();

services.AddAuthentication()
        .AddCookie(options =>
        {
            options.LoginPath = $"/Identity/Account/Login";
            options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
        })
        .AddJwtBearer(options => {
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                ValidIssuer = token.Issuer,
                ValidAudience = token.Audience,
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });
</code>```

Notice how I haven't specified the default authentication schema when I call AddAuthentication. This allows the built-in Authentication to be the default for your pages or controller where you use the [Authorize] attribute.

But when you need to use JWT Authentication then you use this option on the Authorize attribute for your Web API controller or methods

```<code>[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
</code>```

Body:
I'm working on an ASP.NET Core project that has a website as well as an API. I need the API to be secured by some means, so I implemented JWT authentication. This worked as expected, and the API is only accessible by calls made with a valid token.

The problem is, the built-in login functionality on the website no longer works.
This is the code I added to Startup.cs:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

If I remove this code, the built-in login feature works as usual, but the API no longer works.

Is there a way I can make the JWT authentication only apply to the API controllers? Or is there a way I can make the built-in authentication use JWT?

Body:
I had the same problem and resolved it (using Asp.Net Core 3.0).

You can add more than one Authentication schema to your project with code like this.

// Read the token generation data...
var token = Configuration.GetSection("JwtTokenData").Get<JwtTokenData>();

services.AddAuthentication()
        .AddCookie(options =>
        {
            options.LoginPath = $"/Identity/Account/Login";
            options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
        })
        .AddJwtBearer(options => {
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                ValidIssuer = token.Issuer,
                ValidAudience = token.Audience,
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

Notice how I haven't specified the default authentication schema when I call AddAuthentication. This allows the built-in Authentication to be the default for your pages or controller where you use the [Authorize] attribute.

But when you need to use JWT Authentication then you use this option on the Authorize attribute for your Web API controller or methods

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]


问:
Is it possible to create an igraph object from the vertices of another igraph?
I am new to igraph. I need to create an igraph object which has all the vertices of another igraph object with corresponding attributes but none of the edges. Is it possible to do that?</p>

答:
Isn't this the same as asking "can you copy an igraph and remove its edges?" If so, the answer is yes.

You haven't given any sample data, so here's one taken from igraph's own docs:

library(igraph)

set.seed(69)
adjm <- matrix(sample(0:1, 100, replace=TRUE, prob=c(0.9,0.1)), nc=10)
g1 <- graph_from_adjacency_matrix( adjm )
adjm <- matrix(sample(0:5, 100, replace=TRUE,
                      prob=c(0.9,0.02,0.02,0.02,0.02,0.02)), nc=10)
g2 <- graph_from_adjacency_matrix(adjm, weighted=TRUE)

plot(g2)
```

<p><img src="https://i.imgur.com/F0Rt6lN.png" alt=""></p>

<p>So now if we call <code>delete_edges</code>, we should be able to keep the vertices and their attributes:</p>

<pre class="lang-r prettyprint-override"><code>g3 <- delete_edges(g2, c("2|7", "5|3", "5|9", "6|2", "6|10", "8|1", "8|5", "10|2", "10|5"))
plot(g3)
</code>```

Created on 2020-05-31 by the reprex package (v0.3.0)

Body:
Isn't this the same as asking "can you copy an igraph and remove its edges?" If so, the answer is yes.

You haven't given any sample data, so here's one taken from igraph's own docs:

library(igraph)

set.seed(69)
adjm <- matrix(sample(0:1, 100, replace=TRUE, prob=c(0.9,0.1)), nc=10)
g1 <- graph_from_adjacency_matrix( adjm )
adjm <- matrix(sample(0:5, 100, replace=TRUE,
                      prob=c(0.9,0.02,0.02,0.02,0.02,0.02)), nc=10)
g2 <- graph_from_adjacency_matrix(adjm, weighted=TRUE)

plot(g2)

So now if we call delete_edges, we should be able to keep the vertices and their attributes:

g3 <- delete_edges(g2, c("2|7", "5|3", "5|9", "6|2", "6|10", "8|1", "8|5", "10|2", "10|5"))
plot(g3)

Created on 2020-05-31 by the reprex package (v0.3.0)


问:
Photo stitching/panorama API/DLL/Library anyone?
For a special project, I need to find an API/DLL/Library to help me create a big image using parts of this image. For example, if someone take 4 pictures representing the 360 degrees around him, he will be able to create one big image (panorama) by stitching the 4 images together using special algorithm that recognize some patterns.

I know how to do this in Photoshop and I know there are a lot of programs that to this on the internet. But I want one that will be controlled by programming. This can be in C, C++, or .NET. If you have something in another language, you can tell answer too, I may consider to write a wrapper.

答: This is used by GIMP as well http://stitchpanorama.sourceforge.net/


问:
Should I be saving my data in a .csv file?
I am writing a small .py file that contains some classes to be imported later repetitively into other work. The mentioned .py file uses some small database (in order of KB) in the form of tables. Do you think it is better to store this data in the same .py file or is it better to keep it in a separate .csv file? What are the differences in terms of performance and convenience for later use? A point that I might have to mention is that this data is numerical and is not prone to any possible change in the future.
Single items are to be accessed from this data at a time.

答: My Suggestion is to store data in Json format. Like in MongoDb, by adapting No-Sql format. This will help you in easily manage and control over the data. </p>


问:
testing SES lambda locally using a AWS toolkit
I'm trying to set up a project environment to develop lambda functions both in javascript and typescript using VS code and the AWS toolkit. I migrated my (working) lambda code into the hello-world example and changed the template.yaml so that it's able to run locally. However, the SES.sendMail doesn't seem to work. I get a "Function 'awsToolkitSamLocalResource' timed out after 3 seconds" error

I installed all pre-requisites and I'm able to run a simple hello-world function locally through the toolkit. The problem seems to be the SES

Here is my lambda, I replaced the hardcoded email addresses if you don't mind

```<code>const AWS = require('aws-sdk');
const SES = new AWS.SES({ region: 'eu-west-1' });

exports.handler = async (params)  => {
    try {
        console.log(params);

        const {
          to,
          from,
          reply_to: replyTo,
          subject,
        } = params;
        const fromBase64 = Buffer.from(from).toString('base64');

        const htmlBody = `
          <!DOCTYPE html>
          <html>
            <head></head>
            <body><h1>Hello world!</h1></body>
          </html>
        `;

        const sesParams = {
          Destination: {
            ToAddresses: ['mycompany@mail.com'],
          },
          Message: {
            Body: {
              Html: {
                Charset: 'UTF-8',
                Data: htmlBody,
              },
            },
            Subject: {
              Charset: 'UTF-8',
              Data: subject,
            },
          },
          Source: 'mygmail@gmail.com',
        };

        console.log('GOING TO SES')

        const response = await SES.sendEmail(sesParams).promise();

        console.log('DONE')

        console.log(response);
    } catch(error) {
        console.log(error)
    }
};
</code>```

and my yaml file

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sammy

  Sample SAM Template for sammy

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      Policies:
        - AmazonSESFullAccess
      CodeUri: src/hello-world/build
      Handler: sendMail.handler
      Runtime: nodejs10.x
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

provider:
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "ses:SendEmail"
      Resource:
        - "*"
      Condition:
        StringEquals:
          ses:FromAddress:
            - "mygmail@gmail.com"
</code>```

I expect it's some kind of IAM or SAM configuration error, in that the toolkit doesn't reach the actual SES

答:
Actually, this is due to the timeout configuration set on your template.yaml . You need to change the value from 3 to something higher because you are calling an external API and that makes it slow-ish.

```<code>Globals:
  Function:
    Timeout: 30
</code>```

Further explanation: https://github.com/aws/aws-toolkit-vscode/issues/510

Body:
I'm trying to set up a project environment to develop lambda functions both in javascript and typescript using VS code and the AWS toolkit. I migrated my (working) lambda code into the hello-world example and changed the template.yaml so that it's able to run locally. However, the SES.sendMail doesn't seem to work. I get a "Function 'awsToolkitSamLocalResource' timed out after 3 seconds" error

I installed all pre-requisites and I'm able to run a simple hello-world function locally through the toolkit. The problem seems to be the SES

Here is my lambda, I replaced the hardcoded email addresses if you don't mind

const AWS = require('aws-sdk');
const SES = new AWS.SES({ region: 'eu-west-1' });

exports.handler = async (params)  => {
    try {
        console.log(params);

        const {
          to,
          from,
          reply_to: replyTo,
          subject,
        } = params;
        const fromBase64 = Buffer.from(from).toString('base64');

        const htmlBody = `
          <!DOCTYPE html>

Hello world!

        `;

        const sesParams = {
          Destination: {
            ToAddresses: ['mycompany@mail.com'],
          },
          Message: {
            Body: {
              Html: {
                Charset: 'UTF-8',
                Data: htmlBody,
              },
            },
            Subject: {
              Charset: 'UTF-8',
              Data: subject,
            },
          },
          Source: 'mygmail@gmail.com',
        };

        console.log('GOING TO SES')

        const response = await SES.sendEmail(sesParams).promise();

        console.log('DONE')

        console.log(response);
    } catch(error) {
        console.log(error)
    }
};

and my yaml file

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sammy

  Sample SAM Template for sammy

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      Policies:
        - AmazonSESFullAccess
      CodeUri: src/hello-world/build
      Handler: sendMail.handler
      Runtime: nodejs10.x
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /hello
            Method: get

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  # Find out more about other implicit resources you can reference within SAM
  # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
  HelloWorldApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
  HelloWorldFunction:
    Description: "Hello World Lambda Function ARN"
    Value: !GetAtt HelloWorldFunction.Arn
  HelloWorldFunctionIamRole:
    Description: "Implicit IAM Role created for Hello World function"
    Value: !GetAtt HelloWorldFunctionRole.Arn

provider:
  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "ses:SendEmail"
      Resource:
        - "*"
      Condition:
        StringEquals:
          ses:FromAddress:
            - "mygmail@gmail.com"

I expect it's some kind of IAM or SAM configuration error, in that the toolkit doesn't reach the actual SES

Body:
Actually, this is due to the timeout configuration set on your template.yaml . You need to change the value from 3 to something higher because you are calling an external API and that makes it slow-ish.

Globals:
  Function:
    Timeout: 30

Further explanation: https://github.com/aws/aws-toolkit-vscode/issues/510


问:
How do I get the value of href attribute when scraping web in dart?
I am trying to get all the links on the web page with the help of Dart. I've tried web scraper package but I were not able to get the value of the attribute href. Anyone knows the way to do it?</p>

答:
@julemand101 solution should work as well since web_scraper is a wrapper around the html and http packages, but if you want to stick with web_scraper this should work:

```<code>final scraper = WebScraper('https://example.com')..loadWebPage('/test.html'); // Handle errors etc.
var data = scraper.getElement('a', ['href']);
</code>```

I did not test it but ideally should return your data

Body:
@julemand101 solution should work as well since web_scraper is a wrapper around the html and http packages, but if you want to stick with web_scraper this should work:

final scraper = WebScraper('https://example.com')..loadWebPage('/test.html'); // Handle errors etc.
var data = scraper.getElement('a', ['href']);

I did not test it but ideally should return your data


问:
How could I pass value to another View Controller using completion handler
Hello  I'm new in Swift and I have a problem. I have price list of ingredients, stored in Cloud Firestore. I want to calculate price for specific recepie and pass it to another VC, so I wrote this code:

```<code>extension RecepiesViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        func recepieCalculation(_ completion: @escaping (Double) ->()) {
            var totalPrice = 0.0
            for ingridients in cakeRecepies![indexPath.item].ingridientList {
                db.collection("Okey")
                    .document(ingridients.name)
                    .getDocument() { (document, error) in
                        if let document = document, document.exists {
                            let data = document.data()
                            if let price = data!["price"] as? Double, let count = data!["count"] as? Int  {
                                let priceForOne = price / Double(count)
                                totalPrice = totalPrice + priceForOne * Double(ingridients.count)
                            }
                        } else {
                            print("Document does not exist")
                        }
                        completion(totalPrice)
                }

            }
        }
        recepieCalculation {totalPrice in
            func prepare(for segue: UIStoryboardSegue, sender: Any?) {
                let destinationVC = segue.destination as! ResultViewController
                destinationVC.result = totalPrice
            }
            self.performSegue(withIdentifier: "goToResult", sender: self)
        }
    }
}
</code>```

Second VC code:

```<code>class ResultViewController: UIViewController {
    var result: Double? {
        didSet {
            print(result)
        }
    }
    @IBOutlet weak var recepieImage: UIImageView!
    override func viewDidLoad() {
    }
}
</code>```

But there is nothing printed into console. What could be wrong?

答:
Get

```<code> func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      let destinationVC = segue.destination as! ResultViewController
      destinationVC.result = totalPrice
 }
</code>```

Out of the completion

```<code>extension RecepiesViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        recepieCalculation {totalPrice in
            self.performSegue(withIdentifier: "goToResult", sender: self)
        }
    }
    func recepieCalculation(_ completion: @escaping (Double) ->()) {
        var totalPrice = 0.0
        for ingridients in cakeRecepies![indexPath.item].ingridientList {
            db.collection("Okey")
                .document(ingridients.name)
                .getDocument() { (document, error) in
                    if let document = document, document.exists {
                        let data = document.data()
                        if let price = data!["price"] as? Double, let count = data!["count"] as? Int  {
                            let priceForOne = price / Double(count)
                            totalPrice = totalPrice + priceForOne * Double(ingridients.count)
                        }
                    } else {
                        print("Document does not exist")
                    }
                    completion(totalPrice)
            }

        }
    }
    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC = segue.destination as! ResultViewController
        destinationVC.result = totalPrice
    }
}
</code>```

Body:
Hello  I'm new in Swift and I have a problem. I have price list of ingredients, stored in Cloud Firestore. I want to calculate price for specific recepie and pass it to another VC, so I wrote this code:

extension RecepiesViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        func recepieCalculation(_ completion: @escaping (Double) ->()) {
            var totalPrice = 0.0
            for ingridients in cakeRecepies![indexPath.item].ingridientList {
                db.collection("Okey")
                    .document(ingridients.name)
                    .getDocument() { (document, error) in
                        if let document = document, document.exists {
                            let data = document.data()
                            if let price = data!["price"] as? Double, let count = data!["count"] as? Int  {
                                let priceForOne = price / Double(count)
                                totalPrice = totalPrice + priceForOne * Double(ingridients.count)
                            }
                        } else {
                            print("Document does not exist")
                        }
                        completion(totalPrice)
                }

            }
        }
        recepieCalculation {totalPrice in
            func prepare(for segue: UIStoryboardSegue, sender: Any?) {
                let destinationVC = segue.destination as! ResultViewController
                destinationVC.result = totalPrice
            }
            self.performSegue(withIdentifier: "goToResult", sender: self)
        }
    }
}

Second VC code:

class ResultViewController: UIViewController {
    var result: Double? {
        didSet {
            print(result)
        }
    }
    @IBOutlet weak var recepieImage: UIImageView!
    override func viewDidLoad() {
    }
}

But there is nothing printed into console. What could be wrong?

Body:
Get

 func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      let destinationVC = segue.destination as! ResultViewController
      destinationVC.result = totalPrice
 }

Out of the completion

extension RecepiesViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        recepieCalculation {totalPrice in
            self.performSegue(withIdentifier: "goToResult", sender: self)
        }
    }
    func recepieCalculation(_ completion: @escaping (Double) ->()) {
        var totalPrice = 0.0
        for ingridients in cakeRecepies![indexPath.item].ingridientList {
            db.collection("Okey")
                .document(ingridients.name)
                .getDocument() { (document, error) in
                    if let document = document, document.exists {
                        let data = document.data()
                        if let price = data!["price"] as? Double, let count = data!["count"] as? Int  {
                            let priceForOne = price / Double(count)
                            totalPrice = totalPrice + priceForOne * Double(ingridients.count)
                        }
                    } else {
                        print("Document does not exist")
                    }
                    completion(totalPrice)
            }

        }
    }
    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        let destinationVC = segue.destination as! ResultViewController
        destinationVC.result = totalPrice
    }
}


问:
What are "pairs" when comparing the records of each record pair in recordlinkage?
I have a set of real estate ad data. Several of the lines are about the same real estate, so it's full of duplicates that aren't exactly the same. It looks like this :

```<code>    ID  URL CRAWL_SOURCE    PROPERTY_TYPE   NEW_BUILD   DESCRIPTION IMAGES  SURFACE LAND_SURFACE    BALCONY_SURFACE ... DEALER_NAME DEALER_TYPE CITY_ID CITY    ZIP_CODE    DEPT_CODE   PUBLICATION_START_DATE  PUBLICATION_END_DATE    LAST_CRAWL_DATE LAST_PRICE_DECREASE_DATE
0   22c05930-0eb5-11e7-b53d-bbead8ba43fe    http://www.avendrealouer.fr/location/levallois...   A_VENDRE_A_LOUER    APARTMENT   False   Au rez de chaussÃ©e d'un bel immeuble rÃ©cent,...   ["https://cf-medias.avendrealouer.fr/image/_87...   72.0    NaN NaN ... Lamirand Et Associes    AGENCY  54178039    Levallois-Perret    92300.0 92  2017-03-22T04:07:56.095 NaN 2017-04-21T18:52:35.733 NaN
1   8d092fa0-bb99-11e8-a7c9-852783b5a69d    https://www.bienici.com/annonce/ag440414-16547...   BIEN_ICI    APARTMENT   False   Je vous propose un appartement dans la rue Col...   ["http://photos.ubiflow.net/440414/165474561/p...   48.0    NaN NaN ... Proprietes Privees  MANDATARY   54178039    Levallois-Perret    92300.0 92  2018-09-18T11:04:44.461 NaN 2019-06-06T10:08:10.89  2018-09-25
...
</code>```

I want to find records in the dataset belonging to the same entity with recordlinkage. So I read the docs and mimitized the same :

```<code>indexer = recordlinkage.Index()
indexer.full()
candidate_links = indexer.index(df)

print (len(df), len(candidate_links))
</code>```

2164 2340366

Each record pair being a candidate match, to classify the candidate record pairs into matches and non-matches, I want to compare the records on all attributes both records have in common. The recordlinkage module has a class named Compare. This class is used to compare the records. The following code shows how I compared attributes :

compare_cl = recordlinkage.Compare()

```<code>compare_cl = recordlinkage.Compare()

compare_cl.exact('SURFACE', 'SURFACE', label='SURFACE')

features = compare_cl.compute(pairs, df)
</code>```

However it gives me back :

```<code>---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-51-1e55ea540dbd> in <module>
      9 #compare_cl.string('address_1', 'address_1', threshold=0.85, label='address_1')
     10
---> 11 features = compare_cl.compute(pairs, df)

NameError: name 'pairs' is not defined
</code>```

And I can't find what pairs are in the docs ...

答:
try with candidate_links

https://recordlinkage.readthedocs.io/en/latest/ref-compare.html

compute(pairs, x, x_link=None)
Compare the records of each record pair.

Calling this method starts the comparing of records.

Parameters:
pairs (pandas.MultiIndex) – A pandas MultiIndex with the record pairs to compare. The indices in the MultiIndex are indices of the DataFrame(s) to link.

Body:
I have a set of real estate ad data. Several of the lines are about the same real estate, so it's full of duplicates that aren't exactly the same. It looks like this :

    ID  URL CRAWL_SOURCE    PROPERTY_TYPE   NEW_BUILD   DESCRIPTION IMAGES  SURFACE LAND_SURFACE    BALCONY_SURFACE ... DEALER_NAME DEALER_TYPE CITY_ID CITY    ZIP_CODE    DEPT_CODE   PUBLICATION_START_DATE  PUBLICATION_END_DATE    LAST_CRAWL_DATE LAST_PRICE_DECREASE_DATE
0   22c05930-0eb5-11e7-b53d-bbead8ba43fe    http://www.avendrealouer.fr/location/levallois...   A_VENDRE_A_LOUER    APARTMENT   False   Au rez de chaussÃ©e d'un bel immeuble rÃ©cent,...   ["https://cf-medias.avendrealouer.fr/image/_87...   72.0    NaN NaN ... Lamirand Et Associes    AGENCY  54178039    Levallois-Perret    92300.0 92  2017-03-22T04:07:56.095 NaN 2017-04-21T18:52:35.733 NaN
1   8d092fa0-bb99-11e8-a7c9-852783b5a69d    https://www.bienici.com/annonce/ag440414-16547...   BIEN_ICI    APARTMENT   False   Je vous propose un appartement dans la rue Col...   ["http://photos.ubiflow.net/440414/165474561/p...   48.0    NaN NaN ... Proprietes Privees  MANDATARY   54178039    Levallois-Perret    92300.0 92  2018-09-18T11:04:44.461 NaN 2019-06-06T10:08:10.89  2018-09-25
...

I want to find records in the dataset belonging to the same entity with recordlinkage. So I read the docs and mimitized the same :

indexer = recordlinkage.Index()
indexer.full()
candidate_links = indexer.index(df)

print (len(df), len(candidate_links))

2164 2340366

Each record pair being a candidate match, to classify the candidate record pairs into matches and non-matches, I want to compare the records on all attributes both records have in common. The recordlinkage module has a class named Compare. This class is used to compare the records. The following code shows how I compared attributes :

compare_cl = recordlinkage.Compare()

compare_cl = recordlinkage.Compare()

compare_cl.exact('SURFACE', 'SURFACE', label='SURFACE')

features = compare_cl.compute(pairs, df)

However it gives me back :

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-51-1e55ea540dbd> in <module>
      9 #compare_cl.string('address_1', 'address_1', threshold=0.85, label='address_1')
     10
---> 11 features = compare_cl.compute(pairs, df)

NameError: name 'pairs' is not defined

And I can't find what pairs are in the docs ...


问:
Java HTTP getResponseCode returns 200 for non-existent URL
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

```<code>    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }
</code>```

答:
Like @spgennard - I think this is most likely a DNS issue.

The URL you have chosen is owned by a DNS speculator.

The URL you have chosen is "parked" by a DNS provider.

Your ISP is messing with your DNS results to send your browser to some search page.

It is also possible that you are accessing the web via a proxy, and the proxy is doing something strange.

The way to diagnose this is to look at the other information in the HTTP responses you are getting, particularly the response body.

Body:
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }


问:
Calculate Time Difference between events in streaming datasets
In my application, events are generated for every action that user performs, and events are generated with data in the below format -

user_id | step_num | event_timestamp

Order in which these events are streamed are not completely strict i.e. we might have user 2 data streamed in before all events of user 1 are captured.

Sample Data

u1, 1, 2020-05-30 00:00:01

u1, 2, 2020-05-30 00:00:02

u2, 1, 2020-05-30 00:00:02

u3, 1, 2020-05-30 00:00:02

u1, 3, 2020-05-30 00:00:03

....

How would you implement any streaming solution to calculate average time taken for each step. We can assume total time taken by a user for each step to be (time_stamp_at_step_1 - time_stamp_at_step_0).

I am using Spark Streaming to build the solution but could not find anything to compute statistics taking data from 2 event that are grouped by an attribute(user_id in my case). Would love to know if there are any available solutions in other streaming tech like Flink, Kafka etc.

答:
This could be done in various ways with Flink, but one approach would be to use Flink SQL with MATCH_RECOGNIZE:</p>

```<code>SELECT step_num, AVG(seconds)
FROM events
MATCH_RECOGNIZE (
    PARTITION BY userId
    ORDER BY eventTime
    MEASURES
        this_step.userId as id
        this_step.step AS step_num
        TIMESTAMPDIFF(SECOND, this_step.eventTime, next_step.eventTime) AS seconds
    AFTER MATCH SKIP TO LAST next_step
    PATTERN (this_step next_step)
    DEFINE
        this_step AS TRUE,
        next_step AS next_step.step = this_step.step + 1
)
GROUP BY step_num
</code>```

Body:
This could be done in various ways with Flink, but one approach would be to use Flink SQL with MATCH_RECOGNIZE:

SELECT step_num, AVG(seconds)
FROM events
MATCH_RECOGNIZE (
    PARTITION BY userId
    ORDER BY eventTime
    MEASURES
        this_step.userId as id
        this_step.step AS step_num
        TIMESTAMPDIFF(SECOND, this_step.eventTime, next_step.eventTime) AS seconds
    AFTER MATCH SKIP TO LAST next_step
    PATTERN (this_step next_step)
    DEFINE
        this_step AS TRUE,
        next_step AS next_step.step = this_step.step + 1
)
GROUP BY step_num


问:
Change appendChild function
so I have this script to decode b64 string to pdf

```<code>// JavaScript Document
function decode() {
    // The Base64 string of a simple PDF file
    var b64decode = BASE64 STRING

    // Decode Base64 to binary and show some information about the PDF file (note that I skipped all checks)
    var bin = atob(b64decode);

    // Embed the PDF into the HTML page and show it to the user
    var obj = document.createElement('object');
    obj.style.width = '100%';
    obj.style.height = '842pt';
    obj.type = 'application/pdf';
    obj.data = 'data:application/pdf;base64,' + b64decode;
    document.body.appendChild(obj);

    // Insert a link that allows the user to download the PDF file
    var link = document.createElement('a');
    link.innerHTML = 'Download PDF file';
    link.download = 'file.pdf';
    link.href = 'data:application/octet-stream;base64,' + b64decode;
    document.body.appendChild(link);
}
</code>```

And the script creates an object at the bottom of the page. Instead, I need the script to create an object inside an empty div container.

As you might guessed, I'm not a JS expert (or amateur neither)

Thanks!

答:
This line of your code does the appending:

```<code>document.body.appendChild(link);
</code>```

You would have to change it to your div. For that you need to give your div an id:

```<code><div id="pdf-div"></div>
</code>```

And now you can replace the appendChild directive with:

```<code>document.getElementById('pdf-div').innerHTML = link;
</code>```

Title: Change appendChild function

Body:
so I have this script to decode b64 string to pdf

// JavaScript Document
function decode() {
    // The Base64 string of a simple PDF file
    var b64decode = BASE64 STRING

    // Decode Base64 to binary and show some information about the PDF file (note that I skipped all checks)
    var bin = atob(b64decode);

    // Embed the PDF into the HTML page and show it to the user
    var obj = document.createElement('object');
    obj.style.width = '100%';
    obj.style.height = '842pt';
    obj.type = 'application/pdf';
    obj.data = 'data:application/pdf;base64,' + b64decode;
    document.body.appendChild(obj);

    // Insert a link that allows the user to download the PDF file
    var link = document.createElement('a');
    link.innerHTML = 'Download PDF file';
    link.download = 'file.pdf';
    link.href = 'data:application/octet-stream;base64,' + b64decode;
    document.body.appendChild(link);
}

And the script creates an object at the bottom of the page. Instead, I need the script to create an object inside an empty div container.

As you might guessed, I'm not a JS expert (or amateur neither)

Thanks!

Body:
This line of your code does the appending:

document.body.appendChild(link);

You would have to change it to your div. For that you need to give your div an id:

<div id="pdf-div"></div>

And now you can replace the appendChild directive with:

document.getElementById('pdf-div').innerHTML = link;


问:
Cannot pause Dart isolate
I wished to create an Isolate in Dart that I could pause and resume programmatically. This is the code that I used.

import 'dart:io';
import 'dart:isolate';

void main() async {
  print("Starting isolate");
  Isolate isolate;
  ReceivePort receivePort = ReceivePort();
  isolate = await Isolate.spawn(run, receivePort.sendPort);
  print("pausing");
  Capability cap = isolate.pause(isolate.pauseCapability);
  sleep(Duration(seconds: 5));
  print("Resuming");
  isolate.resume(cap);
}

void run(SendPort sendPort) {
  sleep(Duration(seconds: 2));
  print("Woke up, 1");
  sleep(Duration(seconds: 2));
  print("Woke up, 2");
  sleep(Duration(seconds: 2));
  print("Woke up, 3");
  sleep(Duration(seconds: 2));
  print("Woke up, 4");
  sleep(Duration(seconds: 2));
  print("Woke up, 5");
}
```

<p>I'm getting an O/P like</p>

```Starting isolate
pausing
Woke up, 1
Woke up, 2
Resuming
Woke up, 3
Woke up, 4
Woke up, 5
```

<p>But I want to achieve</p>

```Starting isolate
pausing
<--- 5 second delay --->
Resuming
Woke up, 1
Woke up, 2
Woke up, 3
Woke up, 4
Woke up, 5
```

But even after calling pause(), the Isolate keeps running. I found this answer and it said that it was because of the infinite loop in their case but I'm not using any loop. So what am I doing wrong here?

答:
Your problem is that you have missed a detail in the documentation for the pause on isolate:

When the isolate receives the pause command, it stops processing events from the event loop queue. It may still add new events to the queue in response to, e.g., timers or receive-port messages. When the isolate is resumed, it starts handling the already enqueued events.

So pause does not stop the execution of method but will just make sure that after the execution of the current running method, it will then stop giving more work from the event queue.

While sleep is implemented more like a "stop all execution right now for N time" which is more what you expect:

Use this with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call.

To make your example to work you need to replace the sleep calls with Future instances you are awaiting on since this will add events on the event queue.

```<code>import 'dart:async';
import 'dart:io';
import 'dart:isolate';

Future<void> main() async {
  print("Starting isolate");
  Isolate isolate;
  ReceivePort receivePort = ReceivePort();
  isolate = await Isolate.spawn(run, receivePort.sendPort);
  print("pausing");
  Capability cap = isolate.pause(isolate.pauseCapability);
  sleep(const Duration(seconds: 5));
  print("Resuming");
  isolate.resume(cap);
}

Future<void> run(SendPort sendPort) async {
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 1");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 2");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 3");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 4");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 5");
}
</code>```

Output:

Starting isolate
pausing
Resuming
Woke up, 1
Woke up, 2
Woke up, 3
Woke up, 4
Woke up, 5
```

Title: Cannot pause Dart isolate

Body:
I wished to create an Isolate in Dart that I could pause and resume programmatically. This is the code that I used.

import 'dart:io';
import 'dart:isolate';

void main() async {
  print("Starting isolate");
  Isolate isolate;
  ReceivePort receivePort = ReceivePort();
  isolate = await Isolate.spawn(run, receivePort.sendPort);
  print("pausing");
  Capability cap = isolate.pause(isolate.pauseCapability);
  sleep(Duration(seconds: 5));
  print("Resuming");
  isolate.resume(cap);
}

void run(SendPort sendPort) {
  sleep(Duration(seconds: 2));
  print("Woke up, 1");
  sleep(Duration(seconds: 2));
  print("Woke up, 2");
  sleep(Duration(seconds: 2));
  print("Woke up, 3");
  sleep(Duration(seconds: 2));
  print("Woke up, 4");
  sleep(Duration(seconds: 2));
  print("Woke up, 5");
}

I'm getting an O/P like

Starting isolate
pausing
Woke up, 1
Woke up, 2
Resuming
Woke up, 3
Woke up, 4
Woke up, 5

But I want to achieve

Starting isolate
pausing
<--- 5 second delay --->
Resuming
Woke up, 1
Woke up, 2
Woke up, 3
Woke up, 4
Woke up, 5

But even after calling pause(), the Isolate keeps running. I found this answer and it said that it was because of the infinite loop in their case but I'm not using any loop. So what am I doing wrong here?

Body:
Your problem is that you have missed a detail in the documentation for the pause on isolate:

When the isolate receives the pause command, it stops processing events from the event loop queue. It may still add new events to the queue in response to, e.g., timers or receive-port messages. When the isolate is resumed, it starts handling the already enqueued events.

So pause does not stop the execution of method but will just make sure that after the execution of the current running method, it will then stop giving more work from the event queue.

While sleep is implemented more like a "stop all execution right now for N time" which is more what you expect:

Use this with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call.

To make your example to work you need to replace the sleep calls with Future instances you are awaiting on since this will add events on the event queue.

import 'dart:async';
import 'dart:io';
import 'dart:isolate';

Future<void> main() async {
  print("Starting isolate");
  Isolate isolate;
  ReceivePort receivePort = ReceivePort();
  isolate = await Isolate.spawn(run, receivePort.sendPort);
  print("pausing");
  Capability cap = isolate.pause(isolate.pauseCapability);
  sleep(const Duration(seconds: 5));
  print("Resuming");
  isolate.resume(cap);
}

Future<void> run(SendPort sendPort) async {
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 1");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 2");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 3");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 4");
  await Future<void>.delayed(const Duration(seconds: 2));
  print("Woke up, 5");
}

Output:

Starting isolate
pausing
Resuming
Woke up, 1
Woke up, 2
Woke up, 3
Woke up, 4
Woke up, 5


问:
ReactJS passing a state value to onClick event function as a parameter
I have the following component :-

```<code>const PartTable = (props) => {
   const [previousPart, setPreviousPart] = useState();

  useEffect(() => {
    if (localStorage.getItem("read")) {
      const decodedjwtToken = jwt(localStorage.getItem("read"));
      setPreviousPart(decodedjwtToken.p);
    }
  }, []);

  function handlePartSelection(previousSelection) {
    console.log("previouspart", previousSelection); //Here its returning undefined
  }

  return (
    <React.Fragment>
              <div onClick={() => handlePartSelection(previousPart)} >
                Select part
               </div>

    </React.Fragment>
  );
};

export default PartTable;
</code>```

i am trying to pass the "previousPart" state as a parameter for handlePartSelection function, in console log when i tried to check the passed value, its return undefined.

How can i read the previousPart state in handlePartSelection function ?

答:
```<code>const PartTable = (props) => {
   const [previousPart, setPreviousPart] = useState();

  useEffect(() => {
    if (localStorage.getItem("read")) {
      const decodedjwtToken = jwt(localStorage.getItem("read"));
      setPreviousPart(decodedjwtToken.p);
    }
  }, []);

  const handlePartSelection = () => {
    console.log("previouspart", previousPart); //Here its returning undefined
  }

  return (
    <React.Fragment>
              <div onClick={handlePartSelection} >
                Select part
               </div>

    </React.Fragment>
  );
};

export default PartTable;
</code>```

I hope it helps

Body:
I have the following component :-

const PartTable = (props) => {
   const [previousPart, setPreviousPart] = useState();

  useEffect(() => {
    if (localStorage.getItem("read")) {
      const decodedjwtToken = jwt(localStorage.getItem("read"));
      setPreviousPart(decodedjwtToken.p);
    }
  }, []);

  function handlePartSelection(previousSelection) {
    console.log("previouspart", previousSelection); //Here its returning undefined
  }

  return (
    <React.Fragment>

 handlePartSelection(previousPart)} >
                Select part

    </React.Fragment>
  );
};

export default PartTable;

i am trying to pass the "previousPart" state as a parameter for handlePartSelection function, in console log when i tried to check the passed value, its return undefined.

How can i read the previousPart state in handlePartSelection function ?

Body:
const PartTable = (props) => {
   const [previousPart, setPreviousPart] = useState();

  useEffect(() => {
    if (localStorage.getItem("read")) {
      const decodedjwtToken = jwt(localStorage.getItem("read"));
      setPreviousPart(decodedjwtToken.p);
    }
  }, []);

  const handlePartSelection = () => {
    console.log("previouspart", previousPart); //Here its returning undefined
  }

  return (
    <React.Fragment>
              <div onClick={handlePartSelection} >
                Select part
               </div>

    </React.Fragment>
  );
};

export default PartTable;

I hope it helps


问:
Extract part of href link using beautiful soup
I'm new to python requests and beautiful soup, I was trying to create a script to automatically login and logout, but I need the "_wpnonce" value to send a valid post request. I am wondering if there is a way to extract the "_wpnonce" value from this link using beautiful soup, any help is appreciated.

```<code><a href="https://www.example.com/wp-login.php?action=logout&_wpnonce=fc789123fe&redirect_to=%2Fuser%2Flogout">Sign Out</a>
</code>```

The extracted value would be "fc789123fe"

答:
You can use urllib.parse to parse the URL to components (the correct official way):

For example:

```<code>txt = '''<a href="https://www.example.com/wp-login.php?action=logout&_wpnonce=fc789123fe&redirect_to=%2Fuser%2Flogout">Sign Out</a>'''

from bs4 import BeautifulSoup
from urllib.parse import parse_qs, urlparse

soup = BeautifulSoup(txt, 'html.parser')

href = soup.select_one('a')['href']
parameters = parse_qs(urlparse(href).query)

print( parameters['_wpnonce'][0] )
</code>```

Prints:

```<code>fc789123fe
</code>```

To "cheat" a little bit, you can use re module:

```<code>print( re.search(r'_wpnonce=([a-f0-9]+)', soup.select_one('a')['href']).group(1) )
</code>```

EDIT: To find tag  with text Sign Out you can do:

```<code>href = soup.find('a', text='Sign Out')['href']
</code>```

Body:
I'm new to python requests and beautiful soup, I was trying to create a script to automatically login and logout, but I need the "_wpnonce" value to send a valid post request. I am wondering if there is a way to extract the "_wpnonce" value from this link using beautiful soup, any help is appreciated.

Sign Out

The extracted value would be "fc789123fe"

Body:
You can use urllib.parse to parse the URL to components (the correct official way):

For example:

txt = '''<a href="https://www.example.com/wp-login.php?action=logout&amp;_wpnonce=fc789123fe&redirect_to=%2Fuser%2Flogout">Sign Out</a>'''

from bs4 import BeautifulSoup
from urllib.parse import parse_qs, urlparse

soup = BeautifulSoup(txt, 'html.parser')

href = soup.select_one('a')['href']
parameters = parse_qs(urlparse(href).query)

print( parameters['_wpnonce'][0] )

Prints:

fc789123fe

To "cheat" a little bit, you can use re module:

print( re.search(r'_wpnonce=([a-f0-9]+)', soup.select_one('a')['href']).group(1) )

EDIT: To find tag <a> with text Sign Out you can do:

href = soup.find('a', text='Sign Out')['href']