问:
How do i get a variable from within a script tag using python and selenium?
I'm trying to get data for graphs and have found that the data is stored within the script tag. There are numerous other script tags before this and i'd like to access var line1 to get the dates and values. Is this possible?

This is the html:

```<code><script type="text/javascript">
    $J(document).ready(function(){
    var line1=[["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]];
    g_timePriceHistoryEarliest = new Date();
    if ( line1 != false )
    {
        g_timePriceHistoryEarliest = new Date(line1[0][0]);
        g_timePriceHistoryLatest = new Date(line1[line1.length-1][0]);
    }

    var strFormatPrefix = "$";
    var strFormatSuffix = "";

    g_plotPriceHistory = CreatePriceHistoryGraph( line1, 7, strFormatPrefix, strFormatSuffix );

    pricehistory_zoomMonthOrLifetime( g_plotPriceHistory, g_timePriceHistoryEarliest, g_timePriceHistoryLatest );
});
</script>
</code>```

I've tried

```<code>script = driver.find_element_by_tag_name("script")
scriptText = driver.execute_script("return arguments[0].innerHTML", script)
print(scriptText)
</code>```

but scriptText returns empty

The full xpath is

```<code>/html/body/div[1]/div[7]/div[2]/script[2]/text()
</code>```

Would appreciate any help! Thanks!

Solved:

```<code>import urllib.request
import re
url=urllib.request.urlopen("yourURL")
content=url.read()
html = content.decode('utf-8')
var_re = re.compile(r'var line1=\[(.+)\]')
date_match = var_re.findall(html)
print (date_match)
</code>```

答:
Since the data you want to extract is in the HTML itself you don't need to use selenium.  You can use the requests library and re library to extract it directly from the HTML.  Here's the regex code for extracting the data from the sample HTML that you provided.  It returns a list of str with the dates and values you seem to want.

Since you didn't provide the URL you'll need to code the requests portion yourself.

```<code>html = """<script type="text/javascript">
$J(document).ready(function(){
var line1=[["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]];
g_timePriceHistoryEarliest = new Date();
if ( line1 != false )
{
    g_timePriceHistoryEarliest = new Date(line1[0][0]);
    g_timePriceHistoryLatest = new Date(line1[line1.length-1][0]);
}

var strFormatPrefix = "$";
var strFormatSuffix = "";

g_plotPriceHistory = CreatePriceHistoryGraph( line1, 7, strFormatPrefix, strFormatSuffix );

pricehistory_zoomMonthOrLifetime( g_plotPriceHistory, g_timePriceHistoryEarliest, g_timePriceHistoryLatest );
});</script>"""

var_re = re.compile(r'var line1=\[(.+)\]')
date_match = var_re.findall(html)

print(date_match)

Output:
['["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]']
</code>```

Body:
I'm trying to get data for graphs and have found that the data is stored within the script tag. There are numerous other script tags before this and i'd like to access var line1 to get the dates and values. Is this possible?

This is the html:

I've tried

script = driver.find_element_by_tag_name("script")
scriptText = driver.execute_script("return arguments[0].innerHTML", script)
print(scriptText)

but scriptText returns empty

The full xpath is

/html/body/div[1]/div[7]/div[2]/script[2]/text()

Would appreciate any help! Thanks!

Solved:

import urllib.request
import re
url=urllib.request.urlopen("yourURL")
content=url.read()
html = content.decode('utf-8')
var_re = re.compile(r'var line1=\[(.+)\]')
date_match = var_re.findall(html)
print (date_match)

Body:
Since the data you want to extract is in the HTML itself you don't need to use selenium.  You can use the requests library and re library to extract it directly from the HTML.  Here's the regex code for extracting the data from the sample HTML that you provided.  It returns a list of str with the dates and values you seem to want.

Since you didn't provide the URL you'll need to code the requests portion yourself.

html = """<script type="text/javascript">
$J(document).ready(function(){
var line1=[["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]];
g_timePriceHistoryEarliest = new Date();
if ( line1 != false )
{
    g_timePriceHistoryEarliest = new Date(line1[0][0]);
    g_timePriceHistoryLatest = new Date(line1[line1.length-1][0]);
}

var strFormatPrefix = "$";
var strFormatSuffix = "";

g_plotPriceHistory = CreatePriceHistoryGraph( line1, 7, strFormatPrefix, strFormatSuffix );

pricehistory_zoomMonthOrLifetime( g_plotPriceHistory, g_timePriceHistoryEarliest, g_timePriceHistoryLatest );
});</script>"""

var_re = re.compile(r'var line1=\[(.+)\]')
date_match = var_re.findall(html)

print(date_match)

Output:
['["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]']


来源: stackexchange

问:
Profiling tool on Linux showing size of parameters passed to invoked functions
Can any of profiling (performance measure) tools on Linux (OProfile, perf events, HTC Toolkit) show call graph with size of parameters (data size) passed to function / procedure?

In other words I'd like to visualize data flow in a profiled application (best together with profile data, i.e. time spent in a function / subroutine).

Note: when arrays (vectors and matrices) are passed to subroutine / function, I am interested not only in size of pointer, but size of the whole data.

答:
Beyond my skeptic remarks, I have a growing sense that you really want to have a metric that represents 'memory bandwidth', correlated to certain parts of your code.

I have a hunch that you might get mileage out of oprofile. oprof_start gui has a nice checklist of metrics

http://oprofile.sourceforge.net/docs/intel-p6-mobile-events.php

