问:
Fetching data to Django view working manually but not with Selenium. Why?
I am using Selenium to test a Django app I have created.

The following code works fine 'manually' but does not work with Selenium.

Why ?

## dummy.html ##

{% extends 'main.html' %}
{% load static %}

{% block title %}
Dummy page
{% endblock title %}

{% block meta %}
<meta name="robots" content="noindex">
{% endblock meta %}

{% block content %}

Dummy page

THIS IS A DUMMY PAGE

        <button id="trigger-dummy-button" type="button"
            class="btn btn-primary text-white font-base fw-bold text-uppercase"
            title="Trigger dummy button">Trigger dummy button</button>

{% endblock content %}

```
<br/>
## dummy.js ##
<br/>
<pre class="lang-js prettyprint-override"><code>'use strict';

var newValue;

async function postDummyFunction(request) {
    var response = await fetch(request);
    if (response.ok) {
        var updatedReturnedValue = await response.json();
        newValue = updatedReturnedValue.returnedValue;
        alert('-- postDummyFunction --  |  newValue = ' + newValue);
        // When the script is triggered manually by clicking, response.ok = true and newValue = "Hello World OK !"
        return newValue;
    } else {
        // When the script is triggered by Selenium, response.ok = false
        alert('-- postDummyFunction --  |  response.ok ? ' + response.ok);
        return false;
    }
};

document.addEventListener("DOMContentLoaded", function () {

    var triggerDummyButton = document.getElementById("trigger-dummy-button");
    var someDummyVariable = "Hello World ";
    var toPostURL = someDummyURL;

    triggerDummyButton.onclick = (e) => {
        var data = {"dummyValue": someDummyVariable};
        var request = new Request(toPostURL, {
            method: "POST",
            mode: "same-origin",
            headers: {
                "Content-Type": "application/json",
                'X-Requested-With':'XMLHttpRequest',
                "Accept": "application/json",
                'X-CSRFToken': csrftoken
            },
            body: JSON.stringify(data),
        });
        // Works with Selenium
        // if alert(data.dummyValue), browser correctly displays "Hello World "
        postDummyFunction(request);
    }
});

</code>```

## views.py ##

import json

from django.shortcuts import render, redirect
from django.http import JsonResponse

def dev_dummy_script(request):
    context = {}
    return render(request, "dummy.html", context)

def another_dummy_view(request):
    if request.method == "POST":
        post_data = json.loads(request.body.decode("utf-8"))
        posted_value = post_data["dummyValue"]
        value_to_return = posted_value + " " + "OK !"
        response = JsonResponse({"returnedValue": value_to_return})
        return response

```
<br/>
## test_selenium.py ##
<br/>
<pre class="lang-py prettyprint-override"><code>
import time
import os
from decimal import Decimal
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from django.contrib.staticfiles.testing import StaticLiveServerTestCase

from core.settings import BASE_DIR

PATH_TO_WEBDRIVER_CHROME = os.path.join(
    BASE_DIR, "test", "webdrivers", "chromedriver.exe"
)

PATH_TO_WEBDRIVER_FIREFOX = os.path.join(BASE_DIR, "test", "webdrivers", "geckodriver")

SHORT_TIME = 2.5
LONG_TIME = 6
DEFAULT_WAIT_TIME = 10

class FooTest(StaticLiveServerTestCase):
    def setUp(self):
        self.browser = webdriver.Firefox(executable_path=PATH_TO_WEBDRIVER_FIREFOX)

    def tearDown(self):
        self.browser.close()

    def testfoo(self):

        self.browser.get(("%s%s" % (self.live_server_url, "/dev/dummy_script/")))

        elem_trigger_btn = WebDriverWait(self.browser, DEFAULT_WAIT_TIME).until(
            EC.element_to_be_clickable((By.ID, "trigger-dummy-button"))
        )

        elem_trigger_btn.click()

        time.sleep(LONG_TIME)

        self.browser.close()

</code>```

versions

Django==3.2

selenium==3.141.0

Firefox 96.0.3

If I trigger python manage.py runserver, manually head to dummy_script and click on the button, it works fine, i.e. alert window pops up and displays "Hello World OK !".

If I trigger the script with pytest and selenium, the code is executed, but response returned from fetch is ko.

EDIT

main.html

<!DOCTYPE html>
{% load static %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="{% static 'css/main.css' %}" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

    <title>
        {% block title %}
        {% endblock title %}
    </title>
    {% block meta %}
    {% endblock meta %}

        {% block content %}
        {% endblock content %}

```

答:
I realise that when I use Selenium, the function getCookie return csrftoken = null. As a result, It is impossible to fetch data to django view.

To be able to make it work with Selenium in test mode only, I have added the following conditional decorator before 'another_dummy_view'.

views.py

def conditional_decorator(dec, condition):
    def decorator(func):
        if not condition:
            # Return the function unchanged, not decorated.
            return func
        return dec(func)
    return decorator

def dev_dummy_script(request):
    context = {}
    return render(request, "dummy_2.html", context)

@conditional_decorator(csrf_exempt, DEBUG)
def another_dummy_view(request):
    if request.method == "POST":
        post_data = json.loads(request.body.decode("utf-8"))
        posted_value = post_data["dummyValue"]
        value_to_return = posted_value + " " + "OK !"
        response = JsonResponse({"returnedValue": value_to_return})
        return response

```

Body:
I am using Selenium to test a Django app I have created.

The following code works fine 'manually' but does not work with Selenium.

Why ?

## dummy.html ##

{% extends 'main.html' %}
{% load static %}

{% block title %}
Dummy page
{% endblock title %}

{% block meta %}
<meta name="robots" content="noindex">
{% endblock meta %}

{% block content %}

Dummy page

THIS IS A DUMMY PAGE

        <button id="trigger-dummy-button" type="button"
            class="btn btn-primary text-white font-base fw-bold text-uppercase"
            title="Trigger dummy button">Trigger dummy button</button>

{% endblock content %}

## dummy.js ##

'use strict';

var newValue;

async function postDummyFunction(request) {
    var response = await fetch(request);
    if (response.ok) {
        var updatedReturnedValue = await response.json();
        newValue = updatedReturnedValue.returnedValue;
        alert('-- postDummyFunction --  |  newValue = ' + newValue);
        // When the script is triggered manually by clicking, response.ok = true and newValue = "Hello World OK !"
        return newValue;
    } else {
        // When the script is triggered by Selenium, response.ok = false
        alert('-- postDummyFunction --  |  response.ok ? ' + response.ok);
        return false;
    }
};

document.addEventListener("DOMContentLoaded", function () {

    var triggerDummyButton = document.getElementById("trigger-dummy-button");
    var someDummyVariable = "Hello World ";
    var toPostURL = someDummyURL;

    triggerDummyButton.onclick = (e) => {
        var data = {"dummyValue": someDummyVariable};
        var request = new Request(toPostURL, {
            method: "POST",
            mode: "same-origin",
            headers: {
                "Content-Type": "application/json",
                'X-Requested-With':'XMLHttpRequest',
                "Accept": "application/json",
                'X-CSRFToken': csrftoken
            },
            body: JSON.stringify(data),
        });
        // Works with Selenium
        // if alert(data.dummyValue), browser correctly displays "Hello World "
        postDummyFunction(request);
    }
});

## views.py ##

import json

from django.shortcuts import render, redirect
from django.http import JsonResponse

def dev_dummy_script(request):
    context = {}
    return render(request, "dummy.html", context)

def another_dummy_view(request):
    if request.method == "POST":
        post_data = json.loads(request.body.decode("utf-8"))
        posted_value = post_data["dummyValue"]
        value_to_return = posted_value + " " + "OK !"
        response = JsonResponse({"returnedValue": value_to_return})
        return response

## test_selenium.py ##

import time
import os
from decimal import Decimal
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from django.contrib.staticfiles.testing import StaticLiveServerTestCase

from core.settings import BASE_DIR

PATH_TO_WEBDRIVER_CHROME = os.path.join(
    BASE_DIR, "test", "webdrivers", "chromedriver.exe"
)

PATH_TO_WEBDRIVER_FIREFOX = os.path.join(BASE_DIR, "test", "webdrivers", "geckodriver")

SHORT_TIME = 2.5
LONG_TIME = 6
DEFAULT_WAIT_TIME = 10

class FooTest(StaticLiveServerTestCase):
    def setUp(self):
        self.browser = webdriver.Firefox(executable_path=PATH_TO_WEBDRIVER_FIREFOX)

    def tearDown(self):
        self.browser.close()

    def testfoo(self):

        self.browser.get(("%s%s" % (self.live_server_url, "/dev/dummy_script/")))

        elem_trigger_btn = WebDriverWait(self.browser, DEFAULT_WAIT_TIME).until(
            EC.element_to_be_clickable((By.ID, "trigger-dummy-button"))
        )

        elem_trigger_btn.click()

        time.sleep(LONG_TIME)

        self.browser.close()

versions

Django==3.2

selenium==3.141.0

Firefox 96.0.3

If I trigger python manage.py runserver, manually head to dummy_script and click on the button, it works fine, i.e. alert window pops up and displays "Hello World OK !".

If I trigger the script with pytest and selenium, the code is executed, but response returned from fetch is ko.

EDIT

main.html

<!DOCTYPE html>
{% load static %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="{% static 'css/main.css' %}" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

    <title>
        {% block title %}
        {% endblock title %}
    </title>
    {% block meta %}
    {% endblock meta %}

        {% block content %}
        {% endblock content %}


来源: stackexchange

问:
Seting culture info from the project properties
I am creating winforms app in Visual Studio 2019 in C# (.NET) and I have this code:

```<code>   CultureInfo ci = new CultureInfo("de");
   Thread.CurrentThread.CurrentCulture = ci;
</code>```

to set the culture info. However, I wonder if I can set culture info some other way manually like project -> properties but I cannot find it at the moment.

Is this possible?

答:
Try something like this:

```<code><configuration>
  [...]
  <appSettings>
    [...]
    <add key="defaultCulture" value="de" />
    [...]
  </appSettings>
  [...]
</configuration>
</code>```

and recover the value like this:

```<code>var value = System.Configuration.ConfigurationManager.AppSettings["defaultCulture"];
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating winforms app in Visual Studio 2019 in C# (.NET) and I have this code:

   CultureInfo ci = new CultureInfo("de");
   Thread.CurrentThread.CurrentCulture = ci;

to set the culture info. However, I wonder if I can set culture info some other way manually like project -> properties but I cannot find it at the moment.

Is this possible?

Body:
Try something like this:

<configuration>
  [...]
  <appSettings>
    [...]
    <add key="defaultCulture" value="de" />
    [...]
  </appSettings>
  [...]
</configuration>

and recover the value like this:

var value = System.Configuration.ConfigurationManager.AppSettings["defaultCulture"];


问:
Javascript: Fetch DELETE and PUT requests
I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example. </p>

<p>So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit. </p>

答:
Let me simplify this, you can straight up copy the code.

This is for PUT method :

```<code>fetch('https://reqres.in/api/users', + id {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'user'
  })
})
.then(res => {
  return res.json()
})
.then(data => console.log(data))
</code>```

and this is for DELETE :

```<code>fetch('https://reqres.in/api/users' + id, {
  method: 'DELETE',
})
.then(res => {
  return res.json()
})
.then(data => console.log(data))
</code>```

Note: I'm using dummy api here.

Body:
I have gotten outside of GET and POST methods with Fetch. But I couldn't find any good DELETE and PUT example.

So, I ask you for it. Could you give a good example of DELETE and PUT methods with fetch. And explain it a little bit.

Body:
Let me simplify this, you can straight up copy the code.

This is for PUT method :

fetch('https://reqres.in/api/users', + id {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'user'
  })
})
.then(res => {
  return res.json()
})
.then(data => console.log(data))

and this is for DELETE :

fetch('https://reqres.in/api/users' + id, {
  method: 'DELETE',
})
.then(res => {
  return res.json()
})
.then(data => console.log(data))

Note: I'm using dummy api here.


问:
Common character count giving unexpected problems
I have a simple problem where you get two strings where you need to see how many characters are common.

```<code>For s1 = "aabcc" and s2 = "dacaa", the output should be
solution(s1, s2) = 3.
</code>```

I've seen a lot of people solve these types of problems, but I don't want to copy and paste. I want to learn it my way with my solution and improve upon that. I think my solution makes sense but it obviously doesn't, because it doesn't work.

This is my solution:

```<code>#include <iostream>

using namespace std;

int main()
{

        int counter {};
        string s1 = "aabcc";
        string s2 = "dacaa";

        for (int i {}; i < s1.size(); ++i)
        {
            for (int j {}; j < s2.size(); ++j)
            {
                if (s1.at(i) == s2.at(j));
                {
                    cout << "Found character " << s1.at(i) << " at index " << i << " and " << s2.at(j) << " at index " << j << endl;
                    counter++;
                    s2.erase(s2.begin()+j);
                    break;
                }
            }

            cout << s2 << endl;
        }

        cout << counter << endl;

        return 0;
    }
</code>```

This is the output I get (I did a lot of "cout" for debugging purposes.

```<code>Found character a at index 0 and d at index 0
acaa
Found character a at index 1 and a at index 0
caa
Found character b at index 2 and c at index 0
aa
Found character a at index 3 and a at index 0

Found character a at index 4 and a at index 0

5
</code>```

Let's talk about the first iteration. What I don't understand is how s1.at(i) is equal to s2.at(j) at index 0? s1.at(0) is "a" and s2.at(0) is "d". Since when was a = d?
This problem is driving me crazy and I would appreciate if you could explain why my solution acts like this.

答:
There is a small typo in your code as Vlad from Moscow said. The reason why that small semicolon ruins the result is that then the code:

```<code>if (s1.at(i) == s2.at(j));
{ // From here
    cout << "Found character " << s1.at(i) << " at index " << i << " and " << s2.at(j) << " at index " << j << endl;
    counter++;
    s2.erase(s2.begin()+j);
    break;
} // To here
</code>```

...is not considered as the part of the if statement because a semicolon refers to the end of a statement. So the semicolon ended the if statement, and as the code in the brackets is after the if statement has been ended by the semicolon, it is not considered as a part of the if statement. I hope the explanation is clear :).

Body:
I have a simple problem where you get two strings where you need to see how many characters are common.

For s1 = "aabcc" and s2 = "dacaa", the output should be
solution(s1, s2) = 3.

I've seen a lot of people solve these types of problems, but I don't want to copy and paste. I want to learn it my way with my solution and improve upon that. I think my solution makes sense but it obviously doesn't, because it doesn't work.

This is my solution:

#include <iostream>

using namespace std;

int main()
{

        int counter {};
        string s1 = "aabcc";
        string s2 = "dacaa";

        for (int i {}; i < s1.size(); ++i)
        {
            for (int j {}; j < s2.size(); ++j)
            {
                if (s1.at(i) == s2.at(j));
                {
                    cout << "Found character " << s1.at(i) << " at index " << i << " and " << s2.at(j) << " at index " << j << endl;
                    counter++;
                    s2.erase(s2.begin()+j);
                    break;
                }
            }

            cout << s2 << endl;
        }

        cout << counter << endl;

        return 0;
    }

This is the output I get (I did a lot of "cout" for debugging purposes.

Found character a at index 0 and d at index 0
acaa
Found character a at index 1 and a at index 0
caa
Found character b at index 2 and c at index 0
aa
Found character a at index 3 and a at index 0

Found character a at index 4 and a at index 0

5

Let's talk about the first iteration. What I don't understand is how s1.at(i) is equal to s2.at(j) at index 0? s1.at(0) is "a" and s2.at(0) is "d". Since when was a = d?
This problem is driving me crazy and I would appreciate if you could explain why my solution acts like this.

Body:
There is a small typo in your code as Vlad from Moscow said. The reason why that small semicolon ruins the result is that then the code:

if (s1.at(i) == s2.at(j));
{ // From here
    cout << "Found character " << s1.at(i) << " at index " << i << " and " << s2.at(j) << " at index " << j << endl;
    counter++;
    s2.erase(s2.begin()+j);
    break;
} // To here

...is not considered as the part of the if statement because a semicolon refers to the end of a statement. So the semicolon ended the if statement, and as the code in the brackets is after the if statement has been ended by the semicolon, it is not considered as a part of the if statement. I hope the explanation is clear :).


问:
Surefire Maven plugin: "Corrupted STDOUT by directly writing to native stream in forked JVM"
My JUnit tests are failing when running them through Maven and the Surefire plugin (version information below). I see the error message:

```<code>Corrupted STDOUT by directly writing to native stream in forked JVM 4. See FAQ web page and the dump file C:\(...)\target\surefire-reports\2019-03-20T18-57-17_082-jvmRun4.dumpstream
</code>```

The FAQ page points out some possible reasons but I don't see how I can use this information to start solving this problem:

Corrupted STDOUT by directly writing to native stream in forked JVM

If your tests use native library which prints to STDOUT this warning message appears because the library corrupted the channel used by the plugin in order to transmit events with test status back to Maven process. It would be even worse if you override the Java stream by System.setOut because the stream is also supposed to be corrupted but the Maven will never see the tests finished and build may hang.

This warning message appears if you use FileDescriptor.out or JVM prints GC summary.

In that case the warning is printed "Corrupted STDOUT by directly writing to native stream in forked JVM", and a dump file can be found in Reports directory.

If debug level is enabled then messages of corrupted stream appear in the console.

It refers to some native library printing out to STDOUT directly but how can I figure out which one, and even if I do, how do I deal with this issue if I need the library for my project?

It mentions "debug level" but it is unclear if this means Maven's debug level or Surefire plugin's debug level. I enabled Maven's debug but I don't see the console outputs as mentioned by the FAQ. And Surefire's debug option seems to be about pausing tests and waiting for a debugger to be connected to the process, not simply showing more information on the console.

The dump files also don't seem very helpful:

```<code># Created on 2019-03-20T18:42:58.323
Corrupted STDOUT by directly writing to native stream in forked JVM 2. Stream 'FATAL ERROR in native method: processing of -javaagent failed'.
java.lang.IllegalArgumentException: Stream stdin corrupted. Expected comma after third character in command 'FATAL ERROR in native method: processing of -javaagent failed'.
    at org.apache.maven.plugin.surefire.booterclient.output.ForkClient$OperationalData.<init>(ForkClient.java:511)
    at org.apache.maven.plugin.surefire.booterclient.output.ForkClient.processLine(ForkClient.java:209)
    at org.apache.maven.plugin.surefire.booterclient.output.ForkClient.consumeLine(ForkClient.java:176)
    at org.apache.maven.plugin.surefire.booterclient.output.ThreadedStreamConsumer$Pumper.run(ThreadedStreamConsumer.java:88)
    at java.base/java.lang.Thread.run(Thread.java:834)
</code>```

So, how can I solve this problem?

Update: requested configuration information below.

I'm using OpenJDK 11 (Zulu distribution) on Windows 10, Maven 3.5.3, and Surefire 2.21.0 (full configuration below).

I'm running Maven from Eclipse using the "Run As..." context menu option on the pom.xml file, but obtain the same results when running it on the console.

I had never heard of JaCoco before the first comment to this question, but I see several error messages mentioning it:

```<code>[ERROR] ExecutionException The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Zulu\zulu-11\bin\java" -javaagent:C:\\Users\\E26638\\.m2\\repository\\org\\jacoco\\org.jacoco.agent\\0.8.0\\org.jacoco.agent-0.8.0-runtime.jar=destfile=C:\\Users\\E26638\\git\\aic-expresso\\target\\jacoco.exec -Xms256m -Xmx1028m -jar C:\Users\E26638\AppData\Local\Temp\surefire10089630030045878403\surefirebooter8801585361488929382.jar C:\Users\E26638\AppData\Local\Temp\surefire10089630030045878403 2019-03-21T21-26-04_829-jvmRun12 surefire10858509118810158083tmp surefire_115439010304069944813tmp"
[ERROR] Error occurred in starting fork, check output in log
[ERROR] Process Exit Code: 1
</code>```

This is the Surefire Maven plugin configuration:

```<code>    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.21.0</version>
        <configuration>
            <skipTests>${skipUnitTests}</skipTests>
            <testFailureIgnore>false</testFailureIgnore>
            <forkCount>1.5C</forkCount>
            <reuseForks>true</reuseForks>
            <parallel>methods</parallel>
            <threadCount>4</threadCount>
            <perCoreThreadCount>true</perCoreThreadCount>
            <reportFormat>plain</reportFormat>
            <trimStackTrace>false</trimStackTrace>
            <redirectTestOutputToFile>true</redirectTestOutputToFile>
        </configuration>
    </plugin>
</code>```

答:
We are using log4j backend and could also fix it using follow set to true.

```<code><Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="${messagePattern}" />
        <follow>true</follow>
    </Console>
</Appenders>
</code>```

(We had the same error message but without jacoco being involved. But I can confirm that setting the forkNode in maven-surefire-plugin to TCP did also work.)

Body:
My JUnit tests are failing when running them through Maven and the Surefire plugin (version information below). I see the error message:

Corrupted STDOUT by directly writing to native stream in forked JVM 4. See FAQ web page and the dump file C:\(...)\target\surefire-reports\2019-03-20T18-57-17_082-jvmRun4.dumpstream

The FAQ page points out some possible reasons but I don't see how I can use this information to start solving this problem:

Corrupted STDOUT by directly writing to native stream in forked JVM

If your tests use native library which prints to STDOUT this warning message appears because the library corrupted the channel used by the plugin in order to transmit events with test status back to Maven process. It would be even worse if you override the Java stream by System.setOut because the stream is also supposed to be corrupted but the Maven will never see the tests finished and build may hang.

This warning message appears if you use FileDescriptor.out or JVM prints GC summary.

In that case the warning is printed "Corrupted STDOUT by directly writing to native stream in forked JVM", and a dump file can be found in Reports directory.

If debug level is enabled then messages of corrupted stream appear in the console.

It refers to some native library printing out to STDOUT directly but how can I figure out which one, and even if I do, how do I deal with this issue if I need the library for my project?

It mentions "debug level" but it is unclear if this means Maven's debug level or Surefire plugin's debug level. I enabled Maven's debug but I don't see the console outputs as mentioned by the FAQ. And Surefire's debug option seems to be about pausing tests and waiting for a debugger to be connected to the process, not simply showing more information on the console.

The dump files also don't seem very helpful:

# Created on 2019-03-20T18:42:58.323
Corrupted STDOUT by directly writing to native stream in forked JVM 2. Stream 'FATAL ERROR in native method: processing of -javaagent failed'.
java.lang.IllegalArgumentException: Stream stdin corrupted. Expected comma after third character in command 'FATAL ERROR in native method: processing of -javaagent failed'.
    at org.apache.maven.plugin.surefire.booterclient.output.ForkClient$OperationalData.<init>(ForkClient.java:511)
    at org.apache.maven.plugin.surefire.booterclient.output.ForkClient.processLine(ForkClient.java:209)
    at org.apache.maven.plugin.surefire.booterclient.output.ForkClient.consumeLine(ForkClient.java:176)
    at org.apache.maven.plugin.surefire.booterclient.output.ThreadedStreamConsumer$Pumper.run(ThreadedStreamConsumer.java:88)
    at java.base/java.lang.Thread.run(Thread.java:834)

So, how can I solve this problem?

Update: requested configuration information below.

I'm using OpenJDK 11 (Zulu distribution) on Windows 10, Maven 3.5.3, and Surefire 2.21.0 (full configuration below).

I'm running Maven from Eclipse using the "Run As..." context menu option on the pom.xml file, but obtain the same results when running it on the console.

I had never heard of JaCoco before the first comment to this question, but I see several error messages mentioning it:

[ERROR] ExecutionException The forked VM terminated without properly saying goodbye. VM crash or System.exit called?
[ERROR] Command was cmd.exe /X /C ""C:\Program Files\Zulu\zulu-11\bin\java" -javaagent:C:\\Users\\E26638\\.m2\\repository\\org\\jacoco\\org.jacoco.agent\\0.8.0\\org.jacoco.agent-0.8.0-runtime.jar=destfile=C:\\Users\\E26638\\git\\aic-expresso\\target\\jacoco.exec -Xms256m -Xmx1028m -jar C:\Users\E26638\AppData\Local\Temp\surefire10089630030045878403\surefirebooter8801585361488929382.jar C:\Users\E26638\AppData\Local\Temp\surefire10089630030045878403 2019-03-21T21-26-04_829-jvmRun12 surefire10858509118810158083tmp surefire_115439010304069944813tmp"
[ERROR] Error occurred in starting fork, check output in log
[ERROR] Process Exit Code: 1

This is the Surefire Maven plugin configuration:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.21.0</version>
        <configuration>
            <skipTests>${skipUnitTests}</skipTests>
            <testFailureIgnore>false</testFailureIgnore>
            <forkCount>1.5C</forkCount>
            <reuseForks>true</reuseForks>
            <parallel>methods</parallel>
            <threadCount>4</threadCount>
            <perCoreThreadCount>true</perCoreThreadCount>
            <reportFormat>plain</reportFormat>
            <trimStackTrace>false</trimStackTrace>
            <redirectTestOutputToFile>true</redirectTestOutputToFile>
        </configuration>
    </plugin>

Body:
We are using log4j backend and could also fix it using follow set to true.

<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="${messagePattern}" />
        <follow>true</follow>
    </Console>
</Appenders>

(We had the same error message but without jacoco being involved. But I can confirm that setting the forkNode in maven-surefire-plugin to TCP did also work.)


问:
why we need to pass Boolean value to the method
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?</p>

```<code>RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }
</code>```

答:
forExport isn't used, but an earlier implementation might have done. Ie. "for historical reasons".

Check the history of the function in version control.

ContentLicense: CC BY-SA 3.0

Body:
I have confusion on below code i.e why we need to pass Boolean value to the method and what it returns?

RefreshLookupList(false);
private void RefreshLookupList(bool forExport)

    {
        grdLists.Rows.Clear();
        grdLists.DataSource = Lists.GetListItems(cboListType.SelectedValue);
        grdLists.DataBind();

        lblCount.InnerText = "Lookups: " + grdLists.Rows.Count.ToString();
    }


问:
[Q]Select property from object in TypeScript
I am learning TypeScript in React and I have a problem with accessing property via a method argument.

```<code>    const [product, setProduct] = useState("electricity");
        const defaultProps = {
        price: {
              electricity: 0.51,
              gas: 4.7,
              oranges: 3.79,
            },
          };
 const selectPrice = (select: any) => {
    console.log(defaultProps.price[select]);
  };
        const handleSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setProduct(e.target.value);
      };
        <Cash
                price={selectPrice(product)}
              />

    <select value={product} onChange={handleSelect}>
              <option value="electricity">electricity</option>
              <option value="gas">gas</option>
              <option value="oranges">oranges</option>
            </select>
</code>```

Problem is in selectPrice method.
I have the error "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ electricity: number; gas: number; oranges: number; }'.ts(7053)".
I don't know how I can get access to the property of object price in object defaultProps.
In guide teacher is using the javascript and it works fine.

答:
This issue should be fixed once you change select: any to select: string. Since price can be indexed only using strings, when you set select: any there is a possibility that select could be a number, boolean or some other type, which will cause a runtime error, which is why Typescript is complaining.

Since the benefit of using Typescript over Javascript is the stronger typing system, you should avoid using any whenever possible to take advantage of Typescript's ability to catch runtime bugs caused by mismatched types

Body:
I am learning TypeScript in React and I have a problem with accessing property via a method argument.

    const [product, setProduct] = useState("electricity");
        const defaultProps = {
        price: {
              electricity: 0.51,
              gas: 4.7,
              oranges: 3.79,
            },
          };
 const selectPrice = (select: any) => {
    console.log(defaultProps.price[select]);
  };
        const handleSelect = (e: React.ChangeEvent<HTMLSelectElement>) => {
        setProduct(e.target.value);
      };
        <Cash
                price={selectPrice(product)}
              />

    <select value={product} onChange={handleSelect}>
              <option value="electricity">electricity</option>
              <option value="gas">gas</option>
              <option value="oranges">oranges</option>
            </select>

Problem is in selectPrice method.
I have the error "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ electricity: number; gas: number; oranges: number; }'.ts(7053)".
I don't know how I can get access to the property of object price in object defaultProps.
In guide teacher is using the javascript and it works fine.


问:
Which dispatcher in Kotlin coroutines should be chosen for multiple parallel requests to MongoDB?
There is a list of parameters each of which is an input for MongoDB query.
Queries might be different, but for simplicity let's keep only one encapsulated in callMongoReactive.

```<code>fun callMongoReactive(p: Param): Mono<Result>{
    // ...
}

fun queryInParallel(parameters: List<Param>): List<Result> =
    parameters
        .map { async { mongo.findSomething(it).awaitSingle() } }
        .awaitAll()
</code>```

Suppose parameters list size is not greater than 20.

What is the optimal strategy of coroutine dispatchers usage that makes these async requests run in parallel simultaneously?

Should a custom dispatcher (with a dedicated thread pool) be created or is there a standard approach for such situations?

答:
If you want a very general answer, I'd say you may or may not want to care at this level. You don't have to.

In this specific case, the original API is reactive (immediately returns Mono), which means the actual work is not going to be performed on the thread calling callMongoReactive/findSomething, but on whatever thread pool mongoDB decided to use to back this Mono. This means the choice of dispatcher in this case really doesn't matter.

So especially in this case, I'd go for the simplest option: don't choose. Use coroutineScope and expose a suspend function so the caller decides on the coroutine context (including the dispatcher):

suspend fun queryInParallel(parameters: List<Param>): List<Result> = coroutineScope {
    parameters
        .map { async { mongo.findSomething(it).awaitSingle() } }
        .awaitAll()
}
```

This is the usual idiom for "parallel decomposition of work". I'd say it's the most common.

What is the optimal strategy of coroutine dispatchers usage that makes these async requests run in parallel simultaneously?

It's worth noting that the idiom above expresses concurrency, but whether the bodies of the asyncs will be run in parallel or not depends on the dispatcher chosen by the caller.

(To reiterate, the dispatcher only affects the body of those asyncs, and in this specific case they don't use the thread that much because they call a non-blocking method anyway, so it really doesn't matter.)

Now in cases where it does matter, any dispatcher backed by more than 1 thread would allow parallelism here. There are several existing dispatchers that may be useful, without needing to create your own thread pool. Dispatchers.Default has a number of threads adapted to the number of cores of the machine it's running on, so it's a good fit for CPU-bound work. Dispatchers.IO scales the number of threads as needed, which is useful if you have a lot of blocking IO and want to avoid starvation.

You can also use limitedParallelism on any dispatcher to get a view of it with only a limited number of threads, which may be useful in some cases where you don't want to create an extra thread pool, but you do want to limit the number of available threads more than what the built-in dispatchers offer.

Creating a custom thread pool can be interesting if you want to isolate parts of your system in case one subsystem misbehaves and starves threads. It does have a memory overhead, though, since you're creating more threads.

Body:
There is a list of parameters each of which is an input for MongoDB query.
Queries might be different, but for simplicity let's keep only one encapsulated in callMongoReactive.

fun callMongoReactive(p: Param): Mono<Result>{
    // ...
}

fun queryInParallel(parameters: List<Param>): List<Result> =
    parameters
        .map { async { mongo.findSomething(it).awaitSingle() } }
        .awaitAll()

Suppose parameters list size is not greater than 20.

What is the optimal strategy of coroutine dispatchers usage that makes these async requests run in parallel simultaneously?

Should a custom dispatcher (with a dedicated thread pool) be created or is there a standard approach for such situations?

Body:
If you want a very general answer, I'd say you may or may not want to care at this level. You don't have to.

In this specific case, the original API is reactive (immediately returns Mono), which means the actual work is not going to be performed on the thread calling callMongoReactive/findSomething, but on whatever thread pool mongoDB decided to use to back this Mono. This means the choice of dispatcher in this case really doesn't matter.

So especially in this case, I'd go for the simplest option: don't choose. Use coroutineScope and expose a suspend function so the caller decides on the coroutine context (including the dispatcher):

suspend fun queryInParallel(parameters: List<Param>): List<Result> = coroutineScope {
    parameters
        .map { async { mongo.findSomething(it).awaitSingle() } }
        .awaitAll()
}

This is the usual idiom for "parallel decomposition of work". I'd say it's the most common.

What is the optimal strategy of coroutine dispatchers usage that makes these async requests run in parallel simultaneously?

It's worth noting that the idiom above expresses concurrency, but whether the bodies of the asyncs will be run in parallel or not depends on the dispatcher chosen by the caller.

(To reiterate, the dispatcher only affects the body of those asyncs, and in this specific case they don't use the thread that much because they call a non-blocking method anyway, so it really doesn't matter.)

Now in cases where it does matter, any dispatcher backed by more than 1 thread would allow parallelism here. There are several existing dispatchers that may be useful, without needing to create your own thread pool. Dispatchers.Default has a number of threads adapted to the number of cores of the machine it's running on, so it's a good fit for CPU-bound work. Dispatchers.IO scales the number of threads as needed, which is useful if you have a lot of blocking IO and want to avoid starvation.

You can also use limitedParallelism on any dispatcher to get a view of it with only a limited number of threads, which may be useful in some cases where you don't want to create an extra thread pool, but you do want to limit the number of available threads more than what the built-in dispatchers offer.

Creating a custom thread pool can be interesting if you want to isolate parts of your system in case one subsystem misbehaves and starves threads. It does have a memory overhead, though, since you're creating more threads.


问:
What is the recommended F# pattern for this situation?
I have a situation which resembles the following:

```<code>let mutable stopped = false

let runAsync() = async {
    while not stopped do
        let! item = fetchItemToProcessAsync
        match item with
        | Some job -> job |> runJobAsync |> Async.Start
        | None -> do! Async.Sleep(1000)
}

let run() = Async.Start runAsync
let stop() =
    stopped <- true
</code>```

Now when the stop method is called, I have to stop reading further items from the DB and also wait for the ones that are currently started to finish before returning from this function.

What is the best way to accomplish this? I was thinking of using a counter, (with interlocked APIs) and return from the stop method when the counter reaches to 0.

If there is an alternative way to accomplish this, I would appreciate the guidance. I have a feeling that I could use agents here, but I am not sure if there is any available way to accomplish this with agent or if I still have to write my custom logic to determine that the jobs have completed executing.

答: Check out this snippet on fssnip.net. This is generic job processor which you can use.</p>

Body:
I have a situation which resembles the following:

let mutable stopped = false

let runAsync() = async {
    while not stopped do
        let! item = fetchItemToProcessAsync
        match item with
        | Some job -> job |> runJobAsync |> Async.Start
        | None -> do! Async.Sleep(1000)
}

let run() = Async.Start runAsync
let stop() =
    stopped <- true

Now when the stop method is called, I have to stop reading further items from the DB and also wait for the ones that are currently started to finish before returning from this function.

What is the best way to accomplish this? I was thinking of using a counter, (with interlocked APIs) and return from the stop method when the counter reaches to 0.

If there is an alternative way to accomplish this, I would appreciate the guidance. I have a feeling that I could use agents here, but I am not sure if there is any available way to accomplish this with agent or if I still have to write my custom logic to determine that the jobs have completed executing.


问:
Regular expression for non-positive integer (ie negative integers and 0)
Currently my solution is

```<code>/^-\d+$/
</code>```

However, this solution excludes zero ie 0.

How to update this so that it matches integers less or equal to 0?

答:
You can exclude matching a number that starts with 1-9 preceded with optional zeroes.

```<code>^(?!0*[1-9])-?\d+$
</code>```

Regex demo

Or with the alternation as in the comments to match 1+ times a zero, or only a single zero.

If supported, you could use a possessive quantifier 0++ to prevent some backtracking.

```<code>^(?:0+|-\d+)$
</code>```

Regex demo

Body:
Currently my solution is

/^-\d+$/

However, this solution excludes zero ie 0.

How to update this so that it matches integers less or equal to 0?

Body:
You can exclude matching a number that starts with 1-9 preceded with optional zeroes.

^(?!0*[1-9])-?\d+$

Regex demo

Or with the alternation as in the comments to match 1+ times a zero, or only a single zero.

If supported, you could use a possessive quantifier 0++ to prevent some backtracking.

^(?:0+|-\d+)$

Regex demo


问:
How to wait for a python script to complete run and then download the resulting file with PHP?
I have a python script (on Windows Server) that requests information through an API, downloads data into several csv and at the end it 'zips' them all into 1 single .zip file. The idea is to access that zip file through an URL, using PHP.

But the main issue here is PHP making the zip available, even before the file is not yet completely compressed.

Using the 'sleep' function, I believe will halt the execution of PHP, even the Python script, am I right?

My current setting is using a Task, on Windows Task Scheduler, to trigger the Python script, download the necessary files and only then, making the zip file available with PHP.

Is there any way of doing all the process within PHP script, without using Windows Task Scheduler?

```<code><?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/#classes/simple_html_dom.php";

#header("Content-type: text/html");
header("Content-Disposition: attachment; filename=api-week-values.zip");

unlink("api-week-values.zip");
$command = escapeshellcmd('python api_weekly.py');
$output = shell_exec($command);

sleep(15);
?>
</code>```

You can see the code I am using for the whole process.

To clarify the process:

An application needs to access the file I am downloading with the python script

I feed the application with the URL from Apache server

the application goes to the link (through index.php) and triggers the python script (which downloads the zip file)

php should pop-up a save file WHEN the zip file has been completely downloaded

答:
Why not call the PHP from Python at the end of the py script? Link</p>
```<code>import subprocess

# if the script don't need output.
subprocess.call("php /path/to/your/script.php")

# if you want output
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
</code>```

Body:
I have a python script (on Windows Server) that requests information through an API, downloads data into several csv and at the end it 'zips' them all into 1 single .zip file. The idea is to access that zip file through an URL, using PHP.

But the main issue here is PHP making the zip available, even before the file is not yet completely compressed.

Using the 'sleep' function, I believe will halt the execution of PHP, even the Python script, am I right?

My current setting is using a Task, on Windows Task Scheduler, to trigger the Python script, download the necessary files and only then, making the zip file available with PHP.

Is there any way of doing all the process within PHP script, without using Windows Task Scheduler?

<?php
include_once $_SERVER['DOCUMENT_ROOT'] . "/#classes/simple_html_dom.php";

#header("Content-type: text/html");
header("Content-Disposition: attachment; filename=api-week-values.zip");

unlink("api-week-values.zip");
$command = escapeshellcmd('python api_weekly.py');
$output = shell_exec($command);

sleep(15);
?>

You can see the code I am using for the whole process.

To clarify the process:

An application needs to access the file I am downloading with the python script

I feed the application with the URL from Apache server

the application goes to the link (through index.php) and triggers the python script (which downloads the zip file)

php should pop-up a save file WHEN the zip file has been completely downloaded

Body:
Why not call the PHP from Python at the end of the py script? Link

import subprocess

# if the script don't need output.
subprocess.call("php /path/to/your/script.php")

# if you want output
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()


问:
INSERT 6000 Rows - best practice
I have a PHP script that calls an API method that can easily return 6k+ results.

I use PEAR DB_DataObject to write each row in a foreach loop to the DB.

The above script is batch processing 20 users at a time - and although some will only have a few results from the API others will have more. Worst case is that all have 1000's of results.

The loop to call the API seems to be ok, batches of 20 every 5 minutes works fine. My only concern is 1000's of mysql INSERTs for each user (with a long pause between each user for fresh API calls)

Is there a good way to do this? Or am I doing it a good way?!

答: Well, is your method producing more load than you can handle? If it's working, then I don't see any reason to change it offhand.</p>

ContentLicense: CC BY-SA 2.5

Title: INSERT 6000 Rows - best practice

OwnerDisplayName: Kalium


答: It looks like it is never used and the method doesn't return anything.</p>

Title: why we need to pass Boolean value to the method


问:
java.lang.IllegalArgumentException: URI with undefined scheme
Good day. I've defined a 2 URI's for a http call. The first one works great, the code is a complete copy beside some arguments. The second one throws a Exception . I'll list the code below.

```<code>public class WeatherAPI {

         private static String apiKey = "asdasd";
         private HttpResponse<String> response;
         private URI uri;

         private HttpRequest getRequest(URI newUri) {
             return HttpRequest.newBuilder()
                     .uri(newUri)
                     .build();
         }

         private HttpClient getClient() {
             return HttpClient.newBuilder().build();
         }

         private String getResponse(URI uri) {
             var client = getClient();
             var request = getRequest(uri);
             try {
                 response = client.send(request, HttpResponse.BodyHandlers.ofString());
             }  catch (IOException | InterruptedException e) {
                 e.printStackTrace();
             }
             return response.body();
         }
         public JSONObject getCityData(String lat, String lon) {
             String url = "api.openweathermap.org/data/2.5/weather"; //        System.out.println(uri);
             try {
                 uri = new URIBuilder(URI.create(url))
                         .addParameter("lat", lat)
                         .addParameter("lon", lon)
                         .addParameter("appid", apiKey)
                         .build();
                 System.out.println(uri);

             }  catch (URISyntaxException e) {
                 e.printStackTrace();
             }
             var body = getResponse(uri);
             System.out.println(body);
             return null;
         }

     }
</code>```

Throws

Exception in thread "main" java.lang.IllegalArgumentException: URI
with undefined scheme

答:
It seems that the URL is missing the protocol-Prefix like http:// or https://  .. try

http://api.openweathermap.org/data/2.5/weather

or

https://api.openweathermap.org/data/2.5/weather

as URL. This should work.

Body:
Good day. I've defined a 2 URI's for a http call. The first one works great, the code is a complete copy beside some arguments. The second one throws a Exception . I'll list the code below.

public class WeatherAPI {

         private static String apiKey = "asdasd";
         private HttpResponse<String> response;
         private URI uri;

         private HttpRequest getRequest(URI newUri) {
             return HttpRequest.newBuilder()
                     .uri(newUri)
                     .build();
         }

         private HttpClient getClient() {
             return HttpClient.newBuilder().build();
         }

         private String getResponse(URI uri) {
             var client = getClient();
             var request = getRequest(uri);
             try {
                 response = client.send(request, HttpResponse.BodyHandlers.ofString());
             }  catch (IOException | InterruptedException e) {
                 e.printStackTrace();
             }
             return response.body();
         }
         public JSONObject getCityData(String lat, String lon) {
             String url = "api.openweathermap.org/data/2.5/weather"; //        System.out.println(uri);
             try {
                 uri = new URIBuilder(URI.create(url))
                         .addParameter("lat", lat)
                         .addParameter("lon", lon)
                         .addParameter("appid", apiKey)
                         .build();
                 System.out.println(uri);

             }  catch (URISyntaxException e) {
                 e.printStackTrace();
             }
             var body = getResponse(uri);
             System.out.println(body);
             return null;
         }

     }

Throws

Exception in thread "main" java.lang.IllegalArgumentException: URI
with undefined scheme


答:
You could create a type of the possible options of the select.</p>
```<code>const selectPrice = (select: 'electricity'| 'gas' | 'oranges') => {
  console.log(defaultProps.price[select]);
};
</code>```

Title: [Q]Select property from object in TypeScript

Body:
You could create a type of the possible options of the select.

const selectPrice = (select: 'electricity'| 'gas' | 'oranges') => {
  console.log(defaultProps.price[select]);
};


问:
django-tailwind, can't start dev server
I've done everything according to the django-tailwind docs, but when I want to start the dev server I get the following error:

```<code>> theme@3.1.1 start /home/amir/projects/planning-project/src/theme/static_src
> npm run dev

> theme@3.1.1 dev /home/amir/projects/planning-project/src/theme/static_src
> cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w

/home/amir/projects/planning-project/src/theme/static_src/node_modules/tailwindcss/lib/cli.js:300
        throw err;
        ^

TypeError: Object.fromEntries is not a function
    at args (/home/amir/projects/planning-project/src/theme/static_src/node_modules/tailwindcss/lib/cli.js:243:47)
    at Object.<anonymous> (/home/amir/projects/planning-project/src/theme/static_src/node_modules/tailwindcss/lib/cli.js:302:3)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! theme@3.1.1 dev: `cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the theme@3.1.1 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/amir/.npm/_logs/2022-02-11T09_27_46_003Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! theme@3.1.1 start: `npm run dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the theme@3.1.1 start script.
</code>```

I have tried going into "theme/static_src/src" directory and running npm run build-postcss, based on an answer on GitHub issue tracker, but then I get :

```<code>npm ERR! missing script: build-postcss
</code>```

答: Turns out since I installed node via the standard servers it was an old version. You need to install a newer node version to solve this problem.</p>

Title: django-tailwind, can't start dev server

Body:
I've done everything according to the django-tailwind docs, but when I want to start the dev server I get the following error:

> theme@3.1.1 start /home/amir/projects/planning-project/src/theme/static_src
> npm run dev

> theme@3.1.1 dev /home/amir/projects/planning-project/src/theme/static_src
> cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w

/home/amir/projects/planning-project/src/theme/static_src/node_modules/tailwindcss/lib/cli.js:300
        throw err;
        ^

TypeError: Object.fromEntries is not a function
    at args (/home/amir/projects/planning-project/src/theme/static_src/node_modules/tailwindcss/lib/cli.js:243:47)
    at Object.<anonymous> (/home/amir/projects/planning-project/src/theme/static_src/node_modules/tailwindcss/lib/cli.js:302:3)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! theme@3.1.1 dev: `cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the theme@3.1.1 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/amir/.npm/_logs/2022-02-11T09_27_46_003Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! theme@3.1.1 start: `npm run dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the theme@3.1.1 start script.

I have tried going into "theme/static_src/src" directory and running npm run build-postcss, based on an answer on GitHub issue tracker, but then I get :

npm ERR! missing script: build-postcss


问:
filter() function having issues in filtering rows using selectinput(multiple)
The following code filters rows of CO2 with specific names from the 'plant' column. However i have been having trouble doing this. When i use selectinput i dont get all the rows. For example in the following picture i have selected so many types of plants but only a few rows show up.

```<code> library(shiny)
    library(tidyverse)
    ui <- fluidPage((fluidRow(column(6,
        selectInput('co2',choices=CO2[1],multiple = T),
        tableOutput('table'))

        )

        )

    )

    server <- function(input, output, session) {
        output$table <-renderTable(
            filter(CO2,Plant==input$co2))

    }

    shinyApp(ui, server)
</code>```

答:
I made your example reproducible. Does this solve your problem ?

```<code>library(shiny)
library(tidyverse)

CO2 <- data.frame(Plant=c("id1","id2","id3"),Info=c("plant1","plant2","plant3"))

ui <- fluidPage((fluidRow(column(6,
                                 selectInput('co2',"selecting",choices=CO2$Plant,multiple = T),
                                 tableOutput('table')))))

server <- function(input, output, session) {
  output$table <-renderTable(
    if(!length(input$co2)==0){
      CO2 %>% dplyr::filter(Plant %in% input$co2)
  } else CO2
  )
}

shinyApp(ui, server)
</code>```

I think the error was to use the operator == and not %in%, which made the behavior of your filter quite strange.

Body:
The following code filters rows of CO2 with specific names from the 'plant' column. However i have been having trouble doing this. When i use selectinput i dont get all the rows. For example in the following picture i have selected so many types of plants but only a few rows show up.

 library(shiny)
    library(tidyverse)
    ui <- fluidPage((fluidRow(column(6,
        selectInput('co2',choices=CO2[1],multiple = T),
        tableOutput('table'))

        )

        )

    )

    server <- function(input, output, session) {
        output$table <-renderTable(
            filter(CO2,Plant==input$co2))

    }

    shinyApp(ui, server)

Body:
I made your example reproducible. Does this solve your problem ?

library(shiny)
library(tidyverse)

CO2 <- data.frame(Plant=c("id1","id2","id3"),Info=c("plant1","plant2","plant3"))

ui <- fluidPage((fluidRow(column(6,
                                 selectInput('co2',"selecting",choices=CO2$Plant,multiple = T),
                                 tableOutput('table')))))

server <- function(input, output, session) {
  output$table <-renderTable(
    if(!length(input$co2)==0){
      CO2 %>% dplyr::filter(Plant %in% input$co2)
  } else CO2
  )
}

shinyApp(ui, server)

I think the error was to use the operator == and not %in%, which made the behavior of your filter quite strange.


问:
How do I parse a JSON list with different types in Spark?
I have this file saved in /test.json:

{"changes": [["buy", "0.924000", "34100.21"], ["sell", "0.928000", "101.1"]]}
```
<p>I need to define a schema for it in pyspark and read it in <code>FAILFAST</code> mode, but I haven't been able to yet. This is what I have so far and I can't tell why it is wrong:</p>
<pre class="lang-py prettyprint-override"><code>element = StructType(
    [
        StructField("side", StringType(), nullable=False),
        StructField("price", DecimalType(28, 8), nullable=False),
        StructField("size", DecimalType(28, 8), nullable=False),
    ]
)
schema = StructType(
    [
        StructField(
            "changes",
            ArrayType(element, containsNull=False),
        )
    ]
)
df = spark.read.schema(schema).option("mode", "FAILFAST").json("/test.json")
df.show(4, truncate=False)
</code>```

The only kind of useful error line in the logs is

Caused by: org.apache.spark.sql.catalyst.util.BadRecordException:
java.lang.RuntimeException: Failed to parse a value for data type
structside:string,price:decimal(28,8),size:decimal(28,8) (current
token: START_ARRAY).

Even if I change the "price" and "size" types in element to StringType(), it still fails with the same error.

答:
Your schema does not correspond to the data you're trying to read. changes is an array of arrays of strings not array so structs.

Try with this instead:

schema = StructType([
    StructField(
        "changes",
        ArrayType(ArrayType(StringType(), False), containsNull=False),
    )]
)
df = spark.read.schema(schema).option("mode", "FAILFAST").json("/test.json")

df.show(4, truncate=False)
#+----------------------------------------------------+
#|changes                                             |
#+----------------------------------------------------+
#|[[buy, 0.924000, 34100.21], [sell, 0.928000, 101.1]]|
#+----------------------------------------------------+
```
<hr />
<p>That being said, if you always have sub-arrays of 3 elements and you want to convert them into structs then you can use <code>transform</code> function like this:</p>
<pre class="lang-py prettyprint-override"><code>from pyspark.sql import functions as F

df.withColumn(
    "changes",
    F.expr("transform(changes, x -> (x[0] as side, x[1] as price, x[2] as size))")
).show()
</code>```

You can add custom casting inside the transform function to cast x[1] and x[2] into DecimalType(28, 8) if you want.

Body:
I have this file saved in /test.json:

{"changes": [["buy", "0.924000", "34100.21"], ["sell", "0.928000", "101.1"]]}

I need to define a schema for it in pyspark and read it in FAILFAST mode, but I haven't been able to yet. This is what I have so far and I can't tell why it is wrong:

element = StructType(
    [
        StructField("side", StringType(), nullable=False),
        StructField("price", DecimalType(28, 8), nullable=False),
        StructField("size", DecimalType(28, 8), nullable=False),
    ]
)
schema = StructType(
    [
        StructField(
            "changes",
            ArrayType(element, containsNull=False),
        )
    ]
)
df = spark.read.schema(schema).option("mode", "FAILFAST").json("/test.json")
df.show(4, truncate=False)

The only kind of useful error line in the logs is

Caused by: org.apache.spark.sql.catalyst.util.BadRecordException:
java.lang.RuntimeException: Failed to parse a value for data type
structside:string,price:decimal(28,8),size:decimal(28,8) (current
token: START_ARRAY).

Even if I change the "price" and "size" types in element to StringType(), it still fails with the same error.

Body:
Your schema does not correspond to the data you're trying to read. changes is an array of arrays of strings not array so structs.

Try with this instead:

schema = StructType([
    StructField(
        "changes",
        ArrayType(ArrayType(StringType(), False), containsNull=False),
    )]
)
df = spark.read.schema(schema).option("mode", "FAILFAST").json("/test.json")

df.show(4, truncate=False)
#+----------------------------------------------------+
#|changes                                             |
#+----------------------------------------------------+
#|[[buy, 0.924000, 34100.21], [sell, 0.928000, 101.1]]|
#+----------------------------------------------------+

That being said, if you always have sub-arrays of 3 elements and you want to convert them into structs then you can use transform function like this:

from pyspark.sql import functions as F

df.withColumn(
    "changes",
    F.expr("transform(changes, x -> (x[0] as side, x[1] as price, x[2] as size))")
).show()

You can add custom casting inside the transform function to cast x[1] and x[2] into DecimalType(28, 8) if you want.


答:
Well, if this is the WHOLE method, then passing the value of forExport means nothing.

The method doesn't use the parameter whatsoever.

And the return value of a void method is null.


问:
Flutter - How can I follow the uninstall of the application?
I am developing a flutter app. I want to update its status in my database when the user deletes the app from own phone. How can I follow these changes? Is it possible on flutter?</p>

答:
There is no way to do it in iOS, but for android, you can use device_apps package to get the current list of installed apps and then compare it to the previously fetched data.

First, add this to your androids manifest file:

```<code><manifest...>

    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

</manifest>
</code>```

and then use it:

```<code>List<Application> apps = await DeviceApps.getInstalledApplications();
</code>```

Body:
There is no way to do it in iOS, but for android, you can use device_apps package to get the current list of installed apps and then compare it to the previously fetched data.

First, add this to your androids manifest file:

<manifest...>

    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

</manifest>

and then use it:

List<Application> apps = await DeviceApps.getInstalledApplications();


问:
fluentd -> logstash (net.logstash.logback.encoder.LogstashEncoder)
Does anyone have example fluentd & logstash config to make this scenario work?

My Java containers use Logback, with log output encoded into json by the logback LogstashEncoder.
Containers run in OpenShift which enforces use of "fluentd" for log forwarding.
We have fluentd pointing to a stand-alone ELK using its "fluentForward" capability.
On the logstash side we have nominated an input codec of fluent, and a json filter sourcing json from the message field.

We observe errors with text such as:  "reason"=>"Can't get text on a START_OBJECT at 1:1712"

I will happily share config here if that is helpful, but seeing some known-to-be-working example would also help.

Kubernetes (OpenShift) ClusterLogForwarder

```<code>apiVersion: logging.openshift.io/v1
kind: ClusterLogForwarder
spec:
  inputs:
    - application:
        namespaces:
          - unix
      name: my-app-logs
  outputs:
    - name: fluentd-server-insecure
      type: fluentdForward
      url: 'tcp://logstash.domain.com:24224'
  pipelines:
    - inputRefs:
        - application
        - audit
      name: forward-to-fluentd-insecure
      outputRefs:
        - fluentd-server-insecure
</code>```

Logstash Config

```<code>input {
    tcp {
        host => "10.110.250.127"
        port => 24224
        codec => fluent
        type => "rsyslog"
    }
}
filter {
    json {
        source => "message"
        skip_on_invalid_json => true
    }
}
output {
    if [type] == "rsyslog" {
        elasticsearch {
            hosts => [ "elasticsearch.domain.com:9200" ]
        }
    }
}
</code>```

Error

```<code>Can't get text on a START_OBJECT at 1:1712
</code>```

答:
First things first: you don't have to use the built-in logging functionality with OpenShift, but could instead deploy the Elastic Cloud Operator and then use a beat if that suites your needs a little better.

However, if you want to stick to cluster-logging-operator, stick close to the documentation:

```<code>

    input {
      tcp {
        codec => fluent
        port => 4000
      }
    }

</code>```

You are not receiving rsyslog type logs in this scenario, so don't specify that.

Additionally, if you're not doing any bigger processing in your logstash pipeline, which is what it looks like, I'd recommend for you to forward directly to the Elasticsearch instance:

```<code>apiVersion: "logging.openshift.io/v1"
kind: ClusterLogForwarder
metadata:
  name: instance
  namespace: openshift-logging
spec:
  outputs:
   - name: elasticsearch-insecure
     type: "elasticsearch"
     url: http://elasticsearch.insecure.com:9200
</code>```

One last remark: make sure to always check if the versions you use are compatible. There is a lot of change ongoing with OpenShift clusterlogging and the forwarder so things might change. Red Hat provides a table where you can look up the compatiblity

Body:
Does anyone have example fluentd & logstash config to make this scenario work?

My Java containers use Logback, with log output encoded into json by the logback LogstashEncoder.
Containers run in OpenShift which enforces use of "fluentd" for log forwarding.
We have fluentd pointing to a stand-alone ELK using its "fluentForward" capability.
On the logstash side we have nominated an input codec of fluent, and a json filter sourcing json from the message field.

We observe errors with text such as:  "reason"=>"Can't get text on a START_OBJECT at 1:1712"

I will happily share config here if that is helpful, but seeing some known-to-be-working example would also help.

Kubernetes (OpenShift) ClusterLogForwarder

apiVersion: logging.openshift.io/v1
kind: ClusterLogForwarder
spec:
  inputs:
    - application:
        namespaces:
          - unix
      name: my-app-logs
  outputs:
    - name: fluentd-server-insecure
      type: fluentdForward
      url: 'tcp://logstash.domain.com:24224'
  pipelines:
    - inputRefs:
        - application
        - audit
      name: forward-to-fluentd-insecure
      outputRefs:
        - fluentd-server-insecure

Logstash Config

input {
    tcp {
        host => "10.110.250.127"
        port => 24224
        codec => fluent
        type => "rsyslog"
    }
}
filter {
    json {
        source => "message"
        skip_on_invalid_json => true
    }
}
output {
    if [type] == "rsyslog" {
        elasticsearch {
            hosts => [ "elasticsearch.domain.com:9200" ]
        }
    }
}

Error

Can't get text on a START_OBJECT at 1:1712

Body:
First things first: you don't have to use the built-in logging functionality with OpenShift, but could instead deploy the Elastic Cloud Operator and then use a beat if that suites your needs a little better.

However, if you want to stick to cluster-logging-operator, stick close to the documentation:

    input {
      tcp {
        codec => fluent
        port => 4000
      }
    }

You are not receiving rsyslog type logs in this scenario, so don't specify that.

Additionally, if you're not doing any bigger processing in your logstash pipeline, which is what it looks like, I'd recommend for you to forward directly to the Elasticsearch instance:

apiVersion: "logging.openshift.io/v1"
kind: ClusterLogForwarder
metadata:
  name: instance
  namespace: openshift-logging
spec:
  outputs:
   - name: elasticsearch-insecure
     type: "elasticsearch"
     url: http://elasticsearch.insecure.com:9200

One last remark: make sure to always check if the versions you use are compatible. There is a lot of change ongoing with OpenShift clusterlogging and the forwarder so things might change. Red Hat provides a table where you can look up the compatiblity


问:
What token type is ETH on the Polygon network?
I am looking to work with ETH tokens on the Polygon network. My aim is to build a simple payment splitting application. Primarily to split royalties from Opensea. The issue I have come across is that Opensea doesn't seem to pay royalties in Matic token, instead, royalties are paid in ETH (plus other tokens).

I understand how to handle the network native, Matic, as well as ERC20 tokens. My main question is, what token type is ETH on the Polygon network? Is it an ERC20 (or similar) used to represent ETH on Polygon or does it have a special token type and privileges by virtue of Polygon being a layer two solution for Ethereum?

I'm sorry if this is a basic question, I tried to find answers online but because of the keywords all of the results were about bridging ETH to Polygon.

答:
Opensea uses WETH token on Polygon, which is an ERC-20 token representing the Ethereum mainnet ETH.

Please note, the "purple" Polygon ETH you see on OpenSea, is actually WETH (Wrapped Ether) on the blockchain level of Polygon.

Source: https://support.opensea.io/hc/en-us/articles/4403264773523-How-do-I-find-my-funds-on-Polygon-


问:
How can I fix this memory leak in my SharePoint Powershell script?
Purpose of the script: due to our Active Directory infrastructure, we add about 6000 entries directly to the Site User Info List so that they are shown in the address book in the SharePoint people picker.
The script creates about 6000 SPUser objects in order to add them to the Site User Info List. Most of them already exist, in this case new-SPUser should do nothing, right?

EDIT: please leave a feedback or possible solution. I removed some of the large log for better overview and added some details. Perhaps you know another forum where I should post this question?

I get lots of messages like this:

Potentially excessive number of SPRequest objects (20) currently
  unreleased on thread 9.  Ensure that this object or its parent (such
  as an SPWeb or SPSite) is being properly disposed. This object is
  holding on to a separate native heap.This object will not be
  automatically disposed. Allocation Id for this object: {...snip...} Stack
  trace of current allocation: at
  Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite
  site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean
  bNotAddToContext, Byte[] UserToken, String userName, Boolean
  bIgnoreTokenTimeout, Boolean bAsAnonymous)

  ...snip...

And lots of messages like this:

08/17/2011 19:38:35.26    PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     nask    Monitorable An SPRequest object was reclaimed by the garbage collector instead of being explicitly freed.  To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it.  Allocation Id: {09C61E87-2BA1-4CEA-BB3C-266A1345559A}  To determine where this object was allocated, set Microsoft.SharePoint.Administration.SPWebService.ContentService.CollectSPRequestAllocationCallStacks = true.    de663eab-8063-4381-88b5-01cc50d51b77

This is the current script with highlighted four lines (# ***) that we added to solve it (did not work).

```<code>Write-Host "Fill Site User Info List for "$args[0]
add-pssnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

Start-SPAssignment -Global    # ***

#global properties
$ppFilter = "(...)"

get-date

$ldapFilter = "(...)"
$ldapDirectory = "LDAP://DC=..."
Write-Host "Get all users from ..."
$de = New-Object system.directoryservices.directoryentry($ldapDirectory)
$de
$newsearch = New-Object System.DirectoryServices.DirectorySearcher($de)
write-host "Filter all active users with ..."
$newsearch.Filter = $ldapFilter
$newsearch.PageSize = 200
$result = $newsearch.FindAll()

write-Host "Get all domain user accounts..."
$useraccounts = $result | % {"..."}

$siteCollection = get-spsite $args[0]
$webApp = $siteCollection.WebApplication

Write-Host "clear people picker filter" $webApp.Name "..."
$webApp.peoplepickersettings.ActiveDirectoryCustomFilter = ""
$webApp.Update()

write-Host "---------------"
$siteUrl = $siteCollection.Url
Write-Host "add "$useraccounts.Count" users to site collection "$siteUrl "..."
$start =  get-date
$site = $siteCollection.RootWeb       # ***
foreach ($user in $useraccounts) {
    $current = New-SPUser -UserAlias $user -Web $site   # *** was before: $siteUrl
}
$end = get-date
$end - $start
$SiteCollection.Dispose()
Write-Host "---------------"

Write-Host "set people picker filter to" $ppFilter "..."
$webApp.peoplepickersettings.ActiveDirectoryCustomFilter = $ppFilter
$webApp.Update()

Stop-SPAssignment -Global    # ***

Write-Host "Done."
get-date
</code>```

Is there an obvious error we made? Thank you for any suggestions.

In answer to @x0n I post a larger portion of the log. Sorry for this unreadable formatting. Is there a better way to post logs? All line breaks and tab spaces are messed up.

The point is, that the messages about reclaimed SPRequest object come from the powershell process. I am perfectly sure that this script was the only one running. This script used to finish within less than 10 Minutes, but now it does not finish even after 1.5 hours. I am pretty sure I did not change anything in the script that changed the behaviour. The performance view of the Windows Task Manager did show a moderate load on CPU and quite high usage of RAM (not all the way to 100%) while the script was running.

Timestamp                  Process                     TID     Area                    Category        EventID Level       Message     Correlation
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Entering EndProcessing Method of New-SPUser.

  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Leaving EndProcessing Method of New-SPUser.

  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Entering BeginProcessing Method of New-SPUser.  de663eab-8063-4381-88b5-01cc50d51b77
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Leaving BeginProcessing Method of New-SPUser.   de663eab-8063-4381-88b5-01cc50d51b77
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Entering ProcessRecord Method of New-SPUser.    de663eab-8063-4381-88b5-01cc50d51b77
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     naqx    Monitorable Potentially excessive number of SPRequest objects (19) currently unreleased on thread 9.  Ensure that this object or its parent (such as an SPWeb or SPSite) is being properly disposed. This object is holding on to a separate native heap.This object will not be automatically disposed. Allocation Id for this object: {815F9A3D-6635-42FA-9658-B6294968136E} Stack trace of current allocation:    at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)     at Microsoft.SharePoint.SPRequestManager.GetContextRequest(SPRequestAuthenticationMode authenticationMode)     at Microsoft.SharePoint.Administration.SPFarm.g... de663eab-8063-4381-88b5-01cc50d51b77

( .... snip ....)

08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     naqx    Monitorable Potentially excessive number of SPRequest objects (19) currently unreleased on thread 9.  Ensure that this object or its parent (such as an SPWeb or SPSite) is being properly disposed. This object is holding on to a separate native heap. Allocation Id for this object: {F9CDF3DA-41B1-485D-B78F-0266545C417A} Stack trace of current allocation:    at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)     at Microsoft.SharePoint.SPWeb.InitializeSPRequest()     at Microsoft.SharePoint.SPWeb.InitWebPublic()     at Microsoft.SharePoint.SPWeb.get_Exists()     at Microsoft.SharePoint.PowerShell.SPWebPipeBind.Rea... de663eab-8063-4381-88b5-01cc50d51b77

(... snip ...)

  (... many of those messages: )

  08/17/2011 19:38:35.26     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     nask    Monitorable An SPRequest object was reclaimed by the garbage collector instead of being explicitly freed.  To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it.  Allocation Id: {09C61E87-2BA1-4CEA-BB3C-266A1345559A}  To determine where this object was allocated, set Microsoft.SharePoint.Administration.SPWebService.ContentService.CollectSPRequestAllocationCallStacks = true.    de663eab-8063-4381-88b5-01cc50d51b77

答:
This message does not actually indicate a leak - the key thing here is the word "potentially." All that message means is that your thread has a lot open at the same time. The threshhold for emitting that message is actually set quite low for practical use. What's really important is that they are disposed correctly at the end of their lifetime. If you really had a leak, you'd see messages like this:

05/012/2011 12:58:47.31                w3wp.exe (0x105C)

  0x09A8 Windows SharePoint Services                   General

  8l1n       High       An SPRequest object was not disposed before the
  end of this thread.  To avoid wasting system resources, dispose of
  this object or its parent (such as an SPSite or SPWeb) as soon as you
  are done using it.  This object will now be disposed.  Allocation Id:
  {5BFFCA4B-3B91-45BF-98CD-0BB508BE30EE} To determine where this object
  was allocated, create a registry key at
  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Web Server
  Extensions\HeapSettings. Then create a new DWORD named
  SPRequestStackTrace with the value 1 under this key.

Stefan Grossner has a great article explaining the reasoning behind all of this, including why the threshold for the warning is probably too low (and how you can change it to something more practical.)

http://blogs.technet.com/b/stefan_gossner/archive/2008/05/07/troubleshooting-spsite-spweb-leaks-in-wss-v3-and-moss-2007.aspx

Incidentally, even if you did have a leak and you couldn't find it, closing the powershell process will return the memory.

Hope this helps.

Body:
Purpose of the script: due to our Active Directory infrastructure, we add about 6000 entries directly to the Site User Info List so that they are shown in the address book in the SharePoint people picker.
The script creates about 6000 SPUser objects in order to add them to the Site User Info List. Most of them already exist, in this case new-SPUser should do nothing, right?

EDIT: please leave a feedback or possible solution. I removed some of the large log for better overview and added some details. Perhaps you know another forum where I should post this question?

I get lots of messages like this:

Potentially excessive number of SPRequest objects (20) currently
  unreleased on thread 9.  Ensure that this object or its parent (such
  as an SPWeb or SPSite) is being properly disposed. This object is
  holding on to a separate native heap.This object will not be
  automatically disposed. Allocation Id for this object: {...snip...} Stack
  trace of current allocation: at
  Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite
  site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean
  bNotAddToContext, Byte[] UserToken, String userName, Boolean
  bIgnoreTokenTimeout, Boolean bAsAnonymous)

  ...snip...

And lots of messages like this:

08/17/2011 19:38:35.26    PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     nask    Monitorable An SPRequest object was reclaimed by the garbage collector instead of being explicitly freed.  To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it.  Allocation Id: {09C61E87-2BA1-4CEA-BB3C-266A1345559A}  To determine where this object was allocated, set Microsoft.SharePoint.Administration.SPWebService.ContentService.CollectSPRequestAllocationCallStacks = true.    de663eab-8063-4381-88b5-01cc50d51b77

This is the current script with highlighted four lines (# ***) that we added to solve it (did not work).

Write-Host "Fill Site User Info List for "$args[0]
add-pssnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue

Start-SPAssignment -Global    # ***

#global properties
$ppFilter = "(...)"

get-date

$ldapFilter = "(...)"
$ldapDirectory = "LDAP://DC=..."
Write-Host "Get all users from ..."
$de = New-Object system.directoryservices.directoryentry($ldapDirectory)
$de
$newsearch = New-Object System.DirectoryServices.DirectorySearcher($de)
write-host "Filter all active users with ..."
$newsearch.Filter = $ldapFilter
$newsearch.PageSize = 200
$result = $newsearch.FindAll()

write-Host "Get all domain user accounts..."
$useraccounts = $result | % {"..."}

$siteCollection = get-spsite $args[0]
$webApp = $siteCollection.WebApplication

Write-Host "clear people picker filter" $webApp.Name "..."
$webApp.peoplepickersettings.ActiveDirectoryCustomFilter = ""
$webApp.Update()

write-Host "---------------"
$siteUrl = $siteCollection.Url
Write-Host "add "$useraccounts.Count" users to site collection "$siteUrl "..."
$start =  get-date
$site = $siteCollection.RootWeb       # ***
foreach ($user in $useraccounts) {
    $current = New-SPUser -UserAlias $user -Web $site   # *** was before: $siteUrl
}
$end = get-date
$end - $start
$SiteCollection.Dispose()
Write-Host "---------------"

Write-Host "set people picker filter to" $ppFilter "..."
$webApp.peoplepickersettings.ActiveDirectoryCustomFilter = $ppFilter
$webApp.Update()

Stop-SPAssignment -Global    # ***

Write-Host "Done."
get-date

Is there an obvious error we made? Thank you for any suggestions.

In answer to @x0n I post a larger portion of the log. Sorry for this unreadable formatting. Is there a better way to post logs? All line breaks and tab spaces are messed up.

The point is, that the messages about reclaimed SPRequest object come from the powershell process. I am perfectly sure that this script was the only one running. This script used to finish within less than 10 Minutes, but now it does not finish even after 1.5 hours. I am pretty sure I did not change anything in the script that changed the behaviour. The performance view of the Windows Task Manager did show a moderate load on CPU and quite high usage of RAM (not all the way to 100%) while the script was running.

Timestamp                  Process                     TID     Area                    Category        EventID Level       Message     Correlation
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Entering EndProcessing Method of New-SPUser.

  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Leaving EndProcessing Method of New-SPUser.

  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Entering BeginProcessing Method of New-SPUser.  de663eab-8063-4381-88b5-01cc50d51b77
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Leaving BeginProcessing Method of New-SPUser.   de663eab-8063-4381-88b5-01cc50d51b77
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   PowerShell      6tf0    Medium      Entering ProcessRecord Method of New-SPUser.    de663eab-8063-4381-88b5-01cc50d51b77
  08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     naqx    Monitorable Potentially excessive number of SPRequest objects (19) currently unreleased on thread 9.  Ensure that this object or its parent (such as an SPWeb or SPSite) is being properly disposed. This object is holding on to a separate native heap.This object will not be automatically disposed. Allocation Id for this object: {815F9A3D-6635-42FA-9658-B6294968136E} Stack trace of current allocation:    at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)     at Microsoft.SharePoint.SPRequestManager.GetContextRequest(SPRequestAuthenticationMode authenticationMode)     at Microsoft.SharePoint.Administration.SPFarm.g... de663eab-8063-4381-88b5-01cc50d51b77

( .... snip ....)

08/17/2011 19:38:34.30     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     naqx    Monitorable Potentially excessive number of SPRequest objects (19) currently unreleased on thread 9.  Ensure that this object or its parent (such as an SPWeb or SPSite) is being properly disposed. This object is holding on to a separate native heap. Allocation Id for this object: {F9CDF3DA-41B1-485D-B78F-0266545C417A} Stack trace of current allocation:    at Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous)     at Microsoft.SharePoint.SPWeb.InitializeSPRequest()     at Microsoft.SharePoint.SPWeb.InitWebPublic()     at Microsoft.SharePoint.SPWeb.get_Exists()     at Microsoft.SharePoint.PowerShell.SPWebPipeBind.Rea... de663eab-8063-4381-88b5-01cc50d51b77

(... snip ...)

  (... many of those messages: )

  08/17/2011 19:38:35.26     PowerShell.exe (0x1388)     0x20C0  SharePoint Foundation   Performance     nask    Monitorable An SPRequest object was reclaimed by the garbage collector instead of being explicitly freed.  To avoid wasting system resources, dispose of this object or its parent (such as an SPSite or SPWeb) as soon as you are done using it.  Allocation Id: {09C61E87-2BA1-4CEA-BB3C-266A1345559A}  To determine where this object was allocated, set Microsoft.SharePoint.Administration.SPWebService.ContentService.CollectSPRequestAllocationCallStacks = true.    de663eab-8063-4381-88b5-01cc50d51b77


问:
How to clear setInterval ID in Angular?
I am building a basic timer in Angular. For this I have two button, one of them starts the timer and the other stops it. I am implementing setInterval with 1000ms delay. But when I press the stop button, the timer stops but the timeoutId is not cleared. I want to prevent the user not to start another timer when the first one doesnt finish. I use - if (this.timeoutId) return; - But I am not able to start it again as I stop it.
The question is how I can prevent the user to start new timer when the timer started. And how can I start it again when I stop it.

//game-control-component.ts

```<code>import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css'],
})
export class GameControlComponent implements OnInit {

@Output() onIncrement: EventEmitter<number> = new EventEmitter();
timer: number = 0;
timeoutId!: ReturnType<typeof setTimeout>;

constructor() {
  console.log(this.timeoutId);
}

increment() {
  this.timer++;
}

startTimer() {
  if (this.timeoutId) return;
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}

stopTimer() {
  clearInterval(this.timeoutId);
  console.log(this.timeoutId);
}

ngOnInit(): void {
  console.log(this.timeoutId);
 }

}
</code>```

//game-control-component-html

```<code><div class="row mt-5">
  <div class="col-12">
    <div class="button-group d-flex justify-content-evenly">
      <button (click)="startTimer()" class="btn btn-primary">Start</button>
      <button (click)="stopTimer()" class="btn btn-danger">Stop</button>
    </div>
  <h1 class="mt-5" style="text-align: center">{{ timer }}</h1>
  </div>
</code>```

答:
```<code>    // clear the timer once you click the stop button set 0 the timer variable .
stopTimer() {
      clearInterval(this.timeoutId);
      this.timer= 0; // Clear the timer
    }
    startTimer() {
      if (this.timeoutId) return; // remove this one
      this.timeoutId = setInterval(() => {
        this.increment();
        this.onIncrement.emit(this.timer);
      }, 1000);
    }
</code>```

Title: How to clear setInterval ID in Angular?

Body:
I am building a basic timer in Angular. For this I have two button, one of them starts the timer and the other stops it. I am implementing setInterval with 1000ms delay. But when I press the stop button, the timer stops but the timeoutId is not cleared. I want to prevent the user not to start another timer when the first one doesnt finish. I use - if (this.timeoutId) return; - But I am not able to start it again as I stop it.
The question is how I can prevent the user to start new timer when the timer started. And how can I start it again when I stop it.

//game-control-component.ts

import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-game-control',
  templateUrl: './game-control.component.html',
  styleUrls: ['./game-control.component.css'],
})
export class GameControlComponent implements OnInit {

@Output() onIncrement: EventEmitter<number> = new EventEmitter();
timer: number = 0;
timeoutId!: ReturnType<typeof setTimeout>;

constructor() {
  console.log(this.timeoutId);
}

increment() {
  this.timer++;
}

startTimer() {
  if (this.timeoutId) return;
  this.timeoutId = setInterval(() => {
    this.increment();
    this.onIncrement.emit(this.timer);
  }, 1000);
}

stopTimer() {
  clearInterval(this.timeoutId);
  console.log(this.timeoutId);
}

ngOnInit(): void {
  console.log(this.timeoutId);
 }

}

//game-control-component-html

      <button (click)="startTimer()" class="btn btn-primary">Start</button>
      <button (click)="stopTimer()" class="btn btn-danger">Stop</button>

{{ timer }}


答: ETH on the Polygon network is ERC-20 compatible token. Ethereum does not really exist on Matic, it is bridged there over a custodial Matic bridge, so the security guarantees won't be the same.</p>

Title: What token type is ETH on the Polygon network?

Body:
I am looking to work with ETH tokens on the Polygon network. My aim is to build a simple payment splitting application. Primarily to split royalties from Opensea. The issue I have come across is that Opensea doesn't seem to pay royalties in Matic token, instead, royalties are paid in ETH (plus other tokens).

I understand how to handle the network native, Matic, as well as ERC20 tokens. My main question is, what token type is ETH on the Polygon network? Is it an ERC20 (or similar) used to represent ETH on Polygon or does it have a special token type and privileges by virtue of Polygon being a layer two solution for Ethereum?

I'm sorry if this is a basic question, I tried to find answers online but because of the keywords all of the results were about bridging ETH to Polygon.