问:
JQUERY load an array of elements into a DIV
I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers').

I've tried:

```<code>noactiveMsg.appendTo($('#chatCenterMembers'));
</code>```

But this doesn't work.
Can someone advice on the syntax to load an array of elements/objects into a div?

code to made the array:

```<code>var noactiveMsg=[];
 $('div.chatmember').each(function() {
 if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
 alert('offline');
 noactiveMsg.push($(this));
 }
 });
</code>```

答:
You'll want to merge them all into one jQuery object:

```<code>var noactiveMsg = [$('<a>1</a>'), $('<a>1</a>')],
    collection;

$.each(noactiveMsg, function(i, e) {
    collection ? collection = collection.add(e) : collection = e;
});
</code>```

EDIT:

Others have suggested adding every element in the array separately into the DOM. I would strongly advise you against it. Interacting with the DOM is an expensive operation, and should be avoided whenever possible.

Body:
I have an array of DIV elements in an array called 'noactiveMsg'.
I want to load these DIV elements into a DIV called $('#chatCenterMembers').

I've tried:

noactiveMsg.appendTo($('#chatCenterMembers'));

But this doesn't work.
Can someone advice on the syntax to load an array of elements/objects into a div?

code to made the array:

var noactiveMsg=[];
 $('div.chatmember').each(function() {
 if($(this).children().children('div').hasClass('chatactivestatus_offline')) {
 alert('offline');
 noactiveMsg.push($(this));
 }
 });

Body:
You'll want to merge them all into one jQuery object:

var noactiveMsg = [$('<a>1</a>'), $('<a>1</a>')],
    collection;

$.each(noactiveMsg, function(i, e) {
    collection ? collection = collection.add(e) : collection = e;
});

EDIT:

Others have suggested adding every element in the array separately into the DOM. I would strongly advise you against it. Interacting with the DOM is an expensive operation, and should be avoided whenever possible.


来源: stackexchange

问:
Best Practices on refering to resource files in Java code by relative path?
I have a repository which looks something like this:

```<code>/
/resources/resource1.txt
/resources/resource2.txt
/code/
/code/C/...
/code/java/pom.xml
/code/java/src/main/XYZ.java
/code/java/src/main/ABC.java
</code>```

In other words, there is a maven project rooted in /code/java/, and there are resource files located at /resources/.

Now, I want to refer to the resource files in my code. The code will be something like the files in /code/java/src/main/XYZ.java. How should I refer to this file?

I do not want to hard code the filepath from my local machine. For example, I do not want something like /Users/agnishom/projectX/resources/resource1.txt. This will make it difficult for other people who clone my repository to make it work.

I would like to be able to name a file by their relative path, possibly relative to the pom.xml file.

What is the best way to do this? Moving the resource files into the /code/java/ is not an option because they are shared by other projects which are not part of the java

答:
In the build section of your pom.xml, you can specify the resources directory relative to the project's base directory (/pom.xml), as you were suggesting:

```<code><build>
    ...
    <resources>
        <resource>
            <targetPath>.</targetPath>
            <directory>${basedir}/../../resources</directory>
        </resource>
    </resources>
</build>
</code>```

targetPath is the path to where included resources should be placed, relative to the jarfile/resulting build.

directory is the directory to include resources from.

ContentLicense: CC BY-SA 4.0

Body:
I have a repository which looks something like this:

/
/resources/resource1.txt
/resources/resource2.txt
/code/
/code/C/...
/code/java/pom.xml
/code/java/src/main/XYZ.java
/code/java/src/main/ABC.java

In other words, there is a maven project rooted in /code/java/, and there are resource files located at /resources/.

Now, I want to refer to the resource files in my code. The code will be something like the files in /code/java/src/main/XYZ.java. How should I refer to this file?

I do not want to hard code the filepath from my local machine. For example, I do not want something like /Users/agnishom/projectX/resources/resource1.txt. This will make it difficult for other people who clone my repository to make it work.

I would like to be able to name a file by their relative path, possibly relative to the pom.xml file.

What is the best way to do this? Moving the resource files into the /code/java/ is not an option because they are shared by other projects which are not part of the java

Body:
In the build section of your pom.xml, you can specify the resources directory relative to the project's base directory (/pom.xml), as you were suggesting:

<build>
    ...
    <resources>
        <resource>
            <targetPath>.</targetPath>
            <directory>${basedir}/../../resources</directory>
        </resource>
    </resources>
</build>

targetPath is the path to where included resources should be placed, relative to the jarfile/resulting build.

directory is the directory to include resources from.


问:
Kibana - How to count number of error logs and the type of error
I monitor our team project error logs in Kibana and report them, like: From yesterday to today, there has been 50 errors, 20 of them is IP authentification and 30 Host error... or something like that.

I wanted to automate this process, counting the number of errors and their types and displaying them on Slack, kind of a microsoft teams. I was looking at web scrapping with python to extract those error logs but it doesn't quite look like what I'm looking for.

How would you go about this?

答:
Build a Watcher for that.

Query your stuff by timeframe, do the aggregations by "error category" & count your numbers, schedule the Watcher to fire at the frequency you're comfortable with, and send the results directly to Slack (connector is provided out of the box).

How to do it:
https://www.elastic.co/guide/en/elasticsearch/reference/current/watcher-api-put-watch.html


问:
Stored procedure, grouping output into a new column
I have this stored procedure below, it allows me to select a question id and list the username and their answer.

How would i change it so it only shows me the question id with a new column called total as below

```<code>CREATE PROCEDURE dbo.report
  @Question_ID varchar(5)
AS
  SELECT * FROM submit_Answer
  WHERE Question_ID=@Question_ID
</code>```

Thanks!

答:
Use this to get one row for each Question_ID and Answer and count the number of occurrences in column Total.</p>

```<code>CREATE PROCEDURE dbo.report
  @Question_ID varchar(5)
AS
  SELECT Question_ID,
         Answer,
         COUNT(*) as Total
  FROM submit_Answer
  WHERE Question_ID=@Question_ID
  GROUP BY Question_ID,
           Answer
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this stored procedure below, it allows me to select a question id and list the username and their answer.

How would i change it so it only shows me the question id with a new column called total as below

CREATE PROCEDURE dbo.report
  @Question_ID varchar(5)
AS
  SELECT * FROM submit_Answer
  WHERE Question_ID=@Question_ID

Thanks!

Body:
Use this to get one row for each Question_ID and Answer and count the number of occurrences in column Total.

CREATE PROCEDURE dbo.report
  @Question_ID varchar(5)
AS
  SELECT Question_ID,
         Answer,
         COUNT(*) as Total
  FROM submit_Answer
  WHERE Question_ID=@Question_ID
  GROUP BY Question_ID,
           Answer


问:
Custom train-test split using two stratified classes
I am trying to use NLP techniques to predict the mental status of patients at the time doctor's notes were taken. I have two classes, suffix (multilabel) as well as mental_status (binary, Lucid or Delirium). I am trying to build train and test sets from a reduced list that meet the following specifications:

Shared unique suffix list

For each set for each suffix, at least one row for Lucid and Delirium

Any imbalances I will correct with sample weights (I am only trying to predict mental_status, but I need the data to also be balanced on suffix). I just need at least one row for each combination within the full Cartesian product of suffixes and mental_statuses.

For example, in the dataset below, only the DWM Communication suffixes would make it into the train-test split.

```<code>suffix              mental_status
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Psychiatry      Lucid
DWN Psychiatry      Delirium
DWN Psychiatry      Delirium
DWN Cardio stuff    Lucid
DWN Cardio stuff    Delirium
DWN Blood .....     Lucid
DWN Blood .....     Lucid
DWN Blood .....     Lucid
</code>```

The output I would want for the example above for train would be

```<code>DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
</code>```

and test

```<code>DWN Communication   Lucid
DWN Communication   Delirium
</code>```

I've tried

```<code>df.groupby(['suffix','mental_status']).filter(lambda x: len(x) > 1)
</code>```

but it doesn't ensure there is one of each Delirium and Lucid for each suffix.

As another example,

```<code>    suf ms
11  blood   delirium
15  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
10  blood   lucid
16  blood   lucid
3   psych   delirium
19  psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid
14  psych   lucid
18  psych   lucid
7   stool   delirium
2   stool   lucid
12  stool   lucid
17  stool   lucid
</code>```

would be split into

```<code>    suf ms
11  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
3   psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid
</code>```

and

```<code>    suf ms
15  blood   delirium
10  blood   lucid
16  blood   lucid
19  psych   delirium
14  psych   lucid
18  psych   lucid
</code>```

Edit:

I think I arrived at a solution:

```<code>from sklearn.model_selection import train_test_split
def custom_split(df, test_size):
    f = lambda ms: (
        df[df.mental_status==ms]
        .groupby('suffix')
        .filter(lambda x:len(x)>=1/min(test_size,1-test_size))
        .suffix
    )
    delirium = f('Delirium')
    lucid = f('Lucid')
    valid_suffixes = set(delirium).intersection(lucid)
    df = df[df.suffix.isin(valid_suffixes)]
    df_train, df_test = train_test_split(df,test_size,random_state=9,
                                         stratify=df.mental_status+df.suffix)
    return df_train, df_test
</code>```

答:
what about using the index and duplicated(keep=False)?

```<code>test = df[~df.duplicated(keep=False)]
output  = df.drop_duplicates()
output = output[~output.index.isin(test.index)]
</code>```

Body:
I am trying to use NLP techniques to predict the mental status of patients at the time doctor's notes were taken. I have two classes, suffix (multilabel) as well as mental_status (binary, Lucid or Delirium). I am trying to build train and test sets from a reduced list that meet the following specifications:

Shared unique suffix list

For each set for each suffix, at least one row for Lucid and Delirium

Any imbalances I will correct with sample weights (I am only trying to predict mental_status, but I need the data to also be balanced on suffix). I just need at least one row for each combination within the full Cartesian product of suffixes and mental_statuses.

For example, in the dataset below, only the DWM Communication suffixes would make it into the train-test split.

suffix              mental_status
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid
DWN Psychiatry      Lucid
DWN Psychiatry      Delirium
DWN Psychiatry      Delirium
DWN Cardio stuff    Lucid
DWN Cardio stuff    Delirium
DWN Blood .....     Lucid
DWN Blood .....     Lucid
DWN Blood .....     Lucid

The output I would want for the example above for train would be

DWN Communication   Lucid
DWN Communication   Delirium
DWN Communication   Lucid

and test

DWN Communication   Lucid
DWN Communication   Delirium

I've tried

df.groupby(['suffix','mental_status']).filter(lambda x: len(x) > 1)

but it doesn't ensure there is one of each Delirium and Lucid for each suffix.

As another example,

    suf ms
11  blood   delirium
15  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
10  blood   lucid
16  blood   lucid
3   psych   delirium
19  psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid
14  psych   lucid
18  psych   lucid
7   stool   delirium
2   stool   lucid
12  stool   lucid
17  stool   lucid

would be split into

    suf ms
11  blood   delirium
0   blood   lucid
1   blood   lucid
5   blood   lucid
6   blood   lucid
3   psych   delirium
4   psych   lucid
8   psych   lucid
9   psych   lucid
13  psych   lucid

and

    suf ms
15  blood   delirium
10  blood   lucid
16  blood   lucid
19  psych   delirium
14  psych   lucid
18  psych   lucid

Edit:

I think I arrived at a solution:

from sklearn.model_selection import train_test_split
def custom_split(df, test_size):
    f = lambda ms: (
        df[df.mental_status==ms]
        .groupby('suffix')
        .filter(lambda x:len(x)>=1/min(test_size,1-test_size))
        .suffix
    )
    delirium = f('Delirium')
    lucid = f('Lucid')
    valid_suffixes = set(delirium).intersection(lucid)
    df = df[df.suffix.isin(valid_suffixes)]
    df_train, df_test = train_test_split(df,test_size,random_state=9,
                                         stratify=df.mental_status+df.suffix)
    return df_train, df_test

Body:
what about using the index and duplicated(keep=False)?

test = df[~df.duplicated(keep=False)]
output  = df.drop_duplicates()
output = output[~output.index.isin(test.index)]


问:
Pulling Print Drivers from a Server and Installing them to a Workstation Using Powershell
Context: My ultimate goal is to wake up from print Nightmare. To do this, I plan on creating a script that will be deployed via GPO that installs print drivers and network printers. Below is the test script I'm working with.

Script:

```<code>pnputil.exe /a "\\j001-hal2010\HP Universal Print Driver\pcl6-x64-7.0.0.24832\hpcu250u.inf"
Add-PrinterDriver -Name "HP Universal Printing PCL 6" -InfPath "C:\Windows\System32\DriverStore\hpcu250u.inf"
Add-PrinterPort -Name "TCPPort:10.1.1.193" -PrinterHostAddress "10.1.1.193"
Add-Printer -DriverName "HP Universal Printing PCL 6" -Name "Cust Service HP Color LaserJet M653" -PortName "TCPPort:10.1.1.193"
</code>```

Problem: My issue is that the pnputil.exe /a "\\j001-hal2010\HP Universal Print Driver\pcl6-x64-7.0.0.24832\hpcu250u.inf" comes back with the following error:

Adding the driver package failed : Invalid INF passed as parameter.

When I insert a Wilcard for the INF, I receive the same error:
pnputil.exe /a "\\j001-hal2010\HP Universal Print Driver\pcl6-x64-7.0.0.24832\*.inf"

Adding the driver package failed : Invalid INF passed as parameter.

Total attempted:              0 Number successfully imported: 0

Resources:

https://www.pdq.com/blog/using-powershell-to-install-printers/

https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/pnputil-command-syntax

答: It sounds like you are not authenticated to the source.  I got this until I added a net use x: \j001-hal2010\ and entered a username and password.  I could then run pnputil.exe /a "\j001-hal2010\HP Universal Print Driver\pcl6-x64-7.0.0.24832*.inf"</p>

Body:
Context: My ultimate goal is to wake up from print Nightmare. To do this, I plan on creating a script that will be deployed via GPO that installs print drivers and network printers. Below is the test script I'm working with.

Script:

pnputil.exe /a "\\j001-hal2010\HP Universal Print Driver\pcl6-x64-7.0.0.24832\hpcu250u.inf"
Add-PrinterDriver -Name "HP Universal Printing PCL 6" -InfPath "C:\Windows\System32\DriverStore\hpcu250u.inf"
Add-PrinterPort -Name "TCPPort:10.1.1.193" -PrinterHostAddress "10.1.1.193"
Add-Printer -DriverName "HP Universal Printing PCL 6" -Name "Cust Service HP Color LaserJet M653" -PortName "TCPPort:10.1.1.193"

Problem: My issue is that the pnputil.exe /a "\\j001-hal2010\HP Universal Print Driver\pcl6-x64-7.0.0.24832\hpcu250u.inf" comes back with the following error:

Adding the driver package failed : Invalid INF passed as parameter.

When I insert a Wilcard for the INF, I receive the same error:
pnputil.exe /a "\\j001-hal2010\HP Universal Print Driver\pcl6-x64-7.0.0.24832\*.inf"

Adding the driver package failed : Invalid INF passed as parameter.

Total attempted:              0 Number successfully imported: 0

Resources:

https://www.pdq.com/blog/using-powershell-to-install-printers/

https://learn.microsoft.com/en-us/windows-hardware/drivers/devtest/pnputil-command-syntax


问:
Get datetime for USA from local time
I can able to get time of local sql server by GetDate() function. Sql server machine is in india.

Now I want to get the current datetime of USA on same sql server what can I do.

答:
You need to use the SYSDATETIMEOFFSET call (instead of just GETDATE()) to get your local time with the timezone information:

```<code>SELECT SYSDATETIMEOFFSET()
</code>```

and then you can use the SWITCHOFFSET function to define a new timezone you're interested in - based on UTC time. So the East Coast of the USA would be UTC -5 hours

```<code>SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '-05:00') AS 'US East Coast'
</code>```

while the West Coast is UTC -8 hours:

```<code>SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '-08:00') AS 'US West Coast'
</code>```

Title: Get datetime for USA from local time

Body:
You need to use the SYSDATETIMEOFFSET call (instead of just GETDATE()) to get your local time with the timezone information:

SELECT SYSDATETIMEOFFSET()

and then you can use the SWITCHOFFSET function to define a new timezone you're interested in - based on UTC time. So the East Coast of the USA would be UTC -5 hours

SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '-05:00') AS 'US East Coast'

while the West Coast is UTC -8 hours:

SELECT SWITCHOFFSET(SYSDATETIMEOFFSET(), '-08:00') AS 'US West Coast'


问:
Java Spring Webflux: javax.net.ssl.SSLHandshakeException: Empty client certificate chain
Small question regarding a Spring Webflux application please.

Periodically, but sporadically, in the application logs, I am seeing this stack trace:

```<code>2022-02-04 09:20:13.813  WARN [myapplication,,] 11 --- [or-http-epoll-2] .s.ApplicationProtocolNegotiationHandler : [id: 0xc70400fa, L:/.<someIP>:<somePort> ! R:/<someOtherIP>:<someOtherPort>] TLS handshake failed:
javax.net.ssl.SSLHandshakeException: Empty client certificate chain
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[na:na]
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:336) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:292) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:283) ~[na:na]
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1194) ~[na:na]
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1181) ~[na:na]
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392) ~[na:na]
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1074) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1061) ~[na:na]
    at java.base/java.security.AccessController.doPrivileged(Native Method) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask.run(SSLEngineImpl.java:1008) ~[na:na]
    at io.netty.handler.ssl.SslHandler.runDelegatedTasks(SslHandler.java:1550) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1396) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1237) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1286) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507) ~[netty-codec-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446) ~[netty-codec-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) ~[netty-codec-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795) ~[netty-transport-native-epoll-4.1.66.Final-linux-x86_64.jar!/:4.1.66.Final]
    at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:480) ~[netty-transport-native-epoll-4.1.66.Final-linux-x86_64.jar!/:4.1.66.Final]
    at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378) ~[netty-transport-native-epoll-4.1.66.Final-linux-x86_64.jar!/:4.1.66.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986) ~[netty-common-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.66.Final.jar!/:4.1.66.Final]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]
</code>```

There is unfortunately no pattern as when this appears. On high traffic, on low traffic, even when there is no traffic, this message appears. And this is only seen sometime, not always.

The http client (Spring Webclient) is built as follow:

```<code>    @Bean
    @Primary
    public WebClient getWebClient() {
        return WebClient.create().mutate().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).clientConnector(new ReactorClientHttpConnector(HttpClient.create().wiretap(true).secure(sslContextSpec -> sslContextSpec.sslContext(getSslContext())))).build();
    }

public SslContext getSslContext() {
        try {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            try (InputStream file = new FileInputStream(keyStorePath)) {
                final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                keyStore.load(file, keyStorePassPhrase.toCharArray());
                keyManagerFactory.init(keyStore, keyPassPhrase.toCharArray());
            }

            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            try (InputStream trustStoreFile = new FileInputStream(trustStorePath)) {
                final KeyStore trustStore = KeyStore.getInstance(trustStoreType);
                trustStore.load(trustStoreFile, trustStorePassPhrase.toCharArray());
                trustManagerFactory.init(trustStore);
            }

            return SslContextBuilder.forClient().keyManager(keyManagerFactory).trustManager(trustManagerFactory).build();
        } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException | UnrecoverableKeyException e) {
 LOGGER.error( "Error here: Empty client certificate chain?" + e, e);
            return null;
        }
    }
</code>```

I am having a hard time understanding the root cause, and the meaning of this stack trace.

Questions:

I see this [id: 0xc70400fa, L:/.someIP:somePort ! R:/someOtherIP:someOtherPort]
What is the meaning of this please? From Spring documentation, L means "local", R means "remote" and ! means error.
Therefore, does it means the IP in local is trying to "talk to" the IP in remote, but local (me?) presented an empty certificate?

Or is it the opposite remote is trying to talk to me, local, and is presenting an empty certificate?

The request ID (here id: 0xc70400fa) is unusable as there is no way to correlate with anything else. How to properly use this ID please?

Finally, is there a way to get an understanding why and especially when (is it an API call? a health check call, etc) this Empty client certificate chain is happening, and how to prevent it please?

Thank you

答:
There is some config parameters you can check in Spring Boot code to look at their SSL implementation for that kind of thing :

```<code>security.require-ssl=true
server.ssl.key-store:/home/user/folder/keystore.p12
server.ssl.key-store-password: XXXXXX              <========== your password
server.ssl.keyStoreType: PKCS12                    <========== your keystore format
server.ssl.keyAlias: XXXXX                         <========== your keystore alias
</code>```

So you can look at their source code to seek directly their interfaces and provided integrations/implementations.

So it is not required to import a keystore inside our global keystore repository if we do not want it. We can use this another way.

[id: 0xc70400fa, L:/.someIP:somePort ! R:/someOtherIP:someOtherPort]

id: 0xc70400fa => connection id (edited thanks @Violeta)

L:/ip:port ! R:/ip:port => localMachine:localPort did
not connect to remoteMachine:remotePort

Or maybe you could try another way to go : using wget, curl or Guzzle or any good HTTP(s) java client... and maybe an Entreprise Service Bus | middleware application like Apache Camel to connect any future webservices or microservices with plug and play way of life.

Body:
Small question regarding a Spring Webflux application please.

Periodically, but sporadically, in the application logs, I am seeing this stack trace:

2022-02-04 09:20:13.813  WARN [myapplication,,] 11 --- [or-http-epoll-2] .s.ApplicationProtocolNegotiationHandler : [id: 0xc70400fa, L:/.<someIP>:<somePort> ! R:/<someOtherIP>:<someOtherPort>] TLS handshake failed:
javax.net.ssl.SSLHandshakeException: Empty client certificate chain
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[na:na]
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:336) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:292) ~[na:na]
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:283) ~[na:na]
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1194) ~[na:na]
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1181) ~[na:na]
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392) ~[na:na]
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1074) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1061) ~[na:na]
    at java.base/java.security.AccessController.doPrivileged(Native Method) ~[na:na]
    at java.base/sun.security.ssl.SSLEngineImpl$DelegatedTask.run(SSLEngineImpl.java:1008) ~[na:na]
    at io.netty.handler.ssl.SslHandler.runDelegatedTasks(SslHandler.java:1550) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.ssl.SslHandler.unwrap(SslHandler.java:1396) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.ssl.SslHandler.decodeJdkCompatible(SslHandler.java:1237) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.ssl.SslHandler.decode(SslHandler.java:1286) ~[netty-handler-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.decodeRemovalReentryProtection(ByteToMessageDecoder.java:507) ~[netty-codec-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:446) ~[netty-codec-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:276) ~[netty-codec-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:357) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1410) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:379) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:365) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:919) ~[netty-transport-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.channel.epoll.AbstractEpollStreamChannel$EpollStreamUnsafe.epollInReady(AbstractEpollStreamChannel.java:795) ~[netty-transport-native-epoll-4.1.66.Final-linux-x86_64.jar!/:4.1.66.Final]
    at io.netty.channel.epoll.EpollEventLoop.processReady(EpollEventLoop.java:480) ~[netty-transport-native-epoll-4.1.66.Final-linux-x86_64.jar!/:4.1.66.Final]
    at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:378) ~[netty-transport-native-epoll-4.1.66.Final-linux-x86_64.jar!/:4.1.66.Final]
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986) ~[netty-common-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) ~[netty-common-4.1.66.Final.jar!/:4.1.66.Final]
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.66.Final.jar!/:4.1.66.Final]
    at java.base/java.lang.Thread.run(Thread.java:829) ~[na:na]

There is unfortunately no pattern as when this appears. On high traffic, on low traffic, even when there is no traffic, this message appears. And this is only seen sometime, not always.

The http client (Spring Webclient) is built as follow:

    @Bean
    @Primary
    public WebClient getWebClient() {
        return WebClient.create().mutate().defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).clientConnector(new ReactorClientHttpConnector(HttpClient.create().wiretap(true).secure(sslContextSpec -> sslContextSpec.sslContext(getSslContext())))).build();
    }

public SslContext getSslContext() {
        try {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            try (InputStream file = new FileInputStream(keyStorePath)) {
                final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                keyStore.load(file, keyStorePassPhrase.toCharArray());
                keyManagerFactory.init(keyStore, keyPassPhrase.toCharArray());
            }

            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            try (InputStream trustStoreFile = new FileInputStream(trustStorePath)) {
                final KeyStore trustStore = KeyStore.getInstance(trustStoreType);
                trustStore.load(trustStoreFile, trustStorePassPhrase.toCharArray());
                trustManagerFactory.init(trustStore);
            }

            return SslContextBuilder.forClient().keyManager(keyManagerFactory).trustManager(trustManagerFactory).build();
        } catch (CertificateException | NoSuchAlgorithmException | IOException | KeyStoreException | UnrecoverableKeyException e) {
 LOGGER.error( "Error here: Empty client certificate chain?" + e, e);
            return null;
        }
    }

I am having a hard time understanding the root cause, and the meaning of this stack trace.

Questions:

I see this [id: 0xc70400fa, L:/.someIP:somePort ! R:/someOtherIP:someOtherPort]
What is the meaning of this please? From Spring documentation, L means "local", R means "remote" and ! means error.
Therefore, does it means the IP in local is trying to "talk to" the IP in remote, but local (me?) presented an empty certificate?

Or is it the opposite remote is trying to talk to me, local, and is presenting an empty certificate?

The request ID (here id: 0xc70400fa) is unusable as there is no way to correlate with anything else. How to properly use this ID please?

Finally, is there a way to get an understanding why and especially when (is it an API call? a health check call, etc) this Empty client certificate chain is happening, and how to prevent it please?

Thank you

Body:
There is some config parameters you can check in Spring Boot code to look at their SSL implementation for that kind of thing :

security.require-ssl=true
server.ssl.key-store:/home/user/folder/keystore.p12
server.ssl.key-store-password: XXXXXX              <========== your password
server.ssl.keyStoreType: PKCS12                    <========== your keystore format
server.ssl.keyAlias: XXXXX                         <========== your keystore alias

So you can look at their source code to seek directly their interfaces and provided integrations/implementations.

So it is not required to import a keystore inside our global keystore repository if we do not want it. We can use this another way.

[id: 0xc70400fa, L:/.someIP:somePort ! R:/someOtherIP:someOtherPort]

id: 0xc70400fa => connection id (edited thanks @Violeta)

L:/ip:port ! R:/ip:port => localMachine:localPort did
not connect to remoteMachine:remotePort

Or maybe you could try another way to go : using wget, curl or Guzzle or any good HTTP(s) java client... and maybe an Entreprise Service Bus | middleware application like Apache Camel to connect any future webservices or microservices with plug and play way of life.


问:
error NU1102: Unable to find package NuGet.Frameworks with version (>= 4.9.3)
I'm getting this error when I try to build a .NET Core solution with Azure DevOps:

```<code>error NU1102:  Unable to find package NuGet Frameworks with version (>= 4.9.3)
error NU1102:   - Found 33 version(s) in http://nuget.bentley.com/nuget/Default [ Nearest version: 4.7.0-preview1-4986 ]
</code>```

The error occurs in the Cake script when a NuGet restore is being executed by dotnet.exe CLI:

```<code>Executing: "d:/vsts/a/_tool/dncs/2.2.100/x64/dotnet.exe" restore "./src/StorageRegistryPortal.sln" --source "http://nuget.bentley.com/nuget/Default"
</code>```

It tries to restore the NuGet packages from the solution file before throwing the NU1102 error above:

```<code> Restoring packages for d:\vsts\a\2921\s\src\StorageRegistryPortal\StorageRegistryPortal.csproj...
</code>```

Nothing in my solution is referencing this "NuGet.Frameworks" package.  So, I wonder if it is the "dotnet.exe" CLI itself that depends on this nuget package before it can restore the rest of the NuGet packages.  Also, this only happens in AzureDevops.  When I execute the build/cake script on my local PC, it is able to successfully restore all of the nuget packages with no issues.

I've already tried adding a "Use Nuget 4.9.3" task to the build pipeline, but I get the same error.

NOTE:  If I remove that "Use Nuget 4.9.3" task, then the error changes to (>= 4.7.0).  So, it appears to be looking for the Nuget.Framework that matches the current version of nuget.exe but not finding it.

Here is the screenshot of my build pipeline setup:

答:
TL;DR

This sometimes happens when running dotnet restore on one of my Linux/Ubuntu build servers when pulling from a private Azure DevOps Artifacts/Packages NuGet repo.

The solutions that work for me:

Rebooting the Linux machine, or

Deleting the NuGet cache at ~/.local/share/NuGet/v3-cache/[directory-with-name-of-my-private-nuget-repo]

Background

The error I get is:

error NU1102: Unable to find package [Name-of-my-custom-nuget-package] with version (>= 5.0.116)

I have a nuget.config file that is properly configured to pull down my NuGet packages.

The error is complete nonsense.

The version does exist

Other Linux boxes have no problems running dotnet restore and getting the version of the package

I can run dotnet restore on the same Linux machine for other (older) versions and it's fine

It just seems that dotnet restore decides, for whatever reason, that it's not even going to try to look for the new version of the package.

I've generally found Azure DevOps private NuGet repos secured with AAD to be especially problematic and annoying when dealing with Linux. It really needs some love and attention from the NuGet team.

Body:
I'm getting this error when I try to build a .NET Core solution with Azure DevOps:

error NU1102:  Unable to find package NuGet Frameworks with version (>= 4.9.3)
error NU1102:   - Found 33 version(s) in http://nuget.bentley.com/nuget/Default [ Nearest version: 4.7.0-preview1-4986 ]

The error occurs in the Cake script when a NuGet restore is being executed by dotnet.exe CLI:

Executing: "d:/vsts/a/_tool/dncs/2.2.100/x64/dotnet.exe" restore "./src/StorageRegistryPortal.sln" --source "http://nuget.bentley.com/nuget/Default"

It tries to restore the NuGet packages from the solution file before throwing the NU1102 error above:

 Restoring packages for d:\vsts\a\2921\s\src\StorageRegistryPortal\StorageRegistryPortal.csproj...

Nothing in my solution is referencing this "NuGet.Frameworks" package.  So, I wonder if it is the "dotnet.exe" CLI itself that depends on this nuget package before it can restore the rest of the NuGet packages.  Also, this only happens in AzureDevops.  When I execute the build/cake script on my local PC, it is able to successfully restore all of the nuget packages with no issues.

I've already tried adding a "Use Nuget 4.9.3" task to the build pipeline, but I get the same error.

NOTE:  If I remove that "Use Nuget 4.9.3" task, then the error changes to (>= 4.7.0).  So, it appears to be looking for the Nuget.Framework that matches the current version of nuget.exe but not finding it.

Here is the screenshot of my build pipeline setup:


问:
Replace other values with np.nan
I have a pandas data frame:

```<code>import pandas as pd

X = pd.DataFrame({'col1': [1,2],
                  'col2': [4,5]})
</code>```

I have a replacement dictionary:

```<code>dict_replace = {
    'col1': {1:'a', 2:'b'},
    'col2': {4:'c', 5:'d'}
}
</code>```

I can easily replace the values in X using:

```<code>X = X.replace(dict_replace)
</code>```

Resulting in:

```<code>X = pd.DataFrame({'col1': ['a','b'],
                  'col2': ['c','d']})
</code>```

However, if a new value appears in X which is not in dict_replace (for the respective column) I want it replaced with np.nan.

For example, a data frame:

```<code>X = pd.DataFrame({'col1': [1,2,3],
                  'col2': [4,5,7]})
</code>```

Should look like:

```<code>X = pd.DataFrame({'col1': ['a','b',np.nan],
                  'col2': ['c','d',np.nan]})
</code>```

What are some ways I can do this without having to iterate?

答:
You are looking for pandas.Series.map, which, though only available on columns, can be used on the whole dataframe with apply:

```<code>X = X.apply(lambda col: col.map(dict_replace[col.name]))
</code>```

Output:

```<code>>>> X
  col1 col2
0    a    c
1    b    d
2  NaN  NaN
</code>```

Title: Replace other values with np.nan

Body:
I have a pandas data frame:

import pandas as pd

X = pd.DataFrame({'col1': [1,2],
                  'col2': [4,5]})

I have a replacement dictionary:

dict_replace = {
    'col1': {1:'a', 2:'b'},
    'col2': {4:'c', 5:'d'}
}

I can easily replace the values in X using:

X = X.replace(dict_replace)

Resulting in:

X = pd.DataFrame({'col1': ['a','b'],
                  'col2': ['c','d']})

However, if a new value appears in X which is not in dict_replace (for the respective column) I want it replaced with np.nan.

For example, a data frame:

X = pd.DataFrame({'col1': [1,2,3],
                  'col2': [4,5,7]})

Should look like:

X = pd.DataFrame({'col1': ['a','b',np.nan],
                  'col2': ['c','d',np.nan]})

What are some ways I can do this without having to iterate?

Body:
You are looking for pandas.Series.map, which, though only available on columns, can be used on the whole dataframe with apply:

X = X.apply(lambda col: col.map(dict_replace[col.name]))

Output:

>>> X
  col1 col2
0    a    c
1    b    d
2  NaN  NaN


问:
How to close std-streams from java.lang.Process appropriate?
This question is about java.lang.Process and its handling of stdin, stdout and stderr.

We have a class in our project that is an extension to org.apache.commons.io.IOUtils. There we have a quiet new method for closing the std-streams of a Process-Object appropriate? Or is it not appropriate?

```<code>/**
 * Method closes all underlying streams from the given Process object.
 * If Exit-Code is not equal to 0 then Process will be destroyed after
 * closing the streams.
 *
 * It is guaranteed that everything possible is done to release resources
 * even when Throwables are thrown in between.
 *
 * In case of occurances of multiple Throwables then the first occured
 * Throwable will be thrown as Error, RuntimeException or (masked) IOException.
 *
 * The method is null-safe.
 */
public static void close(@Nullable Process process) throws IOException {
    if(process == null) {
      return;
    }

    Throwable t = null;

    try {
      close(process.getOutputStream());
    }
    catch(Throwable e) {
      t = e;
    }

    try{
      close(process.getInputStream());
    }
    catch(Throwable e) {
      t = (t == null) ? e : t;
    }

    try{
      close(process.getErrorStream());
    }
    catch (Throwable e) {
      t = (t == null) ? e : t;
    }

    try{
      try {
        if(process.waitFor() != 0){
          process.destroy();
        }
      }
      catch(InterruptedException e) {
        t = (t == null) ? e : t;
        process.destroy();
      }
    }
    catch (Throwable e) {
      t = (t == null) ? e : t;
    }

    if(t != null) {
      if(t instanceof Error) {
        throw (Error) t;
      }

      if(t instanceof RuntimeException) {
        throw (RuntimeException) t;
      }

      throw t instanceof IOException ? (IOException) t : new IOException(t);
    }
}
</code>```

```<code>public static void closeQuietly(@Nullable Logger log, @Nullable Process process) {
  try {
    close(process);
  }
  catch (Exception e) {
    //log if Logger provided, otherwise discard
    logError(log, "Fehler beim Schließen des Process-Objekts (inkl. underlying streams)!", e);
  }
}
</code>```

```<code>public static void close(@Nullable Closeable closeable) throws IOException {
  if(closeable != null) {
    closeable.close();
  }
}
</code>```

Methods like these are basically used in finally-blocks.

What I really want to know is if I am safe with this implementation? Considering things like: Does a process object always return the same stdin, stdout and stderr streams during its lifetime? Or may I miss closing streams previously returned by process' getInputStream(), getOutputStream() and getErrorStream() methods?

There is a related question on StackOverflow.com: java: closing subprocess std streams?

Edit

As pointed out by me and others here:

InputStreams have to be totally consumed. When not done then the subprocess may not terminate, because there is outstanding data in its output streams.

All three std-streams have to be closed. Regardless if used before or not.

When the subprocess terminates normally everything should be fine. When not then it have to be terminated forcibly.

When an exit code is returned by subprocess then we do not need to destroy() it. It has terminated. (Even when not necessarily terminated normally with Exit Code 0, but it terminated.)

We need to monitor waitFor() and interrupt when timeout exceeds to give process a chance to terminate normally but killing it when it hangs.

Unanswered parts:

Consider Pros and Cons of consuming the InputStreams in parallel. Or must they be consumed in particular order?

答:
As the question you linked to states, it is better to read and discard the output and error streams.  If you are using apache commons io, something like,

```<code>new Thread(new Runnable() {public void run() {IOUtils.copy(process.getInputStream(), new NullOutputStream());}}).start();
new Thread(new Runnable() {public void run() {IOUtils.copy(process.getErrorStream(), new NullOutputStream());}}).start();
</code>```

You want to read and discard stdout and stderr in a separate thread to avoid problems such as the process blocking when it writes enough info to stderr or stdout to fill the buffer.

If you are worried about having two many threads, see this question

I don't think you need to worry about catching IOExceptions when copying stdout, stdin to NullOutputStream, since if there is an IOException reading from the process stdout/stdin, it is probably due to the process being dead itself, and writing to NullOutputStream will never throw an exception.

You don't need to check the return status of waitFor().

Do you want to wait for the process to complete?  If so, you can do,

```<code>while(true) {
     try
     {
         process.waitFor();
         break;
     } catch(InterruptedException e) {
         //ignore, spurious interrupted exceptions can occur
     }

}
</code>```

Looking at the link you provided you do need to close the streams when the process is complete, but destroy will do that for you.

So in the end, the method becomes,

```<code>public void close(Process process) {

    if(process == null) return;

    new Thread(new Runnable() {public void run() {IOUtils.copy(process.getInputStream(), new NullOutputStream());}}).start();
    new Thread(new Runnable() {public void run() {IOUtils.copy(process.getErrorStream(), new NullOutputStream());}}).start();
    while(true) {
        try
        {
            process.waitFor();
            //this will close stdin, stdout and stderr for the process
            process.destroy();
            break;
        } catch(InterruptedException e) {
            //ignore, spurious interrupted exceptions can occur
        }

   }
}
</code>```

Body:
This question is about java.lang.Process and its handling of stdin, stdout and stderr.

We have a class in our project that is an extension to org.apache.commons.io.IOUtils. There we have a quiet new method for closing the std-streams of a Process-Object appropriate? Or is it not appropriate?

/**
 * Method closes all underlying streams from the given Process object.
 * If Exit-Code is not equal to 0 then Process will be destroyed after
 * closing the streams.
 *
 * It is guaranteed that everything possible is done to release resources
 * even when Throwables are thrown in between.
 *
 * In case of occurances of multiple Throwables then the first occured
 * Throwable will be thrown as Error, RuntimeException or (masked) IOException.
 *
 * The method is null-safe.
 */
public static void close(@Nullable Process process) throws IOException {
    if(process == null) {
      return;
    }

    Throwable t = null;

    try {
      close(process.getOutputStream());
    }
    catch(Throwable e) {
      t = e;
    }

    try{
      close(process.getInputStream());
    }
    catch(Throwable e) {
      t = (t == null) ? e : t;
    }

    try{
      close(process.getErrorStream());
    }
    catch (Throwable e) {
      t = (t == null) ? e : t;
    }

    try{
      try {
        if(process.waitFor() != 0){
          process.destroy();
        }
      }
      catch(InterruptedException e) {
        t = (t == null) ? e : t;
        process.destroy();
      }
    }
    catch (Throwable e) {
      t = (t == null) ? e : t;
    }

    if(t != null) {
      if(t instanceof Error) {
        throw (Error) t;
      }

      if(t instanceof RuntimeException) {
        throw (RuntimeException) t;
      }

      throw t instanceof IOException ? (IOException) t : new IOException(t);
    }
}

public static void closeQuietly(@Nullable Logger log, @Nullable Process process) {
  try {
    close(process);
  }
  catch (Exception e) {
    //log if Logger provided, otherwise discard
    logError(log, "Fehler beim Schließen des Process-Objekts (inkl. underlying streams)!", e);
  }
}

public static void close(@Nullable Closeable closeable) throws IOException {
  if(closeable != null) {
    closeable.close();
  }
}

Methods like these are basically used in finally-blocks.

What I really want to know is if I am safe with this implementation? Considering things like: Does a process object always return the same stdin, stdout and stderr streams during its lifetime? Or may I miss closing streams previously returned by process' getInputStream(), getOutputStream() and getErrorStream() methods?

There is a related question on StackOverflow.com: java: closing subprocess std streams?

Edit

As pointed out by me and others here:

InputStreams have to be totally consumed. When not done then the subprocess may not terminate, because there is outstanding data in its output streams.

All three std-streams have to be closed. Regardless if used before or not.

When the subprocess terminates normally everything should be fine. When not then it have to be terminated forcibly.

When an exit code is returned by subprocess then we do not need to destroy() it. It has terminated. (Even when not necessarily terminated normally with Exit Code 0, but it terminated.)

We need to monitor waitFor() and interrupt when timeout exceeds to give process a chance to terminate normally but killing it when it hangs.

Unanswered parts:

Consider Pros and Cons of consuming the InputStreams in parallel. Or must they be consumed in particular order?

Body:
As the question you linked to states, it is better to read and discard the output and error streams.  If you are using apache commons io, something like,

new Thread(new Runnable() {public void run() {IOUtils.copy(process.getInputStream(), new NullOutputStream());}}).start();
new Thread(new Runnable() {public void run() {IOUtils.copy(process.getErrorStream(), new NullOutputStream());}}).start();

You want to read and discard stdout and stderr in a separate thread to avoid problems such as the process blocking when it writes enough info to stderr or stdout to fill the buffer.

If you are worried about having two many threads, see this question

I don't think you need to worry about catching IOExceptions when copying stdout, stdin to NullOutputStream, since if there is an IOException reading from the process stdout/stdin, it is probably due to the process being dead itself, and writing to NullOutputStream will never throw an exception.

You don't need to check the return status of waitFor().

Do you want to wait for the process to complete?  If so, you can do,

while(true) {
     try
     {
         process.waitFor();
         break;
     } catch(InterruptedException e) {
         //ignore, spurious interrupted exceptions can occur
     }

}

Looking at the link you provided you do need to close the streams when the process is complete, but destroy will do that for you.

So in the end, the method becomes,

public void close(Process process) {

    if(process == null) return;

    new Thread(new Runnable() {public void run() {IOUtils.copy(process.getInputStream(), new NullOutputStream());}}).start();
    new Thread(new Runnable() {public void run() {IOUtils.copy(process.getErrorStream(), new NullOutputStream());}}).start();
    while(true) {
        try
        {
            process.waitFor();
            //this will close stdin, stdout and stderr for the process
            process.destroy();
            break;
        } catch(InterruptedException e) {
            //ignore, spurious interrupted exceptions can occur
        }

   }
}


问:
How to activate Speech Recognition with a word in python
currently I'm working on a Virtual Assistant project
wherein, it takes voice commands and executes it.

Now, I have named him as 'MARK'

Now I have given this code the access to my mic

here is the code.....

```<code>import speech_recognition as sr

def takeCommand():
    # It is the recognizer
    r=sr.Recognizer()
    # Kept the microphone as source
    with sr.Microphone() as source: # It should keep listening but only when I say 'Mark'
        print("Listening...")
        r.pause_threshold=1
        audio = r.listen(source)
    try:
        print("Reconizing...")
        query = r.recognize_google(audio, language="en-in")
        print(f"You said : {query}\n")
    except Exception as error:
        # print(error)
        print('Say that again please')
</code>```

Over here in this function, he hears everything and then converts it into text

but I don't want him to always be listening to me, I mean, He should listen, but only respond when I say 'MARK'

So for this purpose, I altered the code like this....

```<code>def listen_to_navdeep():
    # It is the recognizer
    r=sr.Recognizer()
    # Kept the microphone as source
    with sr.Microphone() as source: # It should keep listening but only when I say 'Mark'
        r.pause_threshold=1
        audio = r.listen(source)
    while True:
        try:
            query = r.recognize_google(audio, language="en-in")
            query=query.lower()
            if "mark" in query:
                return query
                break
            else:
                pass
        except:
            pass

# Now I am outside the function....

while True:
    command=listen_to_navdeep
    # Some process runs over here.....
</code>```

Now even though I did it, there would be some time-mishappenings

So what I wanted to do is that he should be actively listening the voice but still should respond (and also not print the exception that there wasn't any speech)or convert it to text and run some process, in fact the moment I tell "Mark" then he should start recording the voice and then process it to text and do whatever is assigned (Please don't worry above the tasks which it will be doing)

Another good example to explain my problem is how "Alexa" works. Alexa keeps on listening everything in the home or surroundings, but doesn't react. She only react whenever I we say 'Alexa'. That's what I want over here....in my AI assistant.

Please tell me how to achieve it....

Looking forward for help....

答:
You can try doing the following:</p>
```<code>wake_word = "Mark"

while True:
    print("Listening")
    text = take_command()

    if text.count(wake_word) > 0:
        talk("I am ready")
        text = take_command()
</code>```

Body:
currently I'm working on a Virtual Assistant project
wherein, it takes voice commands and executes it.

Now, I have named him as 'MARK'

Now I have given this code the access to my mic

here is the code.....

import speech_recognition as sr

def takeCommand():
    # It is the recognizer
    r=sr.Recognizer()
    # Kept the microphone as source
    with sr.Microphone() as source: # It should keep listening but only when I say 'Mark'
        print("Listening...")
        r.pause_threshold=1
        audio = r.listen(source)
    try:
        print("Reconizing...")
        query = r.recognize_google(audio, language="en-in")
        print(f"You said : {query}\n")
    except Exception as error:
        # print(error)
        print('Say that again please')

Over here in this function, he hears everything and then converts it into text

but I don't want him to always be listening to me, I mean, He should listen, but only respond when I say 'MARK'

So for this purpose, I altered the code like this....

def listen_to_navdeep():
    # It is the recognizer
    r=sr.Recognizer()
    # Kept the microphone as source
    with sr.Microphone() as source: # It should keep listening but only when I say 'Mark'
        r.pause_threshold=1
        audio = r.listen(source)
    while True:
        try:
            query = r.recognize_google(audio, language="en-in")
            query=query.lower()
            if "mark" in query:
                return query
                break
            else:
                pass
        except:
            pass

# Now I am outside the function....

while True:
    command=listen_to_navdeep
    # Some process runs over here.....

Now even though I did it, there would be some time-mishappenings

So what I wanted to do is that he should be actively listening the voice but still should respond (and also not print the exception that there wasn't any speech)or convert it to text and run some process, in fact the moment I tell "Mark" then he should start recording the voice and then process it to text and do whatever is assigned (Please don't worry above the tasks which it will be doing)

Another good example to explain my problem is how "Alexa" works. Alexa keeps on listening everything in the home or surroundings, but doesn't react. She only react whenever I we say 'Alexa'. That's what I want over here....in my AI assistant.

Please tell me how to achieve it....

Looking forward for help....

Body:
You can try doing the following:

wake_word = "Mark"

while True:
    print("Listening")
    text = take_command()

    if text.count(wake_word) > 0:
        talk("I am ready")
        text = take_command()


问:
Getting duplicate class error when adding eclipse paho mqtt dependencies to Andrdoid Studio project
I can't compile the project anymore when I add the following dependencies

```<code>dependencies {
    ...
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2'
    ...
}
</code>```

to the project as suggested on the paho eclipse website:

https://www.eclipse.org/paho/clients/android/

I get following errors:

```<code>Duplicate class androidx.collection.LruCache found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-support-v4-r7.jar (com.google.android:support-v4:r7)
Duplicate class androidx.core.accessibilityservice.AccessibilityServiceInfoCompat found in modules core-1.0.1-runtime.jar (androidx.core:core:1.0.1) and jetified-support-v4-r7.jar (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.ActivityCompat found in modules core-1.0.1-runtime.jar (androidx.core:core:1.0.1) and jetified-support-v4-r7.jar (com.google.android:support-v4:r7)
</code>```

and many more others duplicate class errors.
My project setup is quite basic because I just started.

So practically if you open a new project and add those dependencies you should get the same error as I did.

Why is that?How to solve this?

P.S.: I already cleaned, rebuilt, Invalidated caches and restarted, updated Android studio etc..

Nothing, I'm missing something else here.

答:
Late, but for future people who run into this problem:

Replace the Paho dependencies with this:

```<code>implementation'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.4'
implementation'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
</code>```

Looks like a bug in the old versions.

Body:
I can't compile the project anymore when I add the following dependencies

dependencies {
    ...
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.0.2'
    ...
}

to the project as suggested on the paho eclipse website:

https://www.eclipse.org/paho/clients/android/

I get following errors:

Duplicate class androidx.collection.LruCache found in modules collection-1.0.0.jar (androidx.collection:collection:1.0.0) and jetified-support-v4-r7.jar (com.google.android:support-v4:r7)
Duplicate class androidx.core.accessibilityservice.AccessibilityServiceInfoCompat found in modules core-1.0.1-runtime.jar (androidx.core:core:1.0.1) and jetified-support-v4-r7.jar (com.google.android:support-v4:r7)
Duplicate class androidx.core.app.ActivityCompat found in modules core-1.0.1-runtime.jar (androidx.core:core:1.0.1) and jetified-support-v4-r7.jar (com.google.android:support-v4:r7)

and many more others duplicate class errors.
My project setup is quite basic because I just started.

So practically if you open a new project and add those dependencies you should get the same error as I did.

Why is that?How to solve this?

P.S.: I already cleaned, rebuilt, Invalidated caches and restarted, updated Android studio etc..

Nothing, I'm missing something else here.

Body:
Late, but for future people who run into this problem:

Replace the Paho dependencies with this:

implementation'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.4'
implementation'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

Looks like a bug in the old versions.


问:
Import could not be resolve after installing the dependency
I'm trying to install de messagebird dependency into my python project.

I write into requirements.txt and after I run pip install -r requirements.txt as you can see below:

But the pylance was still showing me the error:

Then I try to install using pip install messagebird but still with no success.

I also try to reopen the window but no success too.

I'm using pyenv, and using the right env on the vscode and terminal as you can see on the next images:

And in the terminal:

答:
You may be installing to the wrong Python distro? (could be installing to Python 2.7)

To target python3 you can use the following commands

python3 -m pip install -r requirements.txt
```
<p>Or</p>
<pre class="lang-sh prettyprint-override"><code>pip3 install -r requirements.txt
</code>```

To check that you've installed messagebird correctly you could also use the following command:

pip3 freeze | grep 'messagebird'
```

Body:
You may be installing to the wrong Python distro? (could be installing to Python 2.7)

To target python3 you can use the following commands

python3 -m pip install -r requirements.txt

Or

pip3 install -r requirements.txt

To check that you've installed messagebird correctly you could also use the following command:

pip3 freeze | grep 'messagebird'


问:
Return Missing balancing numbers
A balanced array would be an array in which each element appears the same number of times.

Given an array with n elements:
return a dictionary with the key as the element and the value as the count of elements needed to balance the given array

Examples

```<code>elements = ["a", "b", "abc", "c", "a"]
</code>```

Expected output: {"b":1, "abc":1, "c":1}

Because there are 2 a, we need 1 more of b, abc, c

Hope that helps

答:
This isn't homework but a Meta Data Engineer interview prep question ;)

This is my solution without using Counter

```<code>lst = ["a", "b", "abc", "c", "a"]
tuples = [(i, lst.count(i)) for i in lst]
tuples.sort(key=lambda x: -x[1])
max_value = tuples[0]

{k: max_value[1] - v for k,v in tuples if v < max_value[1]}
</code>```

Title: Return Missing balancing numbers

Body:
A balanced array would be an array in which each element appears the same number of times.

Given an array with n elements:
return a dictionary with the key as the element and the value as the count of elements needed to balance the given array

Examples

elements = ["a", "b", "abc", "c", "a"]

Expected output: {"b":1, "abc":1, "c":1}

Because there are 2 a, we need 1 more of b, abc, c

Hope that helps

Body:
This isn't homework but a Meta Data Engineer interview prep question ;)

This is my solution without using Counter

lst = ["a", "b", "abc", "c", "a"]
tuples = [(i, lst.count(i)) for i in lst]
tuples.sort(key=lambda x: -x[1])
max_value = tuples[0]

{k: max_value[1] - v for k,v in tuples if v < max_value[1]}


问:
Is it possible to check if a function with a string as its name exists?(C++)
I want to be able to do something like this:</p>

```<code>if (Is_Function("helloworld")
    // Run code
</code>```

答:
Well, Qt does something like this when using signals and slots, but then the functions will be registered in a map indexed by a mangling of their name iirc. This registering is achieved by their "MetaObject Compiler" which is basically a preprocessor/code generator and works statically.

Depending on what you want to do, you could use Qt.

Another possibility would be to compile a shared library and use dlsym, if available on your system.

Body:
I want to be able to do something like this:

if (Is_Function("helloworld")
    // Run code


问:
Django - passing one model to another while creating new object
My site has multiple tests with multiple questions each. I'd like to make question creation form which will have preset test object depended on url.
it's better explained in comment in views.py

That's what I have already done;

models

```<code>class Test(models.Model):
    name = models.CharField(max_length=200)
    #questions = models.ManyToManyField(Question)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True)
    date_posted = models.DateTimeField(auto_now_add = True)

    def get_questions(self):
        return self.question_set.all()

    def __str__(self):
        return self.name

class Question(models.Model):

    text = models.CharField(max_length=200, null=True)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add = True)

    def __str__(self):
         return self.text
</code>```

urls

```<code>urlpatterns = [
    path('', views.home, name='home'),
    path('test/<str:pk>/', views.test),

    path('test/<str:pk>/question-create/', views.QuestionCreateView, name='question-create'),

]
</code>```

forms

```<code>from django import forms
from django.forms import ModelForm
from .models import Question,

class QuestionCreationForm(ModelForm):
    class Meta:
        model = Question
        fields = '__all__'  /// all except test which is set by pk in url
</code>```

views

```<code>def QuestionCreateView(request, pk):

    form = QuestionCreationForm()
    if request.method == 'POST':
        test = Test.objects.get(id=pk)   /// I would like to pass it to models to disallow user to choose to which test will question belong, i mean test should pe preset by <pk> in link

        form = QuestionCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')

    context = {'form':form}
    return render(request, 'exam/question_form.html', context)
</code>```

what should I add/change to disallow user to choose test while creating new question ?

答:
```<code>class QuestionCreationForm(ModelForm):
    class Meta:
        model = Question
        exclude = ('user',)
</code>```

this will exclude user from form.

Here is How to set field after excluding

Body:
My site has multiple tests with multiple questions each. I'd like to make question creation form which will have preset test object depended on url.
it's better explained in comment in views.py

That's what I have already done;

models

class Test(models.Model):
    name = models.CharField(max_length=200)
    #questions = models.ManyToManyField(Question)
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None, null=True, blank=True)
    date_posted = models.DateTimeField(auto_now_add = True)

    def get_questions(self):
        return self.question_set.all()

    def __str__(self):
        return self.name

class Question(models.Model):

    text = models.CharField(max_length=200, null=True)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add = True)

    def __str__(self):
         return self.text

urls

urlpatterns = [
    path('', views.home, name='home'),
    path('test/<str:pk>/', views.test),

    path('test/<str:pk>/question-create/', views.QuestionCreateView, name='question-create'),

]

forms

from django import forms
from django.forms import ModelForm
from .models import Question,

class QuestionCreationForm(ModelForm):
    class Meta:
        model = Question
        fields = '__all__'  /// all except test which is set by pk in url

views

def QuestionCreateView(request, pk):

    form = QuestionCreationForm()
    if request.method == 'POST':
        test = Test.objects.get(id=pk)   /// I would like to pass it to models to disallow user to choose to which test will question belong, i mean test should pe preset by <pk> in link

        form = QuestionCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')

    context = {'form':form}
    return render(request, 'exam/question_form.html', context)

what should I add/change to disallow user to choose test while creating new question ?

Body:
class QuestionCreationForm(ModelForm):
    class Meta:
        model = Question
        exclude = ('user',)

this will exclude user from form.

Here is How to set field after excluding


问:
To solve ambiguity of overloaded function without either adding typecasting or remove the overloaded functions
I made a class Dummy, which is just a wrapper of primitive type double. The purpose of the class is to test potential problems before I introduce another class that substitutes the double class.

Dummy.h:

```<code>class Dummy{
private:
    double content;
public:
    Dummy(double _content) :content{ _content } {};
    operator long int()  {return (long int)content;};
}
</code>```

test.cpp:

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

int main(){
    Dummy a = Dummy(1.1);
    double aa = fabs(a);
}
</code>```

It reports:

<source>:17:27: error: call of overloaded 'fabs(Dummy&)' is ambiguous
   17 |     std::cout << std::fabs(foo);
      |                  ~~~~~~~~~^~~~~ In file included from /usr/include/features.h:461,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/x86_64-linux-gnu/bits/os_defines.h:39,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/x86_64-linux-gnu/bits/c++config.h:586,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:41,
                 from <source>:1: /usr/include/x86_64-linux-gnu/bits/mathcalls.h:162:1: note: candidate:
'double fabs(double)'
  162 | __MATHCALLX (fabs,, (_Mdouble_ __x),
(__const__));
      | ^~~~~~~~~~~ In file included from <source>:1: /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:241:3:
note: candidate: 'constexpr float std::fabs(float)'
  241 |
fabs(float __x)
      |   ^~~~ /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:245:3:
note: candidate: 'constexpr long double std::fabs(long double)'
  245 |   fabs(long double __x)
```
<p>If I add a type conversion operator:</p>
```operator double(){
    return content;
}
```

It somehow only works under Visual Studio, not g++ 9.3.0, which is my target compiler.

During the compiling with g++ 9.3.0, the following errors are reported:

I have read the information here, unfortunately I can't remove the overloaded functions in this case. Neither can I add typecasting, because it doesn't make sense for my purpose.

I also check here, but I am not so familiar with templates. Hence my question is:

Can I eliminate the ambiguity of overloaded function within the class, without adding typecasting, or removing the overloaded functions?

答:
The Dummy class you have shown is only convertible to long int, but fabs() does not accept long int, it accepts either float, double, or long double.  Since long int is implicitly convertible to float and double, the call was ambiguous until you added the double conversion operator.

If you don't want to do that, then you have to be explicit about which overload of fabs() you want to call.  Either by:

casting the result of the Dummy conversion:

```<code>double aa = fabs(static_cast<double>(a));
</code>```

assigning/casting fabs() to a function pointer of the desired signature:

```<code>double (*fabs_ptr)(double) = fabs;
fabs_ptr(a);
</code>```
```<code>using fabs_ptr = double (*)(double);
static_cast<fabs_ptr>(fabs)(a);
</code>```

Online Demo

Body:
I made a class Dummy, which is just a wrapper of primitive type double. The purpose of the class is to test potential problems before I introduce another class that substitutes the double class.

Dummy.h:

class Dummy{
private:
    double content;
public:
    Dummy(double _content) :content{ _content } {};
    operator long int()  {return (long int)content;};
}

test.cpp:

#include <math.h>

int main(){
    Dummy a = Dummy(1.1);
    double aa = fabs(a);
}

It reports:

<source>:17:27: error: call of overloaded 'fabs(Dummy&)' is ambiguous
   17 |     std::cout << std::fabs(foo);
      |                  ~~~~~~~~~^~~~~ In file included from /usr/include/features.h:461,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/x86_64-linux-gnu/bits/os_defines.h:39,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/x86_64-linux-gnu/bits/c++config.h:586,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:41,
                 from <source>:1: /usr/include/x86_64-linux-gnu/bits/mathcalls.h:162:1: note: candidate:
'double fabs(double)'
  162 | __MATHCALLX (fabs,, (_Mdouble_ __x),
(__const__));
      | ^~~~~~~~~~~ In file included from <source>:1: /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:241:3:
note: candidate: 'constexpr float std::fabs(float)'
  241 |
fabs(float __x)
      |   ^~~~ /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:245:3:
note: candidate: 'constexpr long double std::fabs(long double)'
  245 |   fabs(long double __x)

If I add a type conversion operator:

operator double(){
    return content;
}

It somehow only works under Visual Studio, not g++ 9.3.0, which is my target compiler.

During the compiling with g++ 9.3.0, the following errors are reported:

I have read the information here, unfortunately I can't remove the overloaded functions in this case. Neither can I add typecasting, because it doesn't make sense for my purpose.

I also check here, but I am not so familiar with templates. Hence my question is:

Can I eliminate the ambiguity of overloaded function within the class, without adding typecasting, or removing the overloaded functions?

Body:
The Dummy class you have shown is only convertible to long int, but fabs() does not accept long int, it accepts either float, double, or long double.  Since long int is implicitly convertible to float and double, the call was ambiguous until you added the double conversion operator.

If you don't want to do that, then you have to be explicit about which overload of fabs() you want to call.  Either by:

casting the result of the Dummy conversion:

double aa = fabs(static_cast<double>(a));

assigning/casting fabs() to a function pointer of the desired signature:

double (*fabs_ptr)(double) = fabs;
fabs_ptr(a);

using fabs_ptr = double (*)(double);
static_cast<fabs_ptr>(fabs)(a);

Online Demo


问:
use of deleted function ofstream
I have a C++ code with multiple files. I use g++-4.8 as my compiler with Ubuntu 18.04. Upon compiling the program I face the error below. Could you please help me to fix this?

use of deleted function 'std::basic_ofstream<char>::basic_ofstream(const std::_basic_ofstream<char>)'

I did not have this error, however by adding emplace_back() to code this error showed up:

```<code>#include "FileOutputHub.h"

#include <boost/filesystem.hpp>

#include "InitialCondition.h"

using namespace std;

const char* LogFileName = "simulation_log.txt";
const char* StatsFilePrefix = "stats_";
const char* QSP_prefix = "QSP_";
const char* OdeStatsFilePrefix = "odeStats_";
const char* SnapShotDir = "/snapShots";
const char* SaveStateDir = "/savedStates";

extern InitialCondition ic;

FileOutputHub::FileOutputHub(void)
: _seed()
, _outDirBase()
, _log()
, _generalStats_core()
, _generalStats_margin()
, _lymph_blood_QSP()
, _gridSnapshotFstream()
, _makeshiftSteam()
{
}

FileOutputHub::~FileOutputHub()
{
    _log.close();
    for (auto& fs : _generalStats_core) {
        fs.close();
    }
    for (auto& fs : _generalStats_margin) {
        fs.close();
    }
}

/*!
    Process paths and setup output file streams
    \param [in] seed: seed is used as part of the ABM/ODE stats file names
    \param [in] baseDirectory: base directory for all output files

    Simulation log file is saved in the base directory. If a new simulation's output
    directory is set to be the same as an older one, new log will append to the end of
    existing log.

    ABM/ODE stats are placed inside the base directory, which has a file name including
    the seed of the simulation. If output directory exists, stats will be attached to
    existing files. This is because when loading from a saved state, if the seed is the same,
    we assume the simulation is continuation of the saved progress, and append statas to
    the end of existing stats file without writing new headers; otherwise, new header is writen,
    so output directory should be set to a new location.

    all grid snapshot output file are placed in a sub-folder "snapShots".

    all serialization (saved states) are placed in a sub-folder "savedStates".
    */
void FileOutputHub::setup(long seed, string baseDirectory){

    _seed = seed;
    _outDirBase = baseDirectory;

    // create directories
    boost::filesystem::path pSnap(_outDirBase + SnapShotDir);
    boost::filesystem::create_directories(pSnap);// create snapshot directory tree

    boost::filesystem::path pState(_outDirBase + SaveStateDir);
    boost::filesystem::create_directories(pState);// create save states directory tree

    // initialize filestreams
    string logFileName = _outDirBase + "/" + LogFileName;
    _log.open(logFileName, ios::out | ios::app);

    string statsFileName;
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_core); i++) {

        _generalStats_core.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "core_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_core[i].open(statsFileName, ios::out | ios::app);
    }
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_margin); i++) {
        _generalStats_margin.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "margin_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_margin[i].open(statsFileName, ios::out | ios::app);
    }

    string QSP_FileName = _outDirBase + "/" + QSP_prefix + to_string(_seed) + ".csv";
    _lymph_blood_QSP.open(QSP_FileName, ios::out | ios::app);

}

ofstream& FileOutputHub::getStatsFstream(bool core, int i){
    if (core)
    {
        return _generalStats_core[i];
    }
    else{
        return _generalStats_margin[i];
    }
}
/*! Create a new output file stream for grid snapshot and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * snap;
    snap = <FileOutputHub instance>.getNewGridToSnapshot(time, tag);
    *snap << [contents] << std::endl;
    snap->close();
*/
ofstream& FileOutputHub::getNewGridToSnapshotStream(unsigned long time, std::string tag){

    string gridSnapFileName = _outDirBase + SnapShotDir+ "/" + tag + to_string(time) + ".csv";
    _gridSnapshotFstream.open(gridSnapFileName, ios::out | ios::trunc);
    return _gridSnapshotFstream;
}

/*! Create a new output file stream for serialzation and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * pState;
    pState = <FileOutputHub instance>.getNewSaveStateStream(time, tag);
    *pState << BOOST_SERIALIZATION_NVP(item1) << [item2] ...;
    pState->close();
    note that the NVP macro uses the variable name as xml tag; if want to use a different
    name, use boost::serialization::make_nvp("tag", variable)
*/
ofstream& FileOutputHub::getNewSaveStateStream(unsigned long time, std::string tag){
    string saveStateFileName = _outDirBase + SaveStateDir+ "/" + tag + to_string(time) + ".dat";
    _saveStateStream.open(saveStateFileName, ios::out | ios::trunc);
    return _saveStateStream;
}

/*!
    Create a new output file stream for temporary and general purposes
    \Param [in] tag: file name
    use case:
    std::ofstream * pOFS;
    pOFS = <output overseer instance>.getNewMakeshiftStream(tag);
    *pOFS << ...
    pOFS->CLOSE()
*/
ofstream& FileOutputHub::getNewMakeshiftStream(std::string tag){

    string makeShiftFileName = _outDirBase + "/" + tag;
    _makeshiftSteam.open(makeShiftFileName, ios::out | ios::trunc);
    return _makeshiftSteam;
}
</code>```

答:
What you are seeing is a compiler bug.

Assuming the containers are e.g. std::vectors, .emplace_back(ofstream()) should be calling the move constructor of ofstream to construct the new vector element in-place from the temporary object created by ofstream().

Apparently your compiler version tries to use the copy constructor, but ofstream isn't copyable.

With GCC 5.1 or later it works are expected: https://godbolt.org/z/KKWKvx65a

I suggest you get a more up-to-date compiler. GCC 4.8 is very old and just barely even supports C++11.

Title: use of deleted function ofstream

Body:
I have a C++ code with multiple files. I use g++-4.8 as my compiler with Ubuntu 18.04. Upon compiling the program I face the error below. Could you please help me to fix this?

use of deleted function 'std::basic_ofstream<char>::basic_ofstream(const std::_basic_ofstream<char>)'

I did not have this error, however by adding emplace_back() to code this error showed up:

#include "FileOutputHub.h"

#include <boost/filesystem.hpp>

#include "InitialCondition.h"

using namespace std;

const char* LogFileName = "simulation_log.txt";
const char* StatsFilePrefix = "stats_";
const char* QSP_prefix = "QSP_";
const char* OdeStatsFilePrefix = "odeStats_";
const char* SnapShotDir = "/snapShots";
const char* SaveStateDir = "/savedStates";

extern InitialCondition ic;

FileOutputHub::FileOutputHub(void)
: _seed()
, _outDirBase()
, _log()
, _generalStats_core()
, _generalStats_margin()
, _lymph_blood_QSP()
, _gridSnapshotFstream()
, _makeshiftSteam()
{
}

FileOutputHub::~FileOutputHub()
{
    _log.close();
    for (auto& fs : _generalStats_core) {
        fs.close();
    }
    for (auto& fs : _generalStats_margin) {
        fs.close();
    }
}

/*!
    Process paths and setup output file streams
    \param [in] seed: seed is used as part of the ABM/ODE stats file names
    \param [in] baseDirectory: base directory for all output files

    Simulation log file is saved in the base directory. If a new simulation's output
    directory is set to be the same as an older one, new log will append to the end of
    existing log.

    ABM/ODE stats are placed inside the base directory, which has a file name including
    the seed of the simulation. If output directory exists, stats will be attached to
    existing files. This is because when loading from a saved state, if the seed is the same,
    we assume the simulation is continuation of the saved progress, and append statas to
    the end of existing stats file without writing new headers; otherwise, new header is writen,
    so output directory should be set to a new location.

    all grid snapshot output file are placed in a sub-folder "snapShots".

    all serialization (saved states) are placed in a sub-folder "savedStates".
    */
void FileOutputHub::setup(long seed, string baseDirectory){

    _seed = seed;
    _outDirBase = baseDirectory;

    // create directories
    boost::filesystem::path pSnap(_outDirBase + SnapShotDir);
    boost::filesystem::create_directories(pSnap);// create snapshot directory tree

    boost::filesystem::path pState(_outDirBase + SaveStateDir);
    boost::filesystem::create_directories(pState);// create save states directory tree

    // initialize filestreams
    string logFileName = _outDirBase + "/" + LogFileName;
    _log.open(logFileName, ios::out | ios::app);

    string statsFileName;
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_core); i++) {

        _generalStats_core.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "core_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_core[i].open(statsFileName, ios::out | ios::app);
    }
    for (int i = 0; i < ic.getVal(IC_NUM_ROI_margin); i++) {
        _generalStats_margin.emplace_back(ofstream());
        statsFileName = _outDirBase + "/" + StatsFilePrefix + "margin_"
            + to_string(i) + "_s_" + to_string(_seed) + ".csv";
        //std::cout << "file: " << i << ", " <<statsFileName << std::endl;
        _generalStats_margin[i].open(statsFileName, ios::out | ios::app);
    }

    string QSP_FileName = _outDirBase + "/" + QSP_prefix + to_string(_seed) + ".csv";
    _lymph_blood_QSP.open(QSP_FileName, ios::out | ios::app);

}

ofstream& FileOutputHub::getStatsFstream(bool core, int i){
    if (core)
    {
        return _generalStats_core[i];
    }
    else{
        return _generalStats_margin[i];
    }
}
/*! Create a new output file stream for grid snapshot and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * snap;
    snap = <FileOutputHub instance>.getNewGridToSnapshot(time, tag);
    *snap << [contents] << std::endl;
    snap->close();
*/
ofstream& FileOutputHub::getNewGridToSnapshotStream(unsigned long time, std::string tag){

    string gridSnapFileName = _outDirBase + SnapShotDir+ "/" + tag + to_string(time) + ".csv";
    _gridSnapshotFstream.open(gridSnapFileName, ios::out | ios::trunc);
    return _gridSnapshotFstream;
}

/*! Create a new output file stream for serialzation and return the pointer
    \param [in] time: used to time stamp the file name
    \param [in] tag: goes to first part of file name
    use case:
    std::ofstream * pState;
    pState = <FileOutputHub instance>.getNewSaveStateStream(time, tag);
    *pState << BOOST_SERIALIZATION_NVP(item1) << [item2] ...;
    pState->close();
    note that the NVP macro uses the variable name as xml tag; if want to use a different
    name, use boost::serialization::make_nvp("tag", variable)
*/
ofstream& FileOutputHub::getNewSaveStateStream(unsigned long time, std::string tag){
    string saveStateFileName = _outDirBase + SaveStateDir+ "/" + tag + to_string(time) + ".dat";
    _saveStateStream.open(saveStateFileName, ios::out | ios::trunc);
    return _saveStateStream;
}

/*!
    Create a new output file stream for temporary and general purposes
    \Param [in] tag: file name
    use case:
    std::ofstream * pOFS;
    pOFS = <output overseer instance>.getNewMakeshiftStream(tag);
    *pOFS << ...
    pOFS->CLOSE()
*/
ofstream& FileOutputHub::getNewMakeshiftStream(std::string tag){

    string makeShiftFileName = _outDirBase + "/" + tag;
    _makeshiftSteam.open(makeShiftFileName, ios::out | ios::trunc);
    return _makeshiftSteam;
}


问:
Font awesome icon not changing in response to the slider change
I'm trying to change the icon in response to the volume control (range) element and can't make it work.

My html is:

```<code><div class="slidercontainer fs-4" id="slider-container">
    <span style="color:white;">    </span>
    <span class="badge rounded-pill bg-warning">Audio Volume</span>
    <span style="color:white;">    </span>

    <i id="volume_low" class="fa fa-volume-down fa-2x"></i>
    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">
    <i id="volume-up" class="fa fa-volume-up fa-2x"></i>

  </div>
</code>```

... and it is shown correctly in a browser

My javascript is:

```<code>// for slider
const slider = document.querySelector("#myRange");

$("#myRange").on("input change", function()
{
  const sliderValue = slider.value;
  if(sliderValue==0){
    console.log('zero', sliderValue );
    $('#volume_low').find("i").toggleClass("fa fa-volume-off fa-2x fa fa-volume-down fa-2x");
  }else
  {
    console.log('nonzero', sliderValue);
    $('#volume_low').find("i").toggleClass("fa fa-volume-down fa-2x fa fa-volume-off fa-2x");
  }

});

// end of for slider
</code>```

Doesn't work (icon not changing in the leftmost position as required), not showing any errors

答:
In the example below, three different icon changes are provided according to the sound status. Class styles previously applied to the  element are removed and new class styles are assigned.

/* Global Variable; It is initialized using the context of the class implemented in the  element. */
let beforeClass = "off";

$("#myRange").on("input change", function() {
  const sliderValue = $("#myRange").val();

  /* previously applied class styles are removed */
  $('#volume_low').removeClass(`fa fa-volume-${beforeClass} fa-2x`);

  if(sliderValue == 0)  {
    $('#volume_low').addClass("fa fa-volume-off fa-2x");
    beforeClass = "off";
  }
  else if(sliderValue > 0 && sliderValue <= 1) {
    $('#volume_low').addClass("fa fa-volume-down fa-2x");
    beforeClass = "down";
  }
  else if(sliderValue > 1) {
    $('#volume_low').addClass("fa fa-volume-up fa-2x");
    beforeClass = "up";
  }

  console.clear();
  console.log(`Value: ${sliderValue}`);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>i {
  margin-left: 40px;
  width: 50px;
}</code>```

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

    Audio Volume

    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">

```

Body:
I'm trying to change the icon in response to the volume control (range) element and can't make it work.

My html is:

    Audio Volume

    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">

... and it is shown correctly in a browser

My javascript is:

// for slider
const slider = document.querySelector("#myRange");

$("#myRange").on("input change", function()
{
  const sliderValue = slider.value;
  if(sliderValue==0){
    console.log('zero', sliderValue );
    $('#volume_low').find("i").toggleClass("fa fa-volume-off fa-2x fa fa-volume-down fa-2x");
  }else
  {
    console.log('nonzero', sliderValue);
    $('#volume_low').find("i").toggleClass("fa fa-volume-down fa-2x fa fa-volume-off fa-2x");
  }

});

// end of for slider

Doesn't work (icon not changing in the leftmost position as required), not showing any errors

Body:
In the example below, three different icon changes are provided according to the sound status. Class styles previously applied to the <i> element are removed and new class styles are assigned.

/* Global Variable; It is initialized using the context of the class implemented in the <i> element. */
let beforeClass = "off";

$("#myRange").on("input change", function() {
  const sliderValue = $("#myRange").val();

  /* previously applied class styles are removed */
  $('#volume_low').removeClass(`fa fa-volume-${beforeClass} fa-2x`);

  if(sliderValue == 0)  {
    $('#volume_low').addClass("fa fa-volume-off fa-2x");
    beforeClass = "off";
  }
  else if(sliderValue > 0 && sliderValue <= 1) {
    $('#volume_low').addClass("fa fa-volume-down fa-2x");
    beforeClass = "down";
  }
  else if(sliderValue > 1) {
    $('#volume_low').addClass("fa fa-volume-up fa-2x");
    beforeClass = "up";
  }

  console.clear();
  console.log(`Value: ${sliderValue}`);
});

i {
  margin-left: 40px;
  width: 50px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<div class="slidercontainer fs-4" id="slider-container">
    <span style="color:white;">&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <span class="badge rounded-pill bg-warning">Audio Volume</span>
    <span style="color:white;">&nbsp;&nbsp;&nbsp;&nbsp;</span><br><br>
    <i id="volume_low" class="fa fa-volume-off fa-2x"></i>
    <input type="range" min="0" max="2.5" value="0" step="0.1" class="slider" id="myRange">
    <i id="volume-up" class="fa fa-volume-up fa-2x"></i>
</div>


问:
Properly refresh frame picture
I have created a dashboard with the help of a userform. I've used a frame to load a background picture.

I want to create a button that will hide the menu on the right side, so the whole background picture can be seen. However, when I hide the menu (theyre labels and 1 multiform), a white square remains after the labels, so the picture cannot be seen.

I've tried various methods to fix this, however none of them worked so far. I use this to hide the menu:

```<code>Label23.Visible = False
Label20.Visible = False
Label22.Visible = False
Label24.Visible = False
Label51.Visible = False
MultiPage2.Visible = False
</code>```

After these, I've tried to repaint the frame:

```<code>Frame1.Repaint
</code>```

Tried to repaint the whole userform:

```<code>Me.Repaint
</code>```

Tried to Reload the Picture:

```<code>Sub LoadSkin()
Dim Path As String
Path = ThisWorkbook.Path & "\Nechytat\Skins\" & Worksheets("Data").Range("R" & Worksheets("Data").Range("B4").Value).Value

        With ZZZDashboard.Frame1
            .Picture = LoadPicture(Path & ".bmp")
            .PictureSizeMode = fmPictureSizeModeStretch
            .Height = ZZZDashboard.Height
            .Width = ZZZDashboard.Width - ZZZDashboard.Frame2.Width
            .Left = ZZZDashboard.Frame2.Width
        End With
    End Sub
</code>```

Tried the DoEvents, tried to call the userform_initialize again and even tried to combine these methods.

```<code>Private Sub CommandButton1_Click()
  Label23.Visible = False
  Label20.Visible = False
  Label22.Visible = False
  Label24.Visible = False
  Label51.Visible = False
  MultiPage2.Visible = False

  Frame1.Picture = LoadPicture("")
  DoEvents
  Frame1.Repaint
  Me.Repaint
  DoEvents
  Call LoadSkin
  Frame1.Repaint
  DoEvents
End Sub
</code>```

None of them worked so far. This looks like an easy fix, but I just can't figure it out.

答: I suggest you create two pages in a multiPage.  one has only the image for its background while the other has that image as well as the controls.  The you control which page is visible by setting the value of the multiPage to the desired value. To hide the tabs that come with the multi page, position its top with a negative value on the form.</p>

Title: Properly refresh frame picture

Body:
I have created a dashboard with the help of a userform. I've used a frame to load a background picture.

I want to create a button that will hide the menu on the right side, so the whole background picture can be seen. However, when I hide the menu (theyre labels and 1 multiform), a white square remains after the labels, so the picture cannot be seen.

I've tried various methods to fix this, however none of them worked so far. I use this to hide the menu:

Label23.Visible = False
Label20.Visible = False
Label22.Visible = False
Label24.Visible = False
Label51.Visible = False
MultiPage2.Visible = False

After these, I've tried to repaint the frame:

Frame1.Repaint

Tried to repaint the whole userform:

Me.Repaint

Tried to Reload the Picture:

Sub LoadSkin()
Dim Path As String
Path = ThisWorkbook.Path & "\Nechytat\Skins\" & Worksheets("Data").Range("R" & Worksheets("Data").Range("B4").Value).Value

        With ZZZDashboard.Frame1
            .Picture = LoadPicture(Path & ".bmp")
            .PictureSizeMode = fmPictureSizeModeStretch
            .Height = ZZZDashboard.Height
            .Width = ZZZDashboard.Width - ZZZDashboard.Frame2.Width
            .Left = ZZZDashboard.Frame2.Width
        End With
    End Sub

Tried the DoEvents, tried to call the userform_initialize again and even tried to combine these methods.

Private Sub CommandButton1_Click()
  Label23.Visible = False
  Label20.Visible = False
  Label22.Visible = False
  Label24.Visible = False
  Label51.Visible = False
  MultiPage2.Visible = False

  Frame1.Picture = LoadPicture("")
  DoEvents
  Frame1.Repaint
  Me.Repaint
  DoEvents
  Call LoadSkin
  Frame1.Repaint
  DoEvents
End Sub

None of them worked so far. This looks like an easy fix, but I just can't figure it out.