问:
Is there a way to enable load time weaving in AspectJ without passing java agent arguments to JVM?
I've a requirement to use load time weaving in AspectJ in a spring application, from what I can see in different sources is that you've to pass the javaagent argument to your JVM for enabling the load time weaving.

i.e.

```<code>-javaagent:path/to/spring-aop-aspectj-ltw/spring-instrument-4.2.5.RELEASE.jar
-javaagent:path/to/spring-aop-aspectj-ltw/aspectjweaver-1.8.8.jar
</code>```

I'm wondering is there any alternative way to initialize this in Spring applications?

P.S I'm using Gradle to build the project

答:
I guess no. You need the agents to actually facilitate the weaving before any of your application classes are loaded since they have to be rewritten. I think the @EnableLoadtimeWeaving config is just to tell CGLIB not to create proxy classes for your annotated code, because it's not necessary any more. But I'm not 100% sure on that last part tbh; it might as well tell the agents to actually weave the code, when they find it during classpath scanning.

And don't forget to configure your aop.xml in the META-INF directory!

Body:
I've a requirement to use load time weaving in AspectJ in a spring application, from what I can see in different sources is that you've to pass the javaagent argument to your JVM for enabling the load time weaving.

i.e.

-javaagent:path/to/spring-aop-aspectj-ltw/spring-instrument-4.2.5.RELEASE.jar
-javaagent:path/to/spring-aop-aspectj-ltw/aspectjweaver-1.8.8.jar

I'm wondering is there any alternative way to initialize this in Spring applications?

P.S I'm using Gradle to build the project


来源: stackexchange

问:
For QML, why LayoutMirroring doesn't work in Slider?
Today I tried the Slider in QtQuick.Controls, my slider is left to right, I  want to set my slider as from right to left by using LayoutMirroring.enabled, at last I found I cann't inverted the slider.

Here is my little demo code, so how can we invert a slider?

```<code>Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Slider{
        id:test
        value: 0.2
        width:400
        LayoutMirroring.enabled: true
    }
}
</code>```

答:
I had a similar problem. My slider was vertical with values increasing from bottom to the top. I wanted them to increase from top to bottom. I accomplished it using rotation. I think that you could have solved your problem like this:</p>

```<code>Slider {
    id: test
    value: 0.2
    width: 400
    rotation: 180 // This should make the slider right-to-left
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Today I tried the Slider in QtQuick.Controls, my slider is left to right, I  want to set my slider as from right to left by using LayoutMirroring.enabled, at last I found I cann't inverted the slider.

Here is my little demo code, so how can we invert a slider?

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")

    Slider{
        id:test
        value: 0.2
        width:400
        LayoutMirroring.enabled: true
    }
}

Body:
I had a similar problem. My slider was vertical with values increasing from bottom to the top. I wanted them to increase from top to bottom. I accomplished it using rotation. I think that you could have solved your problem like this:

Slider {
    id: test
    value: 0.2
    width: 400
    rotation: 180 // This should make the slider right-to-left
}

ContentLicense: CC BY-SA 4.0


问:
how to detect logout of asp.net 4 session
How do you detect when a user logs out using the ASP.Net 4 session management?  I have a site that is using the <LoginTemplate> with a <LoginStatus> control.  When the user clicks the "Log out" link, it should fire the LoggingOut event of the LoginStatus, but I cannot get it to do so.  Is there another way to detect when the user logs out of the application?  Session_End isn't being fired because the session itself is still valid, just that the user isn't logged in.</p>

答:
Use the LoginStatus.LoggedOut event - it is right you need, I think.

Raised after the user clicks the logout link and the logout process is complete.


问:
How to get cumulative sum
```<code>declare  @t table
    (
        id int,
        SomeNumt int
    )

insert into @t
select 1,10
union
select 2,12
union
select 3,3
union
select 4,15
union
select 5,23

