问:
React app POST issues with CORS and fetch
I have a basic react app communicating with a SQL database and have a demo API running with Flask. I know my API works with manual confirmation on Postman.

I am simply trying to post data to my database via my verified API. However, I run into issues with fetch based on the headers in my post method. Below is my current code:

```<code> const request = new Request("http://155.98.25.80:8000/user",
        {method: 'POST',
        headers:{'Content-Type': 'application/json', 'Access-Control-Allow-Origin': "http://localhost:3000/",
        'Accept':'application/json'},
        body: user_data,
        mode:'cors',
       });
        console.log(request)
        fetch(request)
            .then(response => {
                if (response.status === 200) {
                    return response.json();
                }
                else {
                    throw new Error('Something went wrong on api server!');
                }
            })
            .then(response => {
                console.debug(response);
                // ...
            }).catch(error => {
                console.error(error);
            });
    }
</code>```

It is a pretty standard POST request that is triggered on a button click. When I make this request, I can see the API returns a 200 code, meaning it went through to the database. However, in my browser (Chrome) console, I receive the following error: TypeError: Failed to fetch.

I am pretty lost here. I know my post request is going through, but it seems that the return is failing with the response. I have read many of the other posts dealing with this issue, and I am not sure what is going wrong with my app. Any help would be great.

答:
I ran into this frustrating issue a few years ago and my have an answer for you. Your source of pain is probably the preflight check.

Why this happens

When you make a POST request using postman it hits the POST endpoint directly(POST http://155.98.25.80:8000/user)

But when you make a POST request through Chrome it first goes through a preflight check. This means that it first makes an OPTIONS call to the same endpoint (OPTIONS http://155.98.25.80:8000/user). The OPTIONS call must return what is allowed on that endpoint(for CORS security). The OPTIONS call must return headers that lets Chrome what kinds of requests it accepts and from whom.

For you, your OPTIONS http://155.98.25.80:8000/user should return

```<code>Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *
</code>```

Note: Access-Control-Allow-Origin should be your specific api URL(maybe 155.98.25.80), * allows everything

Since Access-Control-Allow-Methods allows POST, POST call will now be allowed when Chrome attempts it.

How to spot it

If you open Chrome Dev Tools and go to the Network tab you will see how before it makes a POST call, it makes a OPTIONS call

The OPTIONS call returns the Access-Control headers

Then, the POST call can be made

Note

Chrome does the preflight check on its own, you don't have to add any additional react code to make this happen.

TL;DR

Create a new endpoint (OPTIONS http://155.98.25.80:8000/user) in Flask API that returns

```<code>Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *
</code>```

Body:
I have a basic react app communicating with a SQL database and have a demo API running with Flask. I know my API works with manual confirmation on Postman.

I am simply trying to post data to my database via my verified API. However, I run into issues with fetch based on the headers in my post method. Below is my current code:

 const request = new Request("http://155.98.25.80:8000/user",
        {method: 'POST',
        headers:{'Content-Type': 'application/json', 'Access-Control-Allow-Origin': "http://localhost:3000/",
        'Accept':'application/json'},
        body: user_data,
        mode:'cors',
       });
        console.log(request)
        fetch(request)
            .then(response => {
                if (response.status === 200) {
                    return response.json();
                }
                else {
                    throw new Error('Something went wrong on api server!');
                }
            })
            .then(response => {
                console.debug(response);
                // ...
            }).catch(error => {
                console.error(error);
            });
    }

It is a pretty standard POST request that is triggered on a button click. When I make this request, I can see the API returns a 200 code, meaning it went through to the database. However, in my browser (Chrome) console, I receive the following error: TypeError: Failed to fetch.

I am pretty lost here. I know my post request is going through, but it seems that the return is failing with the response. I have read many of the other posts dealing with this issue, and I am not sure what is going wrong with my app. Any help would be great.

Body:
I ran into this frustrating issue a few years ago and my have an answer for you. Your source of pain is probably the preflight check.

Why this happens

When you make a POST request using postman it hits the POST endpoint directly(POST http://155.98.25.80:8000/user)

But when you make a POST request through Chrome it first goes through a preflight check. This means that it first makes an OPTIONS call to the same endpoint (OPTIONS http://155.98.25.80:8000/user). The OPTIONS call must return what is allowed on that endpoint(for CORS security). The OPTIONS call must return headers that lets Chrome what kinds of requests it accepts and from whom.

For you, your OPTIONS http://155.98.25.80:8000/user should return

Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *

Note: Access-Control-Allow-Origin should be your specific api URL(maybe 155.98.25.80), * allows everything

Since Access-Control-Allow-Methods allows POST, POST call will now be allowed when Chrome attempts it.

How to spot it

If you open Chrome Dev Tools and go to the Network tab you will see how before it makes a POST call, it makes a OPTIONS call

The OPTIONS call returns the Access-Control headers

Then, the POST call can be made

Note

Chrome does the preflight check on its own, you don't have to add any additional react code to make this happen.

TL;DR

Create a new endpoint (OPTIONS http://155.98.25.80:8000/user) in Flask API that returns

Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Methods: POST
Access-Control-Allow-Origin: *


来源: stackexchange

问:
How to force gradle to trust maven central repo?
I get this error when trying to build with gradle ./gradlew build:

```<code>...
   > Could not resolve org.apache.httpcomponents:httpcore:4.4.15.
     > Could not get resource 'https://repo.maven.apache.org/maven2/org/apache/httpcomponents/httpcore/4.4.15/httpcore-4.4.15.pom'.
        > Could not GET 'https://repo.maven.apache.org/maven2/org/apache/httpcomponents/httpcore/4.4.15/httpcore-4.4.15.pom'.
           > The server may not support the client's requested TLS protocol versions: (SSLv3, TLSv1, TLSv1.1, TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.0.2/userguide/build_environment.html#gradle_system_properties
              > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
              ...
</code>```

Seems unlikely that maven central does not support any of the TLS protocols.

Here's my gradle.properties:

```<code>org.gradle.jvmargs=-Dfile.encoding=UTF-8 -Dhttps.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2,TLSv1.3
org.gradle.java.home=/path/to/jdk-11.0.5+10
org.gradle.allow-insecure-protocol=true
systemProp.scan.uploadInBackground=false
</code>```

I have tried with:

Gradle versions 7.0.2 and 7.3.3

JVM versions OpenJDK 11.0.5+10, Oracle JDK 11.0.13 and OpenJDK 11.0.14+9

Same propblem with all of them.

Also I have tried to:

Import manually repo.maven.apache.org certificate to lib/security/cacerts.

Replaced mavenCentral() with

```<code> maven {
    url "https://repo.maven.apache.org/maven2/"
    allowInsecureProtocol = true
 }
</code>```

Removed SSLv3, TLSv1, TLSv1.1 from jdk.tls.disabledAlgorithms on newer JDKs in conf/security/java.security

What else to try?

答:
Bit of a facepalm. My build.gradle had following lines:

```<code>System.setProperty("javax.net.ssl.trustStore", "my-keystore.jks")
System.setProperty("javax.net.ssl.trustStorePassword", "s3cret")
</code>```

which contained expired certificates.

ContentLicense: CC BY-SA 4.0

Body:
I get this error when trying to build with gradle ./gradlew build:

...
   > Could not resolve org.apache.httpcomponents:httpcore:4.4.15.
     > Could not get resource 'https://repo.maven.apache.org/maven2/org/apache/httpcomponents/httpcore/4.4.15/httpcore-4.4.15.pom'.
        > Could not GET 'https://repo.maven.apache.org/maven2/org/apache/httpcomponents/httpcore/4.4.15/httpcore-4.4.15.pom'.
           > The server may not support the client's requested TLS protocol versions: (SSLv3, TLSv1, TLSv1.1, TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.0.2/userguide/build_environment.html#gradle_system_properties
              > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
              ...

Seems unlikely that maven central does not support any of the TLS protocols.

Here's my gradle.properties:

org.gradle.jvmargs=-Dfile.encoding=UTF-8 -Dhttps.protocols=SSLv3,TLSv1,TLSv1.1,TLSv1.2,TLSv1.3
org.gradle.java.home=/path/to/jdk-11.0.5+10
org.gradle.allow-insecure-protocol=true
systemProp.scan.uploadInBackground=false

I have tried with:

Gradle versions 7.0.2 and 7.3.3

JVM versions OpenJDK 11.0.5+10, Oracle JDK 11.0.13 and OpenJDK 11.0.14+9

Same propblem with all of them.

Also I have tried to:

Import manually repo.maven.apache.org certificate to lib/security/cacerts.

Replaced mavenCentral() with

 maven {
    url "https://repo.maven.apache.org/maven2/"
    allowInsecureProtocol = true
 }

Removed SSLv3, TLSv1, TLSv1.1 from jdk.tls.disabledAlgorithms on newer JDKs in conf/security/java.security

What else to try?

Body:
Bit of a facepalm. My build.gradle had following lines:

System.setProperty("javax.net.ssl.trustStore", "my-keystore.jks")
System.setProperty("javax.net.ssl.trustStorePassword", "s3cret")

which contained expired certificates.


问:
C# object sender - getting the Method from which it was called
I've got these Methods:

```<code>    private void button_Click(object sender, EventArgs e)
    {
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
    }
</code>```

And,

```<code> private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         //Wants something like that
         if(called from button_click)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }
</code>```

How can I handle this, to know if it was called from the Button_click?
Do I have to use the object sender to get informations? But how?

Hope u guys can help me

答:
```<code>private void richTextBox_TextChanged(object sender, EventArgs e)
</code>```

Here sender is the richTextBox, not the button that changed the text.

You could go into the stack trace to discover if the button click is on the call stack, but that's overkill (like using a nuke to crack a walnut).

Add a flag (bool) to your form, set it to true in the button click, and check it in the TextChanged event, then at the end of the button click, set it to false again.

If you do this I would advise wrapping this signal logic in a class that implements IDispose and use it in using statements.

That said, are you sure you need this functionality?

ContentLicense: CC BY-SA 3.0

Body:
I've got these Methods:

    private void button_Click(object sender, EventArgs e)
    {
          //Changes the Text in the RichBox, EXAMPLE:
          richtTextBox.Text = "Now Changed and calling Method richTextBox_TextChanged";
    }

And,

 private void richTextBox_TextChanged(object sender, EventArgs e)
 {
         //Wants something like that
         if(called from button_click)
         {
           //DO SOMETHING
         }
         else
         {
           //DO SOMETHING
         }
 }

How can I handle this, to know if it was called from the Button_click?
Do I have to use the object sender to get informations? But how?

Hope u guys can help me

Body:
private void richTextBox_TextChanged(object sender, EventArgs e)

Here sender is the richTextBox, not the button that changed the text.

You could go into the stack trace to discover if the button click is on the call stack, but that's overkill (like using a nuke to crack a walnut).

Add a flag (bool) to your form, set it to true in the button click, and check it in the TextChanged event, then at the end of the button click, set it to false again.

If you do this I would advise wrapping this signal logic in a class that implements IDispose and use it in using statements.

That said, are you sure you need this functionality?


问:
Java8 Sorting Custom Objects having Custom Object in it
I have an Employee Object, with in it Department Object. I need to sort by Employee Object Fields and then by Department Fields too. Data looks like below.

public static List getEmployeeData() {

```<code>    Department account = new Department("Account", 75);
    Department hr = new Department("HR", 50);
    Department ops = new Department("OP", 25);
    Department tech = new Department("Tech", 150);

    List<Employee> employeeList = Arrays.asList(new Employee("David", 32, "Matara", account),
    new Employee("Brayan", 25, "Galle", hr), new Employee("JoAnne", 45, "Negombo", ops),
    new Employee("Jake", 65, "Galle", hr), new Employee("Brent", 55, "Matara", hr),
    new Employee("Allice", 23, "Matara", ops), new Employee("Austin", 30, "Negombo", tech),
    new Employee("Gerry", 29, "Matara", tech), new Employee("Scote", 20, "Negombo", ops),
    new Employee("Branden", 32, "Matara", account), new Employee("Iflias", 31, "Galle", hr));

    return employeeList;

}
</code>```

I want to sort by Employee::name, Employee::Age, Department::DepartmentName how it can be sorted?

答:
This should led to the desired result:</p>
```<code>List<Employee> employees = getEmployeeData()
                .stream()
                .sorted(Comparator
                        .comparing(Employee::getName)
                        .thenComparing(Employee::getAge)
                        .thenComparing(e -> e.getDepartment().getName()))
                .collect(Collectors.toList());
</code>```

Body:
I have an Employee Object, with in it Department Object. I need to sort by Employee Object Fields and then by Department Fields too. Data looks like below.

public static List getEmployeeData() {

    Department account = new Department("Account", 75);
    Department hr = new Department("HR", 50);
    Department ops = new Department("OP", 25);
    Department tech = new Department("Tech", 150);

    List<Employee> employeeList = Arrays.asList(new Employee("David", 32, "Matara", account),
    new Employee("Brayan", 25, "Galle", hr), new Employee("JoAnne", 45, "Negombo", ops),
    new Employee("Jake", 65, "Galle", hr), new Employee("Brent", 55, "Matara", hr),
    new Employee("Allice", 23, "Matara", ops), new Employee("Austin", 30, "Negombo", tech),
    new Employee("Gerry", 29, "Matara", tech), new Employee("Scote", 20, "Negombo", ops),
    new Employee("Branden", 32, "Matara", account), new Employee("Iflias", 31, "Galle", hr));

    return employeeList;

}

I want to sort by Employee::name, Employee::Age, Department::DepartmentName how it can be sorted?

Body:
This should led to the desired result:

List<Employee> employees = getEmployeeData()
                .stream()
                .sorted(Comparator
                        .comparing(Employee::getName)
                        .thenComparing(Employee::getAge)
                        .thenComparing(e -> e.getDepartment().getName()))
                .collect(Collectors.toList());


问:
How to Switch off and ON the toggle Button based on the click event on icon
In my angular application I have some font icons and also I have one toggle switch ,by default the toggle switch is in ON state.

And My requirement is when I click on any of the icon(the color of the icon should changed from white to red and this was done).the toggle switch should turned to OFF state and when we click on the toggle switch the colored icon should changed to white from red.

.component.html

```<code><label class="rating-switch" id="toggleSwitch">
      <input class="rating-checkbox" type="checkbox" checked >
      <div class="slide round"  >

      </div>
    </label>    <span class="no-rating-switch" >No Rating</span>

<div class="container">
<span class="iconss"></span><i (click)="selectedIcon = icon.id" class="stl" [ngClass]="icon.class"
  [style.color]="selectedIcon === icon.id ? '#FF0000' : '#ffffff'" *ngFor="let icon of icons"></i>
</div>

</code>```

.component.css

```<code>icons = [
    { id: 1, class: "icon-1" },
    { id: 2, class: "icon-2" },
    { id: 3, class: "icon-3" },
    { id: 4, class: "icon-4" },
    { id: 5, class: "icon-5" },
    { id: 6, class: "icon-6" },
    { id: 7, class: "icon-7" },

];
</code>```

So as mentioned above I have to switch off the toggle button (means unchecked)when I click on the icon and when I click on the switch the colored icon should changed to white.

I have tried with multiple ways can anyone help me on this.

答:
I think its a bad idea to toggle multiple icons with one switch (and be able to toggle them manually on a click), it confuses me. But nevermind, here you go.

First you need to declare a state of each of your icons, so you know which one is active/inactive (if there is any logic behind this, you want to know).

Every time you click on an icon which state changes to active, it becomes red. When you click on the toggle, and its state changes to inactive, all of your icons will change back to white.

component.html:

```<code> <label class="rating-switch" id="toggleSwitch">
    <input class="rating-checkbox" type="checkbox" [checked]="toggleState" (change)="onToggleClicked($event)">
    <div class="slide round">

    </div>
  </label> <span class="no-rating-switch">No Rating</span>

  <div class="container">
    <span class="iconss"></span>
    <i (click)="onIconClick(icon)" class="stl" [class]="icon- + i"
       [style.color]="icon.active === true ? '#FF0000' : '#ffffff'" *ngFor="let icon of icons; let i = index">
    </i>
  </div>
</code>```

component.ts:

```<code>  toggleState = true;
  icons = [
    {id: 1, class: 'icon-1', active: false},
    {id: 2, class: 'icon-2', active: false},
    {id: 3, class: 'icon-3', active: false},
    {id: 4, class: 'icon-4', active: false},
    {id: 5, class: 'icon-5', active: false},
    {id: 6, class: 'icon-6', active: false},
    {id: 7, class: 'icon-7', active: false},
  ];

  ngOnInit() {

  }

  onIconClick(icon: any) {
    let iconToEdit = this.icons.find(ico => ico.id === icon.id);
    if (iconToEdit && !iconToEdit.active) {
      this.icons.forEach(i => i.active = false);
      iconToEdit.active = !iconToEdit.active;
      this.markToggleAsActive();
    } else {
      this.icons.forEach(i => i.active = false);
    }
  }

  onToggleClicked(event: any) {
    this.toggleState = event.target.checked;
    this.markIconsAsInactive();
  }

  markIconsAsInactive() {
    if (!this.toggleState) {
      this.icons.forEach(icon => icon.active = false);
    }
  }

  markToggleAsActive() {
    this.toggleState = !!this.icons.find(icon => icon.active);
  }
</code>```

Body:
In my angular application I have some font icons and also I have one toggle switch ,by default the toggle switch is in ON state.

And My requirement is when I click on any of the icon(the color of the icon should changed from white to red and this was done).the toggle switch should turned to OFF state and when we click on the toggle switch the colored icon should changed to white from red.

.component.html

      <input class="rating-checkbox" type="checkbox" checked >

        No Rating

.component.css

icons = [
    { id: 1, class: "icon-1" },
    { id: 2, class: "icon-2" },
    { id: 3, class: "icon-3" },
    { id: 4, class: "icon-4" },
    { id: 5, class: "icon-5" },
    { id: 6, class: "icon-6" },
    { id: 7, class: "icon-7" },

];

So as mentioned above I have to switch off the toggle button (means unchecked)when I click on the icon and when I click on the switch the colored icon should changed to white.

I have tried with multiple ways can anyone help me on this.

Body:
I think its a bad idea to toggle multiple icons with one switch (and be able to toggle them manually on a click), it confuses me. But nevermind, here you go.

First you need to declare a state of each of your icons, so you know which one is active/inactive (if there is any logic behind this, you want to know).

Every time you click on an icon which state changes to active, it becomes red. When you click on the toggle, and its state changes to inactive, all of your icons will change back to white.

component.html:

 <label class="rating-switch" id="toggleSwitch">
    <input class="rating-checkbox" type="checkbox" [checked]="toggleState" (change)="onToggleClicked($event)">
    <div class="slide round">

    </div>
  </label> <span class="no-rating-switch">No Rating</span>

  <div class="container">
    <span class="iconss"></span>
    <i (click)="onIconClick(icon)" class="stl" [class]="icon- + i"
       [style.color]="icon.active === true ? '#FF0000' : '#ffffff'" *ngFor="let icon of icons; let i = index">
    </i>
  </div>

component.ts:

  toggleState = true;
  icons = [
    {id: 1, class: 'icon-1', active: false},
    {id: 2, class: 'icon-2', active: false},
    {id: 3, class: 'icon-3', active: false},
    {id: 4, class: 'icon-4', active: false},
    {id: 5, class: 'icon-5', active: false},
    {id: 6, class: 'icon-6', active: false},
    {id: 7, class: 'icon-7', active: false},
  ];

  ngOnInit() {

  }

  onIconClick(icon: any) {
    let iconToEdit = this.icons.find(ico => ico.id === icon.id);
    if (iconToEdit && !iconToEdit.active) {
      this.icons.forEach(i => i.active = false);
      iconToEdit.active = !iconToEdit.active;
      this.markToggleAsActive();
    } else {
      this.icons.forEach(i => i.active = false);
    }
  }

  onToggleClicked(event: any) {
    this.toggleState = event.target.checked;
    this.markIconsAsInactive();
  }

  markIconsAsInactive() {
    if (!this.toggleState) {
      this.icons.forEach(icon => icon.active = false);
    }
  }

  markToggleAsActive() {
    this.toggleState = !!this.icons.find(icon => icon.active);
  }


问:
Change URl tabs without page refresh NEXT.JS
I'm using material ui tabs, and I'm pushing the tabs to URL. I want to push the tab but not refresh the page every-time I change the tab. Here is my code, and I'm using shallow:true but the problem remains:</p>
```<code>const tabs = [
  { label: 'Details', value: 'details' },
  { label: 'Purchases', value: 'purchases' },
  { label: 'Money Transfer', value: 'moneyTransfer' },
  {label:'User Activity',value:'userActivity'},
  {label:'User Logs',value:'userLogs'}
];
const {
    query: { UsersId,tab },
  } = router
const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => {

  router.push({
    pathname: `/dashboard/twigUsers/${UsersId}`,query: { tab:value}},undefined,{ shallow: true });
};

             <Tabs
              indicatorColor="primary"
              onChange={handleTabsChange}
              scrollButtons="auto"
              sx={{ mt: 3 }}
              textColor="primary"
              value={tab}
              variant="scrollable"
            >
              {tabs.map((tab) => (
                <Tab
                  key={tab.value}
                  label={tab.label}
                  value={tab.value}
                />
              ))}
            </Tabs>

{tab === 'details' && (
             <UsersDetailsContainer user={user} userId={UsersId}/>
            )}
            {tab === 'purchases' && <PurchasesListTable userDetailsId={userDetailsId}/>}
            {tab === 'moneyTransfer' && <MoneyTransferListTable userDetailsIdMT={userDetailsIdMT} />}
            {tab==='userActivity' &&<UserActivity/>}
            {tab==='userLogs' &&<UserLogs user={user} userId={twigUsersId}/>}
</code>```

答:
You need to prevent propagation, else this will actually just propagate to the parent, and will refresh the site.

```<code>const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => {
  event.preventDefault();

  router.push(
    {
      pathname: `/dashboard/twigUsers/${UsersId}`,
      query: { tab: value },
    },
    undefined,
    { shallow: true }
  );
};
</code>```

check out an implementation in action here

Body:
I'm using material ui tabs, and I'm pushing the tabs to URL. I want to push the tab but not refresh the page every-time I change the tab. Here is my code, and I'm using shallow:true but the problem remains:

const tabs = [
  { label: 'Details', value: 'details' },
  { label: 'Purchases', value: 'purchases' },
  { label: 'Money Transfer', value: 'moneyTransfer' },
  {label:'User Activity',value:'userActivity'},
  {label:'User Logs',value:'userLogs'}
];
const {
    query: { UsersId,tab },
  } = router
const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => {

  router.push({
    pathname: `/dashboard/twigUsers/${UsersId}`,query: { tab:value}},undefined,{ shallow: true });
};

             <Tabs
              indicatorColor="primary"
              onChange={handleTabsChange}
              scrollButtons="auto"
              sx={{ mt: 3 }}
              textColor="primary"
              value={tab}
              variant="scrollable"
            >
              {tabs.map((tab) => (
                <Tab
                  key={tab.value}
                  label={tab.label}
                  value={tab.value}
                />
              ))}
            </Tabs>

{tab === 'details' && (
             <UsersDetailsContainer user={user} userId={UsersId}/>
            )}
            {tab === 'purchases' && <PurchasesListTable userDetailsId={userDetailsId}/>}
            {tab === 'moneyTransfer' && <MoneyTransferListTable userDetailsIdMT={userDetailsIdMT} />}
            {tab==='userActivity' &&<UserActivity/>}
            {tab==='userLogs' &&<UserLogs user={user} userId={twigUsersId}/>}

Body:
You need to prevent propagation, else this will actually just propagate to the parent, and will refresh the site.

const handleTabsChange = (event: ChangeEvent<{}>, value: string): void => {
  event.preventDefault();

  router.push(
    {
      pathname: `/dashboard/twigUsers/${UsersId}`,
      query: { tab: value },
    },
    undefined,
    { shallow: true }
  );
};

check out an implementation in action here


问:
How to use pusher.js in service worker
I want to use pusher.js in service worker for sending notification to user when the app(pwa) is closed. But I get below error in pusher.js:</p>
```<code>window is not defined
</code>```

答:
I got the answer, in service worker you can not import pusher as below:

```<code>import Pusher from 'pusher-js';
</code>```

Instead import as below:

```<code>importScripts("https://js.pusher.com/7.0/pusher.worker.min.js");
</code>```

Or

```<code>import Pusher from 'pusher-js/worker';
</code>```

Title: How to use pusher.js in service worker

Body:
I want to use pusher.js in service worker for sending notification to user when the app(pwa) is closed. But I get below error in pusher.js:

window is not defined

Body:
I got the answer, in service worker you can not import pusher as below:

import Pusher from 'pusher-js';

Instead import as below:

importScripts("https://js.pusher.com/7.0/pusher.worker.min.js");

Or

import Pusher from 'pusher-js/worker';


问:
Is there a Perl module to monitor an email queue?
I'm working on an issue tracking system and would like the application to handle email replies.  That is, I would like a script that can monitor an email queue and perform some action based on the email contents.  It should then be able to delete the email, etc.

I currently use MIME::Lite to send email, and I can handle writing the script etc. (read: I'm not new to Perl).  However, I have no idea what modules are good for doing this particular task.  I'd like to get started on this as quickly as possible so I hope to narrow my search space for possible modules.

In case you need to know, the application will be running on a standard linux, Perl, MySQL stack with Exchange as the mail server.

Can anyone suggest a Perl module to help me out?  Any tutorials or best practices related to this would also be helpful.

Thanks!

答: I've done something similar using Mail::POP3Client</p>

OwnerDisplayName: James van Dyke

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: brian d foy

OwnerDisplayName: Roqetman

LastEditorDisplayName: cjm


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

答:
You choose the right way but think that no need to create dict and then modify it if you have ability to do this in the same time:</p>

```<code>keys = ['a','b','c','d']
strK = 'bcad'
res = dict(zip(keys, (strK.index(i) for i in keys)))
</code>```

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
You choose the right way but think that no need to create dict and then modify it if you have ability to do this in the same time:

keys = ['a','b','c','d']
strK = 'bcad'
res = dict(zip(keys, (strK.index(i) for i in keys)))


问:
Python: function that exclude negative values from list and give back new list
I have list of numbers.
I must using function exclude negative values and the positive add to new list.

I know how to do that with for loop but when I try to add there function it does not work for me.
Could you please suggest something.

This is the code which is working but it's loop:

```<code>new_list = []
for i in data:
    if i > 0:
        new_list.append(i)

print(new_list)

</code>```

This function does not work. It gives me None.

```<code>
data2 = [10, 32, 454, 31, -3, 53, -31, -54, -9594, 31314, 53, 10]

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            return new_list.append(i)

preprocessing(data2)
</code>```

答:
Corralien already gave good answers but I feel one is missing. To create an iterable which contains only >0 from data2:

```<code>new_iter = filter(lambda x: x > 0, data2)
</code>```

Using an iterable may be advantageous in circumstances where you are later looping through the list but maybe not all of it. This way the list is only evaluated as far as you need it.

To turn it into a list, just do new_list = list(new_iter).

Body:
I have list of numbers.
I must using function exclude negative values and the positive add to new list.

I know how to do that with for loop but when I try to add there function it does not work for me.
Could you please suggest something.

This is the code which is working but it's loop:

new_list = []
for i in data:
    if i > 0:
        new_list.append(i)

print(new_list)

This function does not work. It gives me None.

data2 = [10, 32, 454, 31, -3, 53, -31, -54, -9594, 31314, 53, 10]

def preprocessing(data):
    new_list = []
    for i in data:
        if i > 0:
            return new_list.append(i)

preprocessing(data2)

Body:
Corralien already gave good answers but I feel one is missing. To create an iterable which contains only >0 from data2:

new_iter = filter(lambda x: x > 0, data2)

Using an iterable may be advantageous in circumstances where you are later looping through the list but maybe not all of it. This way the list is only evaluated as far as you need it.

To turn it into a list, just do new_list = list(new_iter).


问:
How to call randomly selected number from contact list in flutter?
```<code>import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
import 'package:contacts_service/contacts_service.dart';

void checkContactPermission() async {
  var status = await Permission.contacts.status;
  var contacts = ContactsService.getContacts();
  var list = [contacts];
  var randomItem = (list.shuffle());
  if (status.isGranted) {
    FlutterPhoneDirectCaller.callNumber('randomItem');
  }
  if (!status.isGranted) {
    PermissionStatus permissionStatus = await Permission.contacts.request();
    if (status.isDenied) {
      PermissionStatus permissionStatus = await Permission.contacts.request();
    }
  }
}
</code>```

Here is my code to call randomly selected number from contact list yet it is calling a same number that isn't even on the contact list. What should I change?
Thanks in advance

答:
You can use the dart:math package in Flutter to generate a random number between 1 and the size of the contactList, then just call the random contact by the random index generated.

```<code>import 'dart:math';

getRandomContact(List<Contact> contactsList){
   var random = new Random();
   var randomContactIndex = random.nextInt(contactsList.length);
   return contactsList[randomContactIndex];
}
</code>```

You can call it like:

```<code>Contact randomContact = getRandomContact(contactsList);
</code>```

Body:
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
import 'package:contacts_service/contacts_service.dart';

void checkContactPermission() async {
  var status = await Permission.contacts.status;
  var contacts = ContactsService.getContacts();
  var list = [contacts];
  var randomItem = (list.shuffle());
  if (status.isGranted) {
    FlutterPhoneDirectCaller.callNumber('randomItem');
  }
  if (!status.isGranted) {
    PermissionStatus permissionStatus = await Permission.contacts.request();
    if (status.isDenied) {
      PermissionStatus permissionStatus = await Permission.contacts.request();
    }
  }
}

Here is my code to call randomly selected number from contact list yet it is calling a same number that isn't even on the contact list. What should I change?
Thanks in advance

Body:
You can use the dart:math package in Flutter to generate a random number between 1 and the size of the contactList, then just call the random contact by the random index generated.

import 'dart:math';

getRandomContact(List<Contact> contactsList){
   var random = new Random();
   var randomContactIndex = random.nextInt(contactsList.length);
   return contactsList[randomContactIndex];
}

You can call it like:

Contact randomContact = getRandomContact(contactsList);


问:
How to fix this springboot ErrorPageFilter error?
It's a simple web application use external tomcat-9.0.56 and spring 5.3, springboot 2.5.5 and up, which works on windows 10 but not on ubuntu 18. It always display 404 because of the ErrorFilterPage.
The tomcat used Context to point to the folder where the webapp was located at, also virtual host in apache 000-default.conf
I've tried set setRegisterErrorPageFilter(false); or in the application.properties as well as inject @Bean FilterRegistrationBean disableSpringBootErrorFilter with/without return new ErrorPageFilter(); in @Bean public ErrorPageFilter errorPageFilter(), no success.

I feel despair at such a framework that can not deploy to Ubuntu with delays and disappointment that cause me a lot.

It's just a simple hello: http://localhost:8080/home:
https://drive.google.com/file/d/1BiJ4-E0nPjuh1YxREpOcwN4AlzdSe3Pu/view?usp=sharing

How to fix it?!

答:
There's a typo in your application.properties file where you have configured spring.mvc.view.prefix. The value has a trailing space. It is /WEB-INF/views/  and should be /WEB-INF/views/. With this change in place, the /hello endpoint works:

```<code>$ curl localhost:8080/hello

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>SAMPLE</title>
</head>
<body>
HELLO SPRING!
</body>
</html>%
</code>```

Spring Boot intentionally does not trim whitespace from property values as there's no way for it to know whether or not the whitespace is intentional.

Body:
There's a typo in your application.properties file where you have configured spring.mvc.view.prefix. The value has a trailing space. It is /WEB-INF/views/  and should be /WEB-INF/views/. With this change in place, the /hello endpoint works:

$ curl localhost:8080/hello

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>SAMPLE</title>
</head>
<body>
HELLO SPRING!
</body>
</html>%

Spring Boot intentionally does not trim whitespace from property values as there's no way for it to know whether or not the whitespace is intentional.


问:
Uploading a file bigger than 10mb - Apache 2.4 and JBoss EAP 7 connected via Mod_JK
I am receiving a "Bad Gateway The proxy server received an invalid response from an upstream server" error while trying to upload a 20MB file.

The problem starts in pre-production when I access the page via Apache. Any file over 10MB gives the above error. The Apache and JBOSS are configured via MOD_JK.

There is nothing in the Apache Log whereas in the JBOSS log there is an error "org.apache.commons.fileupload.FileUploadException: Processing of multipart/form-data request failed. UT000020: Connection terminated as request was larger than 10485760"

If I access the JBOSS directly bypassing Apache web server, the file is uploaded successfully. I changed the maxpostsize in the JBOSS undertow subsystem which made is possible to load via JBOSS.

I wanted to know what is the equivalent of "maxpostsize" directive in Apache Web server?
There is some default configuration limiting the file upload size to 10MB in Apache.
I just want to increase that limit.

Any help would be appreciated.

Regards,

答:
Increase max-post-size (10485760 = 10MiB by default) on your listeners in the undertow subsystem to accept large file post requests. For example, setting max-post-size to 31457280 (= 30MB):

```<code><subsystem xmlns="urn:jboss:domain:undertow:3.1">
<buffer-cache name="default"/>
<server name="default-server">
    <ajp-listener name="ajp" max-post-size="31457280" socket-binding="ajp"/>
    <http-listener name="default" max-post-size="31457280" socket-binding="http" redirect-socket="https"/>
    <https-listener name="https" max-post-size="31457280" socket-binding="https" security-realm="ApplicationRealm"/>
    ...
</server>
...
</code>```

https://access.redhat.com/solutions/3084671

Body:
Increase max-post-size (10485760 = 10MiB by default) on your listeners in the undertow subsystem to accept large file post requests. For example, setting max-post-size to 31457280 (= 30MB):

<subsystem xmlns="urn:jboss:domain:undertow:3.1">
<buffer-cache name="default"/>
<server name="default-server">
    <ajp-listener name="ajp" max-post-size="31457280" socket-binding="ajp"/>
    <http-listener name="default" max-post-size="31457280" socket-binding="http" redirect-socket="https"/>
    <https-listener name="https" max-post-size="31457280" socket-binding="https" security-realm="ApplicationRealm"/>
    ...
</server>
...

https://access.redhat.com/solutions/3084671


问:
Setting Java AWS Lambda VM Parameters
Is there a way I can configure VM parameters on a Java AWS Lambda? I've already searched the AWS Lambda docs and blogs, and have found no way to configure the underlying system whatsoever.</p>

答: You can provide VM parameters via a wrapper script (see AWS Lambda Developer Guide - Wrapper scripts). The following blog shows how to do this for the -XX:+TieredCompilation -XX:TieredStopAtLevel=1 flags.

Title: Setting Java AWS Lambda VM Parameters


问:
Vue PWA: Use ServiceWorker to cache remote media assets from array of URLs
I am building a PWA where I would like to optionally download and cache ALL media assets used throughout the application, if the user wants to. The default PWA behaviour only caches the assets when they are requested navigating around the app. I need to offer the functionality to press the button, download the assets, go offline and use the entire app and have all the assets cached witout necessarily visiting the various routes and views while online.

For context, when the app loads, Vuex grabs the JSON content from my API, puts it in state, and saves to IndexedDB.

If the user clicks the 'download everything' button, I want to parse the JSON in $store.state, collect the URLs (images, PDFs and MP4s) into an array and pass that array to the ServiceWorker to deliberately cache all the assets at those URLs for offline use (up to the allowed origin storage limit).

I'm using Vue CLI and the Vue PWA plugin, so I have the registerServiceWorker.js file and precache manifest is generated for production.

I find the info on the internet about this slightly confusing I was thinking to use the approach outlined by https://developers.google.com/web/ilt/pwa/lab-caching-files-with-service-worker but I'm not sure about some of the specifics, and also unsure about how to tackle this in a way that fits in nicely with Vue CLI workflow?

If possible, can you include the following questions in your answer:

Do I use GenerateSW or InjectManifest?

Do I need to write my own Service Worker, or can I hook into the lifecycle methods (registered(), cached(), updated()) in registerServiceWorker.js?

Thank you in advance for your help.

答:
I found a way to cache remote files on Vue 3, Vue CLI PWA app.

Set up the vue.conig.js on the root directory as shown below

# vue.config.js
module.exports = {
  // ...other vue-cli plugin options...
  pwa: {
    name: "my-pwa-app",
    themeColor: "#624040",
    msTileColor: "#000000",
    // configure the workbox plugin
    workboxPluginMode: "InjectManifest",
    workboxOptions: {
      // swSrc is required in InjectManifest mode.
      swSrc: "service-worker.js", //path to your own service-worker file
      // ...other Workbox options...
    },
  },
};```
</div>
</div>
</p>
<ol start="2">
<li>Create the <code>service-worker.js</code> with starter code below, add other functionalities you need for caching</li>
</ol>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code># service-worker.js
// workbox functions from the workbox CDN (version 4.3.1)
// Vue 3 PWA automatically adds the CDN
const { precacheAndRoute } = workbox.precaching;
const { registerRoute } = workbox.routing;
const { CacheFirst, StaleWhileRevalidate } = workbox.strategies;
const { Plugin: ExpirationPlugin } = workbox.expiration;
const { Plugin: CacheableResponsePlugin } = workbox.cacheableResponse;

workbox.core.setCacheNameDetails({ prefix: "appname" });

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
precacheAndRoute(self.__precacheManifest, {});

// cache image and render from the cache if it exists or go t the network
registerRoute(
  ({ request }) => request.destination === "image",
  new CacheFirst({
    cacheName: "images",
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 2 * 24 * 60 * 60, // cache the images for only 2 Days
      }),
    ],
  })
);

// cache API response and serve from cache if exists or go to the network
registerRoute(
  ({ url }) => url.pathname.startsWith("https://dog.ceo/api/"),
  new StaleWhileRevalidate()
);</code>```

VueJs takes the service-worker.js and adds its import for the precaching of the files from the /dist folder

Documentation for Workbox could be found here

Notes on workbox 4.3.1 I found useful here

Body:
I found a way to cache remote files on Vue 3, Vue CLI PWA app.

Set up the vue.conig.js on the root directory as shown below

# vue.config.js
module.exports = {
  // ...other vue-cli plugin options...
  pwa: {
    name: "my-pwa-app",
    themeColor: "#624040",
    msTileColor: "#000000",
    // configure the workbox plugin
    workboxPluginMode: "InjectManifest",
    workboxOptions: {
      // swSrc is required in InjectManifest mode.
      swSrc: "service-worker.js", //path to your own service-worker file
      // ...other Workbox options...
    },
  },
};

Create the service-worker.js with starter code below, add other functionalities you need for caching

# service-worker.js
// workbox functions from the workbox CDN (version 4.3.1)
// Vue 3 PWA automatically adds the CDN
const { precacheAndRoute } = workbox.precaching;
const { registerRoute } = workbox.routing;
const { CacheFirst, StaleWhileRevalidate } = workbox.strategies;
const { Plugin: ExpirationPlugin } = workbox.expiration;
const { Plugin: CacheableResponsePlugin } = workbox.cacheableResponse;

workbox.core.setCacheNameDetails({ prefix: "appname" });

self.addEventListener("message", (event) => {
  if (event.data && event.data.type === "SKIP_WAITING") {
    self.skipWaiting();
  }
});

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
precacheAndRoute(self.__precacheManifest, {});

// cache image and render from the cache if it exists or go t the network
registerRoute(
  ({ request }) => request.destination === "image",
  new CacheFirst({
    cacheName: "images",
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 2 * 24 * 60 * 60, // cache the images for only 2 Days
      }),
    ],
  })
);

// cache API response and serve from cache if exists or go to the network
registerRoute(
  ({ url }) => url.pathname.startsWith("https://dog.ceo/api/"),
  new StaleWhileRevalidate()
);

VueJs takes the service-worker.js and adds its import for the precaching of the files from the /dist folder

Documentation for Workbox could be found here

Notes on workbox 4.3.1 I found useful here


问:
How to find all Event IDs in an efficient way?
How could I crawl this database with rvest to identify all tournament IDs for each year? Currently, I'm just going from 1:maxx(event_id), which is really a drain on compute time.

```<code>https://www.worldloppet.com/results/
</code>```

The results filter seems to be dynamic on the webpage, so the url doesn't change.

```<code>outlist <- list()

for (event_id in 2483:2570) {
  event_id = 2483
  # update progress
  message('Retrieving Event ',event_id)

  race_url = paste0('https://www.worldloppet.com/browse/?id=',event_id)

  event_info = read_html(race_url) %>%
    html_nodes('h2') %>%
    .[1] %>%
    gsub('<br>','<br>  ',.) %>%
    gsub("<[^>]+>", "",.) %>%
    str_split(.,'  ') %>%
    unlist()

  #event_info$eventid <- event_id

  outlist <- c(outlist, list(c(event_id, event_info)))

  # temporary break
  Sys.sleep(3)

}
</code>```

答:
You can extract all links containing the word browse from the HTML document:

library(tidyverse)
library(rvest)
#>
#> Attaching package: 'rvest'
#> The following object is masked from 'package:readr':
#>
#>     guess_encoding

read_html("https://www.worldloppet.com/results/") %>%
  html_nodes("a") %>%
  html_attr("href") %>%
  as.character() %>%
  keep(~ .x %>% str_detect("browse")) %>%
  paste0("https://www.worldloppet.com",.)
#>  [1] "https://www.worldloppet.com/browse/?id=2570"
#>  [2] "https://www.worldloppet.com/browse/?id=1818"
#>  [3] "https://www.worldloppet.com/browse/?id=1817"
#>  [4] "https://www.worldloppet.com/browse/?id=2518"
#>  [5] "https://www.worldloppet.com/browse/?id=2517"
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
How could I crawl this database with rvest to identify all tournament IDs for each year? Currently, I'm just going from 1:maxx(event_id), which is really a drain on compute time.

https://www.worldloppet.com/results/

The results filter seems to be dynamic on the webpage, so the url doesn't change.

outlist <- list()

for (event_id in 2483:2570) {
  event_id = 2483
  # update progress
  message('Retrieving Event ',event_id)

  race_url = paste0('https://www.worldloppet.com/browse/?id=',event_id)

  event_info = read_html(race_url) %>%
    html_nodes('h2') %>%
    .[1] %>%
    gsub('
','
  ',.) %>%
    gsub("<[^>]+>", "",.) %>%
    str_split(.,'  ') %>%
    unlist()

  #event_info$eventid <- event_id

  outlist <- c(outlist, list(c(event_id, event_info)))

  # temporary break
  Sys.sleep(3)

}

Body:
You can extract all links containing the word browse from the HTML document:

library(tidyverse)
library(rvest)
#>
#> Attaching package: 'rvest'
#> The following object is masked from 'package:readr':
#>
#>     guess_encoding

read_html("https://www.worldloppet.com/results/") %>%
  html_nodes("a") %>%
  html_attr("href") %>%
  as.character() %>%
  keep(~ .x %>% str_detect("browse")) %>%
  paste0("https://www.worldloppet.com",.)
#>  [1] "https://www.worldloppet.com/browse/?id=2570"
#>  [2] "https://www.worldloppet.com/browse/?id=1818"
#>  [3] "https://www.worldloppet.com/browse/?id=1817"
#>  [4] "https://www.worldloppet.com/browse/?id=2518"
#>  [5] "https://www.worldloppet.com/browse/?id=2517"

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
AutoCompletion KMM
I have been working on a KMM project for 2 months, and I never had any problem.
This thursday morning, I see that my Android Studio doesn't detect the shared module of KMM anymore, but only in the IDE, because it always compiles correctly.
After having Clean, Rebuild, Invalid Caches/Restart, I can't find the autoCompletion.
I try a lot of change on Android Studio but nothing work.

Has anyone ever had this problem?

答:
Yes, I've been having this a couple of times. Usually for multi module KMM projects.

In most cases updating either Android Studio, Kotlin version or Gradle/AGP versions, but also switching from Android Studio to IntellIJ in some cases solved the issue for me.

Could you make sure you are using latest versions?

Title: AutoCompletion KMM


问:
Unhandled Exception: type 'int' is not a subtype of type 'String?' when doing writeStorage
I am facing a little weird error for me

Unhandled Exception: type 'int' is not a subtype of type 'String?'

when

await storage.writeData('id', jsonDecode(request2.body)['data']['id']);

I printed that parameter it gives me 199 but I have no idea where is problem here?
I can't save int as a value for map? It makes no sense. Btw. I have identical line in other part of code and there is working without any errors so I am clueless at this point

答: You can follow this code Snippet what exactly do you need if i am not wrong it will help you.</p>


问:
How to implement something like Terracota?
How Terracotta knows that object is changed inside one JVM to propagate this change to another JVM? I.e. how can I code similar behavior?

I want to be able to watch changes in instances of some classes, without changing them at all.

答: It uses instrumentation. It's explained (in high level) in the terracotta wiki</p>


答:
The IDs of the rage can be found in the links, which can be extracted using the html_attr function. From there we can use some regex to find the numbers, here I include id= to make sure the page is an id, as I'm not sure whether you want to include links like masters=9173.

```<code>library(rvest)
library(stringi)
url <- "https://www.worldloppet.com/results/"
page <- read_html(url)
string <- html_attr(html_elements(page, "a"), "href")

matches <- stri_extract_all_regex(string, "(?<=id=).*", simplify = T)
as.integer(matches[!is.na(matches)])

# first 5
[1] 2570 1818 1817 2518 2517
</code>```

Title: How to find all Event IDs in an efficient way?

Body:
The IDs of the rage can be found in the links, which can be extracted using the html_attr function. From there we can use some regex to find the numbers, here I include id= to make sure the page is an id, as I'm not sure whether you want to include links like masters=9173.

library(rvest)
library(stringi)
url <- "https://www.worldloppet.com/results/"
page <- read_html(url)
string <- html_attr(html_elements(page, "a"), "href")

matches <- stri_extract_all_regex(string, "(?<=id=).*", simplify = T)
as.integer(matches[!is.na(matches)])

# first 5
[1] 2570 1818 1817 2518 2517


问:
Is there any API access to Google Translate's "Did you mean" functionality?
I'd like to fully use Google Translate as an API, and of course their official Cloud Translation service basically does this. But recently I noticed one small difference: in the browser, Google TL may detect typos / small errors and automatically correct them and translate the correction.

For example:

As you can see, it says "Showing translation for "testing" rather than testin. So there's a step here where it automatically detects the mistake and chooses to translate its own corrected version instead (thus resulting in a correct translation).

If you click the "Translate instead", here's the result:

Google's Cloud Translation API shows the second result (i.e. "testin" instead of "tester"). I've done some searching and can't find this "did you mean" corrective functionality anywhere in Google Cloud, do they not provide it? I know I can build my own spellchecker and try it that way, but what I'm looking for specifically here is to just fully mimic Google Translate's behavior for a typical user.

答:
```<code>from googletrans import Translator

translator = Translator()
result= translator.translate("testin if this works",src="en", dest='fr')
result.extra_data['possible-mistakes']
</code>```

Output:
['testing if this works',
'testing if this works',
[1],
None,
None,
False]

Body:
from googletrans import Translator

translator = Translator()
result= translator.translate("testin if this works",src="en", dest='fr')
result.extra_data['possible-mistakes']

Output:
['testing if this works',
'testing if this works',
[1],
None,
None,
False]


问:
Why cant I see Java project view in VS Code?
So I'm trying to add jar files to a java project.

I've been told the following:

If you want a more beginner-friendly way of adding libraries, you can
also use the Project Manager for Java extension, which is included in
the Java Extension Pack. With it, you can click the + icon on
Referenced Libraries in the JAVA PROJECTS view, as shown in this
example. A quick tip if you need to add many libraries from a folder
is to Shift or Alt + click the + icon, which will let you select an
entire folder containing multiple .jar files.

After installing Project manager extension and creating a new Java project in VS code, I get to this screen.

As mentioned by VS code, I should be able to see the project view tab after creating my java project. The issue is I don't see the project view tab as shown in the image above. VS code says I should see the 3 dots by the explorer subheading to enable it, but again, I don't have these 3 dots as shown in the first image.

I have both project manager and the extension pack installed, so I really don't understand why I cant see or enable project view.

Any suggestions on enabling project view?

答:
Have you tried to open a java file? Because the extension activated depends on the opened filename extension.

You can refer to here.

If it still does not work, could you provide the OS and the versions of the
VSCode and extensions?


问:
Cannot convert input [00:00:00.020000] of type <class 'datetime.time'> to Timestamp
My input data has a high resolution of datetime with seconds in fraction. For example, it should be
1900-01-01 17:40:14.410000 instead of 1900-01-01 17:40:14.

Apparently this format has not been recognized by the pandas or python. How should I successfully convert this to pandas recognized time stamp style.

Body:
IIUC, you want a custom format:

pd.to_datetime('[00:00:00.020000]', format='[%H:%M:%S.%f]')

or, automagically:

pd.to_datetime('[00:00:00.020000]'.strip('[]'))

output: Timestamp('2022-02-09 00:00:00.020000')

As series:

s = pd.Series(['[00:00:00.020000]'])
pd.to_datetime(s.str.strip('[]'))

output:

0   2022-02-09 00:00:00.020
dtype: datetime64[ns]


问:
AWS GLUE Not able to write Delta lake in s3
I am working on AWS Glue and created an ETL job for upserts. I have a s3 bucket where I have my csv file in a folder. I am reading the file from s3 and want to write back to s3 using delta lake (parquet file) using this code

```<code>from delta import *
from pyspark.sql.session import SparkSession

spark = SparkSession.builder \
    .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
    .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
    .getOrCreate()
inputDF = spark.read.format("csv").option("header", "true").load('s3://demonidhi/superstore/')
print(inputDF)
# Write data as DELTA TABLE
inputDF.write.format("delta").mode("overwrite").save("s3a://demonidhi/current/")

# Generate MANIFEST file for Athena/Catalog
deltaTable = DeltaTable.forPath(spark, "s3a://demonidhi/current/")
</code>```

I am using a jar file of delta named 'delta-core_2.11-0.6.1.jar' which is in s3 bucket folder and i gave the path of it in python libraby path and in Dependent jars path while creating my job.
Till the reading part the code is working just fine but after that for the writing and manifesting it is not working and giving some error which I am not able to see in GLUE terminal. I tried to follow several different approaches, but not able to figure out how can i resolve this. Any help would be appericiated.

答:
Using the spark.config() notation will not work in Glue, because the abstraction that Glue is using (the GlueContext), will override those parameters.

What you can do instead is provide the config as a parameter to the job itself, with the key --conf and the value spark.delta.logStore.class=org.apache.spark.sql.delta.storage.S3SingleDriverLogStore --conf spark.sql.extensions=io.delta.sql.DeltaSparkSessionExtension --conf spark.sql.catalog.spark_catalog=org.apache.spark.sql.delta.catalog.DeltaCatalog

Body:
I am working on AWS Glue and created an ETL job for upserts. I have a s3 bucket where I have my csv file in a folder. I am reading the file from s3 and want to write back to s3 using delta lake (parquet file) using this code

from delta import *
from pyspark.sql.session import SparkSession

spark = SparkSession.builder \
    .config("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension") \
    .config("spark.sql.catalog.spark_catalog", "org.apache.spark.sql.delta.catalog.DeltaCatalog") \
    .getOrCreate()
inputDF = spark.read.format("csv").option("header", "true").load('s3://demonidhi/superstore/')
print(inputDF)
# Write data as DELTA TABLE
inputDF.write.format("delta").mode("overwrite").save("s3a://demonidhi/current/")

# Generate MANIFEST file for Athena/Catalog
deltaTable = DeltaTable.forPath(spark, "s3a://demonidhi/current/")

I am using a jar file of delta named 'delta-core_2.11-0.6.1.jar' which is in s3 bucket folder and i gave the path of it in python libraby path and in Dependent jars path while creating my job.
Till the reading part the code is working just fine but after that for the writing and manifesting it is not working and giving some error which I am not able to see in GLUE terminal. I tried to follow several different approaches, but not able to figure out how can i resolve this. Any help would be appericiated.


问:
Multiline starred jsdoc-like comments in VS Code
I want to comment out my code in this style

```<code>/**
 * This is
 * A multiline comment
 */
</code>```

Is it possible to do with a shortcut?

EDIT 1:

https://github.com/Microsoft/vscode/issues/50301 Address this issue, however it does not work with a shortcut. I want to be able to select a block of code and comment it out in the style above

答:
The shortcut is shift + alt + a (windows),
shift + option + a (mac)</p>

Body:
I want to comment out my code in this style

/**
 * This is
 * A multiline comment
 */

Is it possible to do with a shortcut?

EDIT 1:

https://github.com/Microsoft/vscode/issues/50301 Address this issue, however it does not work with a shortcut. I want to be able to select a block of code and comment it out in the style above


问:
Kubernetes NGINX Ingress configmap 301 redirect
Using an NGINX Ingresss in Kubernetes, I can't see a way to forward my traffic from non-www to www, or to another domain etc on a per-host basis

I've tried looking in configmap docs but can't see what I need. Maybe it can go in the ingress itself?

I've also seen an example using annotations but this seems to be ingress-wide, so I couldn't have specific redirects per host

答:
I have problem with annotations server-snippet. When the certificate is renewed, the process crashes. When I remove annotations, renewed certificate is successful. Is there another solution? For example, creating a redirect 301 in separate pod?</p>
```<code>    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      annotations:
        cert-manager.io/cluster-issuer: letsencrypt-prod
        certmanager.k8s.io/cluster-issuer: letsencrypt-prod
        ingress.kubernetes.io/ssl-redirect: "true"
        meta.helm.sh/release-name: DOMAIN
        meta.helm.sh/release-namespace: DOMAIN
        nginx.ingress.kubernetes.io/configuration-snippet: |
          location ~ ^/online-web {
            return 301 /online;
          }
          if ($host = 'DOMAIN-alias.cz') {
            return 301 https://DOMAIN.cz;
          }
          if ($host ~ ^(.+)\.DOMAIN-alias\.cz$) {
            return 301 https://$1.DOMAIN.cz$request_uri;
          }
          if ($host = 'DOMAIN-alias-2.cz') {
            return 301 https://DOMAIN.cz;
          }
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
    nginx.ingress.kubernetes.io/server-snippet: |
      if ($host ~ "csas.woltair.cz") {
          return 301 https://woltair.cz/zakaznik/doporuceni;
      }
............
............
  - host: csas.woltair.cz
    http:
      paths:
      - backend:
          service:
            name: woltair-cz-fe
            port:
              number: 8080
        path: /zakaznik/doporuceni
        pathType: ImplementationSpecific
</code>```

Body:
I have problem with annotations server-snippet. When the certificate is renewed, the process crashes. When I remove annotations, renewed certificate is successful. Is there another solution? For example, creating a redirect 301 in separate pod?

    apiVersion: networking.k8s.io/v1
    kind: Ingress
    metadata:
      annotations:
        cert-manager.io/cluster-issuer: letsencrypt-prod
        certmanager.k8s.io/cluster-issuer: letsencrypt-prod
        ingress.kubernetes.io/ssl-redirect: "true"
        meta.helm.sh/release-name: DOMAIN
        meta.helm.sh/release-namespace: DOMAIN
        nginx.ingress.kubernetes.io/configuration-snippet: |
          location ~ ^/online-web {
            return 301 /online;
          }
          if ($host = 'DOMAIN-alias.cz') {
            return 301 https://DOMAIN.cz;
          }
          if ($host ~ ^(.+)\.DOMAIN-alias\.cz$) {
            return 301 https://$1.DOMAIN.cz$request_uri;
          }
          if ($host = 'DOMAIN-alias-2.cz') {
            return 301 https://DOMAIN.cz;
          }
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
    nginx.ingress.kubernetes.io/server-snippet: |
      if ($host ~ "csas.woltair.cz") {
          return 301 https://woltair.cz/zakaznik/doporuceni;
      }
............
............
  - host: csas.woltair.cz
    http:
      paths:
      - backend:
          service:
            name: woltair-cz-fe
            port:
              number: 8080
        path: /zakaznik/doporuceni
        pathType: ImplementationSpecific


问:
Unable to unload BPF program
I am unable to unload a BPF program from code. I am using the Cilium eBPF library to load the program and netlink to add the BPF function to an interface. Here's what I'm doing:

```<code>type BpfObjects struct {
    CollectIpsProg *ebpf.Program        `ebpf:"collect_ips_prog"`
}

    var objects BpfObjects

    // Load the BPF program
    spec, err := ebpf.LoadCollectionSpec("collect_ips.o")

    if err != nil {
        log.Fatalln("ebpf.LoadCollectionSpec", err)
    }

    if err := spec.LoadAndAssign(objects, nil); err != nil {
        log.Fatalln("ebpf.LoadAndAssign", err)
    }

    // Load to XDP
    link, err := netlink.LinkByName("enp0s8")

    if err != nil {
        log.Fatalln("netlink.LinkByName", err)
    }

    err = netlink.LinkSetXdpFdWithFlags(link, objects.CollectIpsProg.FD(), 2)

    if err != nil {
        log.Fatalln("netlink.LinkSetXdpFdWithFlags:", err)
    }
    ...

    // Cleanup. This does not unload the BPF program
    objects.CollectIpsProg.Close()
    objects.CollectIpsProg.Unpin()
</code>```

Even though I am closing the program, bpftool prog and  xdp-loader status still show the BPF program. I can unload the program using bpftool or xdp-loader.

答:
eBPF programs only unload when there are no more references to it(File descriptors, pins), but network links also hold their own references. So to unload the program, you first have to detach it from your network link.

You can do so by setting the program fd to -1:

err = netlink.LinkSetXdpFd(link, -1)
if err != nil {
    log.Fatalln("netlink.LinkSetXdpFd:", err)
}
```

Title: Unable to unload BPF program

Body:
I am unable to unload a BPF program from code. I am using the Cilium eBPF library to load the program and netlink to add the BPF function to an interface. Here's what I'm doing:

type BpfObjects struct {
    CollectIpsProg *ebpf.Program        `ebpf:"collect_ips_prog"`
}

    var objects BpfObjects

    // Load the BPF program
    spec, err := ebpf.LoadCollectionSpec("collect_ips.o")

    if err != nil {
        log.Fatalln("ebpf.LoadCollectionSpec", err)
    }

    if err := spec.LoadAndAssign(objects, nil); err != nil {
        log.Fatalln("ebpf.LoadAndAssign", err)
    }

    // Load to XDP
    link, err := netlink.LinkByName("enp0s8")

    if err != nil {
        log.Fatalln("netlink.LinkByName", err)
    }

    err = netlink.LinkSetXdpFdWithFlags(link, objects.CollectIpsProg.FD(), 2)

    if err != nil {
        log.Fatalln("netlink.LinkSetXdpFdWithFlags:", err)
    }
    ...

    // Cleanup. This does not unload the BPF program
    objects.CollectIpsProg.Close()
    objects.CollectIpsProg.Unpin()

Even though I am closing the program, bpftool prog and  xdp-loader status still show the BPF program. I can unload the program using bpftool or xdp-loader.


问:
Load local files to AWS stage in Snowflake using Python
I am planning to ingest data from local system to snowflake table using the Amazon s3 internal stage. How can I load the data to the s3 stage using python ? Previously for loading the data to snowflake I was using snowflake's internal staging and using the below command to perform the operation.

```<code>put file://<local_file_location> @<creating_stage_snowflake> auto_compress=true
copy into <table_name> from @<creating_stage_snowflake>/<file_name>.gz file_format = (TYPE=CSV FIELD_DELIMITER='~' error_on_column_count_mismatch=false, ENCODING = 'UTF-8')
</code>```

What should be the approach to load the data from local system to amazon s3 and then copying these files from the staged table to the snowflake table using python.

Please share your inputs.

答:
I use the Snowsql tool with a command line, that refers to a small sql script that I created in my code. Its not very elegant, but it does the job. You can hide the connection info for snowsql in the .snowsql\config file.
This works well for individual programs, but is probably not the best solution for a multi process web service.</p>

Body:
I am planning to ingest data from local system to snowflake table using the Amazon s3 internal stage. How can I load the data to the s3 stage using python ? Previously for loading the data to snowflake I was using snowflake's internal staging and using the below command to perform the operation.

put file://<local_file_location> @<creating_stage_snowflake> auto_compress=true
copy into <table_name> from @<creating_stage_snowflake>/<file_name>.gz file_format = (TYPE=CSV FIELD_DELIMITER='~' error_on_column_count_mismatch=false, ENCODING = 'UTF-8')

What should be the approach to load the data from local system to amazon s3 and then copying these files from the staged table to the snowflake table using python.

Please share your inputs.


答:
Convert column or scalar to strings:

```<code>t = datetime.time(17, 40, 14, 410000)
print (pd.to_datetime(str(t)))
2022-02-09 17:40:14.410000
</code>```

If column:

```<code>pd.to_datetime(df['col'].astype(str))
</code>```

Title: Cannot convert input [00:00:00.020000] of type <class 'datetime.time'> to Timestamp

Body:
My input data has a high resolution of datetime with seconds in fraction. For example, it should be
1900-01-01 17:40:14.410000 instead of 1900-01-01 17:40:14.

Apparently this format has not been recognized by the pandas or python. How should I successfully convert this to pandas recognized time stamp style.

Body:
Convert column or scalar to strings:

t = datetime.time(17, 40, 14, 410000)
print (pd.to_datetime(str(t)))
2022-02-09 17:40:14.410000

If column:

pd.to_datetime(df['col'].astype(str))


问:
How to stop a for loop inside an ExecutorService?
I've tried looking on other threads and I can't seem to find a proper answer,

When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.
I have no idea why it happens, but the most I've seen from other threads is that you should be using Thread.currentThread().isInterrupted() to check if it is interrupted, but adding a

```<code>if(Thread.currentThread().isInterrupted())
    {return;}
</code>```

Doesn't actually stop it all.  I'm calling executor shutdownNow when a UI button is toggled off.

Code example:

```<code>executorService.submit(() -> {
            ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
            //Shit keeps going if you call ShutdownNow Todo
            for (Rectangle rect : rects)
            {
                ctx.batzUtils.click(rect);
                try
                {
                    Thread.sleep(minDelayBetween, maxDelayBetween);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
            ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
        });
</code>```

Any ideas as to why or solutions would be greatly appreciated

答:
Adding  Thread.currentThread().interrupt() in my catch statement worked

Credit To @Sambit

Body:
I've tried looking on other threads and I can't seem to find a proper answer,

When using executorService.shutdownNow() almost all tasks stop immediately as intended except ones with for loops in them.
I have no idea why it happens, but the most I've seen from other threads is that you should be using Thread.currentThread().isInterrupted() to check if it is interrupted, but adding a

if(Thread.currentThread().isInterrupted())
    {return;}

Doesn't actually stop it all.  I'm calling executor shutdownNow when a UI button is toggled off.

Code example:

executorService.submit(() -> {
            ctx.batzUtils.keyEvent(KeyEvent.KEY_PRESSED, VK_SHIFT);
            //Shit keeps going if you call ShutdownNow Todo
            for (Rectangle rect : rects)
            {
                ctx.batzUtils.click(rect);
                try
                {
                    Thread.sleep(minDelayBetween, maxDelayBetween);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
            ctx.batzUtils.keyEvent(KeyEvent.KEY_RELEASED, VK_SHIFT);
            ctx.batzUtils.keyEvent(KeyEvent.KEY_TYPED, VK_SHIFT);
        });

Any ideas as to why or solutions would be greatly appreciated


问:
Add multiple primary keys to a table
I have a table with a primary key available; I want to add another one in primary but can't add it.

SRNO
TRNDATE
RATE
AMT

1
08-02-2022
120
120

2
09-02-2022
170
170

3
10-02-2022
180
180

I want to add column Trndate to the primary key.

When I was try to add in primary following code

```<code>ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (srno, trndate);
</code>```

I get an error:

Msg 1779, Level 16, State 0, Line 1

Table 'avgEnt' already has a primary key defined on it.

Msg 1750, Level 16, State 0, Line 1

Could not create constraint or index. See previous errors.

When I open the design of table and add primary key (SRNO, TRNDATE) then it works fine.

When I was trying to add by using the query, it does not work.

What happened when design windows save that time script i want.

My database version is SQL Server 2014.

答:
I find one solution.

```<code>select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='avgEnt'
and type_desc LIKE '%CONSTRAINT'
</code>```

Find constraint of table PK_avgent

After drop primary on table

```<code>-- drop current primary key constraint
ALTER TABLE dbo.avgEnt
DROP CONSTRAINT PK_avgent;
GO
</code>```

After add two column

```<code>-- create new primary key constraint
ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (SrNo, TrnDate);
GO
</code>```

it is work form me.

Title: Add multiple primary keys to a table

Body:
I have a table with a primary key available; I want to add another one in primary but can't add it.

SRNO
TRNDATE
RATE
AMT

1
08-02-2022
120
120

2
09-02-2022
170
170

3
10-02-2022
180
180

I want to add column Trndate to the primary key.

When I was try to add in primary following code

ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (srno, trndate);

I get an error:

Msg 1779, Level 16, State 0, Line 1

Table 'avgEnt' already has a primary key defined on it.

Msg 1750, Level 16, State 0, Line 1

Could not create constraint or index. See previous errors.

When I open the design of table and add primary key (SRNO, TRNDATE) then it works fine.

When I was trying to add by using the query, it does not work.

What happened when design windows save that time script i want.

My database version is SQL Server 2014.

Body:
I find one solution.

select OBJECT_NAME(OBJECT_ID) AS NameofConstraint
FROM sys.objects
where OBJECT_NAME(parent_object_id)='avgEnt'
and type_desc LIKE '%CONSTRAINT'

Find constraint of table PK_avgent

After drop primary on table

-- drop current primary key constraint
ALTER TABLE dbo.avgEnt
DROP CONSTRAINT PK_avgent;
GO

After add two column

-- create new primary key constraint
ALTER TABLE dbo.avgEnt
ADD CONSTRAINT PK_avgent PRIMARY KEY NONCLUSTERED (SrNo, TrnDate);
GO

it is work form me.


问:
How to keep additional URL parameters with Algolia search and pagination
I have some filters predefined and a query parameters in my URL. I need to add some other parameter to the URL to keep track of the source of the user and some other purposes. But, whenever I do a new refinement or entered into a new page(pagination). The additional parameters got deleted. How can I preserve that parameters till I go to any other routes?</p>

答:
In order to preserve your existing url parameters, you have to create your own URL in the router.history.

For that, grab the current location.search and merge in the routeState when you search or remove the routeState object when you exit the search.

I hope the following code helps and if someone has any correction, I'm happy to hear them.

const algoliaAppId = 'APP_ID';
const algoliaApiKey = 'API_KEY';
const algoliaIndex = 'instant_search';

const search = instantsearch({
  indexName: algoliaIndex,
  algoliasearch(algoliaAppId, algoliaApiKey),
  routing: {
    router: instantsearch.routers.history({

      createURL({ qsModule, location, routeState }) {
        // current search params
        const indexState = routeState[algoliaIndex] || {};
        const { origin, pathname, hash, search } = location;
        // grab current query string and convert to object
        const queryParameters = qsModule.parse(search.slice(1)) || {};

        // if there is an active search
        if (Object.keys(indexState).length ){
          // merge the search params with the current query params
          Object.assign(queryParameters, routeState);
        }else{
          // remove the search params
          delete queryParameters[algoliaIndex];
        }

        let queryString = qsModule.stringify(queryParameters);

        if(queryString.length){
          queryString = `?${queryString}`;
        }

        return `${origin}${pathname}${queryString}${hash}`;
      },

    })
  }

});

search.start();
```


问:
How to access smart contract functions from React JS?
I am making lottery contract , but as I try to access my method of manager I get this error in ReactJS.
[![enter image description here][1]][1]
Please help me with the solution. I have developed my contract I am having problems with connecting it to the frontend.

This is the error .
[1]: https://i.stack.imgur.com/QFc2o.png

App.js File

import detectEthereumProvider from "@metamask/detect-provider";
// import { loadContract } from "./utils/LoadContracts";
import Web3 from "web3";
import lottery from "./lottery";
import {
  useEffect,
  useState
} from "react";

function App() {
  const [balance, setBalance] = useState("");
  const [changedAccount, setChangedAccount] = useState([]);

  const loader = async() => {
    let provider = await detectEthereumProvider();
    let web3 = new Web3(provider);
    return {
      provider,
      web3
    };
  };

  useEffect(async() => {
    let newLoad = await loader();
    let account = await newLoad.web3.eth.getAccounts();
    setChangedAccount(account);
  }, []);

  useEffect(async() => {
    let newLoad = await loader();
    newLoad.provider.on("accountsChanged", function(accounts) {
      let newAccount = accounts;
      if (newAccount) {
        setChangedAccount(newAccount);
      }
    });
  }, []);

  useEffect(async() => {
    let newLoad = await loader();
    let accountBal =
      changedAccount.length > 0 &&
      (await newLoad.web3.eth.getBalance(changedAccount[0]));
    setBalance(accountBal);
  }, [changedAccount]);

  useEffect(async() => {
    let newLoad = await loader();
    let account = await newLoad.web3.eth.getAccounts();
    setChangedAccount(account);
    const manager = await lottery.methods.manager().call();
  }, []);
  return (

    Account address {
      changedAccount[0]
    }, Its balance is: {
      balance
    } <
    /p> <
    /div>
  );
}

export default App;```
</div>
</div>
</p>
<blockquote>
<p>lottery.js (containing ABI and contract Address)</p>
</blockquote>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import Web3 from "web3";
let web3 = new Web3();
const address = "0xBEbdb8eC68A5803d0f5E93bACe9EB9E4227f5A20";
const abi = [{
    inputs: [],
    stateMutability: "nonpayable",
    type: "constructor"
  },
  {
    inputs: [],
    name: "manager",
    outputs: [{
      internalType: "address",
      name: "",
      type: "address"
    }],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [{
      internalType: "uint256",
      name: "",
      type: "uint256"
    }],
    name: "players",
    outputs: [{
      internalType: "address",
      name: "",
      type: "address"
    }],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [],
    name: "enter",
    outputs: [],
    stateMutability: "payable",
    type: "function",
  },
  {
    inputs: [],
    name: "getBalance",
    outputs: [{
      internalType: "uint256",
      name: "",
      type: "uint256"
    }],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [],
    name: "pickWinner",
    outputs: [],
    stateMutability: "nonpayable",
    type: "function",
  },
  {
    inputs: [],
    name: "getPlayers",
    outputs: [{
      internalType: "address[]",
      name: "",
      type: "address[]"
    }],
    stateMutability: "view",
    type: "function",
  },
];

export default new web3.eth.Contract(abi, address);</code>```

答:
You have not provided any 'provider' in lottery.js on this line

```<code>let web3 = new Web3();
</code>```

which isn't giving you correct contract instance and thus you cannot access it's methods

Body:
I am making lottery contract , but as I try to access my method of manager I get this error in ReactJS.
[![enter image description here][1]][1]
Please help me with the solution. I have developed my contract I am having problems with connecting it to the frontend.

This is the error .
[1]: https://i.stack.imgur.com/QFc2o.png

App.js File

import detectEthereumProvider from "@metamask/detect-provider";
// import { loadContract } from "./utils/LoadContracts";
import Web3 from "web3";
import lottery from "./lottery";
import {
  useEffect,
  useState
} from "react";

function App() {
  const [balance, setBalance] = useState("");
  const [changedAccount, setChangedAccount] = useState([]);

  const loader = async() => {
    let provider = await detectEthereumProvider();
    let web3 = new Web3(provider);
    return {
      provider,
      web3
    };
  };

  useEffect(async() => {
    let newLoad = await loader();
    let account = await newLoad.web3.eth.getAccounts();
    setChangedAccount(account);
  }, []);

  useEffect(async() => {
    let newLoad = await loader();
    newLoad.provider.on("accountsChanged", function(accounts) {
      let newAccount = accounts;
      if (newAccount) {
        setChangedAccount(newAccount);
      }
    });
  }, []);

  useEffect(async() => {
    let newLoad = await loader();
    let accountBal =
      changedAccount.length > 0 &&
      (await newLoad.web3.eth.getBalance(changedAccount[0]));
    setBalance(accountBal);
  }, [changedAccount]);

  useEffect(async() => {
    let newLoad = await loader();
    let account = await newLoad.web3.eth.getAccounts();
    setChangedAccount(account);
    const manager = await lottery.methods.manager().call();
  }, []);
  return (

    Account address {
      changedAccount[0]
    }, Its balance is: {
      balance
    } <
    /p> <
    /div>
  );
}

export default App;

lottery.js (containing ABI and contract Address)

import Web3 from "web3";
let web3 = new Web3();
const address = "0xBEbdb8eC68A5803d0f5E93bACe9EB9E4227f5A20";
const abi = [{
    inputs: [],
    stateMutability: "nonpayable",
    type: "constructor"
  },
  {
    inputs: [],
    name: "manager",
    outputs: [{
      internalType: "address",
      name: "",
      type: "address"
    }],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [{
      internalType: "uint256",
      name: "",
      type: "uint256"
    }],
    name: "players",
    outputs: [{
      internalType: "address",
      name: "",
      type: "address"
    }],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [],
    name: "enter",
    outputs: [],
    stateMutability: "payable",
    type: "function",
  },
  {
    inputs: [],
    name: "getBalance",
    outputs: [{
      internalType: "uint256",
      name: "",
      type: "uint256"
    }],
    stateMutability: "view",
    type: "function",
  },
  {
    inputs: [],
    name: "pickWinner",
    outputs: [],
    stateMutability: "nonpayable",
    type: "function",
  },
  {
    inputs: [],
    name: "getPlayers",
    outputs: [{
      internalType: "address[]",
      name: "",
      type: "address[]"
    }],
    stateMutability: "view",
    type: "function",
  },
];

export default new web3.eth.Contract(abi, address);

Body:
You have not provided any 'provider' in lottery.js on this line

let web3 = new Web3();

which isn't giving you correct contract instance and thus you cannot access it's methods


问:
Send UWP Object from C++ to C#
I have code in C++ that generates a SpatialCoordinateSystem instance and wish to send this over for my C# code to use. I saw here that a I can simply create such an instance in C# if I have a native pointer to said object, so this was my initial approach. Unfortunately, I am not able to get this to work as I keep encountering access violation errors when trying to pass the pointer from C++ to C#. Any help would be highly appreciated (Note: using the native microsoft function that creates my object in C# is not requires, it was just what made the most sense to me).

C++ (coords is a global variable defined in my header file):

void* getCoords() {
    if (coords == nullptr) {
        SpatialLocator loc = SpatialLocator::GetDefault();
        coords = loc.CreateStationaryFrameOfReferenceAtCurrentLocation().CoordinateSystem();
    }

    return &coords;
}
```
<p>C#:</p>
<pre class="lang-cs prettyprint-override"><code>[System.Runtime.InteropServices.DllImport("MyDLL.dll", EntryPoint = "getCoords"]
public static extern IntPtr getCoords();

public static SpatialCoordinateSystem GetCoordinateSystem()
{
    IntPtr ptr = getCoords();
    return SpatialCoordinateSystem.FromNativePtr(ptr);
}
</code>```

答:
You can use COM to transfer data from C++ to C#. What you have to do is create similar structure (COORD in your case) in C# code. Then create an interface in C# code and implement one function inside that interface that will accept the argument of type of that structure (COORD). Now, you just have to make a tlb file from the CMD prompt. For making the tlb file, what you have to do is you have to make an empty .bat file (You can name it RegisterTlb.bat) in your working directory (where you have placed your C# code project) and open it with notepad and write following command inside that .bat file:

```<code> "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\regasm.exe"
 "your_C++_exe_name.exe" /tlb your_C#_interface_name.tlb"
</code>```

Here the interface name is that in which you have just implemented you function.
Now just open a command prompt with admin mode and change your directory (with cd command in command prompt) to your c# project directory where your bat file is placed and simply write your bat file name in command prompt (with .bat extension). It will show you the message that type registered successfully. Now you will see that new file with .tlb is been generated automatically in your c# project directory. Copy that .tlb file, paste it in c++ project directory and build the c++ project again. You will see that one smart pointer will be generated in your c++ code the the same name as your interface name (interface that you have created in C# code) but with Ptr suffix like "interface_namePtr". Now you can just call your C# function in C++ as:

```<code>interface_namePtr->functionName(structureParamenter (COORD) with data)
</code>```

And this will transfer your data automatically.

Do one thing for simplicity (even I got confused here). Make your interface name and your c# project name the same.

Title: Send UWP Object from C++ to C#

Body:
I have code in C++ that generates a SpatialCoordinateSystem instance and wish to send this over for my C# code to use. I saw here that a I can simply create such an instance in C# if I have a native pointer to said object, so this was my initial approach. Unfortunately, I am not able to get this to work as I keep encountering access violation errors when trying to pass the pointer from C++ to C#. Any help would be highly appreciated (Note: using the native microsoft function that creates my object in C# is not requires, it was just what made the most sense to me).

C++ (coords is a global variable defined in my header file):

void* getCoords() {
    if (coords == nullptr) {
        SpatialLocator loc = SpatialLocator::GetDefault();
        coords = loc.CreateStationaryFrameOfReferenceAtCurrentLocation().CoordinateSystem();
    }

    return &coords;
}

C#:

[System.Runtime.InteropServices.DllImport("MyDLL.dll", EntryPoint = "getCoords"]
public static extern IntPtr getCoords();

public static SpatialCoordinateSystem GetCoordinateSystem()
{
    IntPtr ptr = getCoords();
    return SpatialCoordinateSystem.FromNativePtr(ptr);
}

Body:
You can use COM to transfer data from C++ to C#. What you have to do is create similar structure (COORD in your case) in C# code. Then create an interface in C# code and implement one function inside that interface that will accept the argument of type of that structure (COORD). Now, you just have to make a tlb file from the CMD prompt. For making the tlb file, what you have to do is you have to make an empty .bat file (You can name it RegisterTlb.bat) in your working directory (where you have placed your C# code project) and open it with notepad and write following command inside that .bat file:

 "C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\regasm.exe"
 "your_C++_exe_name.exe" /tlb your_C#_interface_name.tlb"

Here the interface name is that in which you have just implemented you function.
Now just open a command prompt with admin mode and change your directory (with cd command in command prompt) to your c# project directory where your bat file is placed and simply write your bat file name in command prompt (with .bat extension). It will show you the message that type registered successfully. Now you will see that new file with .tlb is been generated automatically in your c# project directory. Copy that .tlb file, paste it in c++ project directory and build the c++ project again. You will see that one smart pointer will be generated in your c++ code the the same name as your interface name (interface that you have created in C# code) but with Ptr suffix like "interface_namePtr". Now you can just call your C# function in C++ as:

interface_namePtr->functionName(structureParamenter (COORD) with data)

And this will transfer your data automatically.

Do one thing for simplicity (even I got confused here). Make your interface name and your c# project name the same.


问:
Instance in upload_image function django framework
I have a issue in my code. I have a user model and it has a profile_image field with ImageField. I defined a profileImageRoot() function and equalized it to upload_to argument of ImageField. I have profile_image_count IntegerField and it increases 1 unit when image is uploaded in profileImageRoot(). I try save the value of profile_image_count on my database but save() method doesn't save. My source code:

User model:

class User(AbstractBaseUser):
    username                = models.CharField(max_length=20, unique=True, verbose_name="Username")
    email                   = models.EmailField(unique=True, verbose_name="Email", help_text="Email you actively use")
    first_name              = models.CharField(max_length=20)
    last_name               = models.CharField(max_length=20)
    date_of_birth           = models.DateField(blank=False)
    date_created            = models.DateTimeField(auto_now_add=True)
    last_login              = models.DateTimeField(auto_now=True)
    profile_image           = models.ImageField(upload_to=profileImageRoot)
    profile_image_count     = models.IntegerField(default=0)
    spent_money             = models.FloatField(default=0)

    is_active               = models.BooleanField(default=True)
    is_admin                = models.BooleanField(default=False)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)
    is_verified             = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ('username', 'first_name', 'last_name', 'date_of_birth')

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    def is_birthday(self):
        if timesince(self.date_of_birth, datetime.today()) == datetime(day=0, month=0):
            return True
        else:
            return False

    def verify(self):
        self.is_verified = True

    def __str__(self):
        return self.get_full_name()
```
<p><strong>profileImageRoot():</strong></p>
<pre class="lang-py prettyprint-override"><code>def profileImageRoot(instance, filename):
    user = User.objects.get(pk=instance.pk)
    ext = filename.split(".")[-1]
    user.profile_image_count += 1
    print(user.profile_image_count)
    user.save()
    return f"{user.username}/profile_image/{user.profile_image_count}.{ext}"
</code>```

答:
This is likely because your original instance contains the old value for profile_image_count. Since the saving process first needs to call profileImageRoot() and then write data from instance to database, your increased value for profile_image_count is overriden with the old value.

Try to also increase instance.profile_image_count in profileImageRoot().

This, however, seems like a poor solution overall. If you want some ordering in file names for profile images consider using timestamps or alike. Besides there's no guarantee that profileImageRoot() will be called just once per save() call, or that it won't be called unless new image is uploaded.

Body:
I have a issue in my code. I have a user model and it has a profile_image field with ImageField. I defined a profileImageRoot() function and equalized it to upload_to argument of ImageField. I have profile_image_count IntegerField and it increases 1 unit when image is uploaded in profileImageRoot(). I try save the value of profile_image_count on my database but save() method doesn't save. My source code:

User model:

class User(AbstractBaseUser):
    username                = models.CharField(max_length=20, unique=True, verbose_name="Username")
    email                   = models.EmailField(unique=True, verbose_name="Email", help_text="Email you actively use")
    first_name              = models.CharField(max_length=20)
    last_name               = models.CharField(max_length=20)
    date_of_birth           = models.DateField(blank=False)
    date_created            = models.DateTimeField(auto_now_add=True)
    last_login              = models.DateTimeField(auto_now=True)
    profile_image           = models.ImageField(upload_to=profileImageRoot)
    profile_image_count     = models.IntegerField(default=0)
    spent_money             = models.FloatField(default=0)

    is_active               = models.BooleanField(default=True)
    is_admin                = models.BooleanField(default=False)
    is_staff                = models.BooleanField(default=False)
    is_superuser            = models.BooleanField(default=False)
    is_verified             = models.BooleanField(default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ('username', 'first_name', 'last_name', 'date_of_birth')

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

    def is_birthday(self):
        if timesince(self.date_of_birth, datetime.today()) == datetime(day=0, month=0):
            return True
        else:
            return False

    def verify(self):
        self.is_verified = True

    def __str__(self):
        return self.get_full_name()

profileImageRoot():

def profileImageRoot(instance, filename):
    user = User.objects.get(pk=instance.pk)
    ext = filename.split(".")[-1]
    user.profile_image_count += 1
    print(user.profile_image_count)
    user.save()
    return f"{user.username}/profile_image/{user.profile_image_count}.{ext}"


问:
How to use JavaScript Array.find() method to make correct arithmetical calculation in array of objects?
I have this simple calculation method which returns commission, I want to return calculated result from this precents array, I am trying to achieve this result with Array.find method, problem is when I pass  price 30 it's calculates from previous object {min: 0, max: 30, percent: 30} but i want to calculation start from {min: 30, max: 40, percent: 29.70000000} this object where min value is 30 How can I achieve this?

function calculateCommisionValue(){
const percents = [{min: 0, max: 30, percent: 30}, {min: 30, max: 40, percent: 29.70000000},];
const result = percents.find(e => e.min <= 30 && e.max >= 30);
    return 30 * result?.percent / 100
}

//result should be 27.82215064```

答:
The Array.find() method will return the first element that satisfies your condition. As you have set both min and max condition to be inferior/superior or equal you will have an issue when the max of a condition is the same as the min of the next one, as it will always return the first one.

You should decide which value will be inclusive and which one will be exclusive. From your question I understand that you want a max exclusive and min inclusive, to select the lower percentage value when the price is 30.

You should remove the equal in the second consition as such:

function calculateCommisionValue(price: number) {
    const percents = [{min: 0, max: 30, percent: 30}, {min: 30, max: 40, percent: 29.70000000},];
    const result = percents.find(e => e.min <= price && e.max > price); // Remove the equal in the max consition
    return price * result?.percent / 100
}
```