(NOTE: these are CPU dependent, see http://oprofile.sourceforge.net/docs/ or op_help for details on your CPU)

These seem interesting:

```<code>DATA_MEM_REFS    all memory references, cachable and non
L2_LD        number of L2 data loads
L2_ST        number of L2 data stores
perhaps some more, but I grew tired of reading things outside my area of expertise here
</code>```

I think that perf superseeds(?) oprofile, and it certainly has the easier interface to do (sampling) call graph profiling but I guess that if you want access to actual CPU performance counter events, oprofile may still be the place to go

ContentLicense: CC BY-SA 3.0

Body:
Beyond my skeptic remarks, I have a growing sense that you really want to have a metric that represents 'memory bandwidth', correlated to certain parts of your code.

I have a hunch that you might get mileage out of oprofile. oprof_start gui has a nice checklist of metrics

http://oprofile.sourceforge.net/docs/intel-p6-mobile-events.php

(NOTE: these are CPU dependent, see http://oprofile.sourceforge.net/docs/ or op_help for details on your CPU)

These seem interesting:

DATA_MEM_REFS    all memory references, cachable and non
L2_LD        number of L2 data loads
L2_ST        number of L2 data stores
perhaps some more, but I grew tired of reading things outside my area of expertise here

I think that perf superseeds(?) oprofile, and it certainly has the easier interface to do (sampling) call graph profiling but I guess that if you want access to actual CPU performance counter events, oprofile may still be the place to go


问:
How can I convert a vector of ints to be a vector of strings using STL algorithms?
For example, I would need {20,6,143} to become {"20","6","143"}.

答:
Simply using a range-based for-loop you could iterate through the vector of integers and using  std::to_string you could convert each element to string and store to the new vector of strings.

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

int main()
{
   std::vector<int> vec{ 20,6,143 };
   std::vector<std::string> strVec;
   strVec.reserve(vec.size());  // reserve memory for unwanted reallocations

   for (int element : vec)
      strVec.emplace_back(std::to_string(element));

   for (const auto& str : strVec)
      std::cout << str << " ";

}
</code>```

(See live online)

Alternatively using std::transform, you could transform the vector of integers as follows.

```<code>#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // std::transform
#include <iterator>  // std::cbegin

int main()
{
   std::vector<int> vec{ 20,6,143 };
   std::vector<std::string> strVec;
   strVec.reserve(vec.size());  // reserve memory for unwanted reallocations

   std::transform(std::cbegin(vec), std::cend(vec),
      std::back_inserter(strVec), // insert to the back of strVec
      [](const int element) { return std::to_string(element);}
   );

   for (const auto& str : strVec)
      std::cout << str << " ";
}
</code>```

(See live online)

ContentLicense: CC BY-SA 4.0

Body:
Simply using a range-based for-loop you could iterate through the vector of integers and using  std::to_string you could convert each element to string and store to the new vector of strings.

#include <iostream>
#include <vector>
#include <string>

int main()
{
   std::vector<int> vec{ 20,6,143 };
   std::vector<std::string> strVec;
   strVec.reserve(vec.size());  // reserve memory for unwanted reallocations

   for (int element : vec)
      strVec.emplace_back(std::to_string(element));

   for (const auto& str : strVec)
      std::cout << str << " ";

}

(See live online)

Alternatively using std::transform, you could transform the vector of integers as follows.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // std::transform
#include <iterator>  // std::cbegin

int main()
{
   std::vector<int> vec{ 20,6,143 };
   std::vector<std::string> strVec;
   strVec.reserve(vec.size());  // reserve memory for unwanted reallocations

   std::transform(std::cbegin(vec), std::cend(vec),
      std::back_inserter(strVec), // insert to the back of strVec
      [](const int element) { return std::to_string(element);}
   );

   for (const auto& str : strVec)
      std::cout << str << " ";
}

(See live online)


问:
Access SMB Fileshare via edge runtime module ( without blob storage module )
I am facing a scenario where I have to access the images from SMB file share through application deployed as edge runtime module.  I have gone through https://learn.microsoft.com/en-us/azure/iot-edge/how-to-store-data-blob#using-smb-share-as-your-local-storage, But that talks via blob module which is not the way I want to go due to some agreed decisions.

Is it possible to access the fileshare via edge runtime module (application).

One of the workaround I see is : Deploy a custom .NET Core Edge-module on a Linux VM tried to read files on a Windows File-share in same VNet and Azure file-share using it...

Mount the fileshare (both windows & azure) on the host using smb protocol

Read it from the container by mapping the mount point to a containers file system.

Just need to understand if this is the correct way, any known challenges or limitation in this approach.

答:
I don't expect any issues or limitations doing like you said.

You will just not be able to leverage Azure Blob Storage functionalities on your IoT Edge nor Azure storage SDK methods or blob API calls.


问:
jQuery: find elements where data attribute is has a specific value
I have a master checkbox Select all along with a button to revert back to their original state to which there were loaded with. After the page is loaded I bind a data property to each of the checkboxes that if there were loaded as checked or un-checked.

$('input[type="checkbox"]').each((i, e) => {
    if($(e).is(':checked'))
       $(e).data('default', true);
});

$('.js-select-all').on('mouseup', () => {
    $('input[type="checkbox"]').prop('checked', true);
});
```

<p>I need to find the <code>checkboxes</code> where <code>data</code> property called <code>default</code> is <code>true</code> and mark them checked again.</p>

<pre class="lang-js prettyprint-override"><code>$('.js-revert').on('mouseup', () => {
    $('input[type="checkbox"]').data('default', true).prop('checked', true);
});
</code>```

I know it can be done with each loop and a condition. But the thing is that I'll have to go through all the checkboxes to do so. Therefore, I am looking for a faster way as there are already dozens of checkboxes in the application.

答:
If you're using just jQuery, there's no faster way to check the .data() stored in the checkboxes besides iterating over all of them.

But incase you're using jQueryUI you can use the :data() selector presented here:

https://api.jqueryui.com/data-selector/

which then you can use

$(':checkbox:data(default)').prop('checked', true);

Body:
I have a master checkbox Select all along with a button to revert back to their original state to which there were loaded with. After the page is loaded I bind a data property to each of the checkboxes that if there were loaded as checked or un-checked.

$('input[type="checkbox"]').each((i, e) => {
    if($(e).is(':checked'))
       $(e).data('default', true);
});

$('.js-select-all').on('mouseup', () => {
    $('input[type="checkbox"]').prop('checked', true);
});

I need to find the checkboxes where data property called default is true and mark them checked again.

$('.js-revert').on('mouseup', () => {
    $('input[type="checkbox"]').data('default', true).prop('checked', true);
});

I know it can be done with each loop and a condition. But the thing is that I'll have to go through all the checkboxes to do so. Therefore, I am looking for a faster way as there are already dozens of checkboxes in the application.


问:
OAuth 2.0 Client ID and Secret Java implementation
I have been asked to make an OAuth 2.0 integration with an external company. All they need from me is to provide them with are client ID and client secret, and authorize their access if the details are correct.

Is there a simple library that does it, or maybe an implementation guide?

答: If you are using Spring, I recommend you to try Spring Security + Spring Security OAuth 2.0 client. Here you can see how to configure these libraries correctly. Customization of OAuth2 if needed you can see here.</p>


问:
How to avoid having "FID issue: longer than 300ms" with Google Search Console?
On some of my websites, Google's Search Console tool and PageSpeed show a Max First Input Delay of 300 seconds on mobile and 900 seconds on PC on my homepages.

Strange phenomenon because even on a development environment where I disable all javascript and css code, the result does not change.

Moreover, I installed on my website the following script, developed by Google: https://github.com/GoogleChromeLabs/first-input-delay

It allows you to send data to Google Analytics on the FID. On my website, I added a line in the code so that the Browser Console returns the FID (console.log(delay);).

And the result is not surprising : Less than 5 or in some cases 10 milliseconds for the browser to respond when you click anywhere on the page.

So I think that google doesn't do a simple click on the page to calculate the FID. By the way, I also know that the FID is calculated by real users on Google Chrome, it can't be done by a bot.

But in this case, how do you identify the element that could take half a second or even a whole second before the browser responds?

Despite my long researches on the internet on this subject, all give the same explanations to make a diagnosis, but this does not help me in my problem.

答:
Since you already tried removing CSS and JavaScript links, you could also try:

Taking a look at any images (img) and see how long those take to load

Taking a look at any iframes in your site and seeing how long those take to load

Checking how long any favicon(s) take to load

Any dns-prefetch or preconnect meta tags.

Taking a look at the Sources tab in DevTools to see what HTTP requests are made while loading

Sorry I couldn't be of more help in terms of specific solutions to your problem — I didn't really have much information on your specific site and what HTTP requests are made while loading it.

I hope this helps.


问:
Why is K-means algorithm preferred over Kruskal's algorithm for Clustering
I'm taking Andrew Ng's course on Machine Learning on Coursera. While discussing clustering, he tells us that K- means clustering algorithm is the most widely used.
I've also used Kruskal's algorithm for clustering earlier which was a very efficient algorithm with path compression and rank-based unions.
What makes K-means better than Kruskal's algorithm?</p>

答:
Kruskal’s algorithm and k-means clustering will usually generate very different clusters, since they’re optimized to find different things.

As an example, consider n points on a line that are more or less evenly spaced out, except that each point is ever so slightly further away from the point on its right than the point on its left. That is, if you zoom out, you more or less see n evenly-spaced points, but on zooming in you’ll see that the distances aren’t exactly the same and increase from left to right.

Kruskal’s algorithm finds a maximum-separation clustering, which means that it splits nodes apart so that the distances between the clusters are as large as possible. In this case, what would a maximum-separation clustering look like with k=2? Since the distances increase as we move from left to right, it’ll find a clustering of “everything except the rightmost node” and “the rightmost node.”

K-means clustering, on the other hand, finds a clustering that minimizes within-cluster variance, which means that it groups nodes so that the clustered nodes are generally close to one another. Running k-means on the above data set will split the points roughly in half down the center line, returning two clusters that are about the same size.

So which is a “better” clustering? It depends on your application. I’d suspect that more often than not we’d like this second clustering because we want nodes in a cluster to be as similar to one another as possible. That’s why we often see k-means clustering used more than Kruskal’s algorithm, though there are still cases where Kruskal is nice to have.

Note that this concern is orthogonal to efficiency. Yes, Kruskal’s algorithm is very fast, but it’s computing something different than what k-means computes.

Hope this helps!


问:
Power Query get files from folders with files with different numbers of columns able to be refreshed
So my goal is to have one folder where we can dump all the files we get daily. Then I would like to just hit a refresh on a power query to update a list. My issue is the files have different numbers of columns depending on which tests we did the previous day and I'm interested in only results from "set 1" "set 2" and "set 3". It gets more frustrating because the file is sent to us with about 8 rows above the useful data and the column headers above the data are 1 row above where you would like it. Eg of data set 1.

The second set of data would look like this:

I am trying to get it to look like this as an output:

I have tried to combine and transform, then change the step before they are combined to remove the pesky floating rows, fill up the number header and remove the empty row below the headers. Then the data gets appended. Any repeating value under the column number was being an issue because I need all individual values but when I removed duplicates it would remove the row with data. I fixed that by putting the output of the query into a pivot table and that seemed to work okay. Then I threw another data sheet in the folder and when I refreshed the query it said a column of the table wasn't found. I have looked through similar issues where there were different numbers of columns and they append empty columns, but I need an automatic solution. Is there a way to do this or am I on a fools errand?

答: Removed the change type step and everything seemed to work more or less.</p>


问:
Laravel excel import, date column in excel cell returns as floating value. How to solve this?
By using Maatwebsite/Laravel-Excel to import excel sheet, here I faced an issue date time column of the excel sheet returns float value. How to solve this?
Example : Consider Cell value "08-04-2016  13:08:29" and returns as "42104.487060185" when import.</p>

答:
This only happend when use chunk. This issue could be solved by:</p>

```<code>$UNIX_DATE = ($row->DOB - 25569) * 86400;
$date_column = gmdate("d-m-Y H:i:s", $UNIX_DATE);
</code>```

Body:
This only happend when use chunk. This issue could be solved by:

$UNIX_DATE = ($row->DOB - 25569) * 86400;
$date_column = gmdate("d-m-Y H:i:s", $UNIX_DATE);


问:
A problem returning a SwiftUI (transformed) Path from a function
I am working on a custom SwiftUI button that has a special shape depending on configuration.

A utility function must return a Shape depending on configuration. Since the path/shape is complicated to programme, transformations are used to get variations depending on configuration.

For demonstration purpose, a simplified version of the utility function looks like this:

```<code>func shape(i: Int) -> some Shape {

        let path = Path()

        switch i {
        case 0:
            return path
        case 1:
            return path.transform(CGAffineTransform(translationX:0,y:0))
        default:
            break
        }

        return path
    }
</code>```

Unfortunately the compiler generate the well known error:

```<code>Function declares an opaque return type, but the return statements in its body do not have matching underlying types
</code>```

I am sure this happens due to the transformation, although it returns a struct

```<code>func transform(_ transform: CGAffineTransform) -> TransformedShape<Self>
</code>```

that conforms to Shape (like Path do):

```<code>struct TransformedShape<Content> where Content : Shape
</code>```

Documentation for Path states that Path conforms to Shape, and this makes me think that I am overlooking something or that this may be a bug in the compiler.

If someone knows a workaround or can see that I am doing something wrong - please let me known.

Thanks.

答:
You must return the same concrete type in all branches when using a some return

In your case, I’d set up identity transforms so that you always end up with the same type.

Alternatively, you could erase the type. Depending on what you are doing, it could cause performance issues.

```<code> let result: Shape = path
 return result
</code>```

If you do this as part of a SwiftUI View hierarchy, then you will slow down the differ when it inspects this part of the view tree. You should not do that if you can help it.

Body:
I am working on a custom SwiftUI button that has a special shape depending on configuration.

A utility function must return a Shape depending on configuration. Since the path/shape is complicated to programme, transformations are used to get variations depending on configuration.

For demonstration purpose, a simplified version of the utility function looks like this:

func shape(i: Int) -> some Shape {

        let path = Path()

        switch i {
        case 0:
            return path
        case 1:
            return path.transform(CGAffineTransform(translationX:0,y:0))
        default:
            break
        }

        return path
    }

Unfortunately the compiler generate the well known error:

Function declares an opaque return type, but the return statements in its body do not have matching underlying types

I am sure this happens due to the transformation, although it returns a struct

func transform(_ transform: CGAffineTransform) -> TransformedShape<Self>

that conforms to Shape (like Path do):

struct TransformedShape<Content> where Content : Shape

Documentation for Path states that Path conforms to Shape, and this makes me think that I am overlooking something or that this may be a bug in the compiler.

If someone knows a workaround or can see that I am doing something wrong - please let me known.

Thanks.

Body:
You must return the same concrete type in all branches when using a some return

In your case, I’d set up identity transforms so that you always end up with the same type.

Alternatively, you could erase the type. Depending on what you are doing, it could cause performance issues.

 let result: Shape = path
 return result

If you do this as part of a SwiftUI View hierarchy, then you will slow down the differ when it inspects this part of the view tree. You should not do that if you can help it.


问:
How to replace double quotes in derived column transformation?
I have flat file. I am loading data from flat file to source table using ssis.And one of the column has following values:

```<code><Somecol1 =""1"" col1values= ""223,567,890,653"">
</code>```

I want following column output:

```<code><Somecol1 ="1" col1values= "223,567,890,653">
</code>```

I have tried to replace in derived column.

```<code>REPLACE( COLA, "\"","\")
</code>```

but this doesnt work.

答:
I think you have almost got the expression correct except for the additional slash in the replacement string. Here are the expressions that might work for you.

Expression #1: Removes all double quotes within a given string.

```<code>REPLACE(COLA, "\"", "")
</code>```

Expression #2: Replaces all double occurrences of double quotes with single occurrence of double quotes.

```<code>REPLACE(COLA, "\"\"", "\"")
</code>```

Here is an example that demonstrates expression #1:

Screenshot #1 shows the CSV file that will be read by a package.

Screenshot #2 shows the Derived Column transformation inside the Data Flow task that will replace all double quotes within the first column named as Header.

Screenshot #3 shows data in the table after the package execution. Notice that the double quotes in second column are left as it is because there is no expression to replace them.

Here is an example that demonstrates expression #2:

This example will use the same file as in example 1. Refer screenshot #1.

Screenshot #4 shows the Derived Column transformation inside the Data Flow task that will replace all double occurrences of double quotes with single occurrence of double quotes within the first column named as Header.

Screenshot #5 shows data in the table after the package execution. Notice that the double quotes in second column are left as it is because there is no expression to replace them.

Hope that helps.

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:

Body:
I have flat file. I am loading data from flat file to source table using ssis.And one of the column has following values:

<Somecol1 =""1"" col1values= ""223,567,890,653"">

I want following column output:

<Somecol1 ="1" col1values= "223,567,890,653">

I have tried to replace in derived column.

REPLACE( COLA, "\"","\")

but this doesnt work.

Body:
I think you have almost got the expression correct except for the additional slash in the replacement string. Here are the expressions that might work for you.

Expression #1: Removes all double quotes within a given string.

REPLACE(COLA, "\"", "")

Expression #2: Replaces all double occurrences of double quotes with single occurrence of double quotes.

REPLACE(COLA, "\"\"", "\"")

Here is an example that demonstrates expression #1:

Screenshot #1 shows the CSV file that will be read by a package.

Screenshot #2 shows the Derived Column transformation inside the Data Flow task that will replace all double quotes within the first column named as Header.

Screenshot #3 shows data in the table after the package execution. Notice that the double quotes in second column are left as it is because there is no expression to replace them.

Here is an example that demonstrates expression #2:

This example will use the same file as in example 1. Refer screenshot #1.

Screenshot #4 shows the Derived Column transformation inside the Data Flow task that will replace all double occurrences of double quotes with single occurrence of double quotes within the first column named as Header.

Screenshot #5 shows data in the table after the package execution. Notice that the double quotes in second column are left as it is because there is no expression to replace them.

Hope that helps.

Screenshot #1:

Screenshot #2:

Screenshot #3:

Screenshot #4:

Screenshot #5:


问:
Display special characters with pipe dilemeter
I'm playing around with Java RegEx and trying to think of different scenarios for string manipulation.  I can strip out special characters from a string with the following:

```<code>String test = "A man,  66  a plan, a can*()al:55 Panama";
String test = test.replaceAll("[a-zA-Z0-9]", "");
System.out.println(test);
</code>```

Output:   ,     ,  *():

What if I wanted those special characters returned with a pipe delimiter?  So, the expected output would be:  ,|,|*|(|)|:|

答:
You may match and extract these symbols other than alphanumeric and whitespace into a list and the join its elements with |:

```<code>String test = "A man,  66  a plan, a can*()al:55 Panama";
Matcher m = Pattern.compile("[^a-zA-Z0-9\\s]").matcher(test);
List<String> results = new ArrayList<>();
while (m.find()) {
    results.add( m.group() );
}
System.out.println(String.join("|", results));
</code>```

See the Java demo yielding ,|,|*|(|)|:.

Body:
I'm playing around with Java RegEx and trying to think of different scenarios for string manipulation.  I can strip out special characters from a string with the following:

String test = "A man,  66  a plan, a can*()al:55 Panama";
String test = test.replaceAll("[a-zA-Z0-9]", "");
System.out.println(test);

Output:   ,     ,  *():

What if I wanted those special characters returned with a pipe delimiter?  So, the expected output would be:  ,|,|*|(|)|:|

Body:
You may match and extract these symbols other than alphanumeric and whitespace into a list and the join its elements with |:

String test = "A man,  66  a plan, a can*()al:55 Panama";
Matcher m = Pattern.compile("[^a-zA-Z0-9\\s]").matcher(test);
List<String> results = new ArrayList<>();
while (m.find()) {
    results.add( m.group() );
}
System.out.println(String.join("|", results));

See the Java demo yielding ,|,|*|(|)|:.


问:
Designing table for historical data from multiple tables
I have different kind of fields in different tables that needs to be versioned as historical data .
what is the best way to approach this ?
what I did is to capture one level of grouping fields.
I will maintain look-up nested tables where I specify the type of fields that will be versioned as below

and the historical table will look something like this .

Is there any Better way to handle this kind of situation ? keep in mind data to be versioned can vary greatly.

答:
I see 2 approaches for this.

You can maintain a history twin for every table you want to keep history about. The original table will always contain the last/current version of items - while the history will contain the historic versions. The history twin tables must not have a primary key because there will be multiple rows with the same ID. You will need to add 2 columns - both to the original table and to the historic twin. The columns will be of type DATETIME and will be called VALID_FROM and VALID_TO. VALID_TO will be NULL in the original table to denote that this is the current version.

You can have one global history table with the following columns - TABLE_COLUMN_ID, VALUE, VALID_FROM, VALID_TO. TABLE_COLUMN_ID will be a foreign key into a mapping table from which you will get the name of the original entity and the name of the corresponding column. The column VALUE should be of type TEXT and VALID_FROM/VALID_TO will be of type DATETIME. Like the other approach you will need 2 additional columns in each of the original tables - VALID_FROM/VALID_TO to represent the current version validity period.

The first approach obviously requires more space because it keeps all columns of the versioned tables. The second approach could be a little uncomfortable to work with especially if you need to make too many JOINs to get all of the versioned fields.


问:
Creating a Register Page by using DJANGO
How can I redirect in such a way that whenever a new USER  account is created in my site in "REGISTER" page then after the creation of that account, the account should get logged in simultaneously into my website??</p>

答:
Using Django form we can create registration page and edit a/c to your requirement using Django forms and template tags find below refrence.
https://pythonprogramming.net/user-registration-django-tutorial/
https://carlofontanos.com/creating-a-registration-page-in-django/</p>


问:
Set ggsave() aspect ratio to the ratio that RStudio's "Zoom" button gives?
I am using ggsave() to save plots from ggplot().

In R-Studio, clicking the "Zoom" button automatically resizes most of my plots to have quite aesthetic proportions, whereas when I try to manually specify the size and aspect ratios, I get plots that don't look as nice.

Is there a way that I can make ggsave use the same aspect ratio or size that R-Studio's "Zoom" button does?

Or how do I call the Zoom button using code?

答:
If you right click on the zoomed image and select 'Inspect element', you'll see the aspect ratio there.  That can then be passed into ggsave.  Note that I'm assuming the aspect ratio selected by R Studio's zoom is constant on a given monitor in which case you would only need to find the aspect ratio once.

Here's an example of where to find it.


问:
Add list to Pandas Dateframe, but keep NaNs at the top
I think this has probably been answered, but I cant find the answer anywhere. It is pretty trivial. How can I add a list to a pandas dataframe as a column, but keep the NaNs at the top?

This is the code i have:

```<code>df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d
print(df)
</code>```

which returns this:

```<code>   a  b    c    d
0  1  2  2.0  1.0
1  2  3  3.0  2.0
2  3  5  5.0  3.0
3  4  6  6.0  4.0
4  5  4  4.0  NaN
5  6  3  3.0  NaN
6  7  2  NaN  NaN
</code>```

However, I would like it to return this instead:

```<code>  a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0
</code>```

答:
You may find out how many rows have NaN in them (using s.isna().sum()) and then do shift() to that column by the amount of Nans you have.

Code example on d column:

```<code>import pandas as pd
df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d

df['d'] = df['d'].shift(df['d'].isna().sum())  # example on the 'd' row
print(df)
</code>```

Output:

```<code>   a  b    c    d
0  1  2  2.0  NaN
1  2  3  3.0  NaN
2  3  5  5.0  NaN
3  4  6  6.0  1.0
4  5  4  4.0  2.0
5  6  3  3.0  3.0
6  7  2  NaN  4.0
</code>```

Body:
I think this has probably been answered, but I cant find the answer anywhere. It is pretty trivial. How can I add a list to a pandas dataframe as a column, but keep the NaNs at the top?

This is the code i have:

df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d
print(df)

which returns this:

   a  b    c    d
0  1  2  2.0  1.0
1  2  3  3.0  2.0
2  3  5  5.0  3.0
3  4  6  6.0  4.0
4  5  4  4.0  NaN
5  6  3  3.0  NaN
6  7  2  NaN  NaN

However, I would like it to return this instead:

  a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0

Body:
You may find out how many rows have NaN in them (using s.isna().sum()) and then do shift() to that column by the amount of Nans you have.

Code example on d column:

import pandas as pd
df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d

df['d'] = df['d'].shift(df['d'].isna().sum())  # example on the 'd' row
print(df)

Output:

   a  b    c    d
0  1  2  2.0  NaN
1  2  3  3.0  NaN
2  3  5  5.0  NaN
3  4  6  6.0  1.0
4  5  4  4.0  2.0
5  6  3  3.0  3.0
6  7  2  NaN  4.0


问:
How to draw a stacked barplot with three categorical variables representing the proportion of only one of them for each facet in r?
This is the data to take up as a reference

df <- data.frame(a = c(3,3,3,3,3,2,2,3,2,1,1,1,3,1,3), b = c(1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2), c = c(4, 5, 3, 2, 4, 2, 3, 4, 5, 4, 4, 3, 3, 1, 2) )

I want to draw a bargraph with the proportion of a for each facet. At the same time I want the bars to be colored according to the b value.
The variable b is not relevant for calculating the percentage. This is what I came up with, when I set the fill = c, it divides the stacked color in two, one corresponding to 1, and the other as NA.

```<code>      ggplot(aes(x = a, y = ...prop..., group = 1, fill = b)) +
          geom_bar(position = "stack") +
          facet_wrap(~c, nrow = 1, ncol = 5) +
          labs(title = "Count of a among c")
</code>```

how can I have a result similar to this one but with the proportions of a for each facet wrap instead of the absolute values?

Thank you!

答:
Here's an approach using the ..count.. and ..PANEL.. special symbols:

```<code>ggplot(df, aes(x = a, fill = as.factor(b))) +
  geom_bar(aes(y = ..count.. / tapply(..count..,..PANEL..,sum)[..PANEL..])) +
  facet_wrap(~c, nrow = 1, ncol = 5) +
  labs(title = "Count of a among c", fill = "b", y = "Proportion")
</code>```

If you weren't using facet_wrap this would be trivial by setting y = ..prop... However, ..prop.. is not caculated properly by facet. So, to get around this problem, we can use tapply and the ..PANEL.. special symbol to sum ..count.. only for that panel. The last [..PANEL..] is to subset the resulting vector.

The other issue you had was that b is class numeric, so you need to convert that to factor.

Body:
This is the data to take up as a reference

df <- data.frame(a = c(3,3,3,3,3,2,2,3,2,1,1,1,3,1,3), b = c(1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2), c = c(4, 5, 3, 2, 4, 2, 3, 4, 5, 4, 4, 3, 3, 1, 2) )

I want to draw a bargraph with the proportion of a for each facet. At the same time I want the bars to be colored according to the b value.
The variable b is not relevant for calculating the percentage. This is what I came up with, when I set the fill = c, it divides the stacked color in two, one corresponding to 1, and the other as NA.

      ggplot(aes(x = a, y = ...prop..., group = 1, fill = b)) +
          geom_bar(position = "stack") +
          facet_wrap(~c, nrow = 1, ncol = 5) +
          labs(title = "Count of a among c")

how can I have a result similar to this one but with the proportions of a for each facet wrap instead of the absolute values?

Thank you!

Body:
Here's an approach using the ..count.. and ..PANEL.. special symbols:

ggplot(df, aes(x = a, fill = as.factor(b))) +
  geom_bar(aes(y = ..count.. / tapply(..count..,..PANEL..,sum)[..PANEL..])) +
  facet_wrap(~c, nrow = 1, ncol = 5) +
  labs(title = "Count of a among c", fill = "b", y = "Proportion")

If you weren't using facet_wrap this would be trivial by setting y = ..prop... However, ..prop.. is not caculated properly by facet. So, to get around this problem, we can use tapply and the ..PANEL.. special symbol to sum ..count.. only for that panel. The last [..PANEL..] is to subset the resulting vector.

The other issue you had was that b is class numeric, so you need to convert that to factor.


问:
Google Chrome Path in Windows 10
Google repeatedly changed the path to the .exe of Chrome. Sometimes it's hidden in %APPDATA%, in Version 35/36 they changed the path back to program files. There are also differencies across the Windows versions.

Where is Google Chrome located in Windows 10?

答:
Right click on the sub process to see the open file location :

Screenshot

Title: Google Chrome Path in Windows 10


问:
Getting Policy sync failed with status code 503 while integrating mip sdk on Android
I am working on integrating mip sdk version 1.6 as per latest release document on Android. I am able to get access token but when provided to initialize policy engine, it throws below error.

Failed API call: profile_add_engine_async Failed with: [NetworkError: 'Policy sync failed, NetworkError.Category=Throttled, HttpRequest.SanitizedUrl=https://dataservice.protection.outlook.com/PsorWebService/v1/ClientSyncFile/MipPolicies, HttpRequest.Id={EC1D0F76-3A38-4F8A-AAC6-TB9059W1B9AM}, HttpResponse.StatusCode=503, CorrelationId=a9381643-2n1r-4q66-933j-77848ca3e15a, CorrelationId.Description=PolicyProfile']

Appreciate any help.

答: Try again and it should work :) The network error indicated you were throttled for some reason. It should be only temporary.</p>


问:
Creating vectors in Recursive Function C++
I have a recursive function where I have an vector of object being passed. I need to traverse this vector and take out elements based on some condition.
Which is a more efficient way of doing this -

a) Declaring a temporary vector in the body of the function

```<code>function(vector<obj> &arr,int l,int r){
some other stuff
vector<obj> temp;
adding elements based on some condition and operating
}
</code>```

b) Declaring something like a global temporary vector (or passing it through the functions by reference), and then clearing it inside the function body and performing the required steps.

```<code>function(vector<obj> &arr,vector<obj> &temp,int l,int r){
some other stuff
temp.clear();
adding elements based on some condition and operating
}
</code>```

I agree it might not cause significant improvement in performance, but just want to understand which is a better practice. Do include some other methods if you think it is more efficient.

答:
If vector is really big then there is a third option.

Create a new vector, set its capacity to input vector, and add stuff to it instead of removing stuff from original vector.

When you remove one item from a big vector then all other items after it must move by one place. This is a wasteful thing to do, so better avoid it.

When you set a capacity to a vector then the space for it is taken in advance, and when you add new items to it it will not gradually grow in size and the underlying code will not have to copy existing items when vector's current capacity is reached, which may happen a lot.

But there is more. You can use your input vector as output. As you iterate the vector you would copy items to places that you want removed. There would be a "moving hole" in the vector that would grow every time some items should be removed, and items would be just copied from the end of the "hole" to the beginning, moving the hole in effect. When the hole reaches the end you just cut it off from the vector, and that's your output.

Body:
I have a recursive function where I have an vector of object being passed. I need to traverse this vector and take out elements based on some condition.
Which is a more efficient way of doing this -

a) Declaring a temporary vector in the body of the function

function(vector<obj> &arr,int l,int r){
some other stuff
vector<obj> temp;
adding elements based on some condition and operating
}

b) Declaring something like a global temporary vector (or passing it through the functions by reference), and then clearing it inside the function body and performing the required steps.

function(vector<obj> &arr,vector<obj> &temp,int l,int r){
some other stuff
temp.clear();
adding elements based on some condition and operating
}

I agree it might not cause significant improvement in performance, but just want to understand which is a better practice. Do include some other methods if you think it is more efficient.


问:
First project in an ASP.NET Core 3.1 application
I have successfully completed my first project in an ASP.NET Core application using Connector/NET Core to explore the possibility to run this application on any .NET Core

This is the tutorial

This project work correctly on http://localhost:62954/Tablename

Now I need publish the project on the windows server 2008 for sharing on the web this work

On the server I have installed dotnet-sdk-3.1.300-win-x64.exe

I have copied the folder and file from project local to remote server c:\inetpub\wwwroot\aspnetcore\mvccore

but if get on the browser the link http://mywebsite/aspnetcore/mvccore/views/tablename/Index.cshtml
the return is page not found

isn't copying the local file and folders on the server enough for the project to work?

I am server administrator... maybe do I have to configure IIS?

can the new configuration create problems to the existing one on IIS?

how to do resolve this?

can you help me, please?

答: You need IIS for that. But, since you have a .NET Core App, why wouldn't you use Docker to avoid environment problems? It's very easy to configure with Visual Studio 2019.</p>


问:
Can't call extension method on generic Array class when element type is a Protocol [Swift]
The following fails as per the error message quoted in the comment. It has been boiled down to the bare minimum, so the code below has no apparent practical value. I'm just trying to get a handle on the truly bizarre (in my opinion) error message. The reason I want to declare the array as [P] and not [S] is for the usual run-time polymorphism of the array contents.

```<code>protocol P {
    func sp()
}

struct S: P {
    func sp() {}
}

extension Array where Element: P {
    func am() {}
}

func t() {
    let goodA = [S]()
    goodA.am() // No problem

    let badA = [P]()
    badA.am() // Error: '[P]' is not convertible to 'P'
}
</code>```

答:
Protocol declarations define new independent types. While they do behave differently than classes, enums, and structs, they can act as the type for a variable or property (provided there are no associated type constraints, but hold on). For instance

```<code>protocol MyProtocol {}
let myConst: MyProtocol // myConst has type `MyProtocol`
</code>```

In a protocol extension with a generic where clause, there are two different ways to constrain the generic type in question: either with :_ or ==. There is a difference between the two.

Use of :_

The colon specifies that the generic type is something matching the type or protocol specified. It can be read as 'inherits from' or 'conforms to'. For example, anything specified in the extensions apply only when the associated type conforms to Equatable or inherits from SomeClass

```<code>protocol AnotherProtocol {
    associatedtype MyType
}

class SomeClass {}

extension AnotherProtocol where MyType: SomeClass {}
extension AnotherProtocol where MyType: Equatable {}
</code>```

Use of ==

The == operator in a generic where clause specifies that the generic type is exactly the type specified and no other. The code below gives a compile-time error

```<code>class CustomType {}
class CustomTypeII: CustomType {}
class MyClass: AnotherProtocol { typealias MyType = CustomTypeII }

extension AnotherProtocol where MyType == CustomType {
    func myFunc() {}
}

let instance = MyClass()
instance.myFunc() // Error: `CustomTypeII` is not the same type as `CustomType`
</code>```

The == operator cannot be used to constrain a generic type to a protocol with associated types. The compiler will complain that the protocol has an associated type requirement.

```<code>protocol ThirdProtocol {}

extension ThirdProtocol where Self == AnotherProtocol {} // Error: `AnotherProtocol` has associated type requirements
</code>```

In essence, the specification is ambiguous: there is no single AnotherProtocol type, much in the same way that there is no single Array type. The associated type in a protocol acts similarly to the generic arguments of a generic type. Here, the use of a colon is needed to specify that the generic type 'is some' AnotherProtocol type (opaque types follow from the need to specify a specific 'type' of a protocol with associated type constraints, but that is beyond the question).

Your extensions

The extension of Array applies only to array instances whose elements are some type that conforms to the protocol type P, which does not apply to arrays whose elements are the type P. Protocols not conforming to themselves is akin to classes not inheriting from themselves.

This is an old thread, but hopefully this helped.

Body:
The following fails as per the error message quoted in the comment. It has been boiled down to the bare minimum, so the code below has no apparent practical value. I'm just trying to get a handle on the truly bizarre (in my opinion) error message. The reason I want to declare the array as [P] and not [S] is for the usual run-time polymorphism of the array contents.

protocol P {
    func sp()
}

struct S: P {
    func sp() {}
}

extension Array where Element: P {
    func am() {}
}

func t() {
    let goodA = [S]()
    goodA.am() // No problem

    let badA = [P]()
    badA.am() // Error: '[P]' is not convertible to 'P'
}

Body:
Protocol declarations define new independent types. While they do behave differently than classes, enums, and structs, they can act as the type for a variable or property (provided there are no associated type constraints, but hold on). For instance

protocol MyProtocol {}
let myConst: MyProtocol // myConst has type `MyProtocol`

In a protocol extension with a generic where clause, there are two different ways to constrain the generic type in question: either with :_ or ==. There is a difference between the two.

Use of :_

The colon specifies that the generic type is something matching the type or protocol specified. It can be read as 'inherits from' or 'conforms to'. For example, anything specified in the extensions apply only when the associated type conforms to Equatable or inherits from SomeClass

protocol AnotherProtocol {
    associatedtype MyType
}

class SomeClass {}

extension AnotherProtocol where MyType: SomeClass {}
extension AnotherProtocol where MyType: Equatable {}

Use of ==

The == operator in a generic where clause specifies that the generic type is exactly the type specified and no other. The code below gives a compile-time error

class CustomType {}
class CustomTypeII: CustomType {}
class MyClass: AnotherProtocol { typealias MyType = CustomTypeII }

extension AnotherProtocol where MyType == CustomType {
    func myFunc() {}
}

let instance = MyClass()
instance.myFunc() // Error: `CustomTypeII` is not the same type as `CustomType`

The == operator cannot be used to constrain a generic type to a protocol with associated types. The compiler will complain that the protocol has an associated type requirement.

protocol ThirdProtocol {}

extension ThirdProtocol where Self == AnotherProtocol {} // Error: `AnotherProtocol` has associated type requirements

In essence, the specification is ambiguous: there is no single AnotherProtocol type, much in the same way that there is no single Array type. The associated type in a protocol acts similarly to the generic arguments of a generic type. Here, the use of a colon is needed to specify that the generic type 'is some' AnotherProtocol type (opaque types follow from the need to specify a specific 'type' of a protocol with associated type constraints, but that is beyond the question).

Your extensions

The extension of Array applies only to array instances whose elements are some type that conforms to the protocol type P, which does not apply to arrays whose elements are the type P. Protocols not conforming to themselves is akin to classes not inheriting from themselves.

This is an old thread, but hopefully this helped.


问:
How can I create SQL table keys with items from looping through a list in Python
I have a list called headers of about 40-50 items, and I'm trying to make them all keys in a table. I'm trying to avoid typing them all out, here's what I have so far:

```<code>def createtable_db():
    cnx = mysql.connector.connect(user='x', password='x', host='x', database='data')

    mycursor = cnx.cursor()

    create_table = "CREATE TABLE IF NOT EXISTS players (id INT AUTO_INCREMENT PRIMARY KEY)"

    for h in headers:
        pop_table = "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

    mycursor.execute(create_table)
    mycursor.execute(pop_table)

    cnx.close()

createtable_db()
</code>```

This only adds the very last key, I tried adding a + to make this line:

```<code> pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"
</code>```

but that's also not working: it gives me a syntax error.

答:
The following demonstrative code is for generating a pop_table string as a sequence of ALTER TABLE SQL commands, one for each column to be added. You can

create a list for the single columns commands, each of them in the form ADD columnName column format

populate it with a column data section for each element of headers

join them to build the complete sequence of queries. ADD sections have to be separated by commas ,

Append the joined list to initial ALTER TABLE. The query is terminated by a semicolon ;

headers = [ "Stack22", "overflow22", "rules22"]

header_columns_commands =[]

for h in headers:
    header_columns_commands .append("ADD "+ h +" VARCHAR(255)")

pop_table = "ALTER TABLE players " + ",".join(header_columns_commands ) + ";"

print(pop_table)
```

<p>Output:</p>

```ALTER TABLE players
    ADD Stack VARCHAR(255),
    ADD overflow VARCHAR(255),
    ADD rules VARCHAR(255);
```

Tested on MySQL.

Body:
I have a list called headers of about 40-50 items, and I'm trying to make them all keys in a table. I'm trying to avoid typing them all out, here's what I have so far:

def createtable_db():
    cnx = mysql.connector.connect(user='x', password='x', host='x', database='data')

    mycursor = cnx.cursor()

    create_table = "CREATE TABLE IF NOT EXISTS players (id INT AUTO_INCREMENT PRIMARY KEY)"

    for h in headers:
        pop_table = "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

    mycursor.execute(create_table)
    mycursor.execute(pop_table)

    cnx.close()

createtable_db()

This only adds the very last key, I tried adding a + to make this line:

 pop_table += "ALTER TABLE players ADD COLUMN "+ h +" VARCHAR(255)"

but that's also not working: it gives me a syntax error.

Body:
The following demonstrative code is for generating a pop_table string as a sequence of ALTER TABLE SQL commands, one for each column to be added. You can

create a list for the single columns commands, each of them in the form ADD columnName column format

populate it with a column data section for each element of headers

join them to build the complete sequence of queries. ADD sections have to be separated by commas ,

Append the joined list to initial ALTER TABLE. The query is terminated by a semicolon ;

headers = [ "Stack22", "overflow22", "rules22"]

header_columns_commands =[]

for h in headers:
    header_columns_commands .append("ADD "+ h +" VARCHAR(255)")

pop_table = "ALTER TABLE players " + ",".join(header_columns_commands ) + ";"

print(pop_table)

Output:

ALTER TABLE players
    ADD Stack VARCHAR(255),
    ADD overflow VARCHAR(255),
    ADD rules VARCHAR(255);

Tested on MySQL.


问:
How to add event handler for deleting a single item from the list?
I have the following code, and I want to add an even handler for detecting when delete button is clicked and then remove the specific item from list.

Favorites.js

```<code> constructor(props) {
        super(props);
        this.state = {
            movies: []
        };

        this.clearSaved = this.clearSaved.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
    }
</code>```

MovieList.js

```<code>export default ({ movies }) => {
    return(
        <div id="saved-movies-list">
        <ul className="saved-movies-list">
        { movies.map(movie => <li key={ movie.imdbID }><Movie movie={ movie } /></li>) }
        </ul>
        </div>
    )
};
</code>```

Movie.js

```<code>const Movie = ({movie}) => {
     return (<div className="movie-card" id={movie.imdbID}>
          {
               // eslint-disable-next-line
               movie.poster == 'N/A' ?
               <div className="movie-card-poster missing">
               <img className="d-block h-100" src={movie_poster} alt="" />
               </div>
               :
               <div className="movie-card-poster">
               <img className="d-block h-100" src={movie.poster} alt="" />
               </div>
          }
          <div className="body">
               <div style={{ maxWidth: '80%' }}>
                    <h5 class="card-title">{movie.title}</h5>
               </div>
               <p className="text-secondary">{ movie.year }</p>
               {!movie.runtime ? "" : <p className="text-secondary">{ movie.runtime }</p>}
               <p className="plot">{movie.description}</p>
               <a href="#" className="delete-movie" title="Remove this movie"><FontAwesomeIcon icon="minus-circle" size="1x" /></a>
          </div>
     </div>)
}
</code>```

I need to attach event to this line:

```<code>       <a href="#" className="delete-movie" title="Remove this movie"><FontAwesomeIcon icon="minus-circle" size="1x" /></a>
</code>```

But, I do NOT know how to? Writing this.props. ... does not work!

答:
export default ({ movies }) => {
    const handleDelete = (id) => {
      // write your deleting logic here with item id
    }
    return(

          {
             movies.map(movie =>

                 <Movie
                  movie={ movie }
                  onDelete={() => handleDelete(movie.imbID)}
                 />

             )
           }

    )
};
```

<p>in Moive.js</p>

<pre class="lang-js prettyprint-override"><code>const Movie = ({movie, onDelete}) => {
  return (
    ...

     <FontAwesomeIcon icon="minus-circle" size="1x" />

    ...
  )
}
</code>```

I passed the handleDelete with parameter item id to every child component as onDelete function.

Body:
I have the following code, and I want to add an even handler for detecting when delete button is clicked and then remove the specific item from list.

Favorites.js

 constructor(props) {
        super(props);
        this.state = {
            movies: []
        };

        this.clearSaved = this.clearSaved.bind(this);
        this.handleDelete = this.handleDelete.bind(this);
    }

MovieList.js

export default ({ movies }) => {
    return(

        { movies.map(movie =>
<Movie movie={ movie } />
) }

    )
};

Movie.js

const Movie = ({movie}) => {
     return (

          {
               // eslint-disable-next-line
               movie.poster == 'N/A' ?

               :

          }

{movie.title}

{ movie.year }

               {!movie.runtime ? "" :
{ movie.runtime }
}

{movie.description}

               <FontAwesomeIcon icon="minus-circle" size="1x" />

)
}

I need to attach event to this line:

       <FontAwesomeIcon icon="minus-circle" size="1x" />

But, I do NOT know how to? Writing this.props. ... does not work!

Body:
export default ({ movies }) => {
    const handleDelete = (id) => {
      // write your deleting logic here with item id
    }
    return(
        <div id="saved-movies-list">
          <ul className="saved-movies-list">
          {
             movies.map(movie =>
               <li key={ movie.imdbID }>
                 <Movie
                  movie={ movie }
                  onDelete={() => handleDelete(movie.imbID)}
                 />
               </li>
             )
           }
          </ul>
        </div>
    )
};

in Moive.js

const Movie = ({movie, onDelete}) => {
  return (
    ...
    <a href="#" className="delete-movie" title="Remove this movie"
      onClick= {onDelete}
    >
     <FontAwesomeIcon icon="minus-circle" size="1x" />
    </a>
    ...
  )
}

I passed the handleDelete with parameter item id to every child component as onDelete function.


问:
Showing failed re-building development npm/react/gatsy errors in browser
I'm doing development work using gatsby develop. Basically, this script monitors the source code files and re-builds whenever there are changes.

When the re-build succeeds, the browser automatically refreshes and shows the newly built page.
However, when the re-build fails, the browser does nothing, and if I were to manually refresh the webpage, it still loads the last working version, leading to confusion as to why my changes are not reflected.

The only way to tell that the re-build failed is by looking at the terminal output of gatsby develop, which I often hide in order to maximize screen real estate.

Is there a way to for me to just look at the browser and code, and be able to tell that a re-build has failed? The best would be to have the errors show up in the browser, much like the javascript errors, where the re-build was successful, but the code ran into issues in the browser, i.e. TypeErrors, undefined etc.

Thank you.

答:
After @gnujoow's comments, I did a quick check and realized that build failures already show up in the browser.

For some reason, my browser does not always refresh when there are build failures. Thanks @gnujoow


Title: Add list to Pandas Dateframe, but keep NaNs at the top

Body:
Let us try

df=df.apply(lambda x : sorted(x,key=pd.notnull))
   a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0


问:
Spring boot path param url encoding issue
I have a spring boot application, where in one of my controller i have a string coming from path parameter. I have my controller like below:

Controller.java

```<code>@GetMapping(value=“/id/{txt}/user”)
public ResponseEntity<MyUser> getUser(@PathVariable String txt) {

}
</code>```

In my requests i will have the txt value as a string with some of the url encoded characters. Below is the example that the request has:

```<code>/id/Siney6jginshbnsu%252Fghshs%253D
</code>```

But when i debug the application the path variable txt  is coming as :

```<code>/id/Siney6jginshbnsu%2Fghshs%3D
</code>```

The problem is i am doing a string comparison for txt using .equals and because of the above encoding/decoding issue, i am seeing the issue.

Is there any way that i can get the url encoded string from request completely as is?

I know i can try to encode the txt which adds %25 but the problem is i might have % in the string which will encode it as %25.  So appreciate if any one can help or suggest a way to fix this.

Thanks in advance.

答:
Can you try this code:</p>

```<code>@GetMapping(value=“/id/{txt}/user”)
public ResponseEntity<MyUser> getUser(@PathVariable("txt") String txt) {

}
</code>```

Body:
I have a spring boot application, where in one of my controller i have a string coming from path parameter. I have my controller like below:

Controller.java

@GetMapping(value=“/id/{txt}/user”)
public ResponseEntity<MyUser> getUser(@PathVariable String txt) {

}

In my requests i will have the txt value as a string with some of the url encoded characters. Below is the example that the request has:

/id/Siney6jginshbnsu%252Fghshs%253D

But when i debug the application the path variable txt  is coming as :

/id/Siney6jginshbnsu%2Fghshs%3D

The problem is i am doing a string comparison for txt using .equals and because of the above encoding/decoding issue, i am seeing the issue.

Is there any way that i can get the url encoded string from request completely as is?

I know i can try to encode the txt which adds %25 but the problem is i might have % in the string which will encode it as %25.  So appreciate if any one can help or suggest a way to fix this.

Thanks in advance.

Body:
Can you try this code:

@GetMapping(value=“/id/{txt}/user”)
public ResponseEntity<MyUser> getUser(@PathVariable("txt") String txt) {

}


问:
How find correct Ip for connection Client/Server Qt?
I created two Qt apps: one client and one server.
I use them to send some data for handle a remote device.
If I am in localhost I haven't issues about them, but when i search to connect them by internet i don't know how to find correct Ip server to connect Socket Client.
How i can find this ip node?
Is there a class to find It?</p>

答:
you cannot find it automatically, if this is what you're asking about.
In real life you would deploy your server on some publicly accessible host, give it a domain name (important part as your host can change the IP address at any time) and connect the client via the DNS domain.

However if you're just playing around and you want to show to the world that your app works, specifying the IP address of the server in your client code would be perfectly fine (assuming you're running both the server and the client in the same network).

In that case, if you're running mac/linux run the command ifconfig (or just ip depending on the distribution). On Windows you can run the command ipconfig. Both windows and linux will give you a similar output resembling this:

Pay attention to the network adapters. There can potentially be many of them. You may have some emulated adapters if you have docker or VMWare, you may have the wireless adapters if you have a WiFi card, and then the ethernet adapters if your computer can connect to the the internet with an ethernet cable. Each of these adapters specifies a different IPv4 address. You want to pick the one that is connected to the same network as your client. So for instance if both your server machine and your client running machine are connected to the same wifi, you pick the address from the Wireless LAN adapter


问:
How can I handle the cancel and the ok button in the dialog
I want when I click the ok button is the dialog it does something,same as the cancel button

override
    fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

```<code>    val builder = AlertDialog.Builder(this.requireActivity())

    // Dialog will have "Make a selection" as the title
    builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
        // An OK button that does nothing
        .setPositiveButton("OK") { dialog, id ->
            // Nothing happening here

        }
        // A "Cancel" button that does nothing
        .setNegativeButton("Cancel") { dialog, id ->
            // Nothing happening here either
        }
</code>```

答:
```<code> val builder = AlertDialog.Builder(this)
            .setMessage("Yes or No")
            .setPositiveButton("OK"){ dialogInterface: DialogInterface, i: Int ->
                    Toast.makeText(this,"Ok Pressed",Toast.LENGTH_LONG).show()
                    dialogInterface.dismiss()
            }
            .setNegativeButton("No"){ dialogInterface: DialogInterface, i: Int ->
                    Toast.makeText(this,"No Pressed", Toast.LENGTH_SHORT).show()
                    dialogInterface.dismiss()
            }
</code>```

The DialogInterface.OnClickListener has two params:-

dialog -> Dialog which receives the click
i -> the position of the item clicked

Write your execution logic like the toast above and you can use the dialog available to dismiss in the end.

Body:
I want when I click the ok button is the dialog it does something,same as the cancel button

override
    fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

    val builder = AlertDialog.Builder(this.requireActivity())

    // Dialog will have "Make a selection" as the title
    builder.setMessage("Details successfully captured.Do you wish to proceed and book your seat?")
        // An OK button that does nothing
        .setPositiveButton("OK") { dialog, id ->
            // Nothing happening here

        }
        // A "Cancel" button that does nothing
        .setNegativeButton("Cancel") { dialog, id ->
            // Nothing happening here either
        }

Body:
 val builder = AlertDialog.Builder(this)
            .setMessage("Yes or No")
            .setPositiveButton("OK"){ dialogInterface: DialogInterface, i: Int ->
                    Toast.makeText(this,"Ok Pressed",Toast.LENGTH_LONG).show()
                    dialogInterface.dismiss()
            }
            .setNegativeButton("No"){ dialogInterface: DialogInterface, i: Int ->
                    Toast.makeText(this,"No Pressed", Toast.LENGTH_SHORT).show()
                    dialogInterface.dismiss()
            }

The DialogInterface.OnClickListener has two params:-

dialog -> Dialog which receives the click
i -> the position of the item clicked

Write your execution logic like the toast above and you can use the dialog available to dismiss in the end.


问:
How to set UIView to receive input on top of a mapView
This is an oddly specific question, but I can't seem to figure it out or find an answer. I have a banner that hangs off of a navigation bar (visible by sliding constraints when volume is low). I want to make this banner tappable, either by button or gesture recognizer, both don't seem to work, and the map is still being controlled below it when tapping

'

I've tried:

setting isExclusiveTouch = true on the bannerView

bringing that bannerView to top of that navigationView (bringSubViewToFront)

setting the BannerView at the bottom in interfaceBuilder

Not sure what else to do. Sorry if it's unclear, I can add more code examples if needed.

答:
After searching for a while I found the answer. I had to override the hitTest function of the parent UIView. I had to do this because in order to 'show' the bannerView I was updating constraints to slide it down (outside of it's parent view). Since it was outside of it's parent View's constraints the banner was ignoring user input.

Code examples for obj-c and swift can be found here:

Capturing touches on a subview outside the frame of its superview using hitTest:withEvent:


问:
Simple Magento question
I have a website in Magento, it's still very simple and unfinished.

Since I'm a beginner in this field, I'd like someone to point me to a solution:
How do I change the Checkout link text?
Is it done inside the phtml/XML structure or inside admin panel?
this is my website: [notice the Checkout link]
http://gale.dev4.webenabled.net/

答:
You should be able to change the text in the the following template

\app\design\frontend\enterprise\default\template\checkout\cart\cartheader.phtml

Kindly note that this is a directory path from an enterprise installation. Yours might be different but the filename of the template should be the same.

Another option is to use the locale files to actually change by Specifying a translation in the appropriate locale file.

HTH :)

Title: Simple Magento question


问:
Error: Cannot find module 'graphql/validation/rules/PossibleTypeExtensions'
I am using the following book to build a MERN stack CRUD application. I'm having trouble installing and running graphql.

https://www.amazon.com/Pro-MERN-Stack-Development-Express-dp-1484243900/dp/1484243900/ref=mt_paperback?_encoding=UTF8&me=&qid=  (published in 2019).

When I try to start the server contained in this repo https://github.com/vasansr/pro-mern-stack-2/tree/05.02-graphql-schema-file with the command npm start the app crashes and it returns an

Error: Cannot find module 'graphql/validation/rules/PossibleTypeExtensions'

I then followed some advice from a previous instance of this question on here to npm install karma-sinon-chai for the dependancies. But then I get the following error:

npm WARN apollo-graphql@0.4.4 requires a peer of graphql@^14.2.1 but none is installed. You must install peer dependencies yourself.

答:
As per the error message apollo-graphql required a module from the graphql library validation/rules/PossibleTypeExtentions. The version of graphql I was using, as found by looking in my package.json, was "graphql":"^0.13.2".

I first tried to change this by changing my package.json to "^14.3.1". But after trying to install and run graphql I got the same error messages and when I looked in my package.json it had reverted back to "^0.13.2".

This may have been caused by my package.lock, locking me into that version. I then deleted package.lock, and node_modules folder.

I then ran the command nom install --save graphql@14.3.1, this worked fine.

I then just had to reinstall babel and Apollo-server-express and after this everything worked fine.


问:
No 'Access-Control-Allow-Origin' in Spring Boot + Spring Security + CORS
I'm trying CORS with Spring security. So here is my WebSecurityConfigurerAdapter :

```<code>
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("*"));
        configuration.setAllowedMethods(List.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
</code>```

And here is my WebMvcCofigurer :

```<code>@EnableWebSecurity
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}
</code>```

But it gives me
from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Current code :
SecurityConfig.java

```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .disable()//some stackoverflow solution(not accepted) said so
                .csrf()
                .disable()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();
    }
}
</code>```

WebConfig.java:

```<code>import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebSecurity
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH")
                .allowedHeaders("*")
                .allowCredentials(true);
    }

}
</code>```

I tried even a filter(As it crashes when starting, so I removed it)
MyCorsFilter.java

```<code>@Configuration
public class MyCorsFilter {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedHeader("*");//tried list and all other collection stuff
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);//tried with negative value
        return bean;
    }
}
</code>```

Also tried

```<code>http
.headers()
.addHeaderWriter(
      new StaticHeadersWriter(
            "Access-Control-Allow-Origin",
            "http://localhost:3000"))
</code>```

And here is the OAuth2 configuration :

```<code>@Configuration
public class OAuth2Config {
    @Bean
    @RequestScope
    public GoogleOAuth2 google(OAuth2AuthorizedClientService clientService) {
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        String accessToken = null;
        if (authentication.getClass()
                .isAssignableFrom(OAuth2AuthenticationToken.class)) {
            OAuth2AuthenticationToken oauthToken =
                    (OAuth2AuthenticationToken) authentication;
            String clientRegistrationId =
                    oauthToken.getAuthorizedClientRegistrationId();
            if (clientRegistrationId.equals("google")) {
                OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
                        clientRegistrationId, oauthToken.getName());
                accessToken = client.getAccessToken().getTokenValue();
            }
        }
        return new GoogleOAuth2(accessToken);
    }

}
</code>```

答:
Recently I faced the exact same error as I was trying to integrate my angular application to enable authentication for JWT based authentication using spring security.

I see what you are missing in your security configuration. Maybe that is the problem.

First of all, if you configure everything related to CORS in your security configuration then you don't need to create filter or extend WebMvcConfigurer.

Below is what you are missing in your security config.

```<code>http.csrf().disable().cors().configurationSource(corsConfigurationSource())
</code>```

Here is complete code I copied and pasted it from my working code which I fixed yesterday.

```<code>@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            .cors()
            .configurationSource(corsConfigurationSource())
            .and()
            .csrf()
            .disable()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .oauth2Login();

}
</code>```

And then cors config code is which is almost same as yours.

```<code>@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    //the below three lines will add the relevant CORS response headers
    configuration.addAllowedOrigin("*");
    configuration.addAllowedHeader("*");
    configuration.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}
</code>```

Remove your MyCorsFilter and WebConfig class. Both are not needed.

Body:
I'm trying CORS with Spring security. So here is my WebSecurityConfigurerAdapter :

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();
    }
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(List.of("*"));
        configuration.setAllowedMethods(List.of("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(List.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

And here is my WebMvcCofigurer :

@EnableWebSecurity
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
                .addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

But it gives me
from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Current code :
SecurityConfig.java

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
        securedEnabled = true,
        jsr250Enabled = true,
        prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .disable()//some stackoverflow solution(not accepted) said so
                .csrf()
                .disable()
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .oauth2Login();
    }
}

WebConfig.java:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@EnableWebSecurity
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH")
                .allowedHeaders("*")
                .allowCredentials(true);
    }

}

I tried even a filter(As it crashes when starting, so I removed it)
MyCorsFilter.java

@Configuration
public class MyCorsFilter {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://localhost:3000");
        config.addAllowedHeader("*");//tried list and all other collection stuff
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);//tried with negative value
        return bean;
    }
}

Also tried

http
.headers()
.addHeaderWriter(
      new StaticHeadersWriter(
            "Access-Control-Allow-Origin",
            "http://localhost:3000"))

And here is the OAuth2 configuration :

@Configuration
public class OAuth2Config {
    @Bean
    @RequestScope
    public GoogleOAuth2 google(OAuth2AuthorizedClientService clientService) {
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        String accessToken = null;
        if (authentication.getClass()
                .isAssignableFrom(OAuth2AuthenticationToken.class)) {
            OAuth2AuthenticationToken oauthToken =
                    (OAuth2AuthenticationToken) authentication;
            String clientRegistrationId =
                    oauthToken.getAuthorizedClientRegistrationId();
            if (clientRegistrationId.equals("google")) {
                OAuth2AuthorizedClient client = clientService.loadAuthorizedClient(
                        clientRegistrationId, oauthToken.getName());
                accessToken = client.getAccessToken().getTokenValue();
            }
        }
        return new GoogleOAuth2(accessToken);
    }

}

Body:
Recently I faced the exact same error as I was trying to integrate my angular application to enable authentication for JWT based authentication using spring security.

I see what you are missing in your security configuration. Maybe that is the problem.

First of all, if you configure everything related to CORS in your security configuration then you don't need to create filter or extend WebMvcConfigurer.

Below is what you are missing in your security config.

http.csrf().disable().cors().configurationSource(corsConfigurationSource())

Here is complete code I copied and pasted it from my working code which I fixed yesterday.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            .cors()
            .configurationSource(corsConfigurationSource())
            .and()
            .csrf()
            .disable()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
            .and()
            .oauth2Login();

}

And then cors config code is which is almost same as yours.

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"));
    configuration.setAllowCredentials(true);
    //the below three lines will add the relevant CORS response headers
    configuration.addAllowedOrigin("*");
    configuration.addAllowedHeader("*");
    configuration.addAllowedMethod("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Remove your MyCorsFilter and WebConfig class. Both are not needed.


问:
How to maintain one copy of things like JS files and views
My ASP.Net Core MVC project consists of 3 website projects, plus associated unit test projects, all collected in a single solution. Each of the website projects relies on common stuff, such as JavaScript libraries (under wwwroot/js/...) and views (under views/...). Is there some feature that lets me package up these files (none of which, as far as I know, can live in a NetStandard library project) and "install" them in all of my website projects so I only need to maintain them in a single place?

A razor class library (RCL) almost does what I want to do, but I want to be able to reference my JavaScript library from views in all three website projects. I also want the bundler/minimizer to be able to find my common JavaScript and CSS files. As far as I can tell, RCL only allows the Razor Pages in the RCL to access the static content (things like my JavaScript and CSS files) in the RCL.

EDIT:

After more thought, I've come to the conclusion that what I'm asking for simply can't be done "out of the box". In order to work correctly, the debugger and the bundler/minimizer need to find js and css files in the project's directory tree. What I'm asking for is a way to have something like a "reference project" that contains these "shared" files. I'm thinking that it's time for the "science project" approach: I'll create a reference project that contains the shared files, and run some code (at build time? via MSBuild? via unit test code?) that updates the files in the project from the reference project if they don't match.

答:
FWIW, here's what I wound up doing:

In my 3 website projects, I have common files in several places:

Views/Shared

wwwroot/js/MyJsLibrary

wwwroot/css/MyCssLibrary

I created a "reference" project that contains copies of the common files in these folders. Then I created a unit test that simply verifies that the files in the "reference" project exist and are identical to files in each of the 3 websites.

No automated magic to keep the folders in sync. If someone changes one of the common files then the unit tests will fail until someone copies the updated file to the website projects and to the "reference" project.