select * from @t
</code>```

the above  select returns me the following.

```<code>id  SomeNumt
1   10
2   12
3   3
4   15
5   23
</code>```

How do I get the following:

```<code>id  srome   CumSrome
1   10  10
2   12  22
3   3   25
4   15  40
5   23  63
</code>```

答:
For  Ex: IF you have a table with two columns one is ID and second is number and wants to find out the cumulative sum.</p>

```<code>SELECT ID,Number,SUM(Number)OVER(ORDER BY ID) FROM T
</code>```

Title: How to get cumulative sum

Body:
declare  @t table
    (
        id int,
        SomeNumt int
    )

insert into @t
select 1,10
union
select 2,12
union
select 3,3
union
select 4,15
union
select 5,23

select * from @t

the above  select returns me the following.

id  SomeNumt
1   10
2   12
3   3
4   15
5   23

How do I get the following:

id  srome   CumSrome
1   10  10
2   12  22
3   3   25
4   15  40
5   23  63

Body:
For  Ex: IF you have a table with two columns one is ID and second is number and wants to find out the cumulative sum.

SELECT ID,Number,SUM(Number)OVER(ORDER BY ID) FROM T


问:
"message" field is empty in error response Spring Boot
I have handled unauthorized exception like this

```<code>@ResponseStatus(value= HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends RuntimeException {
    public UnauthorizedException(String message) {
        super(message);
    }
}
</code>```

but when I throw the error as follows

```<code>throw new UnauthorizedException("Invalid credentials");
</code>```

I get the error message empty in the response as follows

```<code>{
    "timestamp": "2020-05-27T13:44:58.032+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "",
    "path": "/auth/register"
}
</code>```

I tried using,

```<code>throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid credentials");
</code>```

but the result is still the same. When I added spring-boot-devtools dependency, I get the message as expected with the stack trace as well. How can I fix this?

Spring version : 2.3.0
Java Version: 11.0

答:
Ok got it, they have changed the default value for server.error.include-message to "never" (see the comment section here: Spring 2.3.0 Release Info

All the default values are listed here:
Spring Boot Reference Documentation

Just configure your application.yaml (or properties) like this.

```<code>server:
  error:
    include-message: always
    include-binding-errors: always
</code>```

Mind that showing error messages may leak information about your server implementation.

Body:
I have handled unauthorized exception like this

@ResponseStatus(value= HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends RuntimeException {
    public UnauthorizedException(String message) {
        super(message);
    }
}

but when I throw the error as follows

throw new UnauthorizedException("Invalid credentials");

I get the error message empty in the response as follows

{
    "timestamp": "2020-05-27T13:44:58.032+00:00",
    "status": 401,
    "error": "Unauthorized",
    "message": "",
    "path": "/auth/register"
}

I tried using,

throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid credentials");

but the result is still the same. When I added spring-boot-devtools dependency, I get the message as expected with the stack trace as well. How can I fix this?

Spring version : 2.3.0
Java Version: 11.0

Body:
Ok got it, they have changed the default value for server.error.include-message to "never" (see the comment section here: Spring 2.3.0 Release Info

All the default values are listed here:
Spring Boot Reference Documentation

Just configure your application.yaml (or properties) like this.

server:
  error:
    include-message: always
    include-binding-errors: always

Mind that showing error messages may leak information about your server implementation.


问:
Python Compare Data Tables
I am making a project where I need to compare data from python with data from excel or txt file. I will try to explain better: I web scraped a data table from a website (data table with 7 rows and 1 column), and I need to compare the values with a txt or excel file. This txt or excel file have a data table with 3 values that exist in the web scraped data table (3 rows and 1 column).

Web scraped data table:

```<code>FT 202003/69362
FT 202003/62581
FT 202003/41307
FT 202003/32316
FT 202003/4664
FT 201903/215090
FT 201903/197043
</code>```

Data table in txt file or excel file

```<code>FT 202003/62581
FT 202003/41307
FT 202003/32316
</code>```

My code so far:

```<code>faturas = driver.find_elements_by_xpath("//p[@class='text-description-small']//b[contains(text(),'FT')]")
    totalfaturas = len(faturas)
    fat_list = []
    for fat in faturas:
        fat_list.append(fat.text)
        print(fat.text)
</code>```

The objective is to find which values from web scraped data table don't exist in file data table, because all the values from data table have an associated button in this website, bu I just want to click the button from the values that don't exist in txt or excel file (this part I think I can do it). Can anyone help me?

答:
You can use even in to check one text in another text:

```<code>text_from_file = '''FT 202003/62581
FT 202003/41307
FT 202003/32316'''

fat_text = 'FT 202003/62581'

if fat_text in text_from_file:
    print('already in file')
else:
    print('new element')
</code>```

The same when you will have text from file as list of items

```<code>list_from_file = [
    'FT 202003/62581',
    'FT 202003/41307',
    'FT 202003/32316',
]

fat_text = 'FT 202003/62581'

if fat_text in list_from_file:
    print('already in file')
else:
    print('new element')
</code>```

For pandas.DataFrame you can use `

```<code>if any(df['items'] == fat_text):
</code>```

Code:

```<code>import pandas as pd

df = pd.DataFrame({'items': [
    'FT 202003/62581',
    'FT 202003/41307',
    'FT 202003/32316',
]})

fat_text = 'FT 202003/62581'

if any(df['items'] == fat_text):
    print('already in file')
else:
    print('new element')
</code>```

Eventually you can use sum() which convert True to 1 and False to 0

```<code>if sum(df['items'] == fat_text) > 0:
</code>```

or filter rows and check how many rows you get

```<code>if len(df[ df['items'] == fat_text ]) > 0:
</code>```

Title: Python Compare Data Tables

Body:
I am making a project where I need to compare data from python with data from excel or txt file. I will try to explain better: I web scraped a data table from a website (data table with 7 rows and 1 column), and I need to compare the values with a txt or excel file. This txt or excel file have a data table with 3 values that exist in the web scraped data table (3 rows and 1 column).

Web scraped data table:

FT 202003/69362
FT 202003/62581
FT 202003/41307
FT 202003/32316
FT 202003/4664
FT 201903/215090
FT 201903/197043

Data table in txt file or excel file

FT 202003/62581
FT 202003/41307
FT 202003/32316

My code so far:

faturas = driver.find_elements_by_xpath("//p[@class='text-description-small']//b[contains(text(),'FT')]")
    totalfaturas = len(faturas)
    fat_list = []
    for fat in faturas:
        fat_list.append(fat.text)
        print(fat.text)

The objective is to find which values from web scraped data table don't exist in file data table, because all the values from data table have an associated button in this website, bu I just want to click the button from the values that don't exist in txt or excel file (this part I think I can do it). Can anyone help me?

Body:
You can use even in to check one text in another text:

text_from_file = '''FT 202003/62581
FT 202003/41307
FT 202003/32316'''

fat_text = 'FT 202003/62581'

if fat_text in text_from_file:
    print('already in file')
else:
    print('new element')

The same when you will have text from file as list of items

list_from_file = [
    'FT 202003/62581',
    'FT 202003/41307',
    'FT 202003/32316',
]

fat_text = 'FT 202003/62581'

if fat_text in list_from_file:
    print('already in file')
else:
    print('new element')

For pandas.DataFrame you can use `

if any(df['items'] == fat_text):

Code:

import pandas as pd

df = pd.DataFrame({'items': [
    'FT 202003/62581',
    'FT 202003/41307',
    'FT 202003/32316',
]})

fat_text = 'FT 202003/62581'

if any(df['items'] == fat_text):
    print('already in file')
else:
    print('new element')

Eventually you can use sum() which convert True to 1 and False to 0

if sum(df['items'] == fat_text) > 0:

or filter rows and check how many rows you get

if len(df[ df['items'] == fat_text ]) > 0:


问:
AWS CDK Rollback Triggers
My team is working a new service on AWS and uses aws-cdk to manage our infrastructure. CloudFormation supports using-cfn-rollback-triggers. Is this feature supported in either CDK cli or CDK library? Is there a workaround if it's not supported by CDK other than manually updating cloudformation stacks.</p>

答:
AWS CDK does not currently support rollback triggers.

Usually, when a feature is missing from CDK, it can be mitigated by escaping to the Cfn* resources. However, rollback triggers are not represented as CloudFormation resources, but rather are configured at create-stack/create-change-set invocation time, and hence require support from the CDK CLI.

Long story short, unfortunately this means that there is also no workaround available.

Please feel free to Submit a feature request, this definitely sounds like a good addition to have.

Thanks

Title: AWS CDK Rollback Triggers


问:
Modifying of css by document.styleSheets
I try to modify CSS by changing:

```<code>document.styleSheets[0].cssRules[0].style.fontSize = '1rem';
</code>```

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.

答:
If you have the classname or id of whatever you want to modify , you can use the jquery css() method.

e.g : $("#whateverID").css('font-size', '1rem');

Body:
I try to modify CSS by changing:

document.styleSheets[0].cssRules[0].style.fontSize = '1rem';

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.


问:
Cocoa - Present NSViewController programmatically
Generally, We can able to display next view controller from first view controller by having different kind of NSStoryboardSeque like Present, Show, Sheet etc., But, How we can achieve the same programmatically?.

Comparing with UIViewController, presenting a view controller modally by presentViewController:animated:. Is there any same kind of approach for NSViewController?

Thanks in advance.

答:
If you have a view controller (presenting) than it's as simple as following function are provided:

```<code>open func presentAsSheet(_ viewController: NSViewController)
open func presentAsSheet(_ viewController: NSViewController)
open func present(_ viewController: NSViewController, asPopoverRelativeTo positioningRect: NSRect, of positioningView: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior)
</code>```

If you need to present a view controller in a new window (NOT MODAL) you need to create own NSWindow, NSWindowController

```<code>let gridView = NSGridView(views: [
    [NSTextField(labelWithString: "label1"),NSTextField(labelWithString: "label2")],
    [NSTextField(labelWithString: "label3"),NSTextField(labelWithString: "label4")]
])
let viewController = NSViewController()
viewController.view = gridView
let window = NSWindow(contentViewController: viewController)
window.center()
let windowController = NSWindowController(window: window)
windowController.showWindow(nil)
</code>```

EXPLANATION:

Storyboards are using seques to perform some magic. The show seque is simply calling action "perform:" on object NSStoryboardShowSegueTemplate ([NSApp sendAction:to:from]). This seque will create NSWindowController and NSWindow (private method windowWithContentViewController:) for you and on top it will layoutSubviews/resize and center the window. Magic bonus is  self retaining the window so you don't care about memory management.

Example of programatic calling (using Storyboards to instantiate windowController with viewController)

```<code>import Cocoa
import Contacts

class ShorteningHistoryWindowController : NSWindowController, Storyboarded {
    static var defaultStoryboardName = "ShorteningHistory"
}

struct ShorteningHistory {
    static let shared = ShorteningHistory()
    private var windowController : NSWindowController
    private init() {
        windowController = ShorteningHistoryWindowController.instantiate()
    }
    public func showHistory() {
        windowController.showWindow(self)
    }
}

extension Storyboarded where Self: NSWindowController {
    static var defaultStoryboardName: NSStoryboard.Name { return String(describing: self) }
    static var defaultIdentifer: NSStoryboard.SceneIdentifier {
        let fullName = NSStringFromClass(self)
        let className = fullName.components(separatedBy: ".")[1]
        return className
    }

    static func instantiate() -> Self {
        let storyboard = NSStoryboard(name: defaultStoryboardName, bundle: Bundle.main)
        guard let vc = storyboard.instantiateController(withIdentifier: defaultIdentifer) as? Self else {
            fatalError("Could not instantiate initial storyboard with name: \(defaultIdentifer)")
        }

        return vc
    }
}
</code>```

PS: Don't forget to set Storyboard Identifiers in Storyboard

Body:
If you have a view controller (presenting) than it's as simple as following function are provided:

open func presentAsSheet(_ viewController: NSViewController)
open func presentAsSheet(_ viewController: NSViewController)
open func present(_ viewController: NSViewController, asPopoverRelativeTo positioningRect: NSRect, of positioningView: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior)

If you need to present a view controller in a new window (NOT MODAL) you need to create own NSWindow, NSWindowController

let gridView = NSGridView(views: [
    [NSTextField(labelWithString: "label1"),NSTextField(labelWithString: "label2")],
    [NSTextField(labelWithString: "label3"),NSTextField(labelWithString: "label4")]
])
let viewController = NSViewController()
viewController.view = gridView
let window = NSWindow(contentViewController: viewController)
window.center()
let windowController = NSWindowController(window: window)
windowController.showWindow(nil)

EXPLANATION:

Storyboards are using seques to perform some magic. The show seque is simply calling action "perform:" on object NSStoryboardShowSegueTemplate ([NSApp sendAction:to:from]). This seque will create NSWindowController and NSWindow (private method windowWithContentViewController:) for you and on top it will layoutSubviews/resize and center the window. Magic bonus is  self retaining the window so you don't care about memory management.

Example of programatic calling (using Storyboards to instantiate windowController with viewController)

import Cocoa
import Contacts

class ShorteningHistoryWindowController : NSWindowController, Storyboarded {
    static var defaultStoryboardName = "ShorteningHistory"
}

struct ShorteningHistory {
    static let shared = ShorteningHistory()
    private var windowController : NSWindowController
    private init() {
        windowController = ShorteningHistoryWindowController.instantiate()
    }
    public func showHistory() {
        windowController.showWindow(self)
    }
}

extension Storyboarded where Self: NSWindowController {
    static var defaultStoryboardName: NSStoryboard.Name { return String(describing: self) }
    static var defaultIdentifer: NSStoryboard.SceneIdentifier {
        let fullName = NSStringFromClass(self)
        let className = fullName.components(separatedBy: ".")[1]
        return className
    }

    static func instantiate() -> Self {
        let storyboard = NSStoryboard(name: defaultStoryboardName, bundle: Bundle.main)
        guard let vc = storyboard.instantiateController(withIdentifier: defaultIdentifer) as? Self else {
            fatalError("Could not instantiate initial storyboard with name: \(defaultIdentifer)")
        }

        return vc
    }
}

PS: Don't forget to set Storyboard Identifiers in Storyboard


问:
Missing function: Seperate in R
I have my function missing with the correct code. Do you know the root cause? Here is the error

```<code>library(dplyr)
df <- data.frame(x = c(NA, "a.b", "a.d", "b.c"))
df %>% separate(x, c("A", "B"))
</code>```

Error in UseMethod("separate") :    no applicable method for
  'separate' applied to an object of class "data.frame"

答:
separate is a function from the tidyr package not the dplyr package.

use library(tidyr) or tidyr::separate instead.

Title: Missing function: Seperate in R

Body:
I have my function missing with the correct code. Do you know the root cause? Here is the error

library(dplyr)
df <- data.frame(x = c(NA, "a.b", "a.d", "b.c"))
df %>% separate(x, c("A", "B"))

Error in UseMethod("separate") :    no applicable method for
  'separate' applied to an object of class "data.frame"


问:
Convert and parse json string to key value pairs using NewtonSoft
Trying to convert a json string to key value pairs using Newtonsoft but no luck so far.

Response from the API:

```<code>var response = @"{'result':{'0199 - B344EE33':
{
     '6400_00260100':{'1':[{'val':336688}]},
     '6400_00462500':{'1':[{'val':null}]},
     '6800_00832A00':{'1':[{'low':3000,'high':3000,'val':3000}]},
     '6800_008AA200':{'1':[{'low':0,'high':null,'val':0}]}
}}}";
</code>```

Result I want is a new object of key value pairs:

```<code>{
    "6400_00260100" : 336688,
    "6400_00462500" : null,
    "6800_00832A00" : 3000,
    "6800_008AA200" : 0
}
</code>```

In the response the result will always be the first and only prop. In the next level the code 0199 - B344EE33 can change but there will be only one prop in this level so we can always take the first one. Then in the last level we always need the val property.

What I have is the following but for getting the key value pairs in a clean way I got stuck:

```<code>var json = JObject.Parse(response);
var result = json["result"].First;
var path = result.Path;
</code>```

UPDATE

```<code>        var jObjectResult = new JObject();

        var response = @"{'result':{'0199 - B344EE33':
                        {
                            '6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
                            '6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
                            '6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
                            '6800_08822B00':{'1':[{'val':'SMA'}]},
                            '6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
                        }}}";

        var json = JObject.Parse(response);
        var json_serial = json["result"].First.Children<JObject>().ToList()[0];

        foreach(var token in json_serial)
        {
            var tokenKey = token.Key;
            var tokenVal = token.Value.SelectToken("$.1[0].val");

            jObjectResult.Add(tokenKey, tokenVal);
        }
