问:
Windows Service ElapsedEvent doesn't run after elapsed time
I have created an application running as a Windows Service in C#. It uses WinSCP to retrieve files from an FTP and do some work on them. It will run successfully many times but then just never start a new event after the time has elapsed. The amount of successful runs between a failure is seemingly random. I have to kill the process through Task Manager as it is unresponsive to stopping it via the Services GUI in Windows.

The OnStart method below will always run and log successfully without issue. The issue is that after the elapsed time (600000 ms or 10 minutes), the event will never fire again and the service becomes unresponsive.

```<code> protected override void OnStart(string[] args)
    {
        try
        {
            //Set up logging and timer parameters
            Logging.ConfigureTraceListeners();
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------LOG ON START------------");
            System.Timers.Timer timer = new System.Timers.Timer();
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " New Timer");
            timer.Interval = Convert.ToDouble(ConfigurationManager.AppSettings["PollingTime"]);
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Interval Set");
            timer.Elapsed += new System.Timers.ElapsedEventHandler(ProcessDocuments);
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Timer complete");
            timer.Start();
        }
        catch (Exception e)
        {
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Failed OnStart");
            Logging.WriteLine(e.ToString());
            throw;
        }
    }
</code>```

Here is a selection of the ProcessDocuments method.

```<code> public void ProcessDocuments(object sender, System.Timers.ElapsedEventArgs args)
    {
        Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------STARTING PROCESSINGDOCUMENTS METHOD------------");
        bool testmode = Convert.ToBoolean(ConfigurationManager.AppSettings["TestMode"]);
        bool gotfiles = false;
        try
        {
            //Configure FTP session options
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------BEGIN FTP RETRIEVAL------------");
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = ConfigurationManager.AppSettings["HostName"],
                UserName = ConfigurationManager.AppSettings["UserName"],
                Password = ConfigurationManager.AppSettings["Password"],
                SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"]
            };
    }
    catch (Exception e)
    {
       Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Error:" + e.ToString());
    }
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------ALL PROCESSING COMPLETE------------");
        counter++;
        Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Counter:" + counter);
}
</code>```

Here is generally what the logs look like.

```<code>2023-01-01 22:16:16 ------------LOG ON START------------
2023-01-01 22:16:16 New Timer
2023-01-01 22:16:16 Interval Set
2023-01-01 22:16:16 Timer complete
2023-01-04 18:44:03 ------------STARTING PROCESSINGDOCUMENTS METHOD------------
2023-01-04 18:44:03 ------------BEGIN FTP RETRIEVAL------------
2023-01-04 18:44:03 Set Session Options
2023-01-04 18:44:05 In production mode
2023-01-04 18:44:05 Remote Path is: [file path]
2023-01-04 18:44:05 Local Path is: [file path]
2023-01-04 18:44:06 ------------NO FILES FOUND------------
2023-01-04 18:44:06 ------------ALL PROCESSING COMPLETE------------
2023-01-04 18:44:06 Counter:1
</code>```

I added a counter to see if there was a pattern in the failures. When it fails, it logs that counter at the end and then never starts the ProcessDocuments method again. Here is what multiple successful runs looks like in the logs.

```<code>2022-11-09 22:08:16 ------------STARTING PROCESSINGDOCUMENTS METHOD------------
2022-11-09 22:08:16 ------------BEGIN FTP RETRIEVAL------------
2022-11-09 22:08:16 Set Session Options
2022-11-09 22:08:18 In production mode
2022-11-09 22:08:18 Remote Path is: [file path]
2022-11-09 22:08:18 Local Path is: [file path]
2022-11-09 22:08:18 ------------NO FILES FOUND------------
2022-11-09 22:08:19 ------------ALL PROCESSING COMPLETE------------
2022-11-09 22:08:19 Counter:321
2022-11-09 22:18:16 ------------STARTING PROCESSINGDOCUMENTS METHOD------------
2022-11-09 22:18:16 ------------BEGIN FTP RETRIEVAL------------
2022-11-09 22:18:16 Set Session Options
2022-11-09 22:18:18 In production mode
2022-11-09 22:18:18 Remote Path is: [file path]
2022-11-09 22:18:18 Local Path is: [file path]
2022-11-09 22:18:18 ------------NO FILES FOUND------------
2022-11-09 22:18:19 ------------ALL PROCESSING COMPLETE------------
2022-11-09 22:18:19 Counter:322
</code>```

I have it run for thousands of instances or stop after 1. I haven't been able to find anything in my logs or via the Event Viewer linked to the failures.

Body:
I have created an application running as a Windows Service in C#. It uses WinSCP to retrieve files from an FTP and do some work on them. It will run successfully many times but then just never start a new event after the time has elapsed. The amount of successful runs between a failure is seemingly random. I have to kill the process through Task Manager as it is unresponsive to stopping it via the Services GUI in Windows.

The OnStart method below will always run and log successfully without issue. The issue is that after the elapsed time (600000 ms or 10 minutes), the event will never fire again and the service becomes unresponsive.

 protected override void OnStart(string[] args)
    {
        try
        {
            //Set up logging and timer parameters
            Logging.ConfigureTraceListeners();
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------LOG ON START------------");
            System.Timers.Timer timer = new System.Timers.Timer();
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " New Timer");
            timer.Interval = Convert.ToDouble(ConfigurationManager.AppSettings["PollingTime"]);
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Interval Set");
            timer.Elapsed += new System.Timers.ElapsedEventHandler(ProcessDocuments);
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Timer complete");
            timer.Start();
        }
        catch (Exception e)
        {
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Failed OnStart");
            Logging.WriteLine(e.ToString());
            throw;
        }
    }

Here is a selection of the ProcessDocuments method.

 public void ProcessDocuments(object sender, System.Timers.ElapsedEventArgs args)
    {
        Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------STARTING PROCESSINGDOCUMENTS METHOD------------");
        bool testmode = Convert.ToBoolean(ConfigurationManager.AppSettings["TestMode"]);
        bool gotfiles = false;
        try
        {
            //Configure FTP session options
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------BEGIN FTP RETRIEVAL------------");
            SessionOptions sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = ConfigurationManager.AppSettings["HostName"],
                UserName = ConfigurationManager.AppSettings["UserName"],
                Password = ConfigurationManager.AppSettings["Password"],
                SshHostKeyFingerprint = ConfigurationManager.AppSettings["SshHostKeyFingerprint"]
            };
    }
    catch (Exception e)
    {
       Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Error:" + e.ToString());
    }
            Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " ------------ALL PROCESSING COMPLETE------------");
        counter++;
        Logging.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " Counter:" + counter);
}

Here is generally what the logs look like.

2023-01-01 22:16:16 ------------LOG ON START------------
2023-01-01 22:16:16 New Timer
2023-01-01 22:16:16 Interval Set
2023-01-01 22:16:16 Timer complete
2023-01-04 18:44:03 ------------STARTING PROCESSINGDOCUMENTS METHOD------------
2023-01-04 18:44:03 ------------BEGIN FTP RETRIEVAL------------
2023-01-04 18:44:03 Set Session Options
2023-01-04 18:44:05 In production mode
2023-01-04 18:44:05 Remote Path is: [file path]
2023-01-04 18:44:05 Local Path is: [file path]
2023-01-04 18:44:06 ------------NO FILES FOUND------------
2023-01-04 18:44:06 ------------ALL PROCESSING COMPLETE------------
2023-01-04 18:44:06 Counter:1

I added a counter to see if there was a pattern in the failures. When it fails, it logs that counter at the end and then never starts the ProcessDocuments method again. Here is what multiple successful runs looks like in the logs.

2022-11-09 22:08:16 ------------STARTING PROCESSINGDOCUMENTS METHOD------------
2022-11-09 22:08:16 ------------BEGIN FTP RETRIEVAL------------
2022-11-09 22:08:16 Set Session Options
2022-11-09 22:08:18 In production mode
2022-11-09 22:08:18 Remote Path is: [file path]
2022-11-09 22:08:18 Local Path is: [file path]
2022-11-09 22:08:18 ------------NO FILES FOUND------------
2022-11-09 22:08:19 ------------ALL PROCESSING COMPLETE------------
2022-11-09 22:08:19 Counter:321
2022-11-09 22:18:16 ------------STARTING PROCESSINGDOCUMENTS METHOD------------
2022-11-09 22:18:16 ------------BEGIN FTP RETRIEVAL------------
2022-11-09 22:18:16 Set Session Options
2022-11-09 22:18:18 In production mode
2022-11-09 22:18:18 Remote Path is: [file path]
2022-11-09 22:18:18 Local Path is: [file path]
2022-11-09 22:18:18 ------------NO FILES FOUND------------
2022-11-09 22:18:19 ------------ALL PROCESSING COMPLETE------------
2022-11-09 22:18:19 Counter:322

I have it run for thousands of instances or stop after 1. I haven't been able to find anything in my logs or via the Event Viewer linked to the failures.


来源: stackexchange

问:
How to make VSCode indent correctly when pressing enter
I just started using VSCode to program in C/C++.

Sometimes (e.g. after deleting a line break) I am in the following situation, where | represents the cursor:

```<code>    x = 5;|    y = 10;
</code>```

If I press enter, then it becomes

```<code>    x = 5;
    |    y = 10;
</code>```

but I want the line y = 10; to be automatically indented to the correct place, namely

```<code>    x = 5;
    y = 10;
</code>```

This is the expected behavior in Visual Studio, which I can't get in VSCode.

In the setting, Editor: Auto Indent is set to full. I also enabled Editor: Format On Type, if that matters.

How can I get the expected result?

ContentLicense: CC BY-SA 4.0

Body:
I just started using VSCode to program in C/C++.

Sometimes (e.g. after deleting a line break) I am in the following situation, where | represents the cursor:

    x = 5;|    y = 10;

If I press enter, then it becomes

    x = 5;
    |    y = 10;

but I want the line y = 10; to be automatically indented to the correct place, namely

    x = 5;
    y = 10;

This is the expected behavior in Visual Studio, which I can't get in VSCode.

In the setting, Editor: Auto Indent is set to full. I also enabled Editor: Format On Type, if that matters.

How can I get the expected result?


问:
Using Powershell and TextToColumns in an Excel Workbook
I have an Excel sheet with 10 columns each containing two data fields separated by a space.  I want to separate the data fields into two columns.  But I don't want to replicate the code 10 times.  I want code I can loop through 10 times.  Sounds simple right?  The problem is that I can't set the ranges properly for the texttocolumns method.  It seems to insist on having literal references, i.e. "A1".

Trying to use any kind of counter for the range settings throws a COMexception error.

This works:

```<code>`$range  = $sheet.Range("A1").entirecolumn;
$target = $sheet.Range("A1");
$xlDelimited = 1
$xlTextQualifier = -4142
$xlTextFormat = 2
$result = $range.texttocolumns($target,$xlDelimited,$xlTextQualifier,$false,$false,$false,$false,$false,$true," ")`
</code>```

This doesn't work:

```<code>`$range  = $sheet.Range(1).entirecolumn;
$target = $sheet.Range(1);
$xlDelimited = 1
$xlTextQualifier = -4142
$xlTextFormat = 2
$result = $range.texttocolumns($target,$xlDelimited,$xlTextQualifier,$false,$false,$false,$false,$false,$true," ")`
</code>```

Body:
I have an Excel sheet with 10 columns each containing two data fields separated by a space.  I want to separate the data fields into two columns.  But I don't want to replicate the code 10 times.  I want code I can loop through 10 times.  Sounds simple right?  The problem is that I can't set the ranges properly for the texttocolumns method.  It seems to insist on having literal references, i.e. "A1".

Trying to use any kind of counter for the range settings throws a COMexception error.

This works:

`$range  = $sheet.Range("A1").entirecolumn;
$target = $sheet.Range("A1");
$xlDelimited = 1
$xlTextQualifier = -4142
$xlTextFormat = 2
$result = $range.texttocolumns($target,$xlDelimited,$xlTextQualifier,$false,$false,$false,$false,$false,$true," ")`

This doesn't work:

`$range  = $sheet.Range(1).entirecolumn;
$target = $sheet.Range(1);
$xlDelimited = 1
$xlTextQualifier = -4142
$xlTextFormat = 2
$result = $range.texttocolumns($target,$xlDelimited,$xlTextQualifier,$false,$false,$false,$false,$false,$true," ")`


问:
Is it possible to include a view directly from the html?
I would like to know if it's possible, with Django, to include a view in another view like:

Declare a view:

```<code>def ads(request):
    param = ["first_ads_title"]
    return render(request, "blog/ads.html", context={"param": param})
</code>```

With the following html :

```<code><div>ads {{ param[0] }}</div>
</code>```

And be able to call it from another html view like:

```<code><body>
  <h1>hello article {{ article }}</h1>
  {% include "blog/ads" %}
</body>
</code>```

To display first_ads_title in my body ?

Body:
I would like to know if it's possible, with Django, to include a view in another view like:

Declare a view:

def ads(request):
    param = ["first_ads_title"]
    return render(request, "blog/ads.html", context={"param": param})

With the following html :

ads {{ param[0] }}

And be able to call it from another html view like:

hello article {{ article }}

  {% include "blog/ads" %}

To display first_ads_title in my body ?


问:
problem code=exited, status=203/EXEC) when systemctl start odoo15
I installed  odoo 15 in vps and when I try start odoo15 by run

systemctl start odoo15
after that run :

systemctl status odoo15

I installed odoo 15 in vps and when I try start odoo15 by run

systemctl start odoo15
after that run

systemctl status odoo15

`● odoo15.service - Odoo15
Loaded: loaded (/etc/systemd/system/odoo15.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Thu 2023-01-05 12:25:15 UTC; 8s ago
Process: 19453 ExecStart=/opt/odoo/odoo15-venv/bin/python3 /opt/odoo/odoo15/odoo-bin -c /etc/odoo.conf (code=exited, status=203/EXEC)
Main PID: 19453 (code=exited, status=203/EXEC)

Jan 05 12:25:15 vps103.com\ systemd[1]:\ Started\ Odoo15.
Jan\ 05\ 12:25:15\ vps103.com\ systemd[1]:\ odoo15.service:\ main\ proces...C
Jan\ 05\ 12:25:15\ vps103.com\ systemd[1]:\ Unit\ odoo15.service\ entered....
Jan\ 05\ 12:25:15\ vps103.com systemd[1]: odoo15.service failed.
`
Can any one help me, please?

thanks alot


问:
Model checking of conveyor belt system on NuSMV using CTL specifications
apply model checking of conveyor belt system on NuSMV using CTL specifications as the two statements shown below

to validate the correctness using photoelectric sensors as input and synchronous motors as output  and reliability of the system.

verify the safety and reduce the errors using speed switch sensors as input and the same synchronous motor as output.

```<code>MODULE main
  VAR
    state : {BeltRunning, BeltStopped, Error, SafetyShutdown};
    photoelectricSensor : boolean;
    speedSwitchSensor : boolean;
  ASSIGN
    init(state) := BeltStopped;
    next(state) :=
      case
        state = BeltRunning & photoelectricSensor = TRUE  : BeltStopped;
        state = BeltStopped & photoelectricSensor = FALSE : BeltRunning;
        state = BeltRunning & photoelectricSensor = FALSE : Error;
        state = BeltStopped & photoelectricSensor = TRUE  : Error;
        speedSwitchSensor = TRUE : SafetyShutdown;
      esac;
</code>```

To check whether these properties are satisfied, we can use the NuSMV "check_ctlspec" command, followed by the CTL formula that we want to check. For example, to check whether the belt will never run when there is an object on the conveyor belt, we can use the following command:
check_ctlspec -p "AG !(state = BeltRunning & photoelectricSensor = TRUE)"

There's an error on coding shows as line 15: case conditions are not exhaustive

Body:
apply model checking of conveyor belt system on NuSMV using CTL specifications as the two statements shown below

to validate the correctness using photoelectric sensors as input and synchronous motors as output  and reliability of the system.

verify the safety and reduce the errors using speed switch sensors as input and the same synchronous motor as output.

MODULE main
  VAR
    state : {BeltRunning, BeltStopped, Error, SafetyShutdown};
    photoelectricSensor : boolean;
    speedSwitchSensor : boolean;
  ASSIGN
    init(state) := BeltStopped;
    next(state) :=
      case
        state = BeltRunning & photoelectricSensor = TRUE  : BeltStopped;
        state = BeltStopped & photoelectricSensor = FALSE : BeltRunning;
        state = BeltRunning & photoelectricSensor = FALSE : Error;
        state = BeltStopped & photoelectricSensor = TRUE  : Error;
        speedSwitchSensor = TRUE : SafetyShutdown;
      esac;

To check whether these properties are satisfied, we can use the NuSMV "check_ctlspec" command, followed by the CTL formula that we want to check. For example, to check whether the belt will never run when there is an object on the conveyor belt, we can use the following command:
check_ctlspec -p "AG !(state = BeltRunning & photoelectricSensor = TRUE)"

There's an error on coding shows as line 15: case conditions are not exhaustive


问:
How to backup and migrate Gatekeeper settings into a new cluster
I want to move all settings/policies/configurations of an instance ofGatekeepr into new cluster. is there an straight forward approach?</p>


问:
org.json.* is not accessible in JAVA Maven Project as a dependency
I am making a JavaFX project (for the GUI) on Maven and for the moment I want to convert a StringBuffer object to JSON.

I tried to add the dependency org.json from Maven but there is a problem in pom.xml file
Missing Artifact org.json:json:bundle:20220924

I tried adding an older version of org.json dependency, it had the same issue

I tried a different dependency, everything was ok in the pom.xml file but I could not import it into my project (any dependency).

All dependencies return this error: The type org.json.JSONArray is not accessible

Lastly, I tried to download the json-java.jar from github and add it into a libs folder on the base project directory and added it in the pom file as a dependency but it could not be resolved either.

My pom.xml file:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>books</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20220924</version>
            <type>bundle</type>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
            <groupId>com.sample</groupId>
            <artifactId>sample</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/libs/json-20220924.jar</systemPath>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.6</version>
                <executions>
                    <execution>
                        <!-- Default configuration for running -->
                        <!-- Usage: mvn clean javafx:run -->
                        <id>default-cli</id>
                        <configuration>
                            <mainClass>com.example.App</mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

In the end I downloaded Maven again and extracted it into a folder and changed my environment variables on path. Maven is successfully installed on version 3.8.7

Thank you in advance for any help!

UPDATE

I should mention that I tried it on a new java project (without maven) and it works fine, by importing the .jar file from git-hub repository

Body:
I am making a JavaFX project (for the GUI) on Maven and for the moment I want to convert a StringBuffer object to JSON.

I tried to add the dependency org.json from Maven but there is a problem in pom.xml file
Missing Artifact org.json:json:bundle:20220924

I tried adding an older version of org.json dependency, it had the same issue

I tried a different dependency, everything was ok in the pom.xml file but I could not import it into my project (any dependency).

All dependencies return this error: The type org.json.JSONArray is not accessible

Lastly, I tried to download the json-java.jar from github and add it into a libs folder on the base project directory and added it in the pom file as a dependency but it could not be resolved either.

My pom.xml file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>books</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20220924</version>
            <type>bundle</type>
        </dependency>

        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
            <groupId>com.sample</groupId>
            <artifactId>sample</artifactId>
            <version>1.0</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/libs/json-20220924.jar</systemPath>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.6</version>
                <executions>
                    <execution>

                        <id>default-cli</id>
                        <configuration>
                            <mainClass>com.example.App</mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

In the end I downloaded Maven again and extracted it into a folder and changed my environment variables on path. Maven is successfully installed on version 3.8.7

Thank you in advance for any help!

UPDATE

I should mention that I tried it on a new java project (without maven) and it works fine, by importing the .jar file from git-hub repository


问:
Access a 2D array from another class
I am trying to improve current code. To do so, I want to call another class.

I have colours and fruit, essentially something like this:
red = apple, yellow = banana, orange = orange ...

My proposed solution is to put this into a matrix, have the colour from one class and call the other class to get back the fruit name. Here is what I have so far:

```<code>private String c1 = red
...

private String f1 = apple
...

private String[][] food;

public void setFood(){
// HELP NEEDED
}

public String getFruit(string colour){
// HELP NEEDED - I'm guessing some sort of 2 for loops ?

return fruit;
}
</code>```

Title: Access a 2D array from another class

Body:
I am trying to improve current code. To do so, I want to call another class.

I have colours and fruit, essentially something like this:
red = apple, yellow = banana, orange = orange ...

My proposed solution is to put this into a matrix, have the colour from one class and call the other class to get back the fruit name. Here is what I have so far:

private String c1 = red
...

private String f1 = apple
...

private String[][] food;

public void setFood(){
// HELP NEEDED
}

public String getFruit(string colour){
// HELP NEEDED - I'm guessing some sort of 2 for loops ?

return fruit;
}


问:
Simpler way of mocking chained calls in Jest
I have a function and I am using dynamoose lib under the hood to make queries to database simpler:

```<code>export class MyService {
  private rep = new Rep<SomeModel>("sometable");

  public async get(id, user) {
    return await this.rep.instance
      .scan('itemId')
      .eq(id)
      .and()
      .where('belongsTo')
      .not()
      .eq(user)
      .exec();
  }
}
</code>```

I wrote a test that should check if this method is exposed. I mocked this using this way:

```<code>jest.mock("../Rep", () => {
  return {
    Rep: jest.fn().mockImplementation(() => {
      return {
        instance: {
          scan: () => {
            return {
              eq: () => {
                return {
                  and: () => return {} // ... etc. until final exec() returns some object
                }
              }
            }
          }
        }
    });
  }
});

const result = await new MyService().get("testid", "testuser");
expect(result).toBeDefined();
</code>```

It works, but I feel it could be done better, especially when I add new funtions. How to make it work in more elegant way?

Body:
I have a function and I am using dynamoose lib under the hood to make queries to database simpler:

export class MyService {
  private rep = new Rep<SomeModel>("sometable");

  public async get(id, user) {
    return await this.rep.instance
      .scan('itemId')
      .eq(id)
      .and()
      .where('belongsTo')
      .not()
      .eq(user)
      .exec();
  }
}

I wrote a test that should check if this method is exposed. I mocked this using this way:

jest.mock("../Rep", () => {
  return {
    Rep: jest.fn().mockImplementation(() => {
      return {
        instance: {
          scan: () => {
            return {
              eq: () => {
                return {
                  and: () => return {} // ... etc. until final exec() returns some object
                }
              }
            }
          }
        }
    });
  }
});

const result = await new MyService().get("testid", "testuser");
expect(result).toBeDefined();

It works, but I feel it could be done better, especially when I add new funtions. How to make it work in more elegant way?


问:
Create a new remote project with JetBrains Gateway
I have a preexisting Python project on github and want to use PyCharm 2022.3.1 to work remotely via SSH on that project. For this reason, I use JetBrains Gateway to connect to the remote. The SSH connection seems to work properly.
However, PyCharm is not willing to set up a new project for my cloned repository, after I passed the path in the following dialogue.

The final window that will open after specifying the path looks like this.

As you can see, there are no files available in the explorer and nothing is being loaded, even though files exist in this directory.
It must be noted that I don't have a .idea directory for the project yet, but would expect PyCharm to set one up for me.
Unfortunately I can't find a way to do so.
I don't want to create a .idea directory locally and add it to the repository because I don't want the repository to contain IDE specific files.
Interestingly, I have another project on the remote, which I was able to setup with a previous version of PyCharm / Gateway.

So is there any way for me to create a new PyCharm project on the remote with Gateway?


问:
Conditional Base pass dynamic value inside request body

I want to pass dynamic value inside  request body in my case I pass
thirdpartypaymentGatewayToken in two place inside request body and an
other place requestString as requestBody but I want make single
function and pass values inside request body dynamic. for your
reference I post my old code and new code.

Here my old code

```<code>    public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
                    throws AuthenticationException, UnknownHostException, BadRequestException {
                String brandwiseBearerToken = getBrandwiseAuthenticationToken();
                ThirdPartyPaymentGatewayResponse thirdPartyPaymentGatewayResponse = new ThirdPartyPaymentGatewayResponse();

    String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

                        RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
                        Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
                                .post(body)
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Bearer", brandwiseBearerToken)
                                .build();

                        Response response = client.newCall(request).execute();
                        ResponseBody responseBody = response.body();

                        JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
                        JsonElement error = jsonObject.get("Message");
    }

> second function
public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
                throws AuthenticationException, UnknownHostException, BadRequestException {
            String brandwiseBearerToken = getBrandwiseAuthenticationToken();

    String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

                    RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
                    Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
                            .post(body)
                            .addHeader("Content-Type", "application/json")
                            .addHeader("Bearer", brandwiseBearerToken)
                            .build();

                    Response response = client.newCall(request).execute();
                    ResponseBody responseBody = response.body();

                    JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
                    JsonElement error = jsonObject.get("Message");

/** rest of code*/
}
</code>```

third function different than other two

```<code>private String getBrandwiseAuthenticationToken() throws UnknownHostException, AuthenticationException {

OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/json");
                String requestString = "{\"LoginName\": \"" + brandwiseAuthUsername + "\",\"Password\": \""+ brandwiseAuthPassword + "\"}";

                RequestBody body = RequestBody.create(mediaType, requestString);
                Request request = new Request.Builder().url(brandwiseAuthenticationURL)
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();

                Response response = client.newCall(request).execute();
                ResponseBody responseBody = response.body();

                JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
}
</code>```

To overcome from this issue I do this way but I am not able make
request body as dynamic. Here my new code

```<code>private JsonObject gateWayToken(String url,String brandwiseBearerToken,
                            ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken ) throws IOException, AuthenticationException{

                        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

                        String requestString = "{\"LoginName\": \"" + brandwiseAuthUsername + "\",\"Password\": \""+ brandwiseAuthPassword + "\"}";

                        OkHttpClient client = new OkHttpClient();

                        MediaType mediaType = MediaType.parse("application/json");

                        RequestBody body=null;
                        //dynamic  value accept by  body
                        if(!Strings.isNullOrEmpty(requestString)) {
                            String brandwiseBearerPaymentGatewayTokenJson = ow.writeValueAsString(requestString);
                             body = RequestBody.create(mediaType,brandwiseBearerPaymentGatewayTokenJson);
                        }else {
                            String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
                             body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );
                        }
                        //if user is authenticated then header part will show
                            Request request=null;
                            if (brandwiseBearerToken != null && StringUtils.isNotEmpty(brandwiseBearerToken)) {
                                 request =new Request.Builder().url(url).post(body)
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Bearer", brandwiseBearerToken)
                                .build();
                            } else {
                             request=new Request.Builder().url(url).post(body)
                                .addHeader("Content-Type", "application/json")
                                .build();
                            }

                            Response response = client.newCall(request).execute();
                            ResponseBody responseBody = response.body();
                            return new Gson().fromJson(responseBody.string(), JsonObject.class);
                    }
</code>```

I want to dynamic exact at this point

```<code> if(!Strings.isNullOrEmpty(requestString)) {
                            String brandwiseBearerPaymentGatewayTokenJson = ow.writeValueAsString(requestString);
                             body = RequestBody.create(mediaType,brandwiseBearerPaymentGatewayTokenJson);
                        }else {
                            String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
                             body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );
                        }
</code>```

Check Passing values inside ReqestBody

Body:
I want to pass dynamic value inside  request body in my case I pass
thirdpartypaymentGatewayToken in two place inside request body and an
other place requestString as requestBody but I want make single
function and pass values inside request body dynamic. for your
reference I post my old code and new code.

Here my old code

    public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
                    throws AuthenticationException, UnknownHostException, BadRequestException {
                String brandwiseBearerToken = getBrandwiseAuthenticationToken();
                ThirdPartyPaymentGatewayResponse thirdPartyPaymentGatewayResponse = new ThirdPartyPaymentGatewayResponse();

    String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

                        RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
                        Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
                                .post(body)
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Bearer", brandwiseBearerToken)
                                .build();

                        Response response = client.newCall(request).execute();
                        ResponseBody responseBody = response.body();

                        JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
                        JsonElement error = jsonObject.get("Message");
    }

> second function
public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
                throws AuthenticationException, UnknownHostException, BadRequestException {
            String brandwiseBearerToken = getBrandwiseAuthenticationToken();

    String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);

                    RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
                    Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
                            .post(body)
                            .addHeader("Content-Type", "application/json")
                            .addHeader("Bearer", brandwiseBearerToken)
                            .build();

                    Response response = client.newCall(request).execute();
                    ResponseBody responseBody = response.body();

                    JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
                    JsonElement error = jsonObject.get("Message");

/** rest of code*/
}

third function different than other two

private String getBrandwiseAuthenticationToken() throws UnknownHostException, AuthenticationException {

OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/json");
                String requestString = "{\"LoginName\": \"" + brandwiseAuthUsername + "\",\"Password\": \""+ brandwiseAuthPassword + "\"}";

                RequestBody body = RequestBody.create(mediaType, requestString);
                Request request = new Request.Builder().url(brandwiseAuthenticationURL)
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();

                Response response = client.newCall(request).execute();
                ResponseBody responseBody = response.body();

                JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
}

To overcome from this issue I do this way but I am not able make
request body as dynamic. Here my new code

private JsonObject gateWayToken(String url,String brandwiseBearerToken,
                            ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken ) throws IOException, AuthenticationException{

                        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

                        String requestString = "{\"LoginName\": \"" + brandwiseAuthUsername + "\",\"Password\": \""+ brandwiseAuthPassword + "\"}";

                        OkHttpClient client = new OkHttpClient();

                        MediaType mediaType = MediaType.parse("application/json");

                        RequestBody body=null;
                        //dynamic  value accept by  body
                        if(!Strings.isNullOrEmpty(requestString)) {
                            String brandwiseBearerPaymentGatewayTokenJson = ow.writeValueAsString(requestString);
                             body = RequestBody.create(mediaType,brandwiseBearerPaymentGatewayTokenJson);
                        }else {
                            String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
                             body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );
                        }
                        //if user is authenticated then header part will show
                            Request request=null;
                            if (brandwiseBearerToken != null && StringUtils.isNotEmpty(brandwiseBearerToken)) {
                                 request =new Request.Builder().url(url).post(body)
                                .addHeader("Content-Type", "application/json")
                                .addHeader("Bearer", brandwiseBearerToken)
                                .build();
                            } else {
                             request=new Request.Builder().url(url).post(body)
                                .addHeader("Content-Type", "application/json")
                                .build();
                            }

                            Response response = client.newCall(request).execute();
                            ResponseBody responseBody = response.body();
                            return new Gson().fromJson(responseBody.string(), JsonObject.class);
                    }

I want to dynamic exact at this point

 if(!Strings.isNullOrEmpty(requestString)) {
                            String brandwiseBearerPaymentGatewayTokenJson = ow.writeValueAsString(requestString);
                             body = RequestBody.create(mediaType,brandwiseBearerPaymentGatewayTokenJson);
                        }else {
                            String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
                             body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );
                        }

Check Passing values inside ReqestBody


问:
Android interstitial ads orientation in react native
Is it possible to force interstitial Ads orientation to be portrait only ?

I hit the advertisement function when I press the back button in android but the ad will show me as landscape mode depends on my device orientation is it possible to display my interstial ad always portrait mode or any other way.


问:
Swift - Making JSON data available to the viewController
Spent the good part of three weeks trying to solve this problem. I programmed my swift JSON file and successfully brought down JSON data from our website and printed it in the output. What I can't do is get the JSON data out of my func() and into my ViewController! I am missing something and I don't know what it is.

I have a JSON model of the data that is a struct and decodable. That all works great.
I have a JSON manager (code below) that brings the data down using a URLSession and parses the data using a JSON decoder. That all works.

I just don't know how to make the data available outside of the URLSession closure to be used in my ViewController file. As an example I would like to do something like this: textField.text = json[0].acf.common_name in my viewController file.

What am I missing?

```<code>func getDate() {

let task = URLSession.shared.dataTask(with: URL(string: "https://apps.scaquarium.org/wp-json/wp/v2/gotspeciesid")!, completionHandler: { data, response, error in
     guard let data = data else {
         print("Something went wrong!")
         return
     }
     var result: [Response]?

    do {
        result = try JSONDecoder().decode([Response].self, from: data)

    }
     catch { print(error) }

     guard let json = result else {
         return
 }

//--All works and prints out nicely when I create a instance of getData() on my viewcontroller.

       print(json[0].acf.common_name)
       print(json[0].acf.scientific_name)
       print(json[0].acf.size)
       print(json[0].acf.fun_fact)
       print(json[0].acf.conservation_status)
       print(json[0].acf.species_image_1)
       print(json[0].acf.species_image_2)

 })
task.resume()

}
//------------END OF FETCH----------------------
</code>```

Body:
Spent the good part of three weeks trying to solve this problem. I programmed my swift JSON file and successfully brought down JSON data from our website and printed it in the output. What I can't do is get the JSON data out of my func() and into my ViewController! I am missing something and I don't know what it is.

I have a JSON model of the data that is a struct and decodable. That all works great.
I have a JSON manager (code below) that brings the data down using a URLSession and parses the data using a JSON decoder. That all works.

I just don't know how to make the data available outside of the URLSession closure to be used in my ViewController file. As an example I would like to do something like this: textField.text = json[0].acf.common_name in my viewController file.

What am I missing?

func getDate() {

let task = URLSession.shared.dataTask(with: URL(string: "https://apps.scaquarium.org/wp-json/wp/v2/gotspeciesid")!, completionHandler: { data, response, error in
     guard let data = data else {
         print("Something went wrong!")
         return
     }
     var result: [Response]?

    do {
        result = try JSONDecoder().decode([Response].self, from: data)

    }
     catch { print(error) }

     guard let json = result else {
         return
 }

//--All works and prints out nicely when I create a instance of getData() on my viewcontroller.

       print(json[0].acf.common_name)
       print(json[0].acf.scientific_name)
       print(json[0].acf.size)
       print(json[0].acf.fun_fact)
       print(json[0].acf.conservation_status)
       print(json[0].acf.species_image_1)
       print(json[0].acf.species_image_2)

 })
task.resume()

}
//------------END OF FETCH----------------------


问:
Value assigned to a local variable continues to exist after the program leaves the scope of the variable
I was trying to learn about dangling pointers, so I made a quick test including inner local scope, within the main function, and a pointer defined outside that inner local scope. Inside of it i'm defining and initializing local variable, and I'm assigning it's address as value of the pointer.

Here is the example:

```<code>#include <stdio.h>

int main()
{
    int *ptr = NULL;

    //Start of local scope
    {
        int a = 10;
        ptr = &a;
        printf("Address of a: %p\nValue of ptr: %p\n", &a, ptr);
    }
    //End of local scope

    printf("\nDereferenced value of ptr: %d", *ptr);

    return 0;
}
</code>```

The output is:

```<code>Address of a: 0x7ffcacf6146c
Value of ptr: 0x7ffcacf6146c

Dereferenced value of ptr: 10
</code>```

I was expecting some segmentation fault error or undefined behaviour, since the local scope is left, the local variable - terminated, and so I expected it's value to be erased.

Indeed - the variable is terminated, it's impossible to access it outside the scope, since it no longer exists. But the value stored in it continues to exist on the same address. After the local scope is left isn't it supposed the value to be erased alongside the variable, to which is assigned to? Isn't the memory location, which is occupied by the variable, cleansed from it's contents, after the end of the local scope is reached?

Isn't it supposed that this memory location, once freed, to be returned at OS disposal, thus making it inaccessible from the program? Or it remains to program's disposal until program termination occurs, and execution control is reverted back to OS?

One more code example. Let's modify the above example, and just define (without initializing) another variable of the same type, but this time outside of the scope, after it. On all tests I did - it occupied the same memory location, and even more - is being initialized with the same value, just because occupies the memory location on which the value was stored through the previous variable.

```<code>#include <stdio.h>

int main()
{
    int *ptr = NULL;

    //Start of local scope
    {
        int a = 10;
        ptr = &a;
        printf("Address of a: %p\nValue of ptr: %p\n", &a, ptr);
    }
    //End of local scope

    int b;

    printf("\nAddress of b: %p\nValue of b: %d\n", &b, b);

    printf("\nDereferenced value of ptr: %d", *ptr);

    return 0;
}
</code>```

Output is:

```<code>Address of a: 0x7fff5f9faecc
Value of ptr: 0x7fff5f9faecc

Address of b: 0x7fff5f9faecc
Value of b: 10

Dereferenced value of ptr: 10
</code>```

Body:
I was trying to learn about dangling pointers, so I made a quick test including inner local scope, within the main function, and a pointer defined outside that inner local scope. Inside of it i'm defining and initializing local variable, and I'm assigning it's address as value of the pointer.

Here is the example:

#include <stdio.h>

int main()
{
    int *ptr = NULL;

    //Start of local scope
    {
        int a = 10;
        ptr = &a;
        printf("Address of a: %p\nValue of ptr: %p\n", &a, ptr);
    }
    //End of local scope

    printf("\nDereferenced value of ptr: %d", *ptr);

    return 0;
}

The output is:

Address of a: 0x7ffcacf6146c
Value of ptr: 0x7ffcacf6146c

Dereferenced value of ptr: 10

I was expecting some segmentation fault error or undefined behaviour, since the local scope is left, the local variable - terminated, and so I expected it's value to be erased.

Indeed - the variable is terminated, it's impossible to access it outside the scope, since it no longer exists. But the value stored in it continues to exist on the same address. After the local scope is left isn't it supposed the value to be erased alongside the variable, to which is assigned to? Isn't the memory location, which is occupied by the variable, cleansed from it's contents, after the end of the local scope is reached?

Isn't it supposed that this memory location, once freed, to be returned at OS disposal, thus making it inaccessible from the program? Or it remains to program's disposal until program termination occurs, and execution control is reverted back to OS?

One more code example. Let's modify the above example, and just define (without initializing) another variable of the same type, but this time outside of the scope, after it. On all tests I did - it occupied the same memory location, and even more - is being initialized with the same value, just because occupies the memory location on which the value was stored through the previous variable.

#include <stdio.h>

int main()
{
    int *ptr = NULL;

    //Start of local scope
    {
        int a = 10;
        ptr = &a;
        printf("Address of a: %p\nValue of ptr: %p\n", &a, ptr);
    }
    //End of local scope

    int b;

    printf("\nAddress of b: %p\nValue of b: %d\n", &b, b);

    printf("\nDereferenced value of ptr: %d", *ptr);

    return 0;
}

Output is:

Address of a: 0x7fff5f9faecc
Value of ptr: 0x7fff5f9faecc

Address of b: 0x7fff5f9faecc
Value of b: 10

Dereferenced value of ptr: 10


问:
How to apply multiple methods from a list with class objects over Pandas DataFrame in Parallel
Let's say I have a list of "classifiers" and each have a "predict" method. So for example, take the following code

```<code>import pandas as pd

class ClassifierA():
    def __init__(self, name):
        self.name = name

    def predict(self, x):
        return x + 5

class ClassifierB():
    def __init__(self, name):
        self.name = name

    def predict(self, x):
        return x + 10

class ClassifierC():
    def __init__(self, name):
        self.name = name

    def predict(self, x):
        return x - 10

classifierA = ClassifierA(name="classifierA")
classifierB = ClassifierB(name="classifierB")
classifierC = ClassifierC(name="classifierC")

list_of_classifiers = [classifierA, classifierB, classifierC]
</code>```

In this case, the classifiers do something very simple, but in the real world, imagine they actually perform some prediction.

Now, imagine we have a Pandas DataFrame with many observations. In this case, 10 observations each is just a number from 1 to 10.

```<code>df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
})
</code>```

How can I apply each of the classifiers in the list to df.x in parallel? The output of what I want to achieve is the same as:

```<code>for classifier in list_of_classifiers:
    df['{}_prediction'.format(classifier.name)] = df['x'].apply(lambda x: classifier.predict(x))
</code>```

which yields

```<code>    x   classifierA_prediction  classifierB_prediction  classifierC_prediction
0   1   6   11  -9
1   2   7   12  -8
2   3   8   13  -7
3   4   9   14  -6
4   5   10  15  -5
5   6   11  16  -4
6   7   12  17  -3
7   8   13  18  -2
8   9   14  19  -1
9   10  15  20  0
</code>```

but the problem here is that I'm looping over each classifier in the list and also looping over each row in the dataframe via apply. I wonder if there's something more efficient.

For example, I could also do

```<code>predictions = df['x'].apply(
    lambda x: (classifierA.predict(x), classifierB.predict(x), classifierC.predict(x)))
</code>```

but the problem there is that then I am specifying each classifier manually and the list might be very big.

Body:
Let's say I have a list of "classifiers" and each have a "predict" method. So for example, take the following code

import pandas as pd

class ClassifierA():
    def __init__(self, name):
        self.name = name

    def predict(self, x):
        return x + 5

class ClassifierB():
    def __init__(self, name):
        self.name = name

    def predict(self, x):
        return x + 10

class ClassifierC():
    def __init__(self, name):
        self.name = name

    def predict(self, x):
        return x - 10

classifierA = ClassifierA(name="classifierA")
classifierB = ClassifierB(name="classifierB")
classifierC = ClassifierC(name="classifierC")

list_of_classifiers = [classifierA, classifierB, classifierC]

In this case, the classifiers do something very simple, but in the real world, imagine they actually perform some prediction.

Now, imagine we have a Pandas DataFrame with many observations. In this case, 10 observations each is just a number from 1 to 10.

df = pd.DataFrame({
    'x': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
})

How can I apply each of the classifiers in the list to df.x in parallel? The output of what I want to achieve is the same as:

for classifier in list_of_classifiers:
    df['{}_prediction'.format(classifier.name)] = df['x'].apply(lambda x: classifier.predict(x))

which yields

    x   classifierA_prediction  classifierB_prediction  classifierC_prediction
0   1   6   11  -9
1   2   7   12  -8
2   3   8   13  -7
3   4   9   14  -6
4   5   10  15  -5
5   6   11  16  -4
6   7   12  17  -3
7   8   13  18  -2
8   9   14  19  -1
9   10  15  20  0

but the problem here is that I'm looping over each classifier in the list and also looping over each row in the dataframe via apply. I wonder if there's something more efficient.

For example, I could also do

predictions = df['x'].apply(
    lambda x: (classifierA.predict(x), classifierB.predict(x), classifierC.predict(x)))

but the problem there is that then I am specifying each classifier manually and the list might be very big.


问:
ApexChart: Dunot chart ir not showing labels
I'm having a problem with donut charts in ApexCharts in my React App.

I have an API that returns to me a JSON and I pass this JSON data to some charts. The chart it's showing correct data, but the label isn't showing anything.

If I change something in the ChartComponent, for example, change the 'fontSize' from 15 to 10 the values of the labels are shown, but when rendering the screen, they disappear and return to 0.

see here how the graphs are appearing

see here how the graphs are when I change the 'fontSize'

App()

```<code>export default function App() {
  const referenceDate = new Date();
  const currentYear = referenceDate.getFullYear();
  const currentMonth = referenceDate.getMonth() + 1;
  const currentMonthName = referenceDate.toLocaleString("default", {
    month: "long",
  });

  const [month, setMonth] = useState(currentMonthName);
  const [monthId, setMonthId] = useState(currentMonth);
  const [apiData, setApiData] = useState();

  useEffect(() => {
    async function fillData() {
      if (month) {
        await getData(currentYear, monthId).then((response) =>
          setApiData(response)
        );
      }
    }
    fillData();
  }, [monthId]);

  const handleChange = (e) => {
    const selectedMonth = e.target.value;
    const selectedMonthId = Months[e.target.value].id;
    setMonth(selectedMonth);
    setMonthId(selectedMonthId);
  };

  return (
    <>
        <div className={styles.chartGroup}>
          <ChartCard title="Business Unit Head" value={apiData ? apiData['first'] : 0}></ChartCard>
          <ChartCard title="Financial" value={apiData ? apiData['second'] : 0}></ChartCard>
        </div>
        <div className={styles.chartGroup}>
          <ChartCard title="Commercial And Pipeline [LATAM]" value={apiData ? apiData['third'] : 0}></ChartCard>
          <ChartCard title="Commercial And Pipeline [NAM]" value={apiData ? apiData['fourth'] : 0}></ChartCard>
        </div>
        <div className={styles.chartGroup}>
          <ChartCard title="HR And Recuitment" value={apiData ? apiData['fifth'] : 0}></ChartCard>
          <ChartCard title="Delivery" value={apiData ? apiData['sixth] : 0}></ChartCard>
        </div>
      </div>
    </>
  );
}

const getData = async (year, month) => (await axiosInstance.get(`/homeChart/${year}/${month}`)).data;

async function generateChartData(data) {
  if (data) {
    return data;
  } else {
    console.log("no data");
  }
}
</code>```

ChartComponent

```<code>export default function ChartCard(props) {
  let progressValue = 0;
  let lapseValue = 0;
  const data = props.value;

  progressValue = data;
  lapseValue = 100 - data;

  const options = {
        colors: ["#0ead69", "#e71d36"],
        labels: ["Progress", "Lapse"],
        title: {
        text: props.title,
        align: "center",
        style: {
            fontSize: "15px",
            fontWeight: "normal",
            textDecoration: "underline",
        },
        },
        stroke: {
        width: 0,
        },
        legend: {
        show: false,
        },
        dataLabels: {
        enabled: false,
        },
        plotOptions: {
            pie: {
                expandOnClick: true,
                donut: {
                    background: "white",
                    labels: {
                        show: true,
                        total: {
                            show: true,
                            fontSize: "15",
                            fontWeight: 10,
                            formatter: function () {
                                return data + "%";
                            },
                        },
                        name: {
                            show: false,
                        },
                        value: {
                            show: true,
                        },
                    },
                },
            },
        },
    };

  const series = [progressValue, lapseValue];

  return (
    <>
      <div className={styles.ChartDiv}>
        <Chart
          data={data}
          type="donut"
          width="100%"
          height={140}
          series={series}
          options={options}
        />
      </div>
    </>
  );
}
</code>```

JSON return

```<code>{
  "first": 4,
  "second": 24,
  "third": 2.5,
  "forth": 9.5,
  "fifth": 22,
  "sixth": 2
}
</code>```

Body:
I'm having a problem with donut charts in ApexCharts in my React App.

I have an API that returns to me a JSON and I pass this JSON data to some charts. The chart it's showing correct data, but the label isn't showing anything.

If I change something in the ChartComponent, for example, change the 'fontSize' from 15 to 10 the values of the labels are shown, but when rendering the screen, they disappear and return to 0.

see here how the graphs are appearing

see here how the graphs are when I change the 'fontSize'

App()

export default function App() {
  const referenceDate = new Date();
  const currentYear = referenceDate.getFullYear();
  const currentMonth = referenceDate.getMonth() + 1;
  const currentMonthName = referenceDate.toLocaleString("default", {
    month: "long",
  });

  const [month, setMonth] = useState(currentMonthName);
  const [monthId, setMonthId] = useState(currentMonth);
  const [apiData, setApiData] = useState();

  useEffect(() => {
    async function fillData() {
      if (month) {
        await getData(currentYear, monthId).then((response) =>
          setApiData(response)
        );
      }
    }
    fillData();
  }, [monthId]);

  const handleChange = (e) => {
    const selectedMonth = e.target.value;
    const selectedMonthId = Months[e.target.value].id;
    setMonth(selectedMonth);
    setMonthId(selectedMonthId);
  };

  return (
    <>

          <ChartCard title="Business Unit Head" value={apiData ? apiData['first'] : 0}></ChartCard>
          <ChartCard title="Financial" value={apiData ? apiData['second'] : 0}></ChartCard>

          <ChartCard title="Commercial And Pipeline [LATAM]" value={apiData ? apiData['third'] : 0}></ChartCard>
          <ChartCard title="Commercial And Pipeline [NAM]" value={apiData ? apiData['fourth'] : 0}></ChartCard>

          <ChartCard title="HR And Recuitment" value={apiData ? apiData['fifth'] : 0}></ChartCard>
          <ChartCard title="Delivery" value={apiData ? apiData['sixth] : 0}></ChartCard>

    </>
  );
}

const getData = async (year, month) => (await axiosInstance.get(`/homeChart/${year}/${month}`)).data;

async function generateChartData(data) {
  if (data) {
    return data;
  } else {
    console.log("no data");
  }
}

ChartComponent

export default function ChartCard(props) {
  let progressValue = 0;
  let lapseValue = 0;
  const data = props.value;

  progressValue = data;
  lapseValue = 100 - data;

  const options = {
        colors: ["#0ead69", "#e71d36"],
        labels: ["Progress", "Lapse"],
        title: {
        text: props.title,
        align: "center",
        style: {
            fontSize: "15px",
            fontWeight: "normal",
            textDecoration: "underline",
        },
        },
        stroke: {
        width: 0,
        },
        legend: {
        show: false,
        },
        dataLabels: {
        enabled: false,
        },
        plotOptions: {
            pie: {
                expandOnClick: true,
                donut: {
                    background: "white",
                    labels: {
                        show: true,
                        total: {
                            show: true,
                            fontSize: "15",
                            fontWeight: 10,
                            formatter: function () {
                                return data + "%";
                            },
                        },
                        name: {
                            show: false,
                        },
                        value: {
                            show: true,
                        },
                    },
                },
            },
        },
    };

  const series = [progressValue, lapseValue];

  return (
    <>

        <Chart
          data={data}
          type="donut"
          width="100%"
          height={140}
          series={series}
          options={options}
        />

    </>
  );
}

JSON return

{
  "first": 4,
  "second": 24,
  "third": 2.5,
  "forth": 9.5,
  "fifth": 22,
  "sixth": 2
}


问:
Project fails to build with error "does not reference '". NETFramework,Version=v4.7.2" framework'" after restore
I am trying to create a nuget package using MSBuild and am running into problems after I restore.

This error occurs after I do msbuild <solution> "/t:<project>" /t:restore /p:Configuration=Release. To be clear, that command executes successfully, no errors; however, if I try to clean, build, restore or pack following that command is when I get the following error. (note that <path-to-repo>, <solution> and <project> are substitutions)

```<code>Build FAILED.

"C:\Users\<path-to-repo>\build\win32\<solution>.sln" (<project>;restore target) (1) ->
"C:\Users\<path-to-repo>\extras\<project>\<project>.vcxproj.metaproj" (default target) (2) ->
"C:\Users\<path-to-repo>\extras\<project>\<project>.vcxproj" (default target) (4) ->
(ResolveNuGetPackageAssets target) ->
  C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\NuGet\17.0\Microsoft.NuGet.targets(198,5): error : Your project does not reference ".NETFramework,Version=v4.7.2" framework. Add a reference to ".NETFramework,Version=v4.7.2" in the "TargetFrameworks" property of your project file and then re-run NuGet restore. [C:\Users\<path-to-repo>\extras\<project>\<project>.vcxproj]
</code>```

The project restores and builds correctly before I add the following section to the .vcxproj file (which I believe is necessary in order to pack the project as a nuget package).

```<code><ItemGroup>
  <PackageReference Include="NuGet.Build.Tasks.Pack">
    <Version>6.4.0</Version>
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
</ItemGroup>
</code>```

Simply adding that, and running restore and then clean/restore/build/pack afterwards all fail with the error.

This section is present in the project file which seems to correctly reference the target framework.

```<code><PropertyGroup Label="Globals">
  ...
  <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
  ...
</PropertyGroup>
</code>```

I've cleaned out all the bin/obj and other untracked files at the root of the repo with git clean -xdf as that was a very popular suggestion (the only change in the repo is the package reference above added to the project file); I am unaware of any files I would need to clean outside of the repo?

Thanks in advance for any help! Questions about this error seem to be asked a lot for different scenarios, seems like they might need better error messages.

Body:
I am trying to create a nuget package using MSBuild and am running into problems after I restore.

This error occurs after I do msbuild <solution> "/t:<project>" /t:restore /p:Configuration=Release. To be clear, that command executes successfully, no errors; however, if I try to clean, build, restore or pack following that command is when I get the following error. (note that <path-to-repo>, <solution> and <project> are substitutions)

Build FAILED.

"C:\Users\<path-to-repo>\build\win32\<solution>.sln" (<project>;restore target) (1) ->
"C:\Users\<path-to-repo>\extras\<project>\<project>.vcxproj.metaproj" (default target) (2) ->
"C:\Users\<path-to-repo>\extras\<project>\<project>.vcxproj" (default target) (4) ->
(ResolveNuGetPackageAssets target) ->
  C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Microsoft\NuGet\17.0\Microsoft.NuGet.targets(198,5): error : Your project does not reference ".NETFramework,Version=v4.7.2" framework. Add a reference to ".NETFramework,Version=v4.7.2" in the "TargetFrameworks" property of your project file and then re-run NuGet restore. [C:\Users\<path-to-repo>\extras\<project>\<project>.vcxproj]

The project restores and builds correctly before I add the following section to the .vcxproj file (which I believe is necessary in order to pack the project as a nuget package).

<ItemGroup>
  <PackageReference Include="NuGet.Build.Tasks.Pack">
    <Version>6.4.0</Version>
    <PrivateAssets>all</PrivateAssets>
  </PackageReference>
</ItemGroup>

Simply adding that, and running restore and then clean/restore/build/pack afterwards all fail with the error.

This section is present in the project file which seems to correctly reference the target framework.

<PropertyGroup Label="Globals">
  ...
  <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
  ...
</PropertyGroup>

I've cleaned out all the bin/obj and other untracked files at the root of the repo with git clean -xdf as that was a very popular suggestion (the only change in the repo is the package reference above added to the project file); I am unaware of any files I would need to clean outside of the repo?

Thanks in advance for any help! Questions about this error seem to be asked a lot for different scenarios, seems like they might need better error messages.


问:
Troubleshooting high time taken to publish event to Kafka
Publishing to kafka takes 3 seconds in one of the environment, however we see that, in other environments it takes only 20 milli seconds .
We have done following to troubleshoot this issue:

We have run route trace and we dont see an network latency.

Analyzed the logs and found following :

```<code> 2023-01-05T07:26:24.627Z DEBUG 40 --- [ad | producer-5] o.a.k.c.NetworkClient                    : [Producer clientId=producer-5] Using older server API v7 to send PRODUCE {acks=-1,timeout=30000,partitionSizes=[esd.mob.vocc.datacollector.sampio.plab01.raw-9=464]} with correlation id 1156 to node 46

2023-01-05T07:26:24.627Z TRACE 40 --- [ad | producer-5] o.a.k.c.p.i.Sender                       : [Producer clientId=producer-5] Sent produce request to 46: (type=ProduceRequest, acks=-1, timeout=30000, partitionRecords=({esd.mob.vocc.datacollector.sampio.plab01.raw-9=MemoryRecords(size=464, buffer=java.nio.HeapByteBuffer[pos=0 lim=464 cap=464])}), transactionalId=''

2023-01-05T07:26:27.700Z TRACE 40 --- [ad | producer-5] o.a.k.c.NetworkClient                    : [Producer clientId=producer-5] Completed receive from node 46 for PRODUCE with correlation id 1156, received {responses=[{topic=esd.mob.vocc.datacollector.sampio.plab01.raw,partition_responses=[{partition=9,error_code=0,base_offset=31376,log_append_time=-1,log_start_offset=31001}]}],throttle_time_ms=0}

2023-01-05T07:26:27.700Z TRACE 40 --- [ad | producer-5] o.a.k.c.p.i.Sender                       : [Producer clientId=producer-5] Received produce response from node 46 with correlation id 1156
</code>```

the log clearly states that it takes 3 seconds to publish the message .
We are using below mentioned code .

 CompletableFuture<SendResult<String, String>> sendResultCompletableFuture = kafkaTemplate.send(payloadMsg);

  sendResultCompletableFuture.whenComplete((data, ex) -> {
                if (Objects.nonNull(ex)) {
                    LOGGER.error("Exception while publishing message to kafka, {}", ExceptionUtils.getStackTrace(ex));
                    throw new KafkaConnectorException(ExceptionUtils.getStackTrace(ex), topic, message);
                } else {
                    LOGGER.info("Message handle published to kafka successfully for key ::");
                }
            });
```

Please help in troubleshooting this issue further and share thoughts.

Body:
Publishing to kafka takes 3 seconds in one of the environment, however we see that, in other environments it takes only 20 milli seconds .
We have done following to troubleshoot this issue:

We have run route trace and we dont see an network latency.

Analyzed the logs and found following :

 2023-01-05T07:26:24.627Z DEBUG 40 --- [ad | producer-5] o.a.k.c.NetworkClient                    : [Producer clientId=producer-5] Using older server API v7 to send PRODUCE {acks=-1,timeout=30000,partitionSizes=[esd.mob.vocc.datacollector.sampio.plab01.raw-9=464]} with correlation id 1156 to node 46

2023-01-05T07:26:24.627Z TRACE 40 --- [ad | producer-5] o.a.k.c.p.i.Sender                       : [Producer clientId=producer-5] Sent produce request to 46: (type=ProduceRequest, acks=-1, timeout=30000, partitionRecords=({esd.mob.vocc.datacollector.sampio.plab01.raw-9=MemoryRecords(size=464, buffer=java.nio.HeapByteBuffer[pos=0 lim=464 cap=464])}), transactionalId=''

2023-01-05T07:26:27.700Z TRACE 40 --- [ad | producer-5] o.a.k.c.NetworkClient                    : [Producer clientId=producer-5] Completed receive from node 46 for PRODUCE with correlation id 1156, received {responses=[{topic=esd.mob.vocc.datacollector.sampio.plab01.raw,partition_responses=[{partition=9,error_code=0,base_offset=31376,log_append_time=-1,log_start_offset=31001}]}],throttle_time_ms=0}

2023-01-05T07:26:27.700Z TRACE 40 --- [ad | producer-5] o.a.k.c.p.i.Sender                       : [Producer clientId=producer-5] Received produce response from node 46 with correlation id 1156

the log clearly states that it takes 3 seconds to publish the message .
We are using below mentioned code .

 CompletableFuture<SendResult<String, String>> sendResultCompletableFuture = kafkaTemplate.send(payloadMsg);

  sendResultCompletableFuture.whenComplete((data, ex) -> {
                if (Objects.nonNull(ex)) {
                    LOGGER.error("Exception while publishing message to kafka, {}", ExceptionUtils.getStackTrace(ex));
                    throw new KafkaConnectorException(ExceptionUtils.getStackTrace(ex), topic, message);
                } else {
                    LOGGER.info("Message handle published to kafka successfully for key ::");
                }
            });

Please help in troubleshooting this issue further and share thoughts.