问:
interaction effects of marginal effects and its standard errors in glm with R
I viewed lots of relevant bloggers who explained how to generate marginal effects, but somehow most of them did not take interaction effects as sample.

When I use Stata to do it, the margin effects are quite easy to compute, but R seems in another way and show different results.

I want to know how to compute proper marginal effects with interaction properly,

why function margins() does not show the interaction factor?

if I compute this by hand coef(glm)*mean(dlogis(predict(glm, type = "link")),na.rm=T) ,it looks more close to the Stata result, not with the function margins()?

what's more, how can I compute the standard error of marginal effects handly, will it like this sqrt(diag(vcov(glm1)))*mean(dlogis(predict(glm, type = "link")),na.rm=T)  ?

```<code>trydata=read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/palmerpenguins/penguins.csv")
trydata[c("species","sex")]=lapply(trydata[c("species","sex" )], as.factor)
contrasts(trydata$species)=contr.treatment(3)
contrasts(trydata$sex)=contr.treatment(2)

try=glm(bill_length_mm ~sex+species+bill_depth_mm + sex*species, data=trydata)
summary(try)
summary(margins(try))
</code>```

some links I saw before and thought useful:

code: marginal effects with interaction

Marginal effects calculated by hand, but standard error doesn't show

Compare R vs STATA with various packages and functions: Interpreting Regression Results using Average
Marginal Effects with R’s margins

Probit/Logit Marginal Effects in R

An Introduction to ‘margins’

答:
I think margins() is  trying to prevent you from doing something that doesn't make sense.  There are a couple of reasons for the difference.

The most important is that when your x-variable (e.g., sex) is discrete (as it is in this case), the partial first derivative with respect to x is not meaningful because the idea of inducing an infinitesimal change to x doesn't make sense.  In your data, sex can be either male or female.  So, what margins() will do is calculate a first difference rather than a first derivative.

The other reason is that it is similarly not meaningful to think about the partial first derivative of the interaction term - the effect of changing the interaction term while holding the other terms constant.  You can't change the interaction term while holding the constitutive terms fixed.

So, I am not sure how you would want to interpret a marginal effect for just the interaction term itself.

As for the third question, you would have to use the delta method or a parametric bootstrap to calculate the standard error of the partial first derivative since the partial first derivative is a non-linear combination of the coefficients.

Body:
I viewed lots of relevant bloggers who explained how to generate marginal effects, but somehow most of them did not take interaction effects as sample.

When I use Stata to do it, the margin effects are quite easy to compute, but R seems in another way and show different results.

I want to know how to compute proper marginal effects with interaction properly,

why function margins() does not show the interaction factor?

if I compute this by hand coef(glm)*mean(dlogis(predict(glm, type = "link")),na.rm=T) ,it looks more close to the Stata result, not with the function margins()?

what's more, how can I compute the standard error of marginal effects handly, will it like this sqrt(diag(vcov(glm1)))*mean(dlogis(predict(glm, type = "link")),na.rm=T)  ?

trydata=read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/palmerpenguins/penguins.csv")
trydata[c("species","sex")]=lapply(trydata[c("species","sex" )], as.factor)
contrasts(trydata$species)=contr.treatment(3)
contrasts(trydata$sex)=contr.treatment(2)

try=glm(bill_length_mm ~sex+species+bill_depth_mm + sex*species, data=trydata)
summary(try)
summary(margins(try))

some links I saw before and thought useful:

code: marginal effects with interaction

Marginal effects calculated by hand, but standard error doesn't show

Compare R vs STATA with various packages and functions: Interpreting Regression Results using Average
Marginal Effects with R’s margins

Probit/Logit Marginal Effects in R

An Introduction to ‘margins’


来源: stackexchange

问:
Matching a list of sentences (tokens with ntlk) with a column in pandas dataframe

I'm new to python, so still struggling with the basics, but I have this be sorted out and any help would be greatly appreciated.
So I have this long dataframe with hundreds of rows formed by text of a specific pdf page extract from a medical exam, each row is a different person.

I succefully extracted the text (using pymupdf) and iterated it for each row, cleaned the text as much I could and ended up with a dataframe similar to this one below with a column of sentences obtained using nltk sent_tokenize and multiple rows.

```<code>import pandas as pd
from nltk.tokenize import sent_tokenize

df = pd.DataFrame({"text":["hello, this is a sentence. the sun shines. the the night is beautiful",
              "the sun shines",
              "the night is beautiful. tomorrow i work"]})

df["token"] = df["text"].apply(sent_tokenize)
</code>```

The last part of my task is to match specific sentences from a list medical phrases (specific for the exam) to those in my dataframe and keep only the matches, in a new column, for example.  For that, I found this thread Looping through list and row for keyword match in pandas dataframe with @furas solution, clean and looked like would do the job. So, in the end, I have a pandas column of sentences (ntlk tokens) and list of medical phrases also (ntlk tokens as well) and need to match them.

```<code>specific_sent = "the sun shines. hello, this is a sentence."
query = sent_tokenize(''.join(specific_sent))

df["query_match"] = df["token"].str.contains(query)
df["word"] = df["token"].str.extract('({})'.format(query))
</code>```

When I run this code, I get this error "TypeError: unhashable type: 'list'", which is not uncommon and I have of an understanding of it, but I'm struggling to overcome. Any help on how to overcome this error in this particular example and ways to prevent this error in the future is really appreciated. Thanks!

This is an example of desired output:

text
token
query_match
word

hello, this is a sentence. the sun shines. the night is beautiful
[hello, this is a sentence., the sun shines., the night is beautiful]
True
the sun shines., hello, this is a sentence.

the sun shines.
[the sun shines.]
True
the sun shines.

the night is beautiful. tomorrow i work
[the night is beautiful., tomorrow i work.]
False
NaN

答:
Once you tokenize each sentence in the DataFrame and the specific sentence, you obtain lists from which you can find the elements in common and construct the column word. After that you can also populate the column query_match checking if the resulting lists, containing the elements in common, are empty or not.

```<code>df = pd.DataFrame({"text":["hello, this is a sentence. the sun shines. the the night is beautiful",
              "the sun shines.",
              "the night is beautiful. tomorrow i work"]})

specific_sent = "the sun shines. hello, this is a sentence."
query = sent_tokenize(''.join(specific_sent))

df["token"] = df["text"].apply(sent_tokenize)

# check elements in common between each sentence and query
df["word"] = df["token"].apply(lambda x: list(set(query).intersection(x)))

# if they had elements in common insert True, otherwise False
df["query_match"] = df["word"].apply(lambda x: 'True' if x else 'False')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new to python, so still struggling with the basics, but I have this be sorted out and any help would be greatly appreciated.
So I have this long dataframe with hundreds of rows formed by text of a specific pdf page extract from a medical exam, each row is a different person.

I succefully extracted the text (using pymupdf) and iterated it for each row, cleaned the text as much I could and ended up with a dataframe similar to this one below with a column of sentences obtained using nltk sent_tokenize and multiple rows.

import pandas as pd
from nltk.tokenize import sent_tokenize

df = pd.DataFrame({"text":["hello, this is a sentence. the sun shines. the the night is beautiful",
              "the sun shines",
              "the night is beautiful. tomorrow i work"]})

df["token"] = df["text"].apply(sent_tokenize)

The last part of my task is to match specific sentences from a list medical phrases (specific for the exam) to those in my dataframe and keep only the matches, in a new column, for example.  For that, I found this thread Looping through list and row for keyword match in pandas dataframe with @furas solution, clean and looked like would do the job. So, in the end, I have a pandas column of sentences (ntlk tokens) and list of medical phrases also (ntlk tokens as well) and need to match them.

specific_sent = "the sun shines. hello, this is a sentence."
query = sent_tokenize(''.join(specific_sent))

df["query_match"] = df["token"].str.contains(query)
df["word"] = df["token"].str.extract('({})'.format(query))

When I run this code, I get this error "TypeError: unhashable type: 'list'", which is not uncommon and I have of an understanding of it, but I'm struggling to overcome. Any help on how to overcome this error in this particular example and ways to prevent this error in the future is really appreciated. Thanks!

This is an example of desired output:

text
token
query_match
word

hello, this is a sentence. the sun shines. the night is beautiful
[hello, this is a sentence., the sun shines., the night is beautiful]
True
the sun shines., hello, this is a sentence.

the sun shines.
[the sun shines.]
True
the sun shines.

the night is beautiful. tomorrow i work
[the night is beautiful., tomorrow i work.]
False
NaN

Body:
Once you tokenize each sentence in the DataFrame and the specific sentence, you obtain lists from which you can find the elements in common and construct the column word. After that you can also populate the column query_match checking if the resulting lists, containing the elements in common, are empty or not.

df = pd.DataFrame({"text":["hello, this is a sentence. the sun shines. the the night is beautiful",
              "the sun shines.",
              "the night is beautiful. tomorrow i work"]})

specific_sent = "the sun shines. hello, this is a sentence."
query = sent_tokenize(''.join(specific_sent))

df["token"] = df["text"].apply(sent_tokenize)

# check elements in common between each sentence and query
df["word"] = df["token"].apply(lambda x: list(set(query).intersection(x)))

# if they had elements in common insert True, otherwise False
df["query_match"] = df["word"].apply(lambda x: 'True' if x else 'False')


问:
Writing to COM Port
I created an application to read information from a serial interface COM Port using MFC and the program now reads information from the COM Port, but I'm not sure what exactly its displaying. It is showing an arrow, that we usually get in a hyper terminal. If I need to write something onto the hyper terminal by some COMM commands(like creating handles, grouping them, displaying values etc) using my MFC Dialog Based Application, how may I do that?

Basically I have some commands that I use on my hyper terminal.
For Ex:

```<code>-> $PPROCH,A,00000020,1,1*##<crlf>
+>
</code>```

..
The above command creates a handle A. Once the above command gets executed on the hyper terminal, the +> comes which shows that the information is added. This is done by hyper terminal. But I need to be able to do this via my MFC Dialog based program, where in the user can input the above command through a text box or something and the hyper terminal reads it and stores the handle created.Any way of doing this? Could anyone please suggest me a way to go about this?

Many thanks in advance.

Cheers.

答:
This can get quite complicated if you need to avoid the comms from blocking the user interface.

This should be of help:
http://www.codeguru.com/cpp/i-n/network/serialcommunications/article.php/c5425

Ultimately you need to write to the port with the text that the user entered, and then read it to get the '+>'.

Not really sure what you mean by storing the handles?  If you need it to remember that 'A' was set, I'd recommend splitting up the command components into separate user interface elements and constructing the $PPROCH command from the elements.  You can then easily store the details of the request that you have sent and flag it as complete when you read back '+>' from the port.

ContentLicense: CC BY-SA 3.0

Title: Writing to COM Port

Body:
I created an application to read information from a serial interface COM Port using MFC and the program now reads information from the COM Port, but I'm not sure what exactly its displaying. It is showing an arrow, that we usually get in a hyper terminal. If I need to write something onto the hyper terminal by some COMM commands(like creating handles, grouping them, displaying values etc) using my MFC Dialog Based Application, how may I do that?

Basically I have some commands that I use on my hyper terminal.
For Ex:

-> $PPROCH,A,00000020,1,1*##<crlf>
+>

..
The above command creates a handle A. Once the above command gets executed on the hyper terminal, the +> comes which shows that the information is added. This is done by hyper terminal. But I need to be able to do this via my MFC Dialog based program, where in the user can input the above command through a text box or something and the hyper terminal reads it and stores the handle created.Any way of doing this? Could anyone please suggest me a way to go about this?

Many thanks in advance.

Cheers.


问:
Restrict list for table - Flutter
I want to limit the number of rows in the table, because I get about 40 rows from the API, and I need to make 5 rows. Tell me, what method should be applied in List.generate to show only the first 5 elements from the list? Thanks in advance.

DataTable

```<code>child: FutureBuilder<List<BlockModel>>(
              future: futureBlock,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return DataTable(
                      columns: const [
                        DataColumn(label: Text('Height')),
                        DataColumn(label: Text('Hash')),
                        DataColumn(label: Text('Time')),
                      ],
                      rows: List.generate(snapshot.data!.length, (index) {
                        return DataRow(cells: [
                          DataCell(Text('${snapshot.data![index].height}')),
                          DataCell(Text(snapshot.data![index].hash)),
                          DataCell(Text('${snapshot.data![index].time}')),
                        ]);
                      })
                      );
                } else {
</code>```

答:
You can restrict the length of the List while generating it.

```<code>rows: List.generate(5, (index) {

// ---Your Code---

}
</code>```

Here you can see instead of snapshot.data!.length you can pass the predefined length. Please apply the logic yourself if the snapshot.data.length is lesser than five

Title: Restrict list for table - Flutter

Body:
I want to limit the number of rows in the table, because I get about 40 rows from the API, and I need to make 5 rows. Tell me, what method should be applied in List.generate to show only the first 5 elements from the list? Thanks in advance.

DataTable

child: FutureBuilder<List<BlockModel>>(
              future: futureBlock,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return DataTable(
                      columns: const [
                        DataColumn(label: Text('Height')),
                        DataColumn(label: Text('Hash')),
                        DataColumn(label: Text('Time')),
                      ],
                      rows: List.generate(snapshot.data!.length, (index) {
                        return DataRow(cells: [
                          DataCell(Text('${snapshot.data![index].height}')),
                          DataCell(Text(snapshot.data![index].hash)),
                          DataCell(Text('${snapshot.data![index].time}')),
                        ]);
                      })
                      );
                } else {

Body:
You can restrict the length of the List while generating it.

rows: List.generate(5, (index) {

// ---Your Code---

}

Here you can see instead of snapshot.data!.length you can pass the predefined length. Please apply the logic yourself if the snapshot.data.length is lesser than five


问:
TsTables: AttributeError: module 'pandas.tseries' has no attribute 'index'
Background
I have a DataFrame which I am trying to write/append to a TsTable. I am executing it using Jupyter notebook. Python 3.9.7.

Problem
I am getting an error while trying to append.

DataFrame structure

```<code><class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 5000000 entries, 2019-01-01 00:00:00 to 2019-02-27 20:53:19
Freq: S
Data columns (total 3 columns):
    Column  Dtype
---  ------  -----
 0   ts1     float64
 1   ts2     float64
 2   ts3     float64
dtypes: float64(3)
</code>```

Code
(Ref: Python for Finance by Yves Hilpisch)

```<code>import tstables as tstab

class ts_desc(tb.IsDescription):
    timestamp = tb.Int64Col(pos=0)
    ts1 = tb.Float64Col(pos=1)
    ts2 = tb.Float64Col(pos=2)
    ts3 = tb.Float64Col(pos=3)

h5 = tb.open_file(path + 'tstab.h5', 'w')

ts = h5.create_ts('/', 'ts', ts_desc) # create a TsTable object based on the ts_dsc object

%time ts.append(df) # append the data from the DataFrame object to TsTable object
</code>```

The error happens after the above command.

```<code>AttributeError                            Traceback (most recent call last)
<timed eval> in <module>

/opt/conda/lib/python3.9/site-packages/tstables/tstable.py in append(self, rows, convert_strings)
    237             if rows.empty:
    238                 return # Do nothing if we are appending nothing
--> 239             if rows.index.__class__ != pandas.tseries.index.DatetimeIndex:
    240                 raise ValueError('when rows is a DataFrame, the index must be a DatetimeIndex.')
    241

AttributeError: module 'pandas.tseries' has no attribute 'index'
</code>```

答:
You should use this code before your first import:

```<code>pip install git+https://github.com/yhilpisch/tstables.git
</code>```

with this version of tstables, your code works well.

Body:
Background
I have a DataFrame which I am trying to write/append to a TsTable. I am executing it using Jupyter notebook. Python 3.9.7.

Problem
I am getting an error while trying to append.

DataFrame structure

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 5000000 entries, 2019-01-01 00:00:00 to 2019-02-27 20:53:19
Freq: S
Data columns (total 3 columns):
    Column  Dtype
---  ------  -----
 0   ts1     float64
 1   ts2     float64
 2   ts3     float64
dtypes: float64(3)

Code
(Ref: Python for Finance by Yves Hilpisch)

import tstables as tstab

class ts_desc(tb.IsDescription):
    timestamp = tb.Int64Col(pos=0)
    ts1 = tb.Float64Col(pos=1)
    ts2 = tb.Float64Col(pos=2)
    ts3 = tb.Float64Col(pos=3)

h5 = tb.open_file(path + 'tstab.h5', 'w')

ts = h5.create_ts('/', 'ts', ts_desc) # create a TsTable object based on the ts_dsc object

%time ts.append(df) # append the data from the DataFrame object to TsTable object

The error happens after the above command.

AttributeError                            Traceback (most recent call last)
<timed eval> in <module>

/opt/conda/lib/python3.9/site-packages/tstables/tstable.py in append(self, rows, convert_strings)
    237             if rows.empty:
    238                 return # Do nothing if we are appending nothing
--> 239             if rows.index.__class__ != pandas.tseries.index.DatetimeIndex:
    240                 raise ValueError('when rows is a DataFrame, the index must be a DatetimeIndex.')
    241

AttributeError: module 'pandas.tseries' has no attribute 'index'

Body:
You should use this code before your first import:

pip install git+https://github.com/yhilpisch/tstables.git

with this version of tstables, your code works well.


问:
Why do my TCP clients fail to connect to my server with a socket exception when stress-testing it with many connections
When stress-testing a TCP server of mine with a large number of connections, I figured that connection requests will throw a SocketException after some time. The exception displays randomly either

Only one usage of each socket address (protocol/network address/port) is normally permitted.

or

No connection could be made because the target machine actively refused it.

as its message.

This happens usually but randomly after some seconds and some tens of thousands of connects and disconnects. To connect, I use the local end point IPEndPoint clientEndPoint = new(IPAddress.Any, 0);, which I believe would give me the next free ephemeral port.

To isolate the issue, I wrote this simple program that runs both a TCP server and many parallel clients for a simple counter:

```<code>using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;

const int serverPort = 65000;
const int counterRequestMessage = -1;
const int randomCounterResponseMinDelay = 10; //ms
const int randomCounterResponseMaxDelay = 1000; //ms
const int maxParallelCounterRequests = 10000;

#region server

int counterValue = 0;

async void RunCounterServer()
{
    TcpListener listener = new(IPAddress.Any, serverPort);
    listener.Start(maxParallelCounterRequests);
    while (!cancellationToken.IsCancellationRequested)
    {
        HandleCounterRequester(await listener.AcceptTcpClientAsync(cancellationToken));
    }

    listener.Stop();
}

async void HandleCounterRequester(TcpClient client)
{
    await using NetworkStream stream = client.GetStream();
    Memory<byte> memory = new byte[sizeof(int)];

    //read requestMessage
    await stream.ReadAsync(memory, cancellationToken);
    int requestMessage = BitConverter.ToInt32(memory.Span);
    Debug.Assert(requestMessage == counterRequestMessage);

    //increment counter
    int updatedCounterValue = Interlocked.Add(ref counterValue, 1);
    Debug.Assert(BitConverter.TryWriteBytes(memory.Span, updatedCounterValue));

    //wait random timeout
    await Task.Delay(GetRandomCounterResponseDelay());

    //write back response
    await stream.WriteAsync(memory, cancellationToken);

    client.Close();
    client.Dispose();
}

int GetRandomCounterResponseDelay()
{
    return Random.Shared.Next(randomCounterResponseMinDelay, randomCounterResponseMaxDelay);
}

RunCounterServer();

#endregion

IPEndPoint clientEndPoint = new(IPAddress.Any, 0);
IPEndPoint serverEndPoint = new(IPAddress.Parse("127.0.0.1"), serverPort);
ReaderWriterLockSlim isExceptionEncounteredLock = new(LockRecursionPolicy.NoRecursion);
bool isExceptionEncountered = false;

async Task RunCounterClient()
{
    try
    {
        int counterResponse;
        using (TcpClient client = new(clientEndPoint))
        {
            await client.ConnectAsync(serverEndPoint, cancellationToken);

            await using (NetworkStream stream = client.GetStream())
            {
                Memory<byte> memory = new byte[sizeof(int)];

                //send counter request
                Debug.Assert(BitConverter.TryWriteBytes(memory.Span, counterRequestMessage));
                await stream.WriteAsync(memory, cancellationToken);

                //read counter response
                await stream.ReadAsync(memory, cancellationToken);
                counterResponse = BitConverter.ToInt32(memory.Span);
            }

            client.Close();
        }

        isExceptionEncounteredLock.EnterReadLock();
        //log response if there was no exception encountered so far
        if (!isExceptionEncountered)
        {
            Console.WriteLine(counterResponse);
        }

        isExceptionEncounteredLock.ExitReadLock();
    }
    catch (SocketException exception)
    {
        bool isFirstEncounteredException = false;

        isExceptionEncounteredLock.EnterWriteLock();

        //log exception and note that one was encountered if it is the first one
        if (!isExceptionEncountered)
        {
            Console.WriteLine(exception.Message);
            isExceptionEncountered = true;
            isFirstEncounteredException = true;
        }

        isExceptionEncounteredLock.ExitWriteLock();

        //if this is the first exception encountered, rethrow it
        if (isFirstEncounteredException)
        {
            throw;
        }
    }
}

async void RunParallelCounterClients()
{
    SemaphoreSlim clientSlotCount = new(maxParallelCounterRequests, maxParallelCounterRequests);

    async void RunCounterClientAndReleaseSlot()
    {
        await RunCounterClient();
        clientSlotCount.Release();
    }

    while (!cancellationToken.IsCancellationRequested)
    {
        await clientSlotCount.WaitAsync(cancellationToken);
        RunCounterClientAndReleaseSlot();
    }
}

RunParallelCounterClients();

while (true)
{
    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
    if (keyInfo.Key == ConsoleKey.Escape)
    {
        cancellationTokenSource.Cancel();
        break;
    }
}
</code>```

My initial guess is, that I run out of ephemeral ports because I somehow do not free them correctly. I just Close() and Dispose() my TcpClients in both my client and server code when a request is finished. I thought that would automatically release the port, but when I use netstat -ab in a console, it gives me countless entries like this, even after closing the application:

```<code>TCP    127.0.0.1:65000        kubernetes:59996       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:59997       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:59998       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:59999       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60000       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60001       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60002       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60003       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60004       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60005       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60006       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60007       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60009       TIME_WAIT
</code>```

Also, my PC sometimes gets a lot of stutter some time after I exit the application. I assume this is due to Windows cleaning up my leaked port usage?

So I wonder, what am I doing wrong here?

答:
Only one usage of each socket address (protocol/network address/port) is normally permitted. ... My initial guess is, that I run out of ephemeral ports because I somehow do not free them correctly.

TIME_WAIT is a perfectly normal state each TCP connection will enter when the connection is actively closed, i.e. explicitly calling close after sending the data or implicitly closing when exiting the application. See this diagram (source https://en.wikipedia.org/wiki/File:Tcp_state_diagram_fixed.svg):

It will take some timeout to leave the TIME_WAIT state and enter CLOSED. As long as the connection is in TIME_OUT the specific combination of source ip, port and destination ip,port cannot be used for new connections. This effectively limits the number of connections possible within some time from one specific IP address to another specific IP. Note that typical servers don't run into such limits since they get many connections from different system, and from each source IP only a few connections.

There is not much one can do about this except not actively closing the connection. If the other side triggers the connection first (sending FIN) and one continues with this close (ACKing the FIN and sending own FIN) then no TIME_WAIT will happen. Of course in your specific scenario of a single client and a single server this will just shift the problem to the server.

No connection could be made because the target machine actively refused it.

This has another reason. The server does a listen on the socket and gives the intended size of the backlog (the OS might will probably not use exactly this value). This backlog is used to accept new TCP connections in the OS kernel and the server will the call accept to get these accepted TCP connections. If the server calls accept less often than new connections get established the backlog will fill up. And once the backlog is full the server will refuse new connection, resulting in the error you see. In other words: this happens if the server is not able to keep up with the client.

Body:
When stress-testing a TCP server of mine with a large number of connections, I figured that connection requests will throw a SocketException after some time. The exception displays randomly either

Only one usage of each socket address (protocol/network address/port) is normally permitted.

or

No connection could be made because the target machine actively refused it.

as its message.

This happens usually but randomly after some seconds and some tens of thousands of connects and disconnects. To connect, I use the local end point IPEndPoint clientEndPoint = new(IPAddress.Any, 0);, which I believe would give me the next free ephemeral port.

To isolate the issue, I wrote this simple program that runs both a TCP server and many parallel clients for a simple counter:

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

CancellationTokenSource cancellationTokenSource = new();
CancellationToken cancellationToken = cancellationTokenSource.Token;

const int serverPort = 65000;
const int counterRequestMessage = -1;
const int randomCounterResponseMinDelay = 10; //ms
const int randomCounterResponseMaxDelay = 1000; //ms
const int maxParallelCounterRequests = 10000;

#region server

int counterValue = 0;

async void RunCounterServer()
{
    TcpListener listener = new(IPAddress.Any, serverPort);
    listener.Start(maxParallelCounterRequests);
    while (!cancellationToken.IsCancellationRequested)
    {
        HandleCounterRequester(await listener.AcceptTcpClientAsync(cancellationToken));
    }

    listener.Stop();
}

async void HandleCounterRequester(TcpClient client)
{
    await using NetworkStream stream = client.GetStream();
    Memory<byte> memory = new byte[sizeof(int)];

    //read requestMessage
    await stream.ReadAsync(memory, cancellationToken);
    int requestMessage = BitConverter.ToInt32(memory.Span);
    Debug.Assert(requestMessage == counterRequestMessage);

    //increment counter
    int updatedCounterValue = Interlocked.Add(ref counterValue, 1);
    Debug.Assert(BitConverter.TryWriteBytes(memory.Span, updatedCounterValue));

    //wait random timeout
    await Task.Delay(GetRandomCounterResponseDelay());

    //write back response
    await stream.WriteAsync(memory, cancellationToken);

    client.Close();
    client.Dispose();
}

int GetRandomCounterResponseDelay()
{
    return Random.Shared.Next(randomCounterResponseMinDelay, randomCounterResponseMaxDelay);
}

RunCounterServer();

#endregion

IPEndPoint clientEndPoint = new(IPAddress.Any, 0);
IPEndPoint serverEndPoint = new(IPAddress.Parse("127.0.0.1"), serverPort);
ReaderWriterLockSlim isExceptionEncounteredLock = new(LockRecursionPolicy.NoRecursion);
bool isExceptionEncountered = false;

async Task RunCounterClient()
{
    try
    {
        int counterResponse;
        using (TcpClient client = new(clientEndPoint))
        {
            await client.ConnectAsync(serverEndPoint, cancellationToken);

            await using (NetworkStream stream = client.GetStream())
            {
                Memory<byte> memory = new byte[sizeof(int)];

                //send counter request
                Debug.Assert(BitConverter.TryWriteBytes(memory.Span, counterRequestMessage));
                await stream.WriteAsync(memory, cancellationToken);

                //read counter response
                await stream.ReadAsync(memory, cancellationToken);
                counterResponse = BitConverter.ToInt32(memory.Span);
            }

            client.Close();
        }

        isExceptionEncounteredLock.EnterReadLock();
        //log response if there was no exception encountered so far
        if (!isExceptionEncountered)
        {
            Console.WriteLine(counterResponse);
        }

        isExceptionEncounteredLock.ExitReadLock();
    }
    catch (SocketException exception)
    {
        bool isFirstEncounteredException = false;

        isExceptionEncounteredLock.EnterWriteLock();

        //log exception and note that one was encountered if it is the first one
        if (!isExceptionEncountered)
        {
            Console.WriteLine(exception.Message);
            isExceptionEncountered = true;
            isFirstEncounteredException = true;
        }

        isExceptionEncounteredLock.ExitWriteLock();

        //if this is the first exception encountered, rethrow it
        if (isFirstEncounteredException)
        {
            throw;
        }
    }
}

async void RunParallelCounterClients()
{
    SemaphoreSlim clientSlotCount = new(maxParallelCounterRequests, maxParallelCounterRequests);

    async void RunCounterClientAndReleaseSlot()
    {
        await RunCounterClient();
        clientSlotCount.Release();
    }

    while (!cancellationToken.IsCancellationRequested)
    {
        await clientSlotCount.WaitAsync(cancellationToken);
        RunCounterClientAndReleaseSlot();
    }
}

RunParallelCounterClients();

while (true)
{
    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
    if (keyInfo.Key == ConsoleKey.Escape)
    {
        cancellationTokenSource.Cancel();
        break;
    }
}

My initial guess is, that I run out of ephemeral ports because I somehow do not free them correctly. I just Close() and Dispose() my TcpClients in both my client and server code when a request is finished. I thought that would automatically release the port, but when I use netstat -ab in a console, it gives me countless entries like this, even after closing the application:

TCP    127.0.0.1:65000        kubernetes:59996       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:59997       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:59998       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:59999       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60000       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60001       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60002       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60003       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60004       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60005       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60006       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60007       TIME_WAIT
TCP    127.0.0.1:65000        kubernetes:60009       TIME_WAIT

Also, my PC sometimes gets a lot of stutter some time after I exit the application. I assume this is due to Windows cleaning up my leaked port usage?

So I wonder, what am I doing wrong here?


问:
Add multiple properties to serverless.yaml with one line?
We have many serverless services. Many of them share some properties. Here is a subset of what they share:

```<code>// shared.yaml

frameworkVersion: '3'
configValidationMode: error

plugins:
  modules:
    - serverless-prune-plugin
    - serverless-deployment-bucket

custom:
  sharedHost: ${file(./shared-host.config.js)}
  prune:
    automatic: true
    number: 2

  Outputs:
    UserInformation:
      Value: ${self:custom.sharedHost.userId}
      Description: ${self:custom.sharedHost.userArn}

    GitInformation:
      Value: ${self:custom.sharedHost.gitId}
      Description: ${self:custom.sharedHost.gitDescription}
</code>```

Is it possible to add these properties to a serverless.yaml file with one line?

I'm looking for something like:

```<code>// services/some-service/serverless.yaml

service: SomeService
join: ${file(../../shared.yaml)}

custom:
  someProp: someValue
</code>```

I'm adding a json tag to the question because I am thinking that if this is not possible using serverless or yaml features, then maybe there is some json feature that could be used.

答:
I know that in serverless.yml file you can import env variables from a external file in one line like this

environment: ${file(env.yml):${self:provider.stage}, file(env.yml):default}
```
<p>After if you use node js you can have a serverless.ts or serverless.js and import files very easily with <code>Object.assign</code></p>
<pre class="lang-js prettyprint-override"><code>resources: {
    Resources: Object.assign(dynamodbTables, gatewayDomain, gatewayAuthorizer),
  }
</code>```

exemple : https://github.com/TheSmartMonkey/serverless/blob/main/reports-service/serverless.ts

Body:
We have many serverless services. Many of them share some properties. Here is a subset of what they share:

// shared.yaml

frameworkVersion: '3'
configValidationMode: error

plugins:
  modules:
    - serverless-prune-plugin
    - serverless-deployment-bucket

custom:
  sharedHost: ${file(./shared-host.config.js)}
  prune:
    automatic: true
    number: 2

  Outputs:
    UserInformation:
      Value: ${self:custom.sharedHost.userId}
      Description: ${self:custom.sharedHost.userArn}

    GitInformation:
      Value: ${self:custom.sharedHost.gitId}
      Description: ${self:custom.sharedHost.gitDescription}

Is it possible to add these properties to a serverless.yaml file with one line?

I'm looking for something like:

// services/some-service/serverless.yaml

service: SomeService
join: ${file(../../shared.yaml)}

custom:
  someProp: someValue

I'm adding a json tag to the question because I am thinking that if this is not possible using serverless or yaml features, then maybe there is some json feature that could be used.

Body:
I know that in serverless.yml file you can import env variables from a external file in one line like this

environment: ${file(env.yml):${self:provider.stage}, file(env.yml):default}

After if you use node js you can have a serverless.ts or serverless.js and import files very easily with Object.assign

resources: {
    Resources: Object.assign(dynamodbTables, gatewayDomain, gatewayAuthorizer),
  }

exemple : https://github.com/TheSmartMonkey/serverless/blob/main/reports-service/serverless.ts


问:
Function declaration conditioned on a used library version?
I have the following problem: say I'm using library Foo and there's a function bar that I use in my personal library. However, in an upcoming release, the function definition of bar is going to change. For example,

bar(int first, int second, int third)

will become

bar(int first, int newSecond, int second, int third)

It would be beneficial to maintain backwards compatibility in my case so I'm wondering if it's possible to define my functions conditioned on the library version

My original code:

```<code>int myFoo(int first, int second, int third){
    auto something = bar(first, second, third);
    ....
}
</code>```

and the new function might be something like

```<code>int myFoo(int first, int second, int third){
    auto newSecond = X;
    auto something = bar(first, newSecond, second, third);
    ....
}
</code>```

In python I could do something like

```<code>int myFoo(int first, int second, int third){
    if Foo.version == "old":
        auto something = bar(first, second, third);
    else:
        auto newSecond = X;
        auto something = bar(first, newSecond, second, third);
    ....
}
</code>```

but how might I accomplish the same in C++? Would using an #IF ... work? I Googled around but the results weren't particularly useful as I don't really know the right terms to look up (happy to learn some new terms)

答:
There are a few ways to go about this.

The first that comes to mind would be to use preprocessor directives:

```<code>#define OLD_VERSION // Can be set in code or when you compile the code

int myFoo(int first, int second, int third){
    #ifdef OLD_VERSION
        auto something = bar(first, second, third);
    #else
        auto newSecond = X;
        auto something = bar(first, newSecond, second, third);
    ....
    #endif
}
</code>```

Alternatively, you could wrap the bar function and use function overloading and depending on what parameters you pass in, the appropriate function will be called:

```<code>int myFoo(int first, int second, int third) { }
int myFoo(int first, int newSecond, int second, int third){ }
</code>```

Body:
I have the following problem: say I'm using library Foo and there's a function bar that I use in my personal library. However, in an upcoming release, the function definition of bar is going to change. For example,

bar(int first, int second, int third)

will become

bar(int first, int newSecond, int second, int third)

It would be beneficial to maintain backwards compatibility in my case so I'm wondering if it's possible to define my functions conditioned on the library version

My original code:

int myFoo(int first, int second, int third){
    auto something = bar(first, second, third);
    ....
}

and the new function might be something like

int myFoo(int first, int second, int third){
    auto newSecond = X;
    auto something = bar(first, newSecond, second, third);
    ....
}

In python I could do something like

int myFoo(int first, int second, int third){
    if Foo.version == "old":
        auto something = bar(first, second, third);
    else:
        auto newSecond = X;
        auto something = bar(first, newSecond, second, third);
    ....
}

but how might I accomplish the same in C++? Would using an #IF ... work? I Googled around but the results weren't particularly useful as I don't really know the right terms to look up (happy to learn some new terms)

Body:
There are a few ways to go about this.

The first that comes to mind would be to use preprocessor directives:

#define OLD_VERSION // Can be set in code or when you compile the code

int myFoo(int first, int second, int third){
    #ifdef OLD_VERSION
        auto something = bar(first, second, third);
    #else
        auto newSecond = X;
        auto something = bar(first, newSecond, second, third);
    ....
    #endif
}

Alternatively, you could wrap the bar function and use function overloading and depending on what parameters you pass in, the appropriate function will be called:

int myFoo(int first, int second, int third) { }
int myFoo(int first, int newSecond, int second, int third){ }


问:
Android Kotlin - get value from multidimensional / nested JSON
On the server I create this json with PHP:

```<code>    $array = array();
    $array['stuff'] = "yeee";
    $array['bla'] = "ok";

    $serverScaling = array();
    $serverScaling["0"] = "okOne";
    $serverScaling["1"] = "okTwo";
    $serverScaling["2"] = "okThree";

    $array['serverScaling'] = $serverScaling;

    echo json_encode($array);
</code>```

how can I get okTwo?

In volley response I tried:

```<code>val response = JSONObject(it)

val serverScaling = JSONObject(response.getString("serverScaling"))
Log.d(tagg, "hmm: " + serverScaling.getString("1"))
</code>```

and also:

```<code>val response = JSONObject(it)

val serverScaling = response.getJSONObject("serverScaling")
Log.d(tagg, "hmm: " + serverScaling.getString("1"))
</code>```

How to do this correctly?

答:
serverScaling is a jsonArray so fetch it as an array not an object like below :</p>
```<code> val response = JSONObject(it)

 val serverScaling = response.getJSONArray("serverScaling")
 Log.d(tagg, "hmm: " + serverScaling.getString("1"))
</code>```

Body:
On the server I create this json with PHP:

    $array = array();
    $array['stuff'] = "yeee";
    $array['bla'] = "ok";

    $serverScaling = array();
    $serverScaling["0"] = "okOne";
    $serverScaling["1"] = "okTwo";
    $serverScaling["2"] = "okThree";

    $array['serverScaling'] = $serverScaling;

    echo json_encode($array);

how can I get okTwo?

In volley response I tried:

val response = JSONObject(it)

val serverScaling = JSONObject(response.getString("serverScaling"))
Log.d(tagg, "hmm: " + serverScaling.getString("1"))

and also:

val response = JSONObject(it)

val serverScaling = response.getJSONObject("serverScaling")
Log.d(tagg, "hmm: " + serverScaling.getString("1"))

How to do this correctly?

Body:
serverScaling is a jsonArray so fetch it as an array not an object like below :

 val response = JSONObject(it)

 val serverScaling = response.getJSONArray("serverScaling")
 Log.d(tagg, "hmm: " + serverScaling.getString("1"))


问:
Running Python Script in Veins
I already have SUMO, OMNET++ and Veins running on my machine, but I am new to Veins. I would like to run Python scripts using Veins framework.

Let us say in the Python script we are given two objects object_A and object_B that contain data about the corresponding cars car_A and car_B. I would like to enable some exchange of information between the object_A and object_B based on the scenario happening in Veins. Could somebody explain to me, how can I accomplish my goal or point me to the corresponding literature?

I found this repository where Python and Veins are combined, but I cannot make sense of it.

Thank you!

答:
How to use pybind11 in omnet++ projects like veins

You can try using pybind11 as done in the above link if you are running veins in Linux environment.

Title: Running Python Script in Veins


问:
ag grid not passing context to child component in angular
I'm using Ag-grid version 26.2.0 in my angular project. I've referred to the official documentation and implemented the code as they have suggested to pass the parent context to the child components. I've followed all the steps, but getting the parent context as undefined.

I'm not sure what I'm missing here.. Any help is appreciated.

Below are the code snippets:

parent component:

```<code>export class CartComponent implements OnInit {
  public frameworkComponents;
  context: any = { comp: this};
...

constructor(){
this.context = { parent: this };
}
...

}
</code>```

Component html:

```<code>...

    <ag-grid-angular [context]="context" [columnDefs]="savedCartColumns" [rowData]="savedProducts" [pagination]="true"
      [frameworkComponents]="frameworkComponents" [paginationPageSize]="itemsPerPage"
      [suppressDragLeaveHidesColumns]="true" [enableCellTextSelection]="true" [defaultColDef]="defaultColDef"
      [suppressExcelExport]="false" [suppressContextMenu]="false" [popupParent]="popupParent"
      class="ag-theme-balham saved-cart" style="width: 100%; height: 550px" (gridReady)="onGridReady($event)"></ag-grid-angular>

...
</code>```

Child component:

```<code>import { ICellRendererParams } from 'ag-grid-community';
...
export class ManageCartComponent {
  private params: ICellRendererParams;
  componentParent: any;
...

  agInit(params: ICellRendererParams): void {
    this.params = params;
    this.componentParent = params.context.parent;
  }

</code>```

Error at runtime:

```<code>ERROR TypeError: Cannot read properties of undefined (reading 'parent')
    at ManageCartComponent.push.gxGq.ManageCartComponent.agInit (manageCart.component.ts:50:43)
</code>```

答:
Well, I missed to add this piece of code in the right aggrid instance as I have two aggrid instances in one page:

```<code>context="context"
</code>```

After adding this, the child component gets the parent's context as expected!

Body:
I'm using Ag-grid version 26.2.0 in my angular project. I've referred to the official documentation and implemented the code as they have suggested to pass the parent context to the child components. I've followed all the steps, but getting the parent context as undefined.

I'm not sure what I'm missing here.. Any help is appreciated.

Below are the code snippets:

parent component:

export class CartComponent implements OnInit {
  public frameworkComponents;
  context: any = { comp: this};
...

constructor(){
this.context = { parent: this };
}
...

}

Component html:

...

    <ag-grid-angular [context]="context" [columnDefs]="savedCartColumns" [rowData]="savedProducts" [pagination]="true"
      [frameworkComponents]="frameworkComponents" [paginationPageSize]="itemsPerPage"
      [suppressDragLeaveHidesColumns]="true" [enableCellTextSelection]="true" [defaultColDef]="defaultColDef"
      [suppressExcelExport]="false" [suppressContextMenu]="false" [popupParent]="popupParent"
      class="ag-theme-balham saved-cart" style="width: 100%; height: 550px" (gridReady)="onGridReady($event)"></ag-grid-angular>

...

Child component:

import { ICellRendererParams } from 'ag-grid-community';
...
export class ManageCartComponent {
  private params: ICellRendererParams;
  componentParent: any;
...

  agInit(params: ICellRendererParams): void {
    this.params = params;
    this.componentParent = params.context.parent;
  }

Error at runtime:

ERROR TypeError: Cannot read properties of undefined (reading 'parent')
    at ManageCartComponent.push.gxGq.ManageCartComponent.agInit (manageCart.component.ts:50:43)

Body:
Well, I missed to add this piece of code in the right aggrid instance as I have two aggrid instances in one page:

context="context"

After adding this, the child component gets the parent's context as expected!


问:
Python: remove all rows from a dataframe where the date is over 2 years ago
EDIT - Answer as below with the extra code new_df = df_hist[msk]

I'm trying to remove all rows from a DataFrame where the date ('RaceDate') is over 2 years ago. I convert the 'RaceDate' using pd.to_datetime - this gives the format e.g. 2018-09-01. I use datetime.datetime.now().date() and this gives the format datetime.date(2022, 2, 10)

I can't work out how to check the difference is over two years as the code gives me Key error.
Any help would be most welcome.

```<code>d2 = datetime.datetime.now().date()
df_hist['RaceDate'] = pd.to_datetime(df_hist['RaceDate'])

if  df_hist.loc[df_hist['RaceDate']] - d2 > 730:
    df_hist.loc[df_hist['RaceDate']] = ""
</code>```

Sample data:

```<code>Jockey  Code    Course  RaceDate    Ran FPos    TotalBtn
Harry Burns AW  Chelmsford City 01-Sep-18   9   4   4.5
Harry Burns AW  Newcastle   01-Oct-21   14  6   4.75
Harry Burns AW  Kempton 01-Nov-21   11  4   4.25
Harry Burns AW  Southwell   01-Jan-22   12  4   3.75
Harry Burns AW  Wolverhampton   01-Feb-22   12  5   4.75
Christian Howarth   AW  Kempton 01-Dec-21   14  5   3.5
Harry Davies    AW
Jonathan Fisher AW  Southwell   01-Dec-17   14  9   10.5
Jonathan Fisher AW  Chelmsford City 01-Dec-17   10  8   4.82
Jonathan Fisher AW  Southwell   01-Jan-22   12  5   7.75
Jonathan Fisher AW  Southwell   01-Jan-22   14  4   3
Jonathan Fisher AW  Wolverhampton   01-Feb-22   7   4   2
Jonathan Fisher AW  Wolverhampton   01-Feb-22   11  8   3
</code>```

答:
You can convert d2 using pd.to_datetime and subtract (since today's date is greater than yesterday's date, we subtract today's date from the column using rsub). Then convert the timedelta to year and evaluate if the time difference in years is less than 2:

```<code>msk = df_hist['RaceDate'].rsub(pd.to_datetime(d2)).astype('timedelta64[Y]') < 2
races_dates_in_last_2_years = df_hist.loc[msk, 'RaceDate']
</code>```

or if you wish you filter the entire DataFrame:

```<code>new_df = df_hist[msk]
</code>```

For example:

For the below Series:

```<code>s = pd.to_datetime(pd.Series(['2020-02-10', '2020-02-11']))
</code>```

that looks like:

```<code>0   2020-02-10
1   2020-02-11
dtype: datetime64[ns]
</code>```

the above code produces:

```<code>0   2020-02-11
dtype: datetime64[ns]
</code>```

Body:
EDIT - Answer as below with the extra code new_df = df_hist[msk]

I'm trying to remove all rows from a DataFrame where the date ('RaceDate') is over 2 years ago. I convert the 'RaceDate' using pd.to_datetime - this gives the format e.g. 2018-09-01. I use datetime.datetime.now().date() and this gives the format datetime.date(2022, 2, 10)

I can't work out how to check the difference is over two years as the code gives me Key error.
Any help would be most welcome.

d2 = datetime.datetime.now().date()
df_hist['RaceDate'] = pd.to_datetime(df_hist['RaceDate'])

if  df_hist.loc[df_hist['RaceDate']] - d2 > 730:
    df_hist.loc[df_hist['RaceDate']] = ""

Sample data:

Jockey  Code    Course  RaceDate    Ran FPos    TotalBtn
Harry Burns AW  Chelmsford City 01-Sep-18   9   4   4.5
Harry Burns AW  Newcastle   01-Oct-21   14  6   4.75
Harry Burns AW  Kempton 01-Nov-21   11  4   4.25
Harry Burns AW  Southwell   01-Jan-22   12  4   3.75
Harry Burns AW  Wolverhampton   01-Feb-22   12  5   4.75
Christian Howarth   AW  Kempton 01-Dec-21   14  5   3.5
Harry Davies    AW
Jonathan Fisher AW  Southwell   01-Dec-17   14  9   10.5
Jonathan Fisher AW  Chelmsford City 01-Dec-17   10  8   4.82
Jonathan Fisher AW  Southwell   01-Jan-22   12  5   7.75
Jonathan Fisher AW  Southwell   01-Jan-22   14  4   3
Jonathan Fisher AW  Wolverhampton   01-Feb-22   7   4   2
Jonathan Fisher AW  Wolverhampton   01-Feb-22   11  8   3

Body:
You can convert d2 using pd.to_datetime and subtract (since today's date is greater than yesterday's date, we subtract today's date from the column using rsub). Then convert the timedelta to year and evaluate if the time difference in years is less than 2:

msk = df_hist['RaceDate'].rsub(pd.to_datetime(d2)).astype('timedelta64[Y]') < 2
races_dates_in_last_2_years = df_hist.loc[msk, 'RaceDate']

or if you wish you filter the entire DataFrame:

new_df = df_hist[msk]

For example:

For the below Series:

s = pd.to_datetime(pd.Series(['2020-02-10', '2020-02-11']))

that looks like:

0   2020-02-10
1   2020-02-11
dtype: datetime64[ns]

the above code produces:

0   2020-02-11
dtype: datetime64[ns]


问:
$geoNear is only valid as the first stage in a pipeline
I'm getting the following error $geoNear is only valid as the first stage in a pipeline. while I'm doing an aggregation using nodejs as server-side.

Aggregation Object:

```<code>[ { '$geoNear':
     { near: [Object], distanceField: 'distance', spherical: true } },
  { '$lookup':
     { from: 'reviews',
       localField: '_id',
       foreignField: 'restaurant',
       as: 'reviews' } },
  { '$project':
     { logo: '$$ROOT.logo',
       name: '$$ROOT.name',
       cuisine: '$$ROOT.cuisine',
       rate: [Object],
       reservation: '$$ROOT.reservation',
       closeAt: '$$ROOT.closeAt',
       openAt: '$$ROOT.openAt',
       recommendationsLength: [Object],
       isLive: '$$ROOT.isLive',
       avgCost: '$$ROOT.avgCost',
       creationDate: '$$ROOT.creationDate',
       distance: '$$ROOT.distance' } },
  { '$sort': { distance: 1 } } ]
</code>```

Any Idea why I'm getting the error above?

答:
Make sure the fields, you're watching for is indicated in your $project. Like I got this error in:

```<code>[
  {
    $project: {
      title: 1,
      date: 1,
  }
  {
    $match: {
      company, //company is a variable
    },
  },
]
</code>```

You get the idea.

Then another reason why I had similar issue was $sort and $match can't come before $search, so try reordering your pipeline.

Body:
I'm getting the following error $geoNear is only valid as the first stage in a pipeline. while I'm doing an aggregation using nodejs as server-side.

Aggregation Object:

[ { '$geoNear':
     { near: [Object], distanceField: 'distance', spherical: true } },
  { '$lookup':
     { from: 'reviews',
       localField: '_id',
       foreignField: 'restaurant',
       as: 'reviews' } },
  { '$project':
     { logo: '$$ROOT.logo',
       name: '$$ROOT.name',
       cuisine: '$$ROOT.cuisine',
       rate: [Object],
       reservation: '$$ROOT.reservation',
       closeAt: '$$ROOT.closeAt',
       openAt: '$$ROOT.openAt',
       recommendationsLength: [Object],
       isLive: '$$ROOT.isLive',
       avgCost: '$$ROOT.avgCost',
       creationDate: '$$ROOT.creationDate',
       distance: '$$ROOT.distance' } },
  { '$sort': { distance: 1 } } ]

Any Idea why I'm getting the error above?

Body:
Make sure the fields, you're watching for is indicated in your $project. Like I got this error in:

[
  {
    $project: {
      title: 1,
      date: 1,
  }
  {
    $match: {
      company, //company is a variable
    },
  },
]

You get the idea.

Then another reason why I had similar issue was $sort and $match can't come before $search, so try reordering your pipeline.


问:
Is this possible to use outputs from one terraform cloud workspace as variables in another workspace?
Here are further details:

Workspace-A (base stack) : This workspace has code that will create AWS: VPC, SGs, RouteTables, Subnet and related associtions etc.

Workspace-B (Service-1 Stack): This workspace has code to create AWS : ALB, some ECS containers using fargate and some other components related to this service.

Now, in above case any service (Service-1, 2 , 3 etc.) wil use the VPC/base stack created by Workspace-A, how can we use outputs from Workspace A( VPC, SGs, subnets etc.) as variables of workspace-B so that workspace-B can consume those VPC and rest of the components.

答:
You can achieve this with the use of 'remote_state' data source and to do so, you must configure a Terraform remote backend to connect to your Terraform workspaces.

Any workspace to be able to share its state must have configured a 'outputs'.

For Workspace-A, you can configure the VPC as output -

```<code>output "vpc_id" {
  description = "The VPC ID"
  value = aws_vpc.my_vpc.id
}
</code>```

After running terraform apply with Workspace-A, configure the tf file for Workspace-B as below -

```<code>data "terraform_remote_state" "vpc" {
  backend = "remote"

  config = {
    organization = "org-****"
    workspaces = {
      name = "workspace-A"
    }
  }
}
</code>```

This Terraform configuration can now access the outputs from Workspace-A as -

```<code>resource "aws_instance" "foo" {
  # ...
  subnet_id = data.terraform_remote_state.vpc.outputs.subnet_id
}
</code>```

P.S. - I realize it's late, but it might be useful to someone else.

Body:
You can achieve this with the use of 'remote_state' data source and to do so, you must configure a Terraform remote backend to connect to your Terraform workspaces.

Any workspace to be able to share its state must have configured a 'outputs'.

For Workspace-A, you can configure the VPC as output -

output "vpc_id" {
  description = "The VPC ID"
  value = aws_vpc.my_vpc.id
}

After running terraform apply with Workspace-A, configure the tf file for Workspace-B as below -

data "terraform_remote_state" "vpc" {
  backend = "remote"

  config = {
    organization = "org-****"
    workspaces = {
      name = "workspace-A"
    }
  }
}

This Terraform configuration can now access the outputs from Workspace-A as -

resource "aws_instance" "foo" {
  # ...
  subnet_id = data.terraform_remote_state.vpc.outputs.subnet_id
}

P.S. - I realize it's late, but it might be useful to someone else.


问:
accessing properties from javascript object
I have below object.

```<code>export const multerOptions = {
    storage: diskStorage({
        destination: multerConfig.dest,
        filename: (_req: any, file: any, cb: any) => {
            /* istanbul ignore next */
            cb(null, `${uuid()}${extname(file.originalname)}`);
        },
    }),
};
</code>```

when I am printing multerOptions.storage it is returning below.

```<code>   diskStorage({
        destination: multerConfig.dest,
        filename: (_req: any, file: any, cb: any) => {
            /* istanbul ignore next */
            cb(null, `${uuid()}${extname(file.originalname)}`);
        },
    }),
.
</code>```

is there anyway I can access this filename or destination

答:
This one is for single file upload

```<code> /**
 * Module for geting image from s3 cloud server
 */
exports.upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: function (req, file, cb) {
            const path = process.env.AWS_BUCKET_NAME;
            cb(null, path || 'uploads/');
        },
        acl: 'authenticated-read',
        // acl: 'public-read',
        key: function (req, file, cb) {

            console.log("file========", req);
            // console.log(req.path.split('/')[1]);
            // console.log(path.parse(file.originalname).name.replace(" ", "-"));
            // console.log(Date.now() + path.parse(file.originalname).ext);
            // req.path.split('/')[1] ===== Sub-Folder
            // path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext ===== File name
            cb(null, req.path.split('/')[1]+'/'+path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext);
        }
    })
}).single('file');
</code>```

For Multiple file upload

```<code>/**
 * Module for geting image from s3 cloud server
 */
 exports.uploadmultiple = multer({
    storage: multerS3({
        s3: s3,
        bucket: function (req, file, cb) {
            const path = process.env.AWS_BUCKET_NAME;
            cb(null, path || 'uploads/');
        },
        acl: 'authenticated-read',
        // acl: 'public-read',
        key: function (req, file, cb) {

            console.log(req.path.split('/')[1]);
            console.log(path.parse(file.originalname).name.replace(" ", "-"));
            console.log(Date.now() + path.parse(file.originalname).ext);
            // req.path.split('/')[1] ===== Sub-Folder
            // path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext ===== File name
            cb(null, req.path.split('/')[1]+'/'+path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext);
        }
    })
}).array('files', 2);
</code>```

You can get more info over HERE

Body:
I have below object.

export const multerOptions = {
    storage: diskStorage({
        destination: multerConfig.dest,
        filename: (_req: any, file: any, cb: any) => {
            /* istanbul ignore next */
            cb(null, `${uuid()}${extname(file.originalname)}`);
        },
    }),
};

when I am printing multerOptions.storage it is returning below.

   diskStorage({
        destination: multerConfig.dest,
        filename: (_req: any, file: any, cb: any) => {
            /* istanbul ignore next */
            cb(null, `${uuid()}${extname(file.originalname)}`);
        },
    }),
.

is there anyway I can access this filename or destination

Body:
This one is for single file upload

 /**
 * Module for geting image from s3 cloud server
 */
exports.upload = multer({
    storage: multerS3({
        s3: s3,
        bucket: function (req, file, cb) {
            const path = process.env.AWS_BUCKET_NAME;
            cb(null, path || 'uploads/');
        },
        acl: 'authenticated-read',
        // acl: 'public-read',
        key: function (req, file, cb) {

            console.log("file========", req);
            // console.log(req.path.split('/')[1]);
            // console.log(path.parse(file.originalname).name.replace(" ", "-"));
            // console.log(Date.now() + path.parse(file.originalname).ext);
            // req.path.split('/')[1] ===== Sub-Folder
            // path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext ===== File name
            cb(null, req.path.split('/')[1]+'/'+path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext);
        }
    })
}).single('file');

For Multiple file upload

/**
 * Module for geting image from s3 cloud server
 */
 exports.uploadmultiple = multer({
    storage: multerS3({
        s3: s3,
        bucket: function (req, file, cb) {
            const path = process.env.AWS_BUCKET_NAME;
            cb(null, path || 'uploads/');
        },
        acl: 'authenticated-read',
        // acl: 'public-read',
        key: function (req, file, cb) {

            console.log(req.path.split('/')[1]);
            console.log(path.parse(file.originalname).name.replace(" ", "-"));
            console.log(Date.now() + path.parse(file.originalname).ext);
            // req.path.split('/')[1] ===== Sub-Folder
            // path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext ===== File name
            cb(null, req.path.split('/')[1]+'/'+path.parse(file.originalname).name.replace(" ", "-") + Date.now() + path.parse(file.originalname).ext);
        }
    })
}).array('files', 2);

You can get more info over HERE


问:
Sourcing & Filtering - The field type must match the type of the field you are sourcing from (Text Area)
I created a custom record and I am trying to create field (List/Record : Adress Book)  sourced from all address of Vendor Field.

Here the vendor field

Here the Address Book field

And here the different Test and result I got

First configuration test

Result : "The field type must match the type of the field you are sourcing from (Text Area)."

Second configuration test

Result : "The list or record type of the field or source (Vendor) must match the list or record type of the field you are filtering by (Entity)."

答: It is saying that "Address" is technically a text area representation of the address, not actually a reference to the address book. If you make your "Delivery address" field of type text area and do configuration 1, then it will work</p>


问:
ModuleNotFoundError: No module named 'webdriver_manager' coming up even after trying everything
I was following the tutorial from here and it still says ModuleNotFoundError: No module named 'webdriver_manager', even after installing webdrivermanager in multiple ways, already recommended in other posts on stackoverflow. I tried pip install webdriver-manager, pip install webdriver_manager and pip install webdrivermanager, yet nothing seems to work.

Edit: It seems to work on my Laptop, so I think It could be a wrong install of the libary... any suggestions on what I should do?

答: I ended up reinstalling Python completely, and now it works, but still thanks for all the help!</p>


问:
Subdomain with www SSL binding error: No certificates when trying to add SSL Bindings for Azure Web App
I am trying to add SSL binding to a sub domain. I have a wild card certificate in my Azure account.

There is no problem for me to bind to sub domain such as subdomain.domain.com, but it kept throwing the "No certificates when trying to add SSL Bindings for Azure Web App" error when I try to add www to the subdomain (in the picture above, www.subdomain.domain.com)

I have read other posts regarding this issue, but no one mentioned anything about adding www. to the sub domain. I used to be able to do it with other sub domains in Azure without any problems, this might be related to Godaddy (my domain name provider) DNS settings, but I checked everything in Godaddy, the www.subdomain.domain.com link doesn't works unless I add www.subdomain.domain.name to the Azure app customer domain list. The link works, but it's http instead of https.

答: So after talking to 3 different support people at Microsoft, I finally got it working by going to the certificate TLS/SSL settings, click "Private Key Certificates", click "Create App Service Managed Certificate", then add www.subdomain.domain.com to the private key certificates list.


问:
Hyperlink of Branding Image in NSIS
I have the following question - is it possible to define a link for the branding image in NSIS, so that the user would be able to click on the image and open a web page in a browser? If possible, how is to be done? Thanks for the help in advance.

Regards,
Al

答: I wasn't able to find anything that suggests that specifying a hyperlink in a branding image is possible. Eventually I abandoned it.</p>

ContentLicense: CC BY-SA 2.5

Title: Hyperlink of Branding Image in NSIS


问:
SYMFONY NELMIO CORS issue : Access-Control-Allow-Origin header contains multiple values
I created an API with symfony, FOSRestBundle and NelmioCorsBundle and I connect to it with a Ionic APP. some routes return me a CORS error :

Access to XMLHttpRequest at 'http://dev.myapp.com/api/login_check' fromfrom localhost/:1 origin 'http://localhost:8100' has been blocked by CORS policy: Response to the preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost/8100, *', but only one is allowed.

there is some part of my code :

config/nelmio_cors.yml :

```<code>nelmio_cors:
   defaults:
       allow_credentials: false
       allow_origin: []
       allow_headers: []
       allow_methods: []
       expose_headers: []
       max_age: 0
       hosts: []
       origin_regex: false
   paths:
       '^/api':
           allow_origin: ['*']
           allow_headers: ['*']
           allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
           max_age: 3600

</code>```

I tried to add this in the .htaccess but without success:

```<code>   Header always set Access-Control-Allow-Origin: "*"
   Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</code>```

Someone have an idea about this problem ? thanks you

答:
Here is a working example:

```<code>nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['Content-Type', 'Authorization']
            allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['%env(string:CORS_ALLOW_ORIGIN)%']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: [ '^api\.' ]

</code>```

Also your in your .env or .env.local :

```<code>CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'
</code>```

Body:
I created an API with symfony, FOSRestBundle and NelmioCorsBundle and I connect to it with a Ionic APP. some routes return me a CORS error :

Access to XMLHttpRequest at 'http://dev.myapp.com/api/login_check' fromfrom localhost/:1 origin 'http://localhost:8100' has been blocked by CORS policy: Response to the preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost/8100, *', but only one is allowed.

there is some part of my code :

config/nelmio_cors.yml :

nelmio_cors:
   defaults:
       allow_credentials: false
       allow_origin: []
       allow_headers: []
       allow_methods: []
       expose_headers: []
       max_age: 0
       hosts: []
       origin_regex: false
   paths:
       '^/api':
           allow_origin: ['*']
           allow_headers: ['*']
           allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
           max_age: 3600

I tried to add this in the .htaccess but without success:

   Header always set Access-Control-Allow-Origin: "*"
   Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Someone have an idea about this problem ? thanks you

Body:
Here is a working example:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['Content-Type', 'Authorization']
            allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['%env(string:CORS_ALLOW_ORIGIN)%']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: [ '^api\.' ]

Also your in your .env or .env.local :

CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'


问:
Backblaze Python SDK v2 - serve file response from memory
I want some files (images in this case) in a private bucket on Backblaze to be exposed by an API endpoint in Flask. I'm not sure how to handle the DownloadedFile object that is returned from bucket.download_file_by_name

```<code>@app.route('/b2-image/<filename>', methods=('GET',))
def b2_image(filename):
    info = InMemoryAccountInfo()
    b2_api = B2Api(info)
    app_key_id = env['MY_KEY_ID']
    app_key = env['MY_KEY']

    b2_api.authorize_account('production', app_key_id, app_key)
    bucket = b2_api.get_bucket_by_name(env['MY_BUCKET'])

    file = bucket.download_file_by_name(filename)

    bytes = BytesIO()

    #something sort of like this???
    #return Response(bytes.read(file), mimetype='image/jpeg')

</code>```

bucket.download_file_by_name returns a DownloadedFile object, I'm not sure how to handle it. The documentation provides no examples and seems to suggest I'm supposed to do something like:

```<code>file = bucket.download_file_by_name(filename)

#this obviously doesn't make any sense
image_file = file.save(file, file)
</code>```

答:
I had been trying the following but it wasn't working:

```<code>file = bucket.download_file_by_name(filename)
f = BytesIO()
file.save(f)

return Response(f.read(), mimetype='image/jpeg')
</code>```

This SO Answer gave me the clue I needed, specifically setting the seek value on the BytesIO object:

```<code>#this works
file = bucket.download_file_by_name(filename)
f = BytesIO()
file.save(f)
f.seek(0)

return Response(f.read(), mimetype='image/jpeg')
</code>```

Body:
I want some files (images in this case) in a private bucket on Backblaze to be exposed by an API endpoint in Flask. I'm not sure how to handle the DownloadedFile object that is returned from bucket.download_file_by_name

@app.route('/b2-image/<filename>', methods=('GET',))
def b2_image(filename):
    info = InMemoryAccountInfo()
    b2_api = B2Api(info)
    app_key_id = env['MY_KEY_ID']
    app_key = env['MY_KEY']

    b2_api.authorize_account('production', app_key_id, app_key)
    bucket = b2_api.get_bucket_by_name(env['MY_BUCKET'])

    file = bucket.download_file_by_name(filename)

    bytes = BytesIO()

    #something sort of like this???
    #return Response(bytes.read(file), mimetype='image/jpeg')

bucket.download_file_by_name returns a DownloadedFile object, I'm not sure how to handle it. The documentation provides no examples and seems to suggest I'm supposed to do something like:

file = bucket.download_file_by_name(filename)

#this obviously doesn't make any sense
image_file = file.save(file, file)

Body:
I had been trying the following but it wasn't working:

file = bucket.download_file_by_name(filename)
f = BytesIO()
file.save(f)

return Response(f.read(), mimetype='image/jpeg')

This SO Answer gave me the clue I needed, specifically setting the seek value on the BytesIO object:

#this works
file = bucket.download_file_by_name(filename)
f = BytesIO()
file.save(f)
f.seek(0)

return Response(f.read(), mimetype='image/jpeg')


问:
Reading group of lines in HUGE files
I have no idea how to do the following: I want to process a really huge textfile (almost 5 gigabytes). Since I cannot copy the file into temporarily memory, I thought of reading the first 500 lines (or as many as fit into the memory, I am not sure about that yet), do something with them, then go on to the next 500 until I am done with the whole file.

Could you post an example of the "loop" or command that you need for that? Because all the ways I tried resulted in starting from the beginning again but I want to go on after finishing the previous 500 lines.

Help appreciated.

答:
```<code>BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
ArrayList<String> allLines = new ArrayList<String>();

while((line = br.readLine()) != null) {
     allLines.add(line);
     if (allLines.size() > 500) {
          processLines(allLines);
          allLines.clear();
     }
}

processLines(allLines);
</code>```

Title: Reading group of lines in HUGE files


问:
How to set a function parameter's default value as an object of a class which extends an abstract class?
Let's say I have several classes which extend an abstract class. Now I want to pass a default value to a function argument, where the type of the argument is the abstract class. Dart expects a const value, and I couldn't create a const constructor for an abstract class. How can I pass a default value of the abstract class?

Sample code is as following:

```<code>class Main {

  late A objOfA;

  Main({ A nObjOfA = const B() }); // <===== Error here

}

abstract class A {

  abstract String name;

  abstract int id;
}

class B extends A {

  @override
  String name = "B";

  @override
  int id = 1;
}

class C extends A {

  @override
  String name = "C";

  @override
  int id = 1;
}
</code>```

Here, how can I pass a default value of nObjOfA in the constructor of Main?

答:
Dart expects a const value, and I couldn't create a const constructor for an abstract class.

There is no rule that you cannot create a const constructor for an abstract class.  Abstract classes can have constructors; you just can't call them directly to instantiate an abstract class.  The following code is legal:

class Main {
  A objOfA;

  Main({this.objOfA = const B()});

}

abstract class A {
  const A();

  abstract final String name;

  abstract final int id;
}

class B extends A {
  const B();

  @override
  final String name = "B";

  @override
  final int id = 1;
}

class C extends A {
  @override
  String name = "C";

  @override
  int id = 1;
}
```

Note that I needed to add final qualifiers since const objects must be immutable. (Unrelated, but I also fixed the inappropriate use of the late keyword.)

In general, there will be cases where you cannot create a const constructor.  If you want to use an instance of that type as a default argument in such cases, you can use null as a default value and assign a non-const value later.

Body:
Let's say I have several classes which extend an abstract class. Now I want to pass a default value to a function argument, where the type of the argument is the abstract class. Dart expects a const value, and I couldn't create a const constructor for an abstract class. How can I pass a default value of the abstract class?

Sample code is as following:

class Main {

  late A objOfA;

  Main({ A nObjOfA = const B() }); // <===== Error here

}

abstract class A {

  abstract String name;

  abstract int id;
}

class B extends A {

  @override
  String name = "B";

  @override
  int id = 1;
}

class C extends A {

  @override
  String name = "C";

  @override
  int id = 1;
}

Here, how can I pass a default value of nObjOfA in the constructor of Main?

Body:
Dart expects a const value, and I couldn't create a const constructor for an abstract class.

There is no rule that you cannot create a const constructor for an abstract class.  Abstract classes can have constructors; you just can't call them directly to instantiate an abstract class.  The following code is legal:

class Main {
  A objOfA;

  Main({this.objOfA = const B()});

}

abstract class A {
  const A();

  abstract final String name;

  abstract final int id;
}

class B extends A {
  const B();

  @override
  final String name = "B";

  @override
  final int id = 1;
}

class C extends A {
  @override
  String name = "C";

  @override
  int id = 1;
}

Note that I needed to add final qualifiers since const objects must be immutable. (Unrelated, but I also fixed the inappropriate use of the late keyword.)

In general, there will be cases where you cannot create a const constructor.  If you want to use an instance of that type as a default argument in such cases, you can use null as a default value and assign a non-const value later.


问:
facebook throws "An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response" when use oauth2
I want to use oauth2 with facebook in mu web application with spring boot and this is configuration for this purpose:

```<code>spring:
  security:
    oauth2:
      client:
        registration:
          google:
            clientId: clientIdValue
            clientSecret: clientSecretValue
            redirectUri: "https://www.example.com/oauth2/callback/{registrationId}"
            scope:
              - email
              - profile
          facebook:
            clientId: clientIdValue
            clientSecret: clientSecretValue
            redirectUri: "https://www.example.com/oauth2/callback/{registrationId}"
            scope:
              - email
              - public_profile
        provider:
          facebook:
            authorizationUri: https://www.facebook.com/v3.0/dialog/oauth
            tokenUri: https://graph.facebook.com/v3.0/oauth/access_token
            userInfoUri: https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250)
server:
  port: 443
  ssl:
    key-store-type: PKCS12
    key-store: classpath:keystore/sslkeystore.p12
    key-store-password: passwordValue
    key-alias: tomcat
    enabled-protocols:
      - TLSv1
      - TLSv1.1
      - TLSv1.2
</code>```

Google authentication works fine, but in the facebook i get this error after redirect to my site:

```<code>An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: I/O error on POST request for \"https://graph.facebook.com/v3.0/oauth/access_token\": Remote host closed connection during handshake; nested exception is javax.net.ssl.SSLHandshakeException: Remote host closed connection during
</code>```

答:
Try to remove this:

```<code>provider:
  facebook:
    authorizationUri: https://www.facebook.com/v3.0/dialog/oauth
    tokenUri: https://graph.facebook.com/v3.0/oauth/access_token
    userInfoUri: https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250)
</code>```

It's help to me

Body:
I want to use oauth2 with facebook in mu web application with spring boot and this is configuration for this purpose:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            clientId: clientIdValue
            clientSecret: clientSecretValue
            redirectUri: "https://www.example.com/oauth2/callback/{registrationId}"
            scope:
              - email
              - profile
          facebook:
            clientId: clientIdValue
            clientSecret: clientSecretValue
            redirectUri: "https://www.example.com/oauth2/callback/{registrationId}"
            scope:
              - email
              - public_profile
        provider:
          facebook:
            authorizationUri: https://www.facebook.com/v3.0/dialog/oauth
            tokenUri: https://graph.facebook.com/v3.0/oauth/access_token
            userInfoUri: https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250)
server:
  port: 443
  ssl:
    key-store-type: PKCS12
    key-store: classpath:keystore/sslkeystore.p12
    key-store-password: passwordValue
    key-alias: tomcat
    enabled-protocols:
      - TLSv1
      - TLSv1.1
      - TLSv1.2

Google authentication works fine, but in the facebook i get this error after redirect to my site:

An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: I/O error on POST request for \"https://graph.facebook.com/v3.0/oauth/access_token\": Remote host closed connection during handshake; nested exception is javax.net.ssl.SSLHandshakeException: Remote host closed connection during

Body:
Try to remove this:

provider:
  facebook:
    authorizationUri: https://www.facebook.com/v3.0/dialog/oauth
    tokenUri: https://graph.facebook.com/v3.0/oauth/access_token
    userInfoUri: https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250)

It's help to me


问:
In a Github Action how to reference a private package for a test?
I have written a test file for a Github Action:

test.yml

```<code>name: Test
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [14.x, 16.x]
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v2
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm ci
      - run: npm run build --if-present
      - run: npm test
</code>```

but my package.json uses an organization private repo. When the Github Action runs it fails and I get the error:

```<code>npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@org/repo/
npm ERR! 404
npm ERR! 404  '@org/repo@1.2.3' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/runner/.npm/_logs/2022-02-10T17_17_46_961Z-debug.log
Error: Process completed with exit code 1.
</code>```

My research trying to solve the issue:

Package is not publishing to npm (not in the npm registry)

Getting 404 when attempting to publish new package to NPM

Installing npm package fails with 404

404 error while publishing npm package - npm ERR! 404 Not Found - PUT https://registry.npmjs.org/

In my Github Action how can I properly reference the private org repo so that my test will work correctly or is there a step I'm missing?

答:
This answer was correct and here is the sample test.yml file now:

```<code>name: Test
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [14.x, 16.x]
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v2
        with:
          node-version: ${{ matrix.node-version }}
      - run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" >> .npmrc
      - run: npm ci
      - run: npm run build --if-present
      - run: npm test
</code>```

Github Action shows as passed:

Body:
I have written a test file for a Github Action:

test.yml

name: Test
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [14.x, 16.x]
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v2
        with:
          node-version: ${{ matrix.node-version }}
      - run: npm ci
      - run: npm run build --if-present
      - run: npm test

but my package.json uses an organization private repo. When the Github Action runs it fails and I get the error:

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@org/repo/
npm ERR! 404
npm ERR! 404  '@org/repo@1.2.3' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/runner/.npm/_logs/2022-02-10T17_17_46_961Z-debug.log
Error: Process completed with exit code 1.

My research trying to solve the issue:

Package is not publishing to npm (not in the npm registry)

Getting 404 when attempting to publish new package to NPM

Installing npm package fails with 404

404 error while publishing npm package - npm ERR! 404 Not Found - PUT https://registry.npmjs.org/

In my Github Action how can I properly reference the private org repo so that my test will work correctly or is there a step I'm missing?

Body:
This answer was correct and here is the sample test.yml file now:

name: Test
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [14.x, 16.x]
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v2
        with:
          node-version: ${{ matrix.node-version }}
      - run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" >> .npmrc
      - run: npm ci
      - run: npm run build --if-present
      - run: npm test

Github Action shows as passed:


问:
How can I replace comma instead of some phrases?
I have a string of characters that starts with a space and has \r\n,I want to delete the first space and delete \r\n then replace it with a comma after the word if there is a space?

My String : "\r\n                        ram\r\ncomputer\r\n" ....

I want the following mode to change? laptop,computer,ram

答:
As per @valuator answer you can use Trim() to remove trailing spaces. And to address other concerns pointed out in comments, you can use regex replace as below.

```<code>string myString = " laptop  computer ram";
var rx= new Regex(@"[\s]+");
myString= rx.Replace(myString.Trim(), ",");
</code>```

the regex  [\s]+ will match any whitespace characters

Body:
As per @valuator answer you can use Trim() to remove trailing spaces. And to address other concerns pointed out in comments, you can use regex replace as below.

string myString = " laptop  computer ram";
var rx= new Regex(@"[\s]+");
myString= rx.Replace(myString.Trim(), ",");

the regex  [\s]+ will match any whitespace characters


问:
PowerShell return a single element array from function
Today I noticed an interested behavior of PowerShell and I made the following code to show it. When you run:

```<code>function test()
{
    $a = @(1,2);
    Write-Host $a.gettype()
    return $a;
}

$b = test
Write-Host $b.gettype();
</code>```

What you got is:

```<code>System.Object[]
System.Object[]
</code>```

However when you change the code to:

```<code>function test()
{
    $a = @(1);
    Write-Host $a.gettype()
    return $a;
}

$b = test
Write-Host $b.gettype();
</code>```

You will got:

```<code>System.Object[]
System.Int32
</code>```

Can someone provide some more details on this "feature"? Seems the PowerShell specification did not mention this.

Thanks.

BTW, I tested the code on PowerShell version 2, 3 & 4.

答:
Declare the variable as an array before using it.

Then use += when invoking the function.

Whatever you return, it will be considered as an array.

```<code>function test
{
    return [int]1
}

$b = @()
$b += test

$b.GetType()
</code>```

Result:

```<code>IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array
</code>```

Another way of doing:
```<code>$b = @(test)
</code>```

Body:
Today I noticed an interested behavior of PowerShell and I made the following code to show it. When you run:

function test()
{
    $a = @(1,2);
    Write-Host $a.gettype()
    return $a;
}

$b = test
Write-Host $b.gettype();

What you got is:

System.Object[]
System.Object[]

However when you change the code to:

function test()
{
    $a = @(1);
    Write-Host $a.gettype()
    return $a;
}

$b = test
Write-Host $b.gettype();

You will got:

System.Object[]
System.Int32

Can someone provide some more details on this "feature"? Seems the PowerShell specification did not mention this.

Thanks.

BTW, I tested the code on PowerShell version 2, 3 & 4.

Body:
Declare the variable as an array before using it.

Then use += when invoking the function.

Whatever you return, it will be considered as an array.

function test
{
    return [int]1
}

$b = @()
$b += test

$b.GetType()

Result:

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Another way of doing:

$b = @(test)


问:
Jest test case is failing in nestjs
I have below method in nestjs in service class.

```<code>async findOne(id: string): Promise<Certificate> {
    const result = await this.certificateRepository.findOne({ id });
    if (!result) {
        throw new NotFoundException(`Certificate with ID does not exist`);
    }
    return result;
}
</code>```

I have writtern below test case for the same.

```<code>it('should find one certificate', async () => {
        const id = '1';
        const certificate = await service.findOne(id);
        expect(repository.findOne).toHaveBeenCalledTimes(1);
        expect(repository.findOne).toHaveBeenCalledWith(id);
        expect(certificate).toBeInstanceOf(Certificate);
    });
</code>```

I am getting below error on the same.

I am not sure why it is returning object instead of value. if I cant modify the method can I modify this test case to retunr object?

WHat changes I should do in my testcase?

答:
Update the assertion to be the following:

```<code>expect(repository.findOne).toHaveBeenCalledWith({ id: "1" });
</code>```

This will match what how the code uses id to call certificateRepository.findOne.

Title: Jest test case is failing in nestjs

Body:
I have below method in nestjs in service class.

async findOne(id: string): Promise<Certificate> {
    const result = await this.certificateRepository.findOne({ id });
    if (!result) {
        throw new NotFoundException(`Certificate with ID does not exist`);
    }
    return result;
}

I have writtern below test case for the same.

it('should find one certificate', async () => {
        const id = '1';
        const certificate = await service.findOne(id);
        expect(repository.findOne).toHaveBeenCalledTimes(1);
        expect(repository.findOne).toHaveBeenCalledWith(id);
        expect(certificate).toBeInstanceOf(Certificate);
    });

I am getting below error on the same.

I am not sure why it is returning object instead of value. if I cant modify the method can I modify this test case to retunr object?

WHat changes I should do in my testcase?

Body:
Update the assertion to be the following:

expect(repository.findOne).toHaveBeenCalledWith({ id: "1" });

This will match what how the code uses id to call certificateRepository.findOne.


问:
Trying to capitalize the first character in array of strings, why this is not working?
I'm trying to write a function that converts for example list-style-image to listStyleImage.

I came up with a function but it seems not working. Can anybody point me to the problem here ?

```<code>var myStr = "list-style-image";

function camelize(str){
    var newStr = "";
    var newArr = [];
    if(str.indexOf("-") != -1){
        newArr = str.split("-");
        for(var i = 1 ; i < newArr.length ; i++){
            newArr[i].charAt(0).toUpperCase();
        }
        newStr = newArr.join("");
    }
    return newStr;
}

console.log(camelize(myStr));
</code>```

答:
my best way is:

function camelCase(arr) {
  let calc = arr.map(e => e.charAt(0).toUpperCase() + e.slice(1)).join('')
  console.log(calc)
  return calc;
}

// Test
camelCase(['Test', 'Case'])```

Body:
I'm trying to write a function that converts for example list-style-image to listStyleImage.

I came up with a function but it seems not working. Can anybody point me to the problem here ?

var myStr = "list-style-image";

function camelize(str){
    var newStr = "";
    var newArr = [];
    if(str.indexOf("-") != -1){
        newArr = str.split("-");
        for(var i = 1 ; i < newArr.length ; i++){
            newArr[i].charAt(0).toUpperCase();
        }
        newStr = newArr.join("");
    }
    return newStr;
}

console.log(camelize(myStr));


问:
chartjs hover over data without hoveringing on line
When you hover over a specific data point on a chartjs linechart the point's value can be shown. But let's say you hover on the graph, not on a specific data point but over the "empty space". In that case there should be some function to show the values of the points vertically aligned with the pointer. Does any such solution exist?

Basically the reason I'm asking is to be able to make mobile-friendly graphs and it can be difficult/irritating for the user to try and hit the small data points with their fingers.

答:
Yes, you can set intersect to false in the tooltip config:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        intersect: false
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body></code>```

Body:
Yes, you can set intersect to false in the tooltip config:

var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'orange'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'pink'
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        intersect: false
      }
    }
  }
}

var ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>