</code>```

答:
You could use SelectTokens with the recursive descent operator .. to find all the val properties, then walk up the chain using .Parent repeatedly to get the corresponding key.  Create new JProperties from this information and put them into a new JObject to get your result.  Here is a "one-liner":

```<code>var result = new JObject(
    JObject.Parse(response)
           .SelectTokens("$..val")
           .Select(jt => new JProperty(
               ((JProperty)jt.Parent.Parent.Parent.Parent.Parent.Parent).Name,
               jt
           ))
);
</code>```

Fiddle: https://dotnetfiddle.net/TbZ7LS

Body:
Trying to convert a json string to key value pairs using Newtonsoft but no luck so far.

Response from the API:

var response = @"{'result':{'0199 - B344EE33':
{
     '6400_00260100':{'1':[{'val':336688}]},
     '6400_00462500':{'1':[{'val':null}]},
     '6800_00832A00':{'1':[{'low':3000,'high':3000,'val':3000}]},
     '6800_008AA200':{'1':[{'low':0,'high':null,'val':0}]}
}}}";

Result I want is a new object of key value pairs:

{
    "6400_00260100" : 336688,
    "6400_00462500" : null,
    "6800_00832A00" : 3000,
    "6800_008AA200" : 0
}

In the response the result will always be the first and only prop. In the next level the code 0199 - B344EE33 can change but there will be only one prop in this level so we can always take the first one. Then in the last level we always need the val property.

What I have is the following but for getting the key value pairs in a clean way I got stuck:

var json = JObject.Parse(response);
var result = json["result"].First;
var path = result.Path;

UPDATE

        var jObjectResult = new JObject();

        var response = @"{'result':{'0199 - B344EE33':
                        {
                            '6800_10821E00':{'1':[{'val':'SMA Sunny Boy'}]},
                            '6800_00A21E00':{'1':[{'val':'3.0.0.2222'}]},
                            '6800_00823400':{'1':[{'low':3000,'high':3000,'val':3000}]},
                            '6800_08822B00':{'1':[{'val':'SMA'}]},
                            '6800_08822000':{'1':[{'val':'Sunny Boy 3.0'}]}
                        }}}";

        var json = JObject.Parse(response);
        var json_serial = json["result"].First.Children<JObject>().ToList()[0];

        foreach(var token in json_serial)
        {
            var tokenKey = token.Key;
            var tokenVal = token.Value.SelectToken("$.1[0].val");

            jObjectResult.Add(tokenKey, tokenVal);
        }

Body:
You could use SelectTokens with the recursive descent operator .. to find all the val properties, then walk up the chain using .Parent repeatedly to get the corresponding key.  Create new JProperties from this information and put them into a new JObject to get your result.  Here is a "one-liner":

var result = new JObject(
    JObject.Parse(response)
           .SelectTokens("$..val")
           .Select(jt => new JProperty(
               ((JProperty)jt.Parent.Parent.Parent.Parent.Parent.Parent).Name,
               jt
           ))
);

Fiddle: https://dotnetfiddle.net/TbZ7LS


问:
can't get the urls of articles using BeautifulSoup
I'm using BeautifulSoup to get the urls of articles from this page:
https://www.usnews.com/search?q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=1#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1

I expect all the links of the articles should be stored in pagelinks, like this:

```<code>['https://www.usnews.com/news/health-news/articles/2020-04-08/chinas-controls-may-have-headed-off-700-000-covid-19-cases-study']
['https://www.usnews.com/news/health-news/articles/2020-03-18/trump-dubs-covid-19-chinese-virus-despite-hate-crime-risks']
.......
</code>```

But the output gives me a [].
I used this code:

```<code>            #parse the content
            soup_page = bs(response.text, 'lxml')
            #select all the articles for a single page
            #containers = soup_page.findAll("li", {'class': 'usn-site-search-item'})
            containers = soup_page.findAll("div", {'class': 'usn-site-search-item-container'})
            #scrape the links of the articles
            for i in containers:
                url = i.find('a')
                pagelinks.append(url.get('href'))
            print(pagelinks)
</code>```

As you see, I tried two containers, but neither gives me the expected results.

I would greatly appreciate if someone could help me out!

答:
That webpage loads with JavaScript. You need to go around that and one way is with Selenium.

```<code>from selenium import webdriver
from bs4 import BeautifulSoup

url = "https://www.usnews.com/search?q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=1#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1"
driver = webdriver.Chrome()
driver.get(url)

soup = BeautifulSoup(driver.page_source,'lxml')

#the rest of your code here

driver.quit()
</code>```

If you don't have the Selenium package installed, this is the command to run in a terminal:

```<code>pip install selenium
</code>```

Body:
I'm using BeautifulSoup to get the urls of articles from this page:
https://www.usnews.com/search?q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=1#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1

I expect all the links of the articles should be stored in pagelinks, like this:

['https://www.usnews.com/news/health-news/articles/2020-04-08/chinas-controls-may-have-headed-off-700-000-covid-19-cases-study']
['https://www.usnews.com/news/health-news/articles/2020-03-18/trump-dubs-covid-19-chinese-virus-despite-hate-crime-risks']
.......

But the output gives me a [].
I used this code:

            #parse the content
            soup_page = bs(response.text, 'lxml')
            #select all the articles for a single page
            #containers = soup_page.findAll("li", {'class': 'usn-site-search-item'})
            containers = soup_page.findAll("div", {'class': 'usn-site-search-item-container'})
            #scrape the links of the articles
            for i in containers:
                url = i.find('a')
                pagelinks.append(url.get('href'))
            print(pagelinks)

As you see, I tried two containers, but neither gives me the expected results.

I would greatly appreciate if someone could help me out!

Body:
That webpage loads with JavaScript. You need to go around that and one way is with Selenium.

from selenium import webdriver
from bs4 import BeautifulSoup

url = "https://www.usnews.com/search?q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=1#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1"
driver = webdriver.Chrome()
driver.get(url)

soup = BeautifulSoup(driver.page_source,'lxml')

#the rest of your code here

driver.quit()

If you don't have the Selenium package installed, this is the command to run in a terminal:

pip install selenium


问:
Typescript Error: Property 'user' does not exist on type 'Request'
I have the following piece of code in my express app

```<code>router.get('/auth/userInfo', this.validateUser,  (req, res) => {
    res.json(req.user);
});
</code>```

and my IDE seems to be complaining with the error

error TS2339: Property 'user' does not exist on type 'Request'.

When I compile my typescript code it seems to be throwing this error. Any ideas why this is happening?

答:
For people using GraphQL, there comes a problem with the graphqlExpress function not accepting your new interface. I was attempting to follow this guide until I ran into this exact problem. I have figured out this solution:

this.app.use("/graphql", bodyParser.json(), this.auth, graphqlExpress((req: AuthRequest | undefined) => ({
    schema,
    context: {
        user: req!.user
    }
})));
```

<p>And in the <code>AuthRequest</code> interface:</p>

<pre class="lang-js prettyprint-override"><code>import {Request} from "express"

export interface AuthRequest extends Request {
    user?: string
}
</code>```

Typescript will not allow you to use AuthRequest unless it is also allowed to be undefined. Therefore the | undefined. (source)

After this point, the user object does not 100% exist on the Request object, hence the ? after user.

Body:
I have the following piece of code in my express app

router.get('/auth/userInfo', this.validateUser,  (req, res) => {
    res.json(req.user);
});

and my IDE seems to be complaining with the error

error TS2339: Property 'user' does not exist on type 'Request'.

When I compile my typescript code it seems to be throwing this error. Any ideas why this is happening?

Body:
For people using GraphQL, there comes a problem with the graphqlExpress function not accepting your new interface. I was attempting to follow this guide until I ran into this exact problem. I have figured out this solution:

this.app.use("/graphql", bodyParser.json(), this.auth, graphqlExpress((req: AuthRequest | undefined) => ({
    schema,
    context: {
        user: req!.user
    }
})));

And in the AuthRequest interface:

import {Request} from "express"

export interface AuthRequest extends Request {
    user?: string
}

Typescript will not allow you to use AuthRequest unless it is also allowed to be undefined. Therefore the | undefined. (source)

After this point, the user object does not 100% exist on the Request object, hence the ? after user.


问:
How to insert an integer at specific index in a file using Jupyter-Notebook/python?
[]
The Image is the perfect display of my problem.

I have a .txt file. containing the alphabet: a b c d e f g h i ...

I want to insert a number with each letter, so the updated file look like this:

a1 b2 c3 d4 e5 f6 and so on.

How can I do this in Python?

Note: Also, how to do the same when the letters are in a column, not a row?

答:
Try this:

```<code>with open('s.txt') as s:
    alphabet = s.read()
    lst = alphabet.split()
    for x in range( len(lst)):
        print(lst[x]+str(x+1)," ", end='')
</code>```

output:

```<code>a1  b2  c3  d4  e5  f6
</code>```

Body:
Try this:

with open('s.txt') as s:
    alphabet = s.read()
    lst = alphabet.split()
    for x in range( len(lst)):
        print(lst[x]+str(x+1)," ", end='')

output:

a1  b2  c3  d4  e5  f6


问:
Filling Datagrid using Textbox in C# 2005
I am creating a windows application in VS C# 2005 in which a datagrid and a button and a textbox are there, what i want to create is that when i enter something in textbox and presses the button the textbox text will be put in the datagrid column1 and if i press that button again a new row of that column1 will be created with the given text in the cell. let me show u what i have created yet. Thanks in advance.</p>

```<code>private void button1_Click(object sender, EventArgs e)
{
   dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
}
</code>```

答:
Simplist example:

Add the following to a Winform:

A DataGridView with one (unbound) column

A Button

A TextBox

Use the following code to your button's Click event:

```<code>dataGridView1.Rows.Add(textBox1.Text);
</code>```

Body:
I am creating a windows application in VS C# 2005 in which a datagrid and a button and a textbox are there, what i want to create is that when i enter something in textbox and presses the button the textbox text will be put in the datagrid column1 and if i press that button again a new row of that column1 will be created with the given text in the cell. let me show u what i have created yet. Thanks in advance.

private void button1_Click(object sender, EventArgs e)
{
   dataGridView1.Rows[0].Cells[0].Value = textBox1.Text;
}

Body:
Simplist example:

Add the following to a Winform:

A DataGridView with one (unbound) column

A Button

A TextBox

Use the following code to your button's Click event:

dataGridView1.Rows.Add(textBox1.Text);


问:
Gradle application plugin with multiple main classes
I'm using the gradle 'application' plugin to start my application. This works well.
Now I want to add the option to start a different main class in the same project. Can I change the plugin's configuration to allow that?</p>

```<code>apply plugin: 'application'

mainClassName = "net.worcade.my.MainClass"
</code>```

答:
Here's how you can generate multiple start scripts if you need to package your apps

application {
    applicationName = "myapp"
    mainClassName = "my.Main1"
}
tasks.named<CreateStartScripts>("startScripts") {
    applicationName = "myapp-main1"
}
val main2StartScripts by tasks.register("main2StartScripts", CreateStartScripts::class) {
    applicationName = "myapp-main2"
    outputDir = file("build/scripts") // By putting these scripts here, they will be picked up automatically by the installDist task
    mainClassName = "my.Main2"
    classpath = project.tasks.getAt(JavaPlugin.JAR_TASK_NAME).outputs.files.plus(project.configurations.getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME)) // I took this from ApplicationPlugin.java:129
}
tasks.named("installDist") {
    dependsOn(main2StartScripts)
}
```

Body:
I'm using the gradle 'application' plugin to start my application. This works well.
Now I want to add the option to start a different main class in the same project. Can I change the plugin's configuration to allow that?

apply plugin: 'application'

mainClassName = "net.worcade.my.MainClass"


问:
Fast nonzero indices per row/column for (sparse) 2D numpy array
I am looking for the fastest way to obtain a list of the nonzero indices of a 2D array per row and per column. The following is a working piece of code:

```<code>preds = [matrix[:,v].nonzero()[0] for v in range(matrix.shape[1])]
descs = [matrix[v].nonzero()[0] for v in range(matrix.shape[0])]
</code>```

Example input:

```<code>matrix = np.array([[0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0]])
</code>```

Example output

```<code>preds = [array([1, 2, 3]), array([2, 3]), array([3]), array([], dtype=int64)]
descs = [array([], dtype=int64), array([0]), array([0, 1]), array([0, 1, 2])]
</code>```

(The lists are called preds and descs because they refer to the predecessors and descendants in a DAG when the matrix is interpreted as an adjacency matrix but this is not essential to the question.)

Timing example:
For timing purposes, the following matrix is a good representative:

```<code>test_matrix = np.zeros(shape=(4096,4096),dtype=np.float32)
for k in range(16):
    test_matrix[256*(k+1):256*(k+2),256*k:256*(k+1)]=1
</code>```

Background: In my code, these two lines take 75% of the time for a 4000x4000 matrix whereas the ensuing topological sort and DP algorithm take only the rest of the quarter. Roughly 5% of the values in the matrix are nonzero so a sparse-matrix solution may be applicable.

Thank you.

(On suggestion posted here as well: https://scicomp.stackexchange.com/questions/35242/fast-nonzero-indices-per-row-column-for-sparse-2d-numpy-array
There are also answers there to which I will provide timings in the comments. This link contains an accepted answer that is twice as fast.)

答:
```<code>In [182]: arr = np.array([[0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0]])
</code>```

The data is present in the whole-array nonzero, just not broken up into per row/column arrays:

```<code>In [183]: np.nonzero(arr)
Out[183]: (array([1, 2, 2, 3, 3, 3]), array([0, 0, 1, 0, 1, 2]))
In [184]: np.argwhere(arr)
Out[184]:
array([[1, 0],
       [2, 0],
       [2, 1],
       [3, 0],
       [3, 1],
       [3, 2]])
</code>```

It might be possible to break the array([1, 2, 2, 3, 3, 3]) into sublists, [1,2,3],[2,3],[3],[] based on the other array.  But it may take some time to work out the logic for that, and there's no guarantee that it will be faster than your row/column iterations.

Logical operations can reduce the boolean array to column or row, giving the rows or columns where nonzero occurs, but again not ragged:

```<code>In [185]: arr!=0
Out[185]:
array([[False, False, False, False],
       [ True, False, False, False],
       [ True,  True, False, False],
       [ True,  True,  True, False]])
In [186]: (arr!=0).any(axis=0)
Out[186]: array([ True,  True,  True, False])
In [187]: np.nonzero((arr!=0).any(axis=0))
Out[187]: (array([0, 1, 2]),)
In [188]: np.nonzero((arr!=0).any(axis=1))
Out[188]: (array([1, 2, 3]),)
In [189]: arr
Out[189]:
array([[0, 0, 0, 0],
       [1, 0, 0, 0],
       [1, 1, 0, 0],
       [1, 1, 1, 0]])
</code>```

The scipy.sparse lil format does generate the data you want:

```<code>In [190]: sparse
Out[190]: <module 'scipy.sparse' from '/usr/local/lib/python3.6/dist-packages/scipy/sparse/__init__.py'>
In [191]: M = sparse.lil_matrix(arr)
In [192]: M
Out[192]:
<4x4 sparse matrix of type '<class 'numpy.longlong'>'
    with 6 stored elements in List of Lists format>
In [193]: M.rows
Out[193]: array([list([]), list([0]), list([0, 1]), list([0, 1, 2])], dtype=object)
In [194]: M.T
Out[194]:
<4x4 sparse matrix of type '<class 'numpy.longlong'>'
    with 6 stored elements in List of Lists format>
In [195]: M.T.rows
Out[195]: array([list([1, 2, 3]), list([2, 3]), list([3]), list([])], dtype=object)
</code>```

But timing probably isn't any better than your row or column iteration.

Body:
I am looking for the fastest way to obtain a list of the nonzero indices of a 2D array per row and per column. The following is a working piece of code:

preds = [matrix[:,v].nonzero()[0] for v in range(matrix.shape[1])]
descs = [matrix[v].nonzero()[0] for v in range(matrix.shape[0])]

Example input:

matrix = np.array([[0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0]])

Example output

preds = [array([1, 2, 3]), array([2, 3]), array([3]), array([], dtype=int64)]
descs = [array([], dtype=int64), array([0]), array([0, 1]), array([0, 1, 2])]

(The lists are called preds and descs because they refer to the predecessors and descendants in a DAG when the matrix is interpreted as an adjacency matrix but this is not essential to the question.)

Timing example:
For timing purposes, the following matrix is a good representative:

test_matrix = np.zeros(shape=(4096,4096),dtype=np.float32)
for k in range(16):
    test_matrix[256*(k+1):256*(k+2),256*k:256*(k+1)]=1

Background: In my code, these two lines take 75% of the time for a 4000x4000 matrix whereas the ensuing topological sort and DP algorithm take only the rest of the quarter. Roughly 5% of the values in the matrix are nonzero so a sparse-matrix solution may be applicable.

Thank you.

(On suggestion posted here as well: https://scicomp.stackexchange.com/questions/35242/fast-nonzero-indices-per-row-column-for-sparse-2d-numpy-array
There are also answers there to which I will provide timings in the comments. This link contains an accepted answer that is twice as fast.)

Body:
In [182]: arr = np.array([[0,0,0,0],[1,0,0,0],[1,1,0,0],[1,1,1,0]])

The data is present in the whole-array nonzero, just not broken up into per row/column arrays:

In [183]: np.nonzero(arr)
Out[183]: (array([1, 2, 2, 3, 3, 3]), array([0, 0, 1, 0, 1, 2]))
In [184]: np.argwhere(arr)
Out[184]:
array([[1, 0],
       [2, 0],
       [2, 1],
       [3, 0],
       [3, 1],
       [3, 2]])

It might be possible to break the array([1, 2, 2, 3, 3, 3]) into sublists, [1,2,3],[2,3],[3],[] based on the other array.  But it may take some time to work out the logic for that, and there's no guarantee that it will be faster than your row/column iterations.

Logical operations can reduce the boolean array to column or row, giving the rows or columns where nonzero occurs, but again not ragged:

In [185]: arr!=0
Out[185]:
array([[False, False, False, False],
       [ True, False, False, False],
       [ True,  True, False, False],
       [ True,  True,  True, False]])
In [186]: (arr!=0).any(axis=0)
Out[186]: array([ True,  True,  True, False])
In [187]: np.nonzero((arr!=0).any(axis=0))
Out[187]: (array([0, 1, 2]),)
In [188]: np.nonzero((arr!=0).any(axis=1))
Out[188]: (array([1, 2, 3]),)
In [189]: arr
Out[189]:
array([[0, 0, 0, 0],
       [1, 0, 0, 0],
       [1, 1, 0, 0],
       [1, 1, 1, 0]])

The scipy.sparse lil format does generate the data you want:

In [190]: sparse
Out[190]: <module 'scipy.sparse' from '/usr/local/lib/python3.6/dist-packages/scipy/sparse/__init__.py'>
In [191]: M = sparse.lil_matrix(arr)
In [192]: M
Out[192]:
<4x4 sparse matrix of type '<class 'numpy.longlong'>'
    with 6 stored elements in List of Lists format>
In [193]: M.rows
Out[193]: array([list([]), list([0]), list([0, 1]), list([0, 1, 2])], dtype=object)
In [194]: M.T
Out[194]:
<4x4 sparse matrix of type '<class 'numpy.longlong'>'
    with 6 stored elements in List of Lists format>
In [195]: M.T.rows
Out[195]: array([list([1, 2, 3]), list([2, 3]), list([3]), list([])], dtype=object)

But timing probably isn't any better than your row or column iteration.


问:
Is there a way to change the css of the button on keypress?
https://codepen.io/corpsist/pen/NWGZqOb

```<code>class DrumPad extends React.Component{
constructor(props){
super(props);
}

render(){
return(
  <div>
              <button type="button" id='Q' className="btn btn-lg btn-dark" onClick=this.handleClick}>Q</button>

  </div> )
</code>```

}
}

Need to change the CSS so that the button looks the same when pressed as when clicked.

答:
You can attach onKeyDown to the container and get the key that was pressed and use this to set some state to toggle the boostrap .active class manually.

(I re-worked your component a bit to make it easier to work with)

```<code>class DrumPad extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeButton: "" };
    this.buttons = [["Q", "W", "E"], ["A", "S", "D"], ["Z", "X", "C"]];
  }
  onKeyDown = e => {
    this.setState({ activeButton: e.key.toUpperCase() });
  };

  onMouseDown = buttonId => {
    this.setState({ activeButton: buttonId });
  };

  render() {
    const { activeButton } = this.state;
    return (
      <div className="container-fluid d-flex" onKeyDown={this.onKeyDown}>
        <div>
          {this.buttons.map(buttonRow => (
            <div className="row-sm-4">
              <div class="btn-group-toggle">
                {buttonRow.map(buttonId => (
                  <button
                    id={buttonId}
                    key={buttonId}
                    className={`btn btn-lg btn-dark ${
                      activeButton === buttonId ? "active" : ""
                    }`}
                    onMouseDown={() => this.onMouseDown(buttonId)}
                  >
                    {buttonId}
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
}
</code>```

I also had to fiddle with the bootstrap styles a bit:

```<code>.btn {
  margin: 3px;
}
.btn-group-toggle button.btn.btn-dark:focus,
.btn-group-toggle button.btn.btn-dark:active {
  box-shadow: none;
}

button.active {
  box-shadow: 0 0 0 0.2rem rgba(82, 88, 93, 0.5);
}
</code>```

Updated codepen here

Body:
https://codepen.io/corpsist/pen/NWGZqOb

class DrumPad extends React.Component{
constructor(props){
super(props);
}

render(){
return(

              <button type="button" id='Q' className="btn btn-lg btn-dark" onClick=this.handleClick}>Q</button>

 )

}
}

Need to change the CSS so that the button looks the same when pressed as when clicked.

Body:
You can attach onKeyDown to the container and get the key that was pressed and use this to set some state to toggle the boostrap .active class manually.

(I re-worked your component a bit to make it easier to work with)

class DrumPad extends React.Component {
  constructor(props) {
    super(props);
    this.state = { activeButton: "" };
    this.buttons = [["Q", "W", "E"], ["A", "S", "D"], ["Z", "X", "C"]];
  }
  onKeyDown = e => {
    this.setState({ activeButton: e.key.toUpperCase() });
  };

  onMouseDown = buttonId => {
    this.setState({ activeButton: buttonId });
  };

  render() {
    const { activeButton } = this.state;
    return (
      <div className="container-fluid d-flex" onKeyDown={this.onKeyDown}>
        <div>
          {this.buttons.map(buttonRow => (
            <div className="row-sm-4">
              <div class="btn-group-toggle">
                {buttonRow.map(buttonId => (
                  <button
                    id={buttonId}
                    key={buttonId}
                    className={`btn btn-lg btn-dark ${
                      activeButton === buttonId ? "active" : ""
                    }`}
                    onMouseDown={() => this.onMouseDown(buttonId)}
                  >
                    {buttonId}
                  </button>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  }
}

I also had to fiddle with the bootstrap styles a bit:

.btn {
  margin: 3px;
}
.btn-group-toggle button.btn.btn-dark:focus,
.btn-group-toggle button.btn.btn-dark:active {
  box-shadow: none;
}

button.active {
  box-shadow: 0 0 0 0.2rem rgba(82, 88, 93, 0.5);
}

Updated codepen here


问:
Zapier Lead Validation CRM
CRM LEAD VALIDATION

Hello guys, I have 2 scenarios that I want to validate.

1- New lead - Phone number doesn't exist in my CRM.

Example: Get lead from facebook lead ad to my CRM (Powelink), and the lead get in to new clients section.

2- Existing lead - Phone number exist in my CRM.

Example: Get lead from facebook lead ad to my CRM, the CRM recognize that the phone number is existing -> send it to "Existing customer" Section.

How can i do it?

答:
Short answer

You can't do it as long as Powerlink is not available on Zapier.
Here's the list of CRMs that have Zapier integrations: https://zapier.com/apps/categories/crm

Long answer

Zapier offers Facebook Lead Ads integrations and setting up a trigger when a new lead is captured is possible. However, Powerlink is not in the list of the CRMs supported by Zapier, so you can't go anywhere after the trigger. For most of the CRMs integrations, Zapier offers a find action where you can optionally create a new customer when the search fails. This kind of action would have been perfect for you.

Title: Zapier Lead Validation CRM


问:
Hide/Show divs within a dynamic data driven form using jQuery in MVC 3
I have a data driven form generated on the fly from a database. The requirement is that certain form elements can become hidden depending on answers from previous form fields.
For e.g. if we have 3 fields, field 1 is a radiobutton list and if the 1st selection is made then field 3 needs to be hidden as its no longer needed. The rules are stored in the database as well but in a very crude manner. The question is how to render the fields in the View in such a manner so that the jQuery can also be incorporated in such a way which is similar to hard coded page with jquery to hide/show fields.</p>

答:
If you don't want to use jQuery to hard-code the rules into the page, you can use Ajax on the various "trigger" elements to go back to the server and hit the database to determine which elements to show, based on that.  You could simply return a string, for example, containing the form elements you wish to show/hide.

This string of elements could be the actual jQuery selectors, which would make your jQuery code pretty simple.

That's the best answer I can give you, based on the limited information we have regarding the rules used for showing/hiding elements.


问:
Xcode 11.5, excessive network usage
From time to time I work in my parent's house; because the internet sucks I had to buy capped internet from the mobile company, so I installed Bandwith+ to check my data usage.

I do iOS development mostly as a hobby, so I have Xcode sitting open while I work my real job. Today I was horrified when my internet usage reached 20GB by the afternoon, most days I average 2GB the whole day

I blamed Paralells and Windows update at first but since nothing I did seemed to stop the excessive network usage I checked the Activity monitor and found the culprit

Xcode has been sitting open 10 minutes after reload, no simulator open, just the project I'm working on (which has no network usage whatsoever), no additions to the project, just staying in the background while I'm typing this and waiting for the clock to run out

Funny enough it was sitting happy at 28KB received for around 7 minutes until it went crazy

But let's give him another 10 minutes and see where it reaches, remember, it's just sitting in the background, I'm grabbing a drink meanwhile...

It consumed almost a GB in 20 minutes! What is it even downloading?

More information: I downloaded it from the App Store yesterday, actually deleted the old Application before installing it again to see if it solved a Playgrounds bug I've been having (it didn't)

I'll probably redownload it tomorrow, but I want to know if there is something I might be missing or are there some workarounds

答:
Ok, I'll tell what happened

A few days after the bandwidth problem I started getting this issue (I don't use flutter)
https://github.com/flutter/flutter/issues/56826

My trash can was filling with dyld_shared_cache_arm64 files from Xcode

I noticed Xcode was reporting "Copying cache files from device" the whole time I was using it, so I searched for a solution

I have an iPad that I connect wirelessly for convenience, that was the source of the downloads, I disabled the wireless debugging and now the bandwidth issue is over, it does try to copy the cache files every time I try to run an app via USB cable and it seems to never end. I just cancel that run and it works fine the second time

Title: Xcode 11.5, excessive network usage


问:
Interoperability between Swing and Javafx : Closing parent Javafx stage from embedded Swing application
I have embedded a swing application in a JavaFx application using SwingNode as shown below :

```<code>final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
            swingNode.setContent(new ButtonHtml());
            }
        });
</code>```

The ButtonHtml is a swing application as shown below :

```<code>public class ButtonHtml extends JPanel
                            implements ActionListener {
    protected JButton b1, b3;

    public ButtonHtml() {
        ImageIcon buttonIcon = createImageIcon("images/down.gif");

        b1 = new JButton("<html><center><b><u>D</u>isable</b><br>"
                         + "<font color=#ffffdd>FX button</font>",
                         buttonIcon);
        Font font = b1.getFont().deriveFont(Font.PLAIN);
        b1.setFont(font);
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("disable");

        b3 = new JButton("<html><center><b><u>E</u>nable</b><br>"
                         + "<font color=#ffffdd>FX button</font>",
                         buttonIcon);
        b3.setFont(font);
        //Use the default text position of CENTER, TRAILING (RIGHT).
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        b3.setEnabled(false);

        //Listen for actions on buttons 1 and 3.
        b1.addActionListener(this);
        b3.addActionListener(this);

        b1.setToolTipText("Click this button to disable the FX button.");
        b3.setToolTipText("Click this button to enable the FX button.");

        //Add Components to this container, using the default FlowLayout.
        add(b1);
        add(b3);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("disable".equals(e.getActionCommand())) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    //close the parent javafx window

                }
            });

            b1.setEnabled(false);
            b3.setEnabled(true);
        } else {
            Platform.runLater(new Runnable() {
               @Override
               public void run() {
                   //do something
               }
            });
            b1.setEnabled(true);
            b3.setEnabled(false);
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid.
     * @param path
     * @return  */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = ButtonHtml.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

}
</code>```

Now in my javafx application,  I have embedded the SwingNode in a pane and created a scene and doing stage.show to open the javafx window :

```<code>BorderPane pane = new BorderPane();

        Image fxButtonIcon = new Image(getClass().getResourceAsStream("images/middle.gif"));

        fxbutton = new Button("FX button", new ImageView(fxButtonIcon));
        fxbutton.setTooltip(new Tooltip("This middle button does nothing when you click it."));
        fxbutton.setStyle("-fx-font: 22 arial; -fx-base: #cce6ff;");
        pane.setTop(swingNode);
        pane.setCenter(fxbutton);

        Scene scene = new Scene(pane, 300, 100);
        stage.setScene(scene);
        stage.setTitle("Enable FX Button");
        stage.show();
</code>```

I need to know, how can we trigger the hide/dispose/close of the parent Javafx window from the embedded Swing application.
Basically I want on click on a button (in above example say button b1), and close the javafx window. Please note that the swing application and javafx application are independent.

答:
A fairly clean approach is just to define a field in your ButtonHtml class representing what to do when b1 is pressed.

Incorporating that, and modernizing the action listener implementations, you can do:

```<code>public class ButtonHtml extends JPanel {

    protected JButton b1, b3;

    private Runnable onCloseRequested = () -> {} ;

    public void setOnCloseRequested(Runnable onCloseRequested) {
        this.onCloseRequested = onCloseRequested ;
    }

    public Runnable getOnCloseRequested() {
        return onCloseRequested ;
    }

    public ButtonHtml() {
        ImageIcon buttonIcon = createImageIcon("images/down.gif");

        b1 = new JButton("<html><center><b><u>D</u>isable</b><br>"
                         + "<font color=#ffffdd>FX button</font>",
                         buttonIcon);
        Font font = b1.getFont().deriveFont(Font.PLAIN);
        b1.setFont(font);
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("disable");

        b3 = new JButton("<html><center><b><u>E</u>nable</b><br>"
                         + "<font color=#ffffdd>FX button</font>",
                         buttonIcon);
        b3.setFont(font);
        //Use the default text position of CENTER, TRAILING (RIGHT).
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        b3.setEnabled(false);

        //Listen for actions on buttons 1 and 3.
        b1.addActionListener(e -> {
            Platform.runLater(onCloseRequested);
            b1.setEnabled(false);
            b3.setEnabled(true);
        });
        b3.addActionListener(e -> { /* ... */ });

        b1.setToolTipText("Click this button to disable the FX button.");
        b3.setToolTipText("Click this button to enable the FX button.");

        //Add Components to this container, using the default FlowLayout.
        add(b1);
        add(b3);
    }

    /** Returns an ImageIcon, or null if the path was invalid.
     * @param path
     * @return  */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = ButtonHtml.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

}
</code>```

And then you can just do

```<code>final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(() -> {
    ButtonHtml buttonHtml = new ButtonHtml();
    buttonHtml.setOnCloseRequested(() -> swingNode.getScene().getWindow().hide());
    swingNode.setContent(buttonHtml);
});
</code>```

Body:
I have embedded a swing application in a JavaFx application using SwingNode as shown below :

final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
            swingNode.setContent(new ButtonHtml());
            }
        });

The ButtonHtml is a swing application as shown below :

public class ButtonHtml extends JPanel
                            implements ActionListener {
    protected JButton b1, b3;

    public ButtonHtml() {
        ImageIcon buttonIcon = createImageIcon("images/down.gif");

        b1 = new JButton("Disable
"
                         + "FX button",
                         buttonIcon);
        Font font = b1.getFont().deriveFont(Font.PLAIN);
        b1.setFont(font);
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("disable");

        b3 = new JButton("Enable
"
                         + "FX button",
                         buttonIcon);
        b3.setFont(font);
        //Use the default text position of CENTER, TRAILING (RIGHT).
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        b3.setEnabled(false);

        //Listen for actions on buttons 1 and 3.
        b1.addActionListener(this);
        b3.addActionListener(this);

        b1.setToolTipText("Click this button to disable the FX button.");
        b3.setToolTipText("Click this button to enable the FX button.");

        //Add Components to this container, using the default FlowLayout.
        add(b1);
        add(b3);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if ("disable".equals(e.getActionCommand())) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    //close the parent javafx window

                }
            });

            b1.setEnabled(false);
            b3.setEnabled(true);
        } else {
            Platform.runLater(new Runnable() {
               @Override
               public void run() {
                   //do something
               }
            });
            b1.setEnabled(true);
            b3.setEnabled(false);
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid.
     * @param path
     * @return  */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = ButtonHtml.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

}

Now in my javafx application,  I have embedded the SwingNode in a pane and created a scene and doing stage.show to open the javafx window :

BorderPane pane = new BorderPane();

        Image fxButtonIcon = new Image(getClass().getResourceAsStream("images/middle.gif"));

        fxbutton = new Button("FX button", new ImageView(fxButtonIcon));
        fxbutton.setTooltip(new Tooltip("This middle button does nothing when you click it."));
        fxbutton.setStyle("-fx-font: 22 arial; -fx-base: #cce6ff;");
        pane.setTop(swingNode);
        pane.setCenter(fxbutton);

        Scene scene = new Scene(pane, 300, 100);
        stage.setScene(scene);
        stage.setTitle("Enable FX Button");
        stage.show();

I need to know, how can we trigger the hide/dispose/close of the parent Javafx window from the embedded Swing application.
Basically I want on click on a button (in above example say button b1), and close the javafx window. Please note that the swing application and javafx application are independent.

Body:
A fairly clean approach is just to define a field in your ButtonHtml class representing what to do when b1 is pressed.

Incorporating that, and modernizing the action listener implementations, you can do:

public class ButtonHtml extends JPanel {

    protected JButton b1, b3;

    private Runnable onCloseRequested = () -> {} ;

    public void setOnCloseRequested(Runnable onCloseRequested) {
        this.onCloseRequested = onCloseRequested ;
    }

    public Runnable getOnCloseRequested() {
        return onCloseRequested ;
    }

    public ButtonHtml() {
        ImageIcon buttonIcon = createImageIcon("images/down.gif");

        b1 = new JButton("<html><center><b><u>D</u>isable</b><br>"
                         + "<font color=#ffffdd>FX button</font>",
                         buttonIcon);
        Font font = b1.getFont().deriveFont(Font.PLAIN);
        b1.setFont(font);
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
        b1.setMnemonic(KeyEvent.VK_D);
        b1.setActionCommand("disable");

        b3 = new JButton("<html><center><b><u>E</u>nable</b><br>"
                         + "<font color=#ffffdd>FX button</font>",
                         buttonIcon);
        b3.setFont(font);
        //Use the default text position of CENTER, TRAILING (RIGHT).
        b3.setMnemonic(KeyEvent.VK_E);
        b3.setActionCommand("enable");
        b3.setEnabled(false);

        //Listen for actions on buttons 1 and 3.
        b1.addActionListener(e -> {
            Platform.runLater(onCloseRequested);
            b1.setEnabled(false);
            b3.setEnabled(true);
        });
        b3.addActionListener(e -> { /* ... */ });

        b1.setToolTipText("Click this button to disable the FX button.");
        b3.setToolTipText("Click this button to enable the FX button.");

        //Add Components to this container, using the default FlowLayout.
        add(b1);
        add(b3);
    }

    /** Returns an ImageIcon, or null if the path was invalid.
     * @param path
     * @return  */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = ButtonHtml.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

}

And then you can just do

final SwingNode swingNode = new SwingNode();
SwingUtilities.invokeLater(() -> {
    ButtonHtml buttonHtml = new ButtonHtml();
    buttonHtml.setOnCloseRequested(() -> swingNode.getScene().getWindow().hide());
    swingNode.setContent(buttonHtml);
});


问:
JAVA 8: how to pass -xms and -xmx JVM values in the command
I'm running a springboot app on Java 8 environment

The command I use to run my app is this:

```<code>spring-boot:run -Plocalmysql -Dmaven.test.skip=true -Dspring.profiles.active=localmysql
</code>```

My purpose is to add JVM values specification to my command; so i was suggested to use this options syntax:
"-Drun.jvmArguments=Xms512m -Xmx512m"

But while running it throws me this warning :

```<code>> Java HotSpot(TM) 64-Bit Server VM warning: ignoring option
> PermSize=512m; support was removed in 8.0
</code>```

Is there any workaround or a solution to keep passing it in the command?

答:
It is just a warning message about another JVM parameter -XX:PermSize which is not supported since Java 8, because Permanent Generation was replaced with Metaspace.

If you're having issues with setting JVM options for the memory size, for Spring Boot 2 you should use spring-boot.run.jvmArguments parameter:

```<code>mvn spring-boot:run -Plocalmysql -Dmaven.test.skip=true -Dspring.profiles.active=localmysql -Dspring-boot.run.jvmArguments="-Xms512m -Xmx1024m"
</code>```

Or you can set these parameters in the Maven plugin configuration part of pom.xml:

```<code><plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>
            -Xms512m
            -Xmx1024m
        </jvmArguments>
    </configuration>
</plugin>
</code>```

Body:
I'm running a springboot app on Java 8 environment

The command I use to run my app is this:

spring-boot:run -Plocalmysql -Dmaven.test.skip=true -Dspring.profiles.active=localmysql

My purpose is to add JVM values specification to my command; so i was suggested to use this options syntax:
"-Drun.jvmArguments=Xms512m -Xmx512m"

But while running it throws me this warning :

> Java HotSpot(TM) 64-Bit Server VM warning: ignoring option
> PermSize=512m; support was removed in 8.0

Is there any workaround or a solution to keep passing it in the command?

Body:
It is just a warning message about another JVM parameter -XX:PermSize which is not supported since Java 8, because Permanent Generation was replaced with Metaspace.

If you're having issues with setting JVM options for the memory size, for Spring Boot 2 you should use spring-boot.run.jvmArguments parameter:

mvn spring-boot:run -Plocalmysql -Dmaven.test.skip=true -Dspring.profiles.active=localmysql -Dspring-boot.run.jvmArguments="-Xms512m -Xmx1024m"

Or you can set these parameters in the Maven plugin configuration part of pom.xml:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <jvmArguments>
            -Xms512m
            -Xmx1024m
        </jvmArguments>
    </configuration>
</plugin>


答:
From MDN docs (about DocumentOrShadowRoot.styleSheets):

This is an experimental technology.

Check the Browser compatibility table carefully before using this in production.

Expect behavior to change in the future.

I would therefore advise against using the method.

I can't, however, explain in any more detail why you're seeing the problem you describe, as most browsers are supposed to support this feature in the linked compatibility table.

Now to answer your next question:

how can I modify CSS different way?

I would always get an element through the DOM first and then apply styles to an element directly. For example:

var myEl = document.getElementById("myId");
```
<p>Then you can do:</p>
<pre class="lang-js prettyprint-override"><code>myEl.style.fontSize = "1rem";
</code>```

If you don't want to target the element by its id attribute, you can use several other methods:

getElementsByClassName() – takes a string value of a class name, eg. "myClass"

getElementsByTagName() – takes a string value of a tag name, eg. "body", "div"

querySelector() – takes a string  value of a CSS selector eg. "div.myClass p"

However, these don't return a single element like the id selector. For example, to get the first element of a particular class:

var myEl = document.getElementsByClassName("myClass")[0];
```
<p>And the fourth would be:</p>
<pre class="lang-js prettyprint-override"><code>var myEl = document.getElementsByClassName("myClass")[3];
</code>```

Title: Modifying of css by document.styleSheets

Body:
I try to modify CSS by changing:

document.styleSheets[0].cssRules[0].style.fontSize = '1rem';

It works perfect at PC, but using mobile browsers (at least chrome & mozilla) triggering of this script makes no effect.

What did I do wrong? If such way of modification of CSS is not globaly supported by some reason, how can I modify CSS different way?

EDIT: I want to change style for of all existing and all future dynamically added objects with exact class. So el.style.fontSize is not very good option.

Body:
From MDN docs (about DocumentOrShadowRoot.styleSheets):

This is an experimental technology.

Check the Browser compatibility table carefully before using this in production.

Expect behavior to change in the future.

I would therefore advise against using the method.

I can't, however, explain in any more detail why you're seeing the problem you describe, as most browsers are supposed to support this feature in the linked compatibility table.

Now to answer your next question:

how can I modify CSS different way?

I would always get an element through the DOM first and then apply styles to an element directly. For example:

var myEl = document.getElementById("myId");

Then you can do:

myEl.style.fontSize = "1rem";

If you don't want to target the element by its id attribute, you can use several other methods:

getElementsByClassName() – takes a string value of a class name, eg. "myClass"

getElementsByTagName() – takes a string value of a tag name, eg. "body", "div"

querySelector() – takes a string  value of a CSS selector eg. "div.myClass p"

However, these don't return a single element like the id selector. For example, to get the first element of a particular class:

var myEl = document.getElementsByClassName("myClass")[0];

And the fourth would be:

var myEl = document.getElementsByClassName("myClass")[3];


问:
Load only first byte into a register, from a string at a label
I am trying to load only the first byte in a register after data is passed into it
for example if I have the following ASM code

```<code>global _start
section .data
string db "Hello", 0x00 ; string = Hello
section .text
_start:
mov eax, string ; move "Hello" into eax (just to store it for now)
</code>```

this is where I am stuck, I want to ONLY store "H" into eax, so for instance if I moved "H" into EAX, then moved eax into edx so EDX = "H", I could do:

```<code>mov ebx, 1
mov ecx, edx ; This is so I can store "H" in ecx
mov edx, 12 ; 12 is longer than the string, however, I am just using this to test, as it should only output "H", rather than anything else, the reason for this is later I want to use "H" in a  cmp statement
int 0x80 ; execute the system call
</code>```

Now I have also tried using al, ex: mov [edx], al after moving string into eax, but this still outputs the full string, if a working example can be provided for this, that would be greatly appreciated

答:
To move the first byte of the string into al (which is the lowest byte of eax), use

```<code>mov al, [string]
</code>```

If you want to move the byte into the low byte of eax and zero out the rest of eax, you can do

```<code>movzx eax, byte [string]
</code>```

But you don't have to use EAX for that. You can load the byte into whatever register you want. Specifically EAX is probably a bad choice, since int 80h expects the syscall number there. It's not immediately obvious from the pasted code what are you trying to do with that "H" character afterwards...

If you are going to print the string to the console using the write syscall (#4) with the stdout file descriptor (1), which sounds like the natural thing to do, then, like fuz said, you don't need to load the contents of the string into any registers; the syscall expects the address of the string rather than its contents. To the best of my knowledge, there's no single character output in Linux.

In general, you seem to be confused between the address of the string and the contents on the string.

Body:
I am trying to load only the first byte in a register after data is passed into it
for example if I have the following ASM code

global _start
section .data
string db "Hello", 0x00 ; string = Hello
section .text
_start:
mov eax, string ; move "Hello" into eax (just to store it for now)

this is where I am stuck, I want to ONLY store "H" into eax, so for instance if I moved "H" into EAX, then moved eax into edx so EDX = "H", I could do:

mov ebx, 1
mov ecx, edx ; This is so I can store "H" in ecx
mov edx, 12 ; 12 is longer than the string, however, I am just using this to test, as it should only output "H", rather than anything else, the reason for this is later I want to use "H" in a  cmp statement
int 0x80 ; execute the system call

Now I have also tried using al, ex: mov [edx], al after moving string into eax, but this still outputs the full string, if a working example can be provided for this, that would be greatly appreciated

Body:
To move the first byte of the string into al (which is the lowest byte of eax), use

mov al, [string]

If you want to move the byte into the low byte of eax and zero out the rest of eax, you can do

movzx eax, byte [string]

But you don't have to use EAX for that. You can load the byte into whatever register you want. Specifically EAX is probably a bad choice, since int 80h expects the syscall number there. It's not immediately obvious from the pasted code what are you trying to do with that "H" character afterwards...

If you are going to print the string to the console using the write syscall (#4) with the stdout file descriptor (1), which sounds like the natural thing to do, then, like fuz said, you don't need to load the contents of the string into any registers; the syscall expects the address of the string rather than its contents. To the best of my knowledge, there's no single character output in Linux.

In general, you seem to be confused between the address of the string and the contents on the string.


问:
Flask template inheritance - not executing but no errors
I'm learning about template inheritance and I'm a little confused. When I navigate to index.html, I want the title to appear on the tab in my browser. And I want this functionality to be built into the base.html file, which I'm inheriting from, such that the function index on app.py need only be passed the argument title (and the html file name) to execute as described above.

For some reason, the code is not functioning as intended; the title is not present on the browser tab.

app.py:

```<code>from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',title='index')

if __name__ == "__main__":
    app.run(debug=True)
</code>```

index.html:

<!DOCTYPE html>
{%extends "base.html"%}

    <meta charset="utf-8">

```

<p>base.html:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>
</code>```

Both index.html and base.html are found in the templates folder as is necessary for jinja to function. No errors are being triggered, the title is simply not being formatted as intended.

What am I doing wrong?

答:
I figured it out, I needed to pull the title lines OUT of the block statement! Subtle but makes a big difference.</p>

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    {%block head%}
    {%endblock%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>
</code>```

Body:
I'm learning about template inheritance and I'm a little confused. When I navigate to index.html, I want the title to appear on the tab in my browser. And I want this functionality to be built into the base.html file, which I'm inheriting from, such that the function index on app.py need only be passed the argument title (and the html file name) to execute as described above.

For some reason, the code is not functioning as intended; the title is not present on the browser tab.

app.py:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html',title='index')

if __name__ == "__main__":
    app.run(debug=True)

index.html:

<!DOCTYPE html>
{%extends "base.html"%}

    <meta charset="utf-8">

base.html:

<!DOCTYPE html>

    <meta charset="utf-8">
    <title></title>
    {%block head%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
    {%endblock%}

    {%block body%}{%endblock%}

Both index.html and base.html are found in the templates folder as is necessary for jinja to function. No errors are being triggered, the title is simply not being formatted as intended.

What am I doing wrong?

Body:
I figured it out, I needed to pull the title lines OUT of the block statement! Subtle but makes a big difference.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    {%block head%}
    {%endblock%}
      {% if title %}
      <title> {{title}} </title>
      {%endif%}
  </head>
  <body>
    {%block body%}{%endblock%}
  </body>
</html>


问:
how to send data from the function to angular material dialog?
I got the data from clicking the row of the table. Now I got the data, then how do I send data to the dialog component and use it? </p>

```<code>    rowClicked(data) {
        console.log("row data");
        console.log(data);
        const dialogRef = this.dialog.open(DashboardTableDialogComponent, {
            scrollStrategy: new NoopScrollStrategy(),
        });
        dialogRef.afterClosed().subscribe((result) => {
            console.log(`Dialog result: ${result}`);
        });
    }

</code>```

答:
From your component, where you are creating an instance of Dialog Component, we need to send data to Dialog as below:

const dialogRef = this.dialog.open(DashboardTableDialogComponent, {
            scrollStrategy: new NoopScrollStrategy(),
            data : data //This is where you can pass data to your dialog component.
        });

Inside the DashboardTableDialogComponent, Get the data via Dependency Injection as shown below:

private data:any;
constructor ( @Inject(MAT_DIALOG_DATA) public data: any, ...)
{
   this.dataFromParent = data;
}

Hope this should help your problem.

Body:
I got the data from clicking the row of the table. Now I got the data, then how do I send data to the dialog component and use it?

    rowClicked(data) {
        console.log("row data");
        console.log(data);
        const dialogRef = this.dialog.open(DashboardTableDialogComponent, {
            scrollStrategy: new NoopScrollStrategy(),
        });
        dialogRef.afterClosed().subscribe((result) => {
            console.log(`Dialog result: ${result}`);
        });
    }


问:
Azure Cognitive Speech Services STT - Partial Text
In my code (below) when I process it through STT it only gives me the first alphabet/word of the entire audio.

The audio has "A   B    C    D E F"

What am I missing?

```<code>Imports Microsoft.CognitiveServices.Speech
Imports Microsoft.CognitiveServices.Speech.SpeechConfig
Imports Microsoft.CognitiveServices.Speech.Audio

Module Module1

    Sub Main()
        Dim SpeechConfig As SpeechConfig = FromSubscription("<CHANGED>", "eastus")
        Dim audioConfig As Audio.AudioConfig = Audio.AudioConfig.FromWavFileInput("<CHANGED>.wav")
        SpeechConfig.OutputFormat = Microsoft.CognitiveServices.Speech.OutputFormat.Detailed
        Dim recognizer As New SpeechRecognizer(SpeechConfig, audioConfig)
        Dim result = recognizer.RecognizeOnceAsync().Result

        Select Case result.Reason
            Case ResultReason.RecognizedSpeech
                Console.WriteLine($"RECOGNIZED: Text={result.Text}")
                Console.WriteLine($"    Intent not recognized.")
            Case ResultReason.NoMatch
                Console.WriteLine($"NOMATCH: Speech could not be recognized.")
            Case ResultReason.Canceled
                Dim cancellation = CancellationDetails.FromResult(result)
                Console.WriteLine($"CANCELED: Reason={cancellation.Reason}")

                If cancellation.Reason = CancellationReason.[Error] Then
                    Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}")
                    Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}")
                    Console.WriteLine($"CANCELED: Did you update the subscription info?")
                End If
        End Select

    End Sub

End Module
</code>```

You can download the audio file on github here
https://github.com/ullfindsmit/StackOverflowAssets/blob/master/abcdef.wav

Also, if you know where I could get a more detailed STT data i'd appreciate it.
What I am looking for is like a JSON output that says start time and end time along with the word and/or sentence.

Your help is much appreciated.

UPDATE
So The async handlers did not work for me for some reason
However, the code below did

```<code>        While True
            Dim result = recognizer.RecognizeOnceAsync().Result
            Select Case result.Reason
                Case ResultReason.RecognizedSpeech
                    Console.WriteLine($"RECOGNIZED: Text={result.Text}")
                    Console.WriteLine($"    Intent not recognized.")
                Case ResultReason.NoMatch
                    Console.WriteLine($"NOMATCH: Speech could not be recognized.")
                Case ResultReason.Canceled
                    Dim cancellation = CancellationDetails.FromResult(result)
                    Console.WriteLine($"CANCELED: Reason={cancellation.Reason}")

                    If cancellation.Reason = CancellationReason.[Error] Then
                        Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}")
                        Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}")
                        Console.WriteLine($"CANCELED: Did you update the subscription info?")
                    End If

                    Exit While
            End Select
        End While
</code>```

答:
The RecognizeOnceAsync method will only recognize "once" ... the first "utterance/phrase" contained in the audio data file. If you'd like to recognize more than one phrase, you can do one of these two things:

Call RecognizeOnceAsync repeatedly... After the last phrase is recognized, the next call to the method will return a result that has result.Reason set to Canceled.

Switch from using RecognizeOnceAsync to using StartContinuousRecognitionAsync and hook an event hanlder up to the Recognizing event. The event callback will allow you to see the results by inspecting the SpeechRecognitionEventArgs passed, like this: e.Result ...

You can see both of these behaviors by running the Speech CLI like this:

```<code>spx recognize --once+ --key YOUR-KEY --region YOUR-REGION --file "https://github.com/ullfindsmit/StackOverflowAssets/blob/master/abcdef.wav"
spx recognize --continuous --key YOUR-KEY --region YOUR-REGION --file "https://github.com/ullfindsmit/StackOverflowAssets/blob/master/abcdef.wav"
</code>```

You can download the Speech CLI here: https://aka.ms/speech/spx-zips.zip

Body:
In my code (below) when I process it through STT it only gives me the first alphabet/word of the entire audio.

The audio has "A   B    C    D E F"

What am I missing?

Imports Microsoft.CognitiveServices.Speech
Imports Microsoft.CognitiveServices.Speech.SpeechConfig
Imports Microsoft.CognitiveServices.Speech.Audio

Module Module1

    Sub Main()
        Dim SpeechConfig As SpeechConfig = FromSubscription("<CHANGED>", "eastus")
        Dim audioConfig As Audio.AudioConfig = Audio.AudioConfig.FromWavFileInput("<CHANGED>.wav")
        SpeechConfig.OutputFormat = Microsoft.CognitiveServices.Speech.OutputFormat.Detailed
        Dim recognizer As New SpeechRecognizer(SpeechConfig, audioConfig)
        Dim result = recognizer.RecognizeOnceAsync().Result

        Select Case result.Reason
            Case ResultReason.RecognizedSpeech
                Console.WriteLine($"RECOGNIZED: Text={result.Text}")
                Console.WriteLine($"    Intent not recognized.")
            Case ResultReason.NoMatch
                Console.WriteLine($"NOMATCH: Speech could not be recognized.")
            Case ResultReason.Canceled
                Dim cancellation = CancellationDetails.FromResult(result)
                Console.WriteLine($"CANCELED: Reason={cancellation.Reason}")

                If cancellation.Reason = CancellationReason.[Error] Then
                    Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}")
                    Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}")
                    Console.WriteLine($"CANCELED: Did you update the subscription info?")
                End If
        End Select

    End Sub

End Module

You can download the audio file on github here
https://github.com/ullfindsmit/StackOverflowAssets/blob/master/abcdef.wav

Also, if you know where I could get a more detailed STT data i'd appreciate it.
What I am looking for is like a JSON output that says start time and end time along with the word and/or sentence.

Your help is much appreciated.

UPDATE
So The async handlers did not work for me for some reason
However, the code below did

        While True
            Dim result = recognizer.RecognizeOnceAsync().Result
            Select Case result.Reason
                Case ResultReason.RecognizedSpeech
                    Console.WriteLine($"RECOGNIZED: Text={result.Text}")
                    Console.WriteLine($"    Intent not recognized.")
                Case ResultReason.NoMatch
                    Console.WriteLine($"NOMATCH: Speech could not be recognized.")
                Case ResultReason.Canceled
                    Dim cancellation = CancellationDetails.FromResult(result)
                    Console.WriteLine($"CANCELED: Reason={cancellation.Reason}")

                    If cancellation.Reason = CancellationReason.[Error] Then
                        Console.WriteLine($"CANCELED: ErrorCode={cancellation.ErrorCode}")
                        Console.WriteLine($"CANCELED: ErrorDetails={cancellation.ErrorDetails}")
                        Console.WriteLine($"CANCELED: Did you update the subscription info?")
                    End If

                    Exit While
            End Select
        End While

Body:
The RecognizeOnceAsync method will only recognize "once" ... the first "utterance/phrase" contained in the audio data file. If you'd like to recognize more than one phrase, you can do one of these two things:

Call RecognizeOnceAsync repeatedly... After the last phrase is recognized, the next call to the method will return a result that has result.Reason set to Canceled.

Switch from using RecognizeOnceAsync to using StartContinuousRecognitionAsync and hook an event hanlder up to the Recognizing event. The event callback will allow you to see the results by inspecting the SpeechRecognitionEventArgs passed, like this: e.Result ...

You can see both of these behaviors by running the Speech CLI like this:

spx recognize --once+ --key YOUR-KEY --region YOUR-REGION --file "https://github.com/ullfindsmit/StackOverflowAssets/blob/master/abcdef.wav"
spx recognize --continuous --key YOUR-KEY --region YOUR-REGION --file "https://github.com/ullfindsmit/StackOverflowAssets/blob/master/abcdef.wav"

You can download the Speech CLI here: https://aka.ms/speech/spx-zips.zip


答:
The response you get when you called the above-mentioned URL doesn't contain the links you are looking for. You might need to use headless browsers like selenium OR puppeteer since the page needs javascript to load

But you can use this URL to get the desired result programmable search engine

Here is a small python code:

```<code>import requests
import json

headers = {
    "user-agent": <User Agent Goes Here>
}

res = requests.get(url, headers=headers)
json_res = res.text.split("api2768")[1][1:-2]

urls = []
for url in json.loads(json_res)['results']:
    urls.append(url['url'])
</code>```

P.S: Please take care of the cookies

Title: can't get the urls of articles using BeautifulSoup

Body:
I'm using BeautifulSoup to get the urls of articles from this page:
https://www.usnews.com/search?q=China+COVID-19&gsc.tab=0&gsc.q=China+COVID-19&gsc.page=1#gsc.tab=0&gsc.q=China%20COVID-19&gsc.page=1

I expect all the links of the articles should be stored in pagelinks, like this:

['https://www.usnews.com/news/health-news/articles/2020-04-08/chinas-controls-may-have-headed-off-700-000-covid-19-cases-study']
['https://www.usnews.com/news/health-news/articles/2020-03-18/trump-dubs-covid-19-chinese-virus-despite-hate-crime-risks']
.......

But the output gives me a [].
I used this code:

            #parse the content
            soup_page = bs(response.text, 'lxml')
            #select all the articles for a single page
            #containers = soup_page.findAll("li", {'class': 'usn-site-search-item'})
            containers = soup_page.findAll("div", {'class': 'usn-site-search-item-container'})
            #scrape the links of the articles
            for i in containers:
                url = i.find('a')
                pagelinks.append(url.get('href'))
            print(pagelinks)

As you see, I tried two containers, but neither gives me the expected results.

I would greatly appreciate if someone could help me out!

Body:
The response you get when you called the above-mentioned URL doesn't contain the links you are looking for. You might need to use headless browsers like selenium OR puppeteer since the page needs javascript to load

But you can use this URL to get the desired result <a href="https://cse.google.com/cse/element/v1?rsz=filtered_cse&num=10&hl=en&source=gcsc&gss=.com&cselibv=57975621473fd078&cx=009692862532464842631:ckoj05188pi&q=China%20COVID-19&safe=off&cse_tok=AJvRUv3i250WVSYejM2ODNDaIHE-:1590680381832&sort=&exp=csqr,cc,4355059&oq=China%20COVID-19&gs_l=partner-generic.12...0.0.0.212743.0.0.0.0.0.0.0.0..0.0.csems%2Cnrl%3D13...0.0....34.partner-generic..0.0.0.&callback=google.search.cse.api2768" rel="nofollow noreferrer">programmable search engine

Here is a small python code:

import requests
import json

headers = {
    "user-agent": <User Agent Goes Here>
}

res = requests.get(url, headers=headers)
json_res = res.text.split("api2768")[1][1:-2]

urls = []
for url in json.loads(json_res)['results']:
    urls.append(url['url'])

P.S: Please take care of the cookies


问:
Problem with the date format in a column of my DataFrame
So I have a column which contains dates as string objects, however the dates are not all in the same format. Some are MM/YYYY or YYYY. I would like them to be all YYYY, and then convert them to floating objects. I am trying to use a regular expression to replace these strings but I am having difficulty. The column name is 'cease_date' and the DF is called 'dete_resignations'.

```<code>pattern2 = r"(?P<cease_date>[1-2][0-9]{3})?"
years = dete_resignations['cease_date'].str.extractall(pattern2)
print(years['cease_date'].value_counts())
2013    146
2012    129
2014     22
2010      2
2006      1
</code>```

So from the above the regular expression works, but I have no idea how to get it back into the original dataframe. I tried doing a boolean index but it didn't work. Am I going about this the wrong way?

答:
You can use this regex to extract the last four digits in your strings:</p>

```<code> years = dete_resignations['cease_date'].str.extract('(\d{4})$')[0]
</code>```

Body:
So I have a column which contains dates as string objects, however the dates are not all in the same format. Some are MM/YYYY or YYYY. I would like them to be all YYYY, and then convert them to floating objects. I am trying to use a regular expression to replace these strings but I am having difficulty. The column name is 'cease_date' and the DF is called 'dete_resignations'.

pattern2 = r"(?P<cease_date>[1-2][0-9]{3})?"
years = dete_resignations['cease_date'].str.extractall(pattern2)
print(years['cease_date'].value_counts())
2013    146
2012    129
2014     22
2010      2
2006      1

So from the above the regular expression works, but I have no idea how to get it back into the original dataframe. I tried doing a boolean index but it didn't work. Am I going about this the wrong way?

Body:
You can use this regex to extract the last four digits in your strings:

 years = dete_resignations['cease_date'].str.extract('(\d{4})$')[0]