问:
Trouble with MJPG stream from IP camera in C#
I'm trying to connect to an Amcrest IP camera via C# winforms.  Here is what I am trying and the instructions from the Amcrest API manual.  I don't get any errors running this code but my picturebox never updates.  This is my first dive into working with an IP camera or doing any sort of server requests.  Can anyone steer me in the right direction?  Thanks in advance.

```<code>    private void Connect()
    {
        // Omitting the username and password does not help either.
        MJPEGStream stream = new MJPEGStream("http://192.168.1.108/cgi-bin/mjpg/video.cgi?channel=1&subtype=0&username=admin&password=pwd11");
        stream.NewFrame += new NewFrameEventHandler(video_NewFrame);
        stream.Start();
    }

    private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
        pictureBox1.Image = bmp;
    }
</code>```

There is this section in the manual regarding authentication.

答:
```<code>working.....

public Form1()
        {
            InitializeComponent();
            stream = new MJPEGStream("http://192.168.1.108/cgi-bin/mjpg/video.cgi?channel=0&subtype=1");
            stream.NewFrame += new NewFrameEventHandler(video_NewFrame);
        }
        private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
            pictureBox1.Image = bmp;
        }
        private void startbtn_Click(object sender, EventArgs e)
        {
            stream.Login = "admin";
            stream.Password = "passwordx";
            stream.Start();
        }
        private void stopbtn_Click(object sender, EventArgs e)
        {
            stream.Stop();
        }
</code>```

Body:
I'm trying to connect to an Amcrest IP camera via C# winforms.  Here is what I am trying and the instructions from the Amcrest API manual.  I don't get any errors running this code but my picturebox never updates.  This is my first dive into working with an IP camera or doing any sort of server requests.  Can anyone steer me in the right direction?  Thanks in advance.

    private void Connect()
    {
        // Omitting the username and password does not help either.
        MJPEGStream stream = new MJPEGStream("http://192.168.1.108/cgi-bin/mjpg/video.cgi?channel=1&subtype=0&username=admin&password=pwd11");
        stream.NewFrame += new NewFrameEventHandler(video_NewFrame);
        stream.Start();
    }

    private void video_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
        Bitmap bmp = (Bitmap)eventArgs.Frame.Clone();
        pictureBox1.Image = bmp;
    }

There is this section in the manual regarding authentication.


来源: stackexchange

问:
Why GPU is much slower than cpu in google colab?
I'm training a RNN on google colab and this is my first time using gpu to train a neural network. From my point of view, GPU should be much faster than cpu, and changing device from cpu to gpu only need to add .to('cuda') in the definition of model/loss/variable and set google colab 'running on gpu'.

When I train it on cpu, the average speed is 650 iteration/s

Training on cpu in google colab

But when I train it on gpu, the average speed is only 340 iterations/s, only half of the cpu

Training on gpu in google colab

and this happened on every epoch

Here is my code.

```<code>def train(num_epoch = 30,len_vocab = 1, num_hidden=256,embedding_dim = 8,batch_size = 100):
    data = get_data()

    model = MyRNN(len_vocab,num_hidden,embedding_dim).to('cuda') #here
    if os.path.exists('QingBinLi'):
        model.load_state_dict(torch.load('QingBinLi'))

    criterion = nn.MSELoss().to('cuda')   #here
    optimizer = torch.optim.Adam(model.parameters(), lr=0.1, weight_decay=1e-5)
    loss_for_draw = []
    model.train()
    data = data.detach().to('cuda') #here

    for epoch in range(num_epoch+1):

        h = torch.randn(1,batch_size,num_hidden).to('cuda')  #here
        loss_average = 0
        for i in tqdm(range(data.shape[-2] -batch_size)):
            optimizer.zero_grad()
            pre,h = model(data[:,:,i:i+batch_size,:].squeeze(0) ,h)
            h = h.detach()
            pre = pre.unsqueeze(0).unsqueeze(0)
            loss = criterion(pre, data[:,:,i+1:i+1+batch_size,:].squeeze(0))
            loss_average += loss.item()
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), max_norm=10)
            optimizer.step()

        loss_for_draw.append(loss_average/(data.shape[-2] -batch_size))
        torch.save(model.state_dict(), 'QingBinLi')
        print(f'now epoch:{epoch}, loss = {loss_for_draw[-1]}')

    return loss_for_draw

</code>```

I just add '.to('cuda')' there when I try to run it on gpu.

So, why it's much slower when I running my code on gpu? Maybe I should modify more code?

答:
My brother says that when the tensor is very big, such as 1 million dimension, gpu can be faster than cpu, otherwise we don't even need parallel computing because computing are not mainly on tensor multiply, but on copy tensors and other things like that.

My RNN has about 256x256+256x8 parameters and batch_size is 100, and the dimention of that is much lower than 1 million. So gpu is much slower.

And, when I change my batch_size to 10000, gpu is 145 iteration/s while cpu is only 15iterations/s. This time gpu is much faster.

A CNN, with stride one, in gpu we can calculate filter_size *image_size * batch_size, about 2,415,919,104 times multiply simultaneously. So in this kind of computing, gpu is much faster.

ContentLicense: CC BY-SA 4.0

Body:
I'm training a RNN on google colab and this is my first time using gpu to train a neural network. From my point of view, GPU should be much faster than cpu, and changing device from cpu to gpu only need to add .to('cuda') in the definition of model/loss/variable and set google colab 'running on gpu'.

When I train it on cpu, the average speed is 650 iteration/s

Training on cpu in google colab

But when I train it on gpu, the average speed is only 340 iterations/s, only half of the cpu

Training on gpu in google colab

and this happened on every epoch

Here is my code.

def train(num_epoch = 30,len_vocab = 1, num_hidden=256,embedding_dim = 8,batch_size = 100):
    data = get_data()

    model = MyRNN(len_vocab,num_hidden,embedding_dim).to('cuda') #here
    if os.path.exists('QingBinLi'):
        model.load_state_dict(torch.load('QingBinLi'))

    criterion = nn.MSELoss().to('cuda')   #here
    optimizer = torch.optim.Adam(model.parameters(), lr=0.1, weight_decay=1e-5)
    loss_for_draw = []
    model.train()
    data = data.detach().to('cuda') #here

    for epoch in range(num_epoch+1):

        h = torch.randn(1,batch_size,num_hidden).to('cuda')  #here
        loss_average = 0
        for i in tqdm(range(data.shape[-2] -batch_size)):
            optimizer.zero_grad()
            pre,h = model(data[:,:,i:i+batch_size,:].squeeze(0) ,h)
            h = h.detach()
            pre = pre.unsqueeze(0).unsqueeze(0)
            loss = criterion(pre, data[:,:,i+1:i+1+batch_size,:].squeeze(0))
            loss_average += loss.item()
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), max_norm=10)
            optimizer.step()

        loss_for_draw.append(loss_average/(data.shape[-2] -batch_size))
        torch.save(model.state_dict(), 'QingBinLi')
        print(f'now epoch:{epoch}, loss = {loss_for_draw[-1]}')

    return loss_for_draw

I just add '.to('cuda')' there when I try to run it on gpu.

So, why it's much slower when I running my code on gpu? Maybe I should modify more code?


问:
Password reset flow for "Classic" accounts
The docs state:

This self-service password reset flow applies to local accounts in Azure Active Directory B2C (Azure AD B2C)
https://learn.microsoft.com/en-us/azure/active-directory-b2c/add-password-reset-policy?pivots=b2c-custom-policy

How can I have a password reset functionality if my users are located in a legacy user store. (I'm using a REST Technical Profile to connect those)

If there is no built-in functionality for this kind of accounts, can I at least add a link to the sign-in form that will send the user to our legacy password reset page?

To clarify: by legacy/classic user store I mean a service that you can all over REST to validate credentials. Not another OIDC identity provider.

答:
To answer your comment.

Replace this in the "PasswordReset" user journey:

```<code><OrchestrationStep Order="3" Type="ClaimsExchange">
  <ClaimsExchanges>
    <ClaimsExchange Id="NewCredentials"   TechnicalProfileReferenceId="LocalAccountWritePasswordUsingObjectId" />
  </ClaimsExchanges>
</OrchestrationStep>
</code>```

with the call to your REST API.

Body:
To answer your comment.

Replace this in the "PasswordReset" user journey:

<OrchestrationStep Order="3" Type="ClaimsExchange">
  <ClaimsExchanges>
    <ClaimsExchange Id="NewCredentials"   TechnicalProfileReferenceId="LocalAccountWritePasswordUsingObjectId" />
  </ClaimsExchanges>
</OrchestrationStep>

with the call to your REST API.


问:
Save fitted and predicted values to data frame in r
I am trying to extract the fitted and predicted values from the different classes of the object. But when I save them to a column in a data frame I got a column with NA. I tried to fix that by making the fitted value numeric, a data frame. But when it comes to saving the values in a data frame I still got the NA or errors. Adjusting the number of rows did neither helped.

This is my code:
library(forecast)

```<code>#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =3, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =3, nrow=4))
colnames(df1)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1= arima(b)
model_2=naive(b)
model_3=HoltWinters(ts(b, frequency=4))

#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$xhat

#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#

#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted
df2[,3]=Predictedmodel_2$fitted
df2[,4]=Predictedmodel_3$fitted
</code>```

Can somebody help me pls?

答:
Edit: I manage to make it work, but there are a lot of changes, not to mention that some functions you are using are not even in the package described in your post. I solved the problem only using forecast package. Let me know if this helps.

```<code>library(forecast)

#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =4, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =4, nrow=4))
colnames(df2)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1 <- forecast::Arima(b)
model_2 = forecast::naive(b)
model_3 = forecast::holt(ts(b, frequency=4))

model_1$fitted

model_2$fitted

model_3$x

#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$x

df1

#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#

#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted[1:4]
df2[,3]=Predictedmodel_2$fitted[1:4]
df2[,4]=Predictedmodel_3$fitted[1:4]

df2
</code>```

First Result Set:

```<code>> model_1$fitted
Time Series:
Start = 1
End = 10
Frequency = 1
 [1] -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639
>
> model_2$fitted
Time Series:
Start = 1
End = 10
Frequency = 1
 [1]           NA -0.858431677  0.091330323 -0.380993711 -0.004967207 -0.188007449  0.408278796 -0.538164307 -0.782095624
[10]  0.998132989
>
> model_3$x
          Qtr1         Qtr2         Qtr3         Qtr4
1 -0.858431677  0.091330323 -0.380993711 -0.004967207
2 -0.188007449  0.408278796 -0.538164307 -0.782095624
3  0.998132989  0.950853919
>
</code>```

Second Result Set:

```<code>> df1
   month        Fit1         Fit2         Fit3
1      1 -0.03040639           NA -0.858431677
2      2 -0.03040639 -0.858431677  0.091330323
3      3 -0.03040639  0.091330323 -0.380993711
4      4 -0.03040639 -0.380993711 -0.004967207
5      5 -0.03040639 -0.004967207 -0.188007449
6      6 -0.03040639 -0.188007449  0.408278796
7      7 -0.03040639  0.408278796 -0.538164307
8      8 -0.03040639 -0.538164307 -0.782095624
9      9 -0.03040639 -0.782095624  0.998132989
10    10 -0.03040639  0.998132989  0.950853919

</code>```

Third Results Set:

```<code>> df2
  month       Pred1       Pred2      Pred3
1    11 -0.03040639          NA -0.5862699
2    12 -0.03040639 -0.85843168 -0.4627794
3    13 -0.03040639  0.09133032 -0.3391509
4    14 -0.03040639 -0.38099371 -0.2155862
>
</code>```

Body:
I am trying to extract the fitted and predicted values from the different classes of the object. But when I save them to a column in a data frame I got a column with NA. I tried to fix that by making the fitted value numeric, a data frame. But when it comes to saving the values in a data frame I still got the NA or errors. Adjusting the number of rows did neither helped.

This is my code:
library(forecast)

#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =3, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =3, nrow=4))
colnames(df1)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1= arima(b)
model_2=naive(b)
model_3=HoltWinters(ts(b, frequency=4))

#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$xhat

#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#

#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted
df2[,3]=Predictedmodel_2$fitted
df2[,4]=Predictedmodel_3$fitted

Can somebody help me pls?

Body:
Edit: I manage to make it work, but there are a lot of changes, not to mention that some functions you are using are not even in the package described in your post. I solved the problem only using forecast package. Let me know if this helps.

library(forecast)

#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =4, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =4, nrow=4))
colnames(df2)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1 <- forecast::Arima(b)
model_2 = forecast::naive(b)
model_3 = forecast::holt(ts(b, frequency=4))

model_1$fitted

model_2$fitted

model_3$x

#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$x

df1

#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#

#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted[1:4]
df2[,3]=Predictedmodel_2$fitted[1:4]
df2[,4]=Predictedmodel_3$fitted[1:4]

df2

First Result Set:

> model_1$fitted
Time Series:
Start = 1
End = 10
Frequency = 1
 [1] -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639 -0.03040639
>
> model_2$fitted
Time Series:
Start = 1
End = 10
Frequency = 1
 [1]           NA -0.858431677  0.091330323 -0.380993711 -0.004967207 -0.188007449  0.408278796 -0.538164307 -0.782095624
[10]  0.998132989
>
> model_3$x
          Qtr1         Qtr2         Qtr3         Qtr4
1 -0.858431677  0.091330323 -0.380993711 -0.004967207
2 -0.188007449  0.408278796 -0.538164307 -0.782095624
3  0.998132989  0.950853919
>

Second Result Set:

> df1
   month        Fit1         Fit2         Fit3
1      1 -0.03040639           NA -0.858431677
2      2 -0.03040639 -0.858431677  0.091330323
3      3 -0.03040639  0.091330323 -0.380993711
4      4 -0.03040639 -0.380993711 -0.004967207
5      5 -0.03040639 -0.004967207 -0.188007449
6      6 -0.03040639 -0.188007449  0.408278796
7      7 -0.03040639  0.408278796 -0.538164307
8      8 -0.03040639 -0.538164307 -0.782095624
9      9 -0.03040639 -0.782095624  0.998132989
10    10 -0.03040639  0.998132989  0.950853919

Third Results Set:

> df2
  month       Pred1       Pred2      Pred3
1    11 -0.03040639          NA -0.5862699
2    12 -0.03040639 -0.85843168 -0.4627794
3    13 -0.03040639  0.09133032 -0.3391509
4    14 -0.03040639 -0.38099371 -0.2155862
>


问:
Stack is always empty
Even if when I am pushing something, the keni(S) always returns -1. Like I can push, but when I am trying to pop, it always returns "Stack is empty!". Thanks for your time!

```<code>#include <stdio.h>
#define N 5

typedef struct{
    float s[N];
    int top;
}Stiva;

int keni(Stiva);
void dimiourgia(Stiva*);
void push(Stiva *, float);
float pop(Stiva *);

void dimiourgia(Stiva *St)
{
    St->top = -1;
}

int keni(Stiva S)
{
    if (S.top == -1)
        return -1;
    else
        return 0;
}

void push(Stiva *St, float a)
{
    if (St->top == N-1) {
        printf("\n\nStack Overflow");
        return;
    }
    else {
        St->top ++;
        St->s[St->top] = a;
    }
}

float pop(Stiva *St)
{
    float c;

    c = St->s[St->top];
    St -> top--;

    return c;
}

int main()
{
    Stiva S;
    float x;
    int epil;

    dimiourgia(&S);
    do{
        do{
            printf("\n\n1.Push 2.Pop 3.End\n");
            scanf("%d", &epil);
        }while (epil<1 || epil>3);
        switch (epil) {
            case 1: if (S.top == N-1)
                        printf("\n\nStack is empty!\n\n");
                    else {
                        printf("\nPick a num\n\n");
                        scanf("%f", &x);
                        push(&S, x);
                    }
            case 2: if (keni(S) == -1)
                        printf("\n\nStack is empty!\n\n");
                    else {
                        x = pop(&S);
                        printf("\n\n==> %10.2f", x);
                    }
        }
    } while(epil!=3);
    return 0;
}

</code>```

答:
anyway heres the fix

```<code>    switch (epil) {
        case 1: if (S.top == N-1)
                    printf("\n\nStack is empty!\n\n");
                else {
                    printf("\nPick a num\n\n");
                    scanf("%f", &x);
                    push(&S, x);
                }
                break; <<<<==============================
        case 2: if (keni(S) == -1)
                    printf("\n\nStack is empty!\n\n");
                else {
                    x = pop(&S);
                    printf("\n\n==> %10.2f", x);
                }
    }
</code>```

at the moment after you push a number you immediately pop it again

```<code>1.Push 2.Pop 3.End
1

Pick a num

42

1.Push 2.Pop 3.End
1

Pick a num

44

1.Push 2.Pop 3.End
2

==>      44.00

1.Push 2.Pop 3.End
2

==>      42.00

1.Push 2.Pop 3.End
2

Stack is empty!

1.Push 2.Pop 3.End
</code>```

Found by setting a break point where you call push and simply simgle stepping and watching the code

Title: Stack is always empty

Body:
Even if when I am pushing something, the keni(S) always returns -1. Like I can push, but when I am trying to pop, it always returns "Stack is empty!". Thanks for your time!

#include <stdio.h>
#define N 5

typedef struct{
    float s[N];
    int top;
}Stiva;

int keni(Stiva);
void dimiourgia(Stiva*);
void push(Stiva *, float);
float pop(Stiva *);

void dimiourgia(Stiva *St)
{
    St->top = -1;
}

int keni(Stiva S)
{
    if (S.top == -1)
        return -1;
    else
        return 0;
}

void push(Stiva *St, float a)
{
    if (St->top == N-1) {
        printf("\n\nStack Overflow");
        return;
    }
    else {
        St->top ++;
        St->s[St->top] = a;
    }
}

float pop(Stiva *St)
{
    float c;

    c = St->s[St->top];
    St -> top--;

    return c;
}

int main()
{
    Stiva S;
    float x;
    int epil;

    dimiourgia(&S);
    do{
        do{
            printf("\n\n1.Push 2.Pop 3.End\n");
            scanf("%d", &epil);
        }while (epil<1 || epil>3);
        switch (epil) {
            case 1: if (S.top == N-1)
                        printf("\n\nStack is empty!\n\n");
                    else {
                        printf("\nPick a num\n\n");
                        scanf("%f", &x);
                        push(&S, x);
                    }
            case 2: if (keni(S) == -1)
                        printf("\n\nStack is empty!\n\n");
                    else {
                        x = pop(&S);
                        printf("\n\n==> %10.2f", x);
                    }
        }
    } while(epil!=3);
    return 0;
}

Body:
anyway heres the fix

    switch (epil) {
        case 1: if (S.top == N-1)
                    printf("\n\nStack is empty!\n\n");
                else {
                    printf("\nPick a num\n\n");
                    scanf("%f", &x);
                    push(&S, x);
                }
                break; <<<<==============================
        case 2: if (keni(S) == -1)
                    printf("\n\nStack is empty!\n\n");
                else {
                    x = pop(&S);
                    printf("\n\n==> %10.2f", x);
                }
    }

at the moment after you push a number you immediately pop it again

1.Push 2.Pop 3.End
1

Pick a num

42

1.Push 2.Pop 3.End
1

Pick a num

44

1.Push 2.Pop 3.End
2

==>      44.00

1.Push 2.Pop 3.End
2

==>      42.00

1.Push 2.Pop 3.End
2

Stack is empty!

1.Push 2.Pop 3.End

Found by setting a break point where you call push and simply simgle stepping and watching the code


问:
cakephp shell is not available
I am experienced in php, but new to cake and having some trouble, I did read through quite a bit on this before posting, so I do apologize if I am asking a very basic question as I feel like it has been answered, however maybe my lack of understanding for cakephp is holding me up.

I have a file 'convert.php' with the following code it it

```<code><?php
class ConvertShell extends Shell {
    function main() {
        $time = date('Y-m-d H:i:s', time());
        $this->out("Testing - ".$time."\n");
    }
}
?>
</code>```

This file is in '/home/photo/public_html/vendors/shells/convert.php'

when I run 'cake convert' I get the following:

```<code>Welcome to CakePHP v1.2.4 Console

Current Paths:
-app: photo
-working: /home/photo
-root: /home
-core: /usr/share/php

Available Shells:
    acl
    api
    bake
    console
    i18n
    schema
    testsuite
</code>```

I have seen a number of solutions pointing to the fact that I should have the shell file in '/home/photo/app/vendors/shells' instead, however I don't have an app folder.  There is a log of cakephp code already running and working correctly, so cake is running fine as far as I know.

答: The issue was I was not set up as a production setup of cakephp, so you have to use the core setup. So the app folder is located in the cake folder, not in your webroot.</p>

ContentLicense: CC BY-SA 3.0

Title: cakephp shell is not available

Body:
I am experienced in php, but new to cake and having some trouble, I did read through quite a bit on this before posting, so I do apologize if I am asking a very basic question as I feel like it has been answered, however maybe my lack of understanding for cakephp is holding me up.

I have a file 'convert.php' with the following code it it

<?php
class ConvertShell extends Shell {
    function main() {
        $time = date('Y-m-d H:i:s', time());
        $this->out("Testing - ".$time."\n");
    }
}
?>

This file is in '/home/photo/public_html/vendors/shells/convert.php'

when I run 'cake convert' I get the following:

Welcome to CakePHP v1.2.4 Console

Current Paths:
-app: photo
-working: /home/photo
-root: /home
-core: /usr/share/php

Available Shells:
    acl
    api
    bake
    console
    i18n
    schema
    testsuite

I have seen a number of solutions pointing to the fact that I should have the shell file in '/home/photo/app/vendors/shells' instead, however I don't have an app folder.  There is a log of cakephp code already running and working correctly, so cake is running fine as far as I know.


问:
message box in tkinter is not showing any output
```<code>from tkinter import *
def s():
    messagebox.showinfo("Oh hi")

w = Tk()

s = Entry()
s.grid(row =0, column =1)

l = Label(text = "What is your name?" )
l.grid(row = 0, column = 0)

button = Button(text = "Submit", command = s )
button.grid(row = 1,column = 3)
w.mainloop()
</code>```

My message box option is not showing me the output? why so? It is not giving me the error but when I click the submit button it is not doing what it is supposed to do?

答:
The first parameter to showinfo is the title of the window. If you want the information to be inside the dialog, assign it to the message parameter.

```<code>messagebox.showinfo(message="Oh hi")
</code>```

Unrelated to the question that was asked, the code you posted won't ever display the message in s because you've redefined s to be an entry widget rather than your function.

Body:
from tkinter import *
def s():
    messagebox.showinfo("Oh hi")

w = Tk()

s = Entry()
s.grid(row =0, column =1)

l = Label(text = "What is your name?" )
l.grid(row = 0, column = 0)

button = Button(text = "Submit", command = s )
button.grid(row = 1,column = 3)
w.mainloop()

My message box option is not showing me the output? why so? It is not giving me the error but when I click the submit button it is not doing what it is supposed to do?

Body:
The first parameter to showinfo is the title of the window. If you want the information to be inside the dialog, assign it to the message parameter.

messagebox.showinfo(message="Oh hi")

Unrelated to the question that was asked, the code you posted won't ever display the message in s because you've redefined s to be an entry widget rather than your function.


问:
Replacing characters with other characters in C files
I am attempting to write a program that takes in two files (or if not provided either file, uses stdin/stdout to replace a specified character array with another character array.

For example: if passed "--ax -+td" then my program will replace every instance of 'a' with 't' and every 'x' with 'd'.

Here is what I am trying:

char *takeOut = "ax";
char *putIn = "td";

FILE *in = freopen(src, "r", stdin);
FILE *out = freopen(dest, "w", stdout);
int ch;

   for (int i=0; i<strlen(putIn); i++) {

      while ((ch = getc(in)) != EOF) {
           if (ch == '\n') { // for stdout displaying without "%"
              putc('\n', out);
              break;
           } else if (ch != takeOut[i]) {
              putc(ch, out);
           } else {
              putc((putIn[i]), out);
           }
       }
    }
```

The program ensures that the putIn and takeOut are of the same size, by the way.

The result is that only the first letter specified is replaced in every instance (in this case all "a's" are replaced with "t's". But no "x's" are replaced with "d's".

What am I doing wrong?

答:
I would redesign the loop as already stated. It makes more sense to read one character at a time then checking if it matches.
One flaw I noticed in your code is you're complicating how you're performing the checks. I would simply check if there's a match on an inner for loop, if the match is found, replace and break out of the loop. Outside of the inner loop you can then write whatever was read prior in the case a match didn't occur.

```<code>    while ((ch = getc(in)) != EOF) {
        for(int x =0; x < strlen(putIn);++x){
            if(ch==takeOut[x]){
                putc(putIn[x], out);
                ch = 0;
                break;
            }
        }
        if(ch){
            putc(ch, out);
        }
    }
</code>```

If a replacement occured, we set ch to 0 and there's no need to perform another write. If a replacement did not occur then put the original char into the outfile.

Body:
I am attempting to write a program that takes in two files (or if not provided either file, uses stdin/stdout to replace a specified character array with another character array.

For example: if passed "--ax -+td" then my program will replace every instance of 'a' with 't' and every 'x' with 'd'.

Here is what I am trying:

char *takeOut = "ax";
char *putIn = "td";

FILE *in = freopen(src, "r", stdin);
FILE *out = freopen(dest, "w", stdout);
int ch;

   for (int i=0; i<strlen(putIn); i++) {

      while ((ch = getc(in)) != EOF) {
           if (ch == '\n') { // for stdout displaying without "%"
              putc('\n', out);
              break;
           } else if (ch != takeOut[i]) {
              putc(ch, out);
           } else {
              putc((putIn[i]), out);
           }
       }
    }

The program ensures that the putIn and takeOut are of the same size, by the way.

The result is that only the first letter specified is replaced in every instance (in this case all "a's" are replaced with "t's". But no "x's" are replaced with "d's".

What am I doing wrong?

Body:
I would redesign the loop as already stated. It makes more sense to read one character at a time then checking if it matches.
One flaw I noticed in your code is you're complicating how you're performing the checks. I would simply check if there's a match on an inner for loop, if the match is found, replace and break out of the loop. Outside of the inner loop you can then write whatever was read prior in the case a match didn't occur.

    while ((ch = getc(in)) != EOF) {
        for(int x =0; x < strlen(putIn);++x){
            if(ch==takeOut[x]){
                putc(putIn[x], out);
                ch = 0;
                break;
            }
        }
        if(ch){
            putc(ch, out);
        }
    }

If a replacement occured, we set ch to 0 and there's no need to perform another write. If a replacement did not occur then put the original char into the outfile.


问:
disable auto-prettier in react-native app
I'm using vim as my default editor which complains when some external tool changes the code while the buffer is open. I recently started working on a react-native app but every time i save the file it runs prettier in the background before pushing the app to the device, changing the files causing my vim to misbehave.

I initialized a default react-native app using

```<code>npx react-native init <project name>
</code>```

I already had vim configured to run prettier on save but there is some external prettier run competing, and vim is losing. I can't find where this autolinting on save is configured anywhere in the files though.

Where can i disable this?

答:
I think following doc will give some solution for your problem

Prettier and ESLint

Auto formatting

Body:
I'm using vim as my default editor which complains when some external tool changes the code while the buffer is open. I recently started working on a react-native app but every time i save the file it runs prettier in the background before pushing the app to the device, changing the files causing my vim to misbehave.

I initialized a default react-native app using

npx react-native init <project name>

I already had vim configured to run prettier on save but there is some external prettier run competing, and vim is losing. I can't find where this autolinting on save is configured anywhere in the files though.

Where can i disable this?


问:
Pandas conditional merge 2 dataframes with one to many relationship
I am trying to merge two pandas DataFrames with one of many relationship. However, there are a couple of caveats. Explanation below.

```<code>import pandas as pd

df1 = pd.DataFrame({'name': ['AA', 'BB', 'CC', 'DD'],
                    'col1': [1, 2, 3, 4],
                    'col2': [1, 2, 3, 4] })

df2 = pd.DataFrame({'name': ['AA', 'AA', 'BB', 'BB', 'CC', 'DD'],
                    'col3': [0, 10, np.nan, 11, 12, np.nan] })
</code>```

I'd like to merge the 2 DataFrames, however, ignore the 0 and np.nan in df2 when joining. I cannot simply filter df2 as there are other columns that I need.

Basically, I'd like to join on rows with one-to-many relationship that are not 0 or NaNs.

Expected output:

答:
One way:</p>
```<code>>>> df1.merge(df2).drop_duplicates(subset=['name'], keep='last')
  name  col1  col2  col3
1   AA     1     1  10.0
3   BB     2     2  11.0
4   CC     3     3  12.0
5   DD     4     4  13.0
</code>```

Body:
I am trying to merge two pandas DataFrames with one of many relationship. However, there are a couple of caveats. Explanation below.

import pandas as pd

df1 = pd.DataFrame({'name': ['AA', 'BB', 'CC', 'DD'],
                    'col1': [1, 2, 3, 4],
                    'col2': [1, 2, 3, 4] })

df2 = pd.DataFrame({'name': ['AA', 'AA', 'BB', 'BB', 'CC', 'DD'],
                    'col3': [0, 10, np.nan, 11, 12, np.nan] })

I'd like to merge the 2 DataFrames, however, ignore the 0 and np.nan in df2 when joining. I cannot simply filter df2 as there are other columns that I need.

Basically, I'd like to join on rows with one-to-many relationship that are not 0 or NaNs.

Expected output:

Body:
One way:

>>> df1.merge(df2).drop_duplicates(subset=['name'], keep='last')
  name  col1  col2  col3
1   AA     1     1  10.0
3   BB     2     2  11.0
4   CC     3     3  12.0
5   DD     4     4  13.0


问:
How do I create a Spring boot object from the Angular front-end?
I'm developing an e-commerce with back-end in Spring boot and front-end in Angular material. When I'm in the payment page of the browser, after a click event on the button Pay, I'd like that an order, that is related to the payment on which the click event occured, is created but I don't know how to do this thing.
The problem is that, when I create an object of type Payment after the click event, this object (due to the 1:1 relationship between Payment and Order) needs an object of type Order (as shown in the following entities) and I don't know how to create it from the front-end and connect it with the relative Payment object.

BACK-END

Order entity:

```<code>@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity

@Table(name = "order", schema = "purchase")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "order_time")
    private Date orderTime;

    @OneToMany(mappedBy = "order", cascade = CascadeType.MERGE)
    private List<ProductInOrder> productsInOrder;

    @ManyToOne
    @JoinColumn(name = "buyer")
    private User buyer;

    @OneToOne(mappedBy= "order")
    private TheReturn theReturn;

    @OneToOne
    @JoinColumn(name = "payment_id")
    @JsonIgnore
    private Payment payment;

    @OneToOne
    @JoinColumn(name = "cart_id")
    private Cart cart;
}
</code>```

Payment entity:

```<code>@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    //il numero di una carta PayPal è di 16 cifre
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;

    @OneToOne(mappedBy = "payment")
    private Order order;

    @OneToOne(mappedBy = "payment")
    private TheReturn theReturn;
}
</code>```

OrderService:

```<code>@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductInOrderRepository productInOrderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false)
    public Order addOrder(Order order) throws ProductUnavailableException, EmptyOrderException, UserNotFoundException, CartNotFoundException, CartAlreadyExistsException{//

        if(order.getProductsInOrder()==null || order.getProductsInOrder().size()<=0){
            throw new EmptyOrderException();
        }
        if(!userRepository.existsById(order.getBuyer().getId())){
            throw new UserNotFoundException();
        }

        if(!cartRepository.existsById(order.getCart().getId())){
            throw new CartNotFoundException();
        }

        if(orderRepository.findByCart(order.getCart())!=null){
            throw new CartAlreadyExistsException();
        }
        Order result = orderRepository.save(order);
        for(ProductInOrder p : result.getProductsInOrder()){
            p.setOrder(result);
            ProductInOrder justAdded = productInOrderRepository.save(p);

            entityManager.refresh(justAdded);
            Product product = justAdded.getProduct();
            int newQuantity = product.getQuantity() - p.getQuantity();
            if(newQuantity < 0){
                orderRepository.delete(order);
                p.setOrder(null);
                productInOrderRepository.delete(p);
                throw new ProductUnavailableException(product);
            }
            product.setQuantity(newQuantity);
            entityManager.refresh(p);
        }
        entityManager.refresh(result);
        return result;
    }
</code>```

OrderController:

```<code>@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/createOrder")
    @ResponseStatus(code = HttpStatus.OK)
    public ResponseEntity create(@RequestBody @Valid Order order){//Funziona
    //System.out.println("Ordine in orderController: "+order+"\n");
        try{
            return new ResponseEntity<>(orderService.addOrder(order), HttpStatus.OK);
        }catch (ProductUnavailableException e){
            return new ResponseEntity<>(new ResponseMessage("The quantity of product: "+e.getProduct().getName()+" is unavailable!"), HttpStatus.BAD_REQUEST);
        } catch (EmptyOrderException e) {
            return new ResponseEntity<>(new ResponseMessage("The order has no products."), HttpStatus.BAD_REQUEST);
        } catch (UserNotFoundException e) {
            return new ResponseEntity<>(new ResponseMessage("User not found."), HttpStatus.BAD_REQUEST);
        } catch (CartNotFoundException e) {
            return new ResponseEntity<>(new ResponseMessage("Cart not found."), HttpStatus.BAD_REQUEST);
        } catch (CartAlreadyExistsException e) {
            return new ResponseEntity<>(new ResponseMessage("Cannot associate the same cart cart to more than one order."), HttpStatus.BAD_REQUEST);
        }
    }
</code>```

PaymentService:

```<code>@Service
public class PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Payment addPayment(Payment p) throws PaymentAlreadyExistsException, IncorrectCardNumberException, IncorrectCvvException{//
        if(paymentRepository.existsByCardNumber(p.getCardNumber())){
            throw new PaymentAlreadyExistsException();
        }
        if(p.getCardNumber().length()!=16){
            throw new IncorrectCardNumberException();
        }
        if(p.getCvv().length()!=3)
        {
            throw new IncorrectCvvException();
        }
        Order newOrder = new Order();
        newOrder.setPayment(p);
        Order justAdded=orderRepository.save(newOrder);
        entityManager.refresh(justAdded);
        p.setOrder(justAdded);
        return paymentRepository.save(p);
    }
</code>```

PaymentController:

```<code>@RestController
@RequestMapping("/payments")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @PostMapping("/createPayment")//funziona
    public ResponseEntity<Payment> create(@RequestBody @Valid Payment payment){
        System.out.print("Sono in paymentController.");
        try {
            Payment added=paymentService.addPayment(payment);
            return new ResponseEntity<>(added, HttpStatus.OK);
        } catch (PaymentAlreadyExistsException e) {
            return new ResponseEntity(new ResponseMessage("Payment already exists!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCardNumberException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect card number!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCvvException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect CVV"), HttpStatus.BAD_REQUEST);
        }
}
</code>```

FRONT-END

payment.component.html (in this html file there is the click event I was talking about):

```<code><form #paymentForm="ngForm">

 <div class="form-group">
    <label for="ownerName">OwnerName*</label>
    <input type="text" ngModel name="ownerName" class="form-control" id="ownerName" placeholder="OwnerName" required>
 </div>
  <div class="form-group">
    <label for="ownerLastName">OwnerLastName*</label>
    <input type="text" ngModel name="ownerLastName" class="form-control" id="ownerLastName" placeholder="OwnerLastName" required>
 </div>

  <div class="form-group">
     <label for="cardNumber">CardNumber*</label>
     <input type="text" ngModel name="cardNumber" class="form-control" id="cardNumber" placeholder="CardNumber" required>
  </div>

  <div class="form-group">
     <label for="cvv">Cvv*</label>
     <input type="text" ngModel name="cvv" class="form-control" id="cvv" placeholder="cvv" required>
  </div>

  <div class="form-group">
    <label for="expiration">Expiration*</label>
    <input type="date" ngModel name="expiration" class="form-control" id="expiration" placeholder="expiration" required>
 </div>

 <p>(Tutti i campi contrassegnati con * devono essere riempiti)</p>

  <div class="modal-footer">
     <button [disabled]="paymentForm.invalid" type="submit" class="btn btn-primary" (click)="createPayment('Payment successful!', 'ok', paymentForm)" routerLink="/orders"  routerLinkActive="active">Pay</button>
  </div>
  </form>
</code>```

payment.component.ts:

```<code>export class PaymentComponent implements OnInit {
  public total:number=0;
  public payment!: Payment;
  ownerNameFormControl = new FormControl('', [Validators.required]);
  ownerLastNameFormControl = new FormControl('', [Validators.required]);
  constructor(private _snackBar: MatSnackBar, private paymentService:PaymentService, private shared: SharedService) { }

  ngOnInit(): void {
    this.shared.castTotal.subscribe(total=>this.total=total);
    this.shared.castPayment.subscribe(payment=>this.payment=payment);
  }
  public createPayment(message:string, action:string, createForm:NgForm ) {
    this.paymentService.createPayment(createForm.value).subscribe(
      (response: Payment) => {
        this.payment=response;
        this.shared.setPayment(this.payment);
        console.log(response);
        this._snackBar.open(message, action);
        createForm.reset();

      },
      (error: HttpErrorResponse)=>{
        alert(error.message);
        createForm.reset();
      }
    )
  }
}
</code>```

payment.service.ts:

```<code>@Injectable({
  providedIn: 'root'
})
export class PaymentService {

  constructor(private http: HttpClient) { }

  public createPayment(payment: Payment): Observable<Payment> {
    console.log("Sono in payment service");
    return this.http.post<Payment>('http://localhost:8080/payments/createPayment', payment);
  }
</code>```

shared.service.ts:

```<code>export class SharedService {
  public defaultPayment!: Payment;
  private payment= new BehaviorSubject<Payment>(this.defaultPayment);
  castPayment = this.payment.asObservable();

  constructor() { }

   setPayment(data: Payment){
      this.payment.next(data);   }
</code>```

order.component.ts:

```<code>@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    //il numero di una carta PayPal è di 16 cifre
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;

    @OneToOne(mappedBy = "payment")
    private Order order;

    @OneToOne(mappedBy = "payment")
    private TheReturn theReturn;
}
</code>```0

order.service.ts:

```<code>@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    //il numero di una carta PayPal è di 16 cifre
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;

    @OneToOne(mappedBy = "payment")
    private Order order;

    @OneToOne(mappedBy = "payment")
    private TheReturn theReturn;
}
</code>```1

payment.ts:

```<code>@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    //il numero di una carta PayPal è di 16 cifre
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;

    @OneToOne(mappedBy = "payment")
    private Order order;

    @OneToOne(mappedBy = "payment")
    private TheReturn theReturn;
}
</code>```2

答:
Sending a request from FE to BE has essentially 2 steps:

FE sends request to backend:

As you can see in this example from the Angular documentation:

```<code>/** POST: add a new hero to the database */
addHero(hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(`http://localhost:portNumber/hero`, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}
</code>```

You just send the object that has all the fields you need to the backend. When it is sent - it is sent as JSON which means if the Hero class has fields name and power it will be sent like this:

```<code>{
  "name": "Superman",
  "power": "Can disguise himself by wearing glasses"
}
</code>```

Consume it on the backend side:

In Spring Controller you just need to define a controller method that expects an object with the same fields. Spring has a dependency of Jackson which automatically will deserialize JSON for you, so as I said you just need to create a DTO that has all the fields you need.

```<code>class HeroDTO {
  private String name;
  private String power;

  //getters, setters and noArg constructor - important to have for deserialization to work!
}
</code>```

and then in controller method:

```<code>@PostMapping(value = "/hero", produces = APPLICATION_JSON_VALUE)
public ResponseEntity createHero(@RequestBody HeroDTO heroDTO) {
    //do whatever
}
</code>```

btw you might get CORS errors - that is normal and CORS can be disabled by adding @CrossOrigin to the top of your Controller. More here

Body:
I'm developing an e-commerce with back-end in Spring boot and front-end in Angular material. When I'm in the payment page of the browser, after a click event on the button Pay, I'd like that an order, that is related to the payment on which the click event occured, is created but I don't know how to do this thing.
The problem is that, when I create an object of type Payment after the click event, this object (due to the 1:1 relationship between Payment and Order) needs an object of type Order (as shown in the following entities) and I don't know how to create it from the front-end and connect it with the relative Payment object.

BACK-END

Order entity:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity

@Table(name = "order", schema = "purchase")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @CreationTimestamp
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "order_time")
    private Date orderTime;

    @OneToMany(mappedBy = "order", cascade = CascadeType.MERGE)
    private List<ProductInOrder> productsInOrder;

    @ManyToOne
    @JoinColumn(name = "buyer")
    private User buyer;

    @OneToOne(mappedBy= "order")
    private TheReturn theReturn;

    @OneToOne
    @JoinColumn(name = "payment_id")
    @JsonIgnore
    private Payment payment;

    @OneToOne
    @JoinColumn(name = "cart_id")
    private Cart cart;
}

Payment entity:

@Getter
@Setter
@EqualsAndHashCode
@ToString
@Entity
@Table(name = "payment", schema = "purchase")
public class Payment {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;

    @Basic
    @Column(name = "owner_name", nullable = true, length = 70)
    private String ownerName;

    @Basic
    @Column(name = "owner_last_name", nullable = true, length = 70)
    private String ownerLastName;

    @Basic
    @Column(name = "card_number", nullable = true, length = 16)
    //il numero di una carta PayPal è di 16 cifre
    private String cardNumber;

    @Basic
    @Temporal(TemporalType.DATE)

    @Column(name = "expiration", nullable = true)
    private Date expiration;

    @Basic
    @Column(name = "cvv", nullable = true, length = 3)
    private String cvv;

    @Basic
    @Column(name = "total", nullable = true)
    private float total;

    @OneToOne(mappedBy = "payment")
    private Order order;

    @OneToOne(mappedBy = "payment")
    private TheReturn theReturn;
}

OrderService:

@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private ProductInOrderRepository productInOrderRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false)
    public Order addOrder(Order order) throws ProductUnavailableException, EmptyOrderException, UserNotFoundException, CartNotFoundException, CartAlreadyExistsException{//

        if(order.getProductsInOrder()==null || order.getProductsInOrder().size()<=0){
            throw new EmptyOrderException();
        }
        if(!userRepository.existsById(order.getBuyer().getId())){
            throw new UserNotFoundException();
        }

        if(!cartRepository.existsById(order.getCart().getId())){
            throw new CartNotFoundException();
        }

        if(orderRepository.findByCart(order.getCart())!=null){
            throw new CartAlreadyExistsException();
        }
        Order result = orderRepository.save(order);
        for(ProductInOrder p : result.getProductsInOrder()){
            p.setOrder(result);
            ProductInOrder justAdded = productInOrderRepository.save(p);

            entityManager.refresh(justAdded);
            Product product = justAdded.getProduct();
            int newQuantity = product.getQuantity() - p.getQuantity();
            if(newQuantity < 0){
                orderRepository.delete(order);
                p.setOrder(null);
                productInOrderRepository.delete(p);
                throw new ProductUnavailableException(product);
            }
            product.setQuantity(newQuantity);
            entityManager.refresh(p);
        }
        entityManager.refresh(result);
        return result;
    }

OrderController:

@RestController
@RequestMapping("/orders")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/createOrder")
    @ResponseStatus(code = HttpStatus.OK)
    public ResponseEntity create(@RequestBody @Valid Order order){//Funziona
    //System.out.println("Ordine in orderController: "+order+"\n");
        try{
            return new ResponseEntity<>(orderService.addOrder(order), HttpStatus.OK);
        }catch (ProductUnavailableException e){
            return new ResponseEntity<>(new ResponseMessage("The quantity of product: "+e.getProduct().getName()+" is unavailable!"), HttpStatus.BAD_REQUEST);
        } catch (EmptyOrderException e) {
            return new ResponseEntity<>(new ResponseMessage("The order has no products."), HttpStatus.BAD_REQUEST);
        } catch (UserNotFoundException e) {
            return new ResponseEntity<>(new ResponseMessage("User not found."), HttpStatus.BAD_REQUEST);
        } catch (CartNotFoundException e) {
            return new ResponseEntity<>(new ResponseMessage("Cart not found."), HttpStatus.BAD_REQUEST);
        } catch (CartAlreadyExistsException e) {
            return new ResponseEntity<>(new ResponseMessage("Cannot associate the same cart cart to more than one order."), HttpStatus.BAD_REQUEST);
        }
    }

PaymentService:

@Service
public class PaymentService {

    @Autowired
    private PaymentRepository paymentRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private EntityManager entityManager;

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
    public Payment addPayment(Payment p) throws PaymentAlreadyExistsException, IncorrectCardNumberException, IncorrectCvvException{//
        if(paymentRepository.existsByCardNumber(p.getCardNumber())){
            throw new PaymentAlreadyExistsException();
        }
        if(p.getCardNumber().length()!=16){
            throw new IncorrectCardNumberException();
        }
        if(p.getCvv().length()!=3)
        {
            throw new IncorrectCvvException();
        }
        Order newOrder = new Order();
        newOrder.setPayment(p);
        Order justAdded=orderRepository.save(newOrder);
        entityManager.refresh(justAdded);
        p.setOrder(justAdded);
        return paymentRepository.save(p);
    }

PaymentController:

@RestController
@RequestMapping("/payments")
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @PostMapping("/createPayment")//funziona
    public ResponseEntity<Payment> create(@RequestBody @Valid Payment payment){
        System.out.print("Sono in paymentController.");
        try {
            Payment added=paymentService.addPayment(payment);
            return new ResponseEntity<>(added, HttpStatus.OK);
        } catch (PaymentAlreadyExistsException e) {
            return new ResponseEntity(new ResponseMessage("Payment already exists!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCardNumberException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect card number!"), HttpStatus.BAD_REQUEST);
        } catch (IncorrectCvvException e) {
            return new ResponseEntity(new ResponseMessage("Incorrect CVV"), HttpStatus.BAD_REQUEST);
        }
}

FRONT-END

payment.component.html (in this html file there is the click event I was talking about):

<form #paymentForm="ngForm">

    OwnerName*
    <input type="text" ngModel name="ownerName" class="form-control" id="ownerName" placeholder="OwnerName" required>

    OwnerLastName*
    <input type="text" ngModel name="ownerLastName" class="form-control" id="ownerLastName" placeholder="OwnerLastName" required>

     CardNumber*
     <input type="text" ngModel name="cardNumber" class="form-control" id="cardNumber" placeholder="CardNumber" required>

     Cvv*
     <input type="text" ngModel name="cvv" class="form-control" id="cvv" placeholder="cvv" required>

    Expiration*
    <input type="date" ngModel name="expiration" class="form-control" id="expiration" placeholder="expiration" required>

(Tutti i campi contrassegnati con * devono essere riempiti)

     <button [disabled]="paymentForm.invalid" type="submit" class="btn btn-primary" (click)="createPayment('Payment successful!', 'ok', paymentForm)" routerLink="/orders"  routerLinkActive="active">Pay</button>

  </form>

payment.component.ts:

export class PaymentComponent implements OnInit {
  public total:number=0;
  public payment!: Payment;
  ownerNameFormControl = new FormControl('', [Validators.required]);
  ownerLastNameFormControl = new FormControl('', [Validators.required]);
  constructor(private _snackBar: MatSnackBar, private paymentService:PaymentService, private shared: SharedService) { }

  ngOnInit(): void {
    this.shared.castTotal.subscribe(total=>this.total=total);
    this.shared.castPayment.subscribe(payment=>this.payment=payment);
  }
  public createPayment(message:string, action:string, createForm:NgForm ) {
    this.paymentService.createPayment(createForm.value).subscribe(
      (response: Payment) => {
        this.payment=response;
        this.shared.setPayment(this.payment);
        console.log(response);
        this._snackBar.open(message, action);
        createForm.reset();

      },
      (error: HttpErrorResponse)=>{
        alert(error.message);
        createForm.reset();
      }
    )
  }
}

payment.service.ts:

@Injectable({
  providedIn: 'root'
})
export class PaymentService {

  constructor(private http: HttpClient) { }

  public createPayment(payment: Payment): Observable<Payment> {
    console.log("Sono in payment service");
    return this.http.post<Payment>('http://localhost:8080/payments/createPayment', payment);
  }

shared.service.ts:

export class SharedService {
  public defaultPayment!: Payment;
  private payment= new BehaviorSubject<Payment>(this.defaultPayment);
  castPayment = this.payment.asObservable();

  constructor() { }

   setPayment(data: Payment){
      this.payment.next(data);   }

order.component.ts:

export class OrderComponent implements OnInit {
  public payment!: Payment;
  public cart!: Cart;
  displayedColumns = ['img', 'name', 'description', 'price', 'quantity'];
  constructor(private shared: SharedService) { }

  ngOnInit(): void {
    this.shared.castPayment.subscribe(payment=>this.payment=payment);
    this.shared.castCart.subscribe(cart=>this.cart=cart);
  }

}

order.service.ts:

export class OrderService {

  constructor(private http: HttpClient) { }

  public createOrder(order: Order): Observable<void> {
    return this.http.post<void>('http://localhost:8080/orders/createOrder', order);
  }

payment.ts:

export interface Payment{
  id: number;
  ownerName: string;
  ownerLastName: string;
  cardNumber: string;
  expiration: Date;
  cvv: string;
  total: number;
  order: Order;
  theReturn: TheReturn;

}

Body:
Sending a request from FE to BE has essentially 2 steps:

FE sends request to backend:

As you can see in this example from the Angular documentation:

/** POST: add a new hero to the database */
addHero(hero: Hero): Observable<Hero> {
  return this.http.post<Hero>(`http://localhost:portNumber/hero`, hero, httpOptions)
    .pipe(
      catchError(this.handleError('addHero', hero))
    );
}

You just send the object that has all the fields you need to the backend. When it is sent - it is sent as JSON which means if the Hero class has fields name and power it will be sent like this:

{
  "name": "Superman",
  "power": "Can disguise himself by wearing glasses"
}

Consume it on the backend side:

In Spring Controller you just need to define a controller method that expects an object with the same fields. Spring has a dependency of Jackson which automatically will deserialize JSON for you, so as I said you just need to create a DTO that has all the fields you need.

class HeroDTO {
  private String name;
  private String power;

  //getters, setters and noArg constructor - important to have for deserialization to work!
}

and then in controller method:

@PostMapping(value = "/hero", produces = APPLICATION_JSON_VALUE)
public ResponseEntity createHero(@RequestBody HeroDTO heroDTO) {
    //do whatever
}

btw you might get CORS errors - that is normal and CORS can be disabled by adding @CrossOrigin to the top of your Controller. More here


问:
Is there a simple way to test a migration before running it?
In other words I'd like to know the best way to make sure that self.down actually rolls back self.up before running the migration in question.

What can I do if I need to rollback a migration but self.down doesn't serve the purpose?

Which is the best practice when dealing with potentially destructive migrations?
Just a database backup?

Thanks,
Duccio.

答:
Each migration runs inside a transaction. Keep that in mind. That means that if something would go wrong inside a single migration, the migration is rolled back (and if there are any following they are not executed).

To test migrations, be it up or down I insert a lot of puts-statements, to check everything has worked has supposed to, and then in my last line I raise an exception. This will make rails think the migration has failed, and it will rollback the operation (as if it never happened).

When I am sure everything works as it should, I remove the raise line and let the migration really work.
In your case, you would test with the raise, remove the raise and NOT run it again I assume :)

Hope this helps.


问:
How to cope with this error while compiling latex with vscode?
I followed several tutorials on the Internet and tried to build a latex environment in vscode. However, after I've installed everything and started running a .tex file, it came up with the following error:

```<code>Qt: Untested Windows version 6.2 detected!
xelatex: Bad parameter value.
xelatex: Data: font_mem_size
</code>```

source code test.tex: (I put it in a folder on desktop)

```<code>\documentclass{article}
\begin{document}
    Hello World!
\end{document}
</code>```

I tried Google, but didn't find any effective approach. I also restarted my computer and reinstalled MiKTeX, but nothing changed.

By the way: I installed LaTeX workshop, MiKTeX and Strawberry Perl (just following the tutorial) and added this into the settings.json of vscode.

```<code>"latex-workshop.latex.tools": [
        {
            "name": "xelatex",
            "command": "xelatex",
            "args": [
                "-synctex=1",
                "-interaction=nonstopmode",
                "-file-line-error",
                "%DOCFILE%"
            ]
        },
        {
            "name": "pdflatex",
            "command": "pdflatex",
            "args": [
                "-synctex=1",
                "-interaction=nonstopmode",
                "-file-line-error",
                "%DOCFILE%"
            ]
        },
        {
            "name": "bibtex",
            "command": "bibtex",
            "args": [
                "%DOCFILE%"
            ]
        }
    ],
    "latex-workshop.latex.recipes": [
        {
            "name": "xelatex",
            "tools": [
                "xelatex"
            ],
        },
        {
            "name": "pdflatex",
            "tools": [
                "pdflatex"
            ]
        },
        {
            "name": "xe->bib->xe->xe",
            "tools": [
                "xelatex",
                "bibtex",
                "xelatex",
                "xelatex"
            ]
        },
        {
            "name": "pdf->bib->pdf->pdf",
            "tools": [
                "pdflatex",
                "bibtex",
                "pdflatex",
                "pdflatex"
            ]
        }
    ],
    "latex-workshop.view.pdf.viewer": "tab",
    "latex-workshop.latex.autoBuild.run": "onFileChange",
    "latex-workshop.message.error.show": false,
    "latex-workshop.message.warning.show": false,
</code>```

Update: the issue was solved by reinstalling MiKTeX and resetting its environment variables in PATH.

答: The issue was eventually solved by reinstalling MiKTeX and resetting its environment variables in PATH. (Another way is to directly install MiKTeX in its recommended directory, which is how I solved the problem.) In addition, the code I added in the settings.json should be discarded (or vscode will report errors).

Body:
I followed several tutorials on the Internet and tried to build a latex environment in vscode. However, after I've installed everything and started running a .tex file, it came up with the following error:

Qt: Untested Windows version 6.2 detected!
xelatex: Bad parameter value.
xelatex: Data: font_mem_size

source code test.tex: (I put it in a folder on desktop)

\documentclass{article}
\begin{document}
    Hello World!
\end{document}

I tried Google, but didn't find any effective approach. I also restarted my computer and reinstalled MiKTeX, but nothing changed.

By the way: I installed LaTeX workshop, MiKTeX and Strawberry Perl (just following the tutorial) and added this into the settings.json of vscode.

"latex-workshop.latex.tools": [
        {
            "name": "xelatex",
            "command": "xelatex",
            "args": [
                "-synctex=1",
                "-interaction=nonstopmode",
                "-file-line-error",
                "%DOCFILE%"
            ]
        },
        {
            "name": "pdflatex",
            "command": "pdflatex",
            "args": [
                "-synctex=1",
                "-interaction=nonstopmode",
                "-file-line-error",
                "%DOCFILE%"
            ]
        },
        {
            "name": "bibtex",
            "command": "bibtex",
            "args": [
                "%DOCFILE%"
            ]
        }
    ],
    "latex-workshop.latex.recipes": [
        {
            "name": "xelatex",
            "tools": [
                "xelatex"
            ],
        },
        {
            "name": "pdflatex",
            "tools": [
                "pdflatex"
            ]
        },
        {
            "name": "xe->bib->xe->xe",
            "tools": [
                "xelatex",
                "bibtex",
                "xelatex",
                "xelatex"
            ]
        },
        {
            "name": "pdf->bib->pdf->pdf",
            "tools": [
                "pdflatex",
                "bibtex",
                "pdflatex",
                "pdflatex"
            ]
        }
    ],
    "latex-workshop.view.pdf.viewer": "tab",
    "latex-workshop.latex.autoBuild.run": "onFileChange",
    "latex-workshop.message.error.show": false,
    "latex-workshop.message.warning.show": false,

Update: the issue was solved by reinstalling MiKTeX and resetting its environment variables in PATH.


问:
flutter scrollable modal bottom sheet
Is there a way to make the ModalBottomSheet with a fixed heigh i don't want it's height to expand when scrolling

This is the code i used

```<code>showModalBottomSheet(
               context: context,
               isScrollControlled: true,
               backgroundColor: Colors.transparent,
                 builder: (context) => DraggableScrollableSheet(
                 builder: (BuildContext context,
               ScrollController scrollController) {
               return Container(
               color: Colors.blue[100],
               child: ListView.builder(
               controller: scrollController,
               itemCount: 25,
               itemBuilder:(BuildContext context,int index) {
                return ListTile(
                        title: Text('Item $index'));
               },
             ),
          );
        },
     ),
    );
</code>```

答:
You can remove the DraggableScrollableSheet. That widget allows for the height expanding I think. So after removing it, you can set a height on the container</p>
```<code>final double height = 200;
showModalBottomSheet(
       context: context,
       backgroundColor: Colors.transparent,
       builder: (context){
       return Container(
         height: height,
         color: Colors.blue[100],
         child: ListView.builder(
         itemCount: 25,
         itemBuilder:(BuildContext context,int index) {
          return ListTile(
                  title: Text('Item $index'));
         }
      )
    );
  },
);
</code>```

Title: flutter scrollable modal bottom sheet

Body:
Is there a way to make the ModalBottomSheet with a fixed heigh i don't want it's height to expand when scrolling

This is the code i used

showModalBottomSheet(
               context: context,
               isScrollControlled: true,
               backgroundColor: Colors.transparent,
                 builder: (context) => DraggableScrollableSheet(
                 builder: (BuildContext context,
               ScrollController scrollController) {
               return Container(
               color: Colors.blue[100],
               child: ListView.builder(
               controller: scrollController,
               itemCount: 25,
               itemBuilder:(BuildContext context,int index) {
                return ListTile(
                        title: Text('Item $index'));
               },
             ),
          );
        },
     ),
    );

Body:
You can remove the DraggableScrollableSheet. That widget allows for the height expanding I think. So after removing it, you can set a height on the container

final double height = 200;
showModalBottomSheet(
       context: context,
       backgroundColor: Colors.transparent,
       builder: (context){
       return Container(
         height: height,
         color: Colors.blue[100],
         child: ListView.builder(
         itemCount: 25,
         itemBuilder:(BuildContext context,int index) {
          return ListTile(
                  title: Text('Item $index'));
         }
      )
    );
  },
);


问:
LAB: Output values in a list below a user defined amount
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, which indicates a threshold. Output all integers less than or equal to that last threshold value.

Ex: If the input is:

```<code>5
50
60
140
200
75
100
</code>```

the output is:

```<code>50,60,75,
</code>```

The 5 indicates that there are five integers in the list, namely 50, 60, 140, 200, and 75. The 100 indicates that the program should output all integers less than or equal to 100, so the program outputs 50, 60, and 75.

For coding simplicity, follow every output value by a comma, including the last one.

Such functionality is common on sites like Amazon, where a user can filter results.

My code is:

```<code>n = int(input())
user_values =[]

def get_user_values():
    for i in range(n):
        num = int(input())
        user_values.append(num)
        upper_threshold=user_values[-1]
    return user_values, upper_threshold

def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
    user_values = [i for i in user_values if i <= upper_threshold]
    print(*user_values, sep = "\n")

if __name__ == '__main__':
    user_values, upper_threshold = get_user_values()
    output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold)
</code>```

With inputs:

```<code>7
25
30
47
28
27
25
31
30
</code>```

My output:

```<code>25
30
28
27
25
31
</code>```

But my expected output:

```<code>25,30,28,27,25,
</code>```

答:
def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
    for value in user_values:
        if value <= upper_threshold:
            print(value, end="," )

def get_user_values():
    n = int(input())
    lst = []
    for i in range(n):
        lst.append(int(input()))
    return lst

if __name__ == '__main__':
    userValues = get_user_values()
    upperThreshold = int(input())
    output_ints_less_than_or_equal_to_threshold(userValues, upperThreshold)
```

Body:
Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, which indicates a threshold. Output all integers less than or equal to that last threshold value.

Ex: If the input is:

5
50
60
140
200
75
100

the output is:

50,60,75,

The 5 indicates that there are five integers in the list, namely 50, 60, 140, 200, and 75. The 100 indicates that the program should output all integers less than or equal to 100, so the program outputs 50, 60, and 75.

For coding simplicity, follow every output value by a comma, including the last one.

Such functionality is common on sites like Amazon, where a user can filter results.

My code is:

n = int(input())
user_values =[]

def get_user_values():
    for i in range(n):
        num = int(input())
        user_values.append(num)
        upper_threshold=user_values[-1]
    return user_values, upper_threshold

def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
    user_values = [i for i in user_values if i <= upper_threshold]
    print(*user_values, sep = "\n")

if __name__ == '__main__':
    user_values, upper_threshold = get_user_values()
    output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold)

With inputs:

7
25
30
47
28
27
25
31
30

My output:

25
30
28
27
25
31

But my expected output:

25,30,28,27,25,


答: You can give your container that is currently blue coloured. a fixed height say height:200.. And you also need to remove draggable scrollable sheet builder from you bottom sheet.</p>

Title: flutter scrollable modal bottom sheet


问:
Close all instances of Http connection
I have used Java applet for developing an application which has the option of uploading of multiple files simultaneously.

Multiple threads are handling the simultaneous upload of files.

When the user clicks on the Cancel button , all the uploads should get cancelled.

I am using HttpMethod for uploading over http connection.

What approach should I follow to close all the instances of http connection at the same time?

I closed the connection manager as follows when the user clicks on the Cancel button to stop all the connections:

```<code>manager = new MultiThreadedHttpConnectionManager();
manager.shutdownAll()
</code>```

But when the user again clicks once again on the Start button , I am trying to create a new instance of connection manager but unable to do so.

I am getting the error

```<code>java.lang.IllegalStateException: Connection factory has been shutdown
</code>```

Also , I tried with the Thread.interrupt() but its not working accordingly i.e. not interrupting all the threads.

Any suggestions/hints will be helpful.

答:
If thread A is blocked inside a socket, you should be able have another thread (I'll call it 'B') close that socket and unblock 'A'.  I don't recall exactly how this works in HttpClient but it uses sockets under the hood so it should still apply.

A single thread 'B' should be able unblock all the sockets sequentially.  This is likely overkill but if there's a concern that something could get stuck in close(), you can spawn a separate thread for each blocked socket.

Title: Close all instances of Http connection

Body:
I have used Java applet for developing an application which has the option of uploading of multiple files simultaneously.

Multiple threads are handling the simultaneous upload of files.

When the user clicks on the Cancel button , all the uploads should get cancelled.

I am using HttpMethod for uploading over http connection.

What approach should I follow to close all the instances of http connection at the same time?

I closed the connection manager as follows when the user clicks on the Cancel button to stop all the connections:

manager = new MultiThreadedHttpConnectionManager();
manager.shutdownAll()

But when the user again clicks once again on the Start button , I am trying to create a new instance of connection manager but unable to do so.

I am getting the error

java.lang.IllegalStateException: Connection factory has been shutdown

Also , I tried with the Thread.interrupt() but its not working accordingly i.e. not interrupting all the threads.

Any suggestions/hints will be helpful.


问:
Gradle Signing plugin
I am trying to use Gradle's signing plugin with "in memory" keys[1], but am having difficulty understanding which values to use where.  I have the following:

```<code>$ gpg --list-keys --keyid-format=long
...
----------------------------------
pub <PUB>
uid ...
sub <SUB>

$ export GPG_KEY=$(gpg --armor --export <PUB>)
</code>```

along with this build fragment

```<code>signing {
  sign publishing.publications.publishedArtifacts

  def signingKeyId = findProperty('signingKeyId')
  def signingKey = findProperty('signingKey')
  def signingPassword = findProperty('signingPassword')
  useInMemoryPgpKeys(signingKeyId, signingKey, signingPassword)
}
</code>```

I'm sure much of this is my limited knowledge of GPG and PGP, but as I understand it, when the plugin doc talks about "signingKey", that is my $GPG_KEY variable.

I am a bit unclear about what the doc calls "signingKeyId" - whether that is <PUB> or .  I've tried both and get the same error either way.

```<code>$ gradlew sign -PsigningKeyId=<PUB> -PsigningKey="$GPG_KEY" -PsigningPassword=...

> Error while evaluating property 'signatory' of task ':hibernate-core:signPublishedArtifactsPublication'
   > Could not read PGP secret key
</code>```

I've also tried the form without passing a key-id - still same result.  So I am clearly not understanding something here.

```<code>$ gradlew --version

------------------------------------------------------------
Gradle 7.3.3
------------------------------------------------------------

Build time:   2021-12-22 12:37:54 UTC
Revision:     6f556c80f945dc54b50e0be633da6c62dbe8dc71

Kotlin:       1.5.31
Groovy:       3.0.9
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          11.0.6 (AdoptOpenJDK 11.0.6+10)
OS:           Linux 5.15.12-100.fc34.x86_64 amd64

</code>```

[1] either https://docs.gradle.org/current/userguide/signing_plugin.html#sec:in-memory-keys or https://docs.gradle.org/current/userguide/signing_plugin.html#using_in_memory_ascii_armored_openpgp_subkeys

答:
If you do gpg --armor --export there are two signs that show you, that you are using the wrong command.

you are not asked for a passphrase, so it would be shocking if you could access the secret key

if you look at the output, you see that the ASCII armor says PGP PUBLIC KEY BLOCK

The docs you linked to say, you need to provide the secret key, which of course makes sense, as you want to sign something with your secret key, not encrypt it for a specific recipient for which you would need that persons public key. If you specify the id of the parent key it should use the parent key if you leave out the key id it also uses the parent key.

If you replace --export by --export-secret-key (yes, this option is not shown in the --help output), then you get the secret key exported instead after being asked for your passphrase, which is what you need for signing.

The key id you only need if you want to sign with the subkey.
As a parent key can have multiple subkeys you have to tell which subkey to use and thus have to give the id of the subkey, not the id of the parent key.
iirc it should also just be the part after the slash, before the slash is just the algorithm.

Title: Gradle Signing plugin

Body:
I am trying to use Gradle's signing plugin with "in memory" keys[1], but am having difficulty understanding which values to use where.  I have the following:

$ gpg --list-keys --keyid-format=long
...
----------------------------------
pub <PUB>
uid ...
sub

$ export GPG_KEY=$(gpg --armor --export <PUB>)

along with this build fragment

signing {
  sign publishing.publications.publishedArtifacts

  def signingKeyId = findProperty('signingKeyId')
  def signingKey = findProperty('signingKey')
  def signingPassword = findProperty('signingPassword')
  useInMemoryPgpKeys(signingKeyId, signingKey, signingPassword)
}

I'm sure much of this is my limited knowledge of GPG and PGP, but as I understand it, when the plugin doc talks about "signingKey", that is my $GPG_KEY variable.

I am a bit unclear about what the doc calls "signingKeyId" - whether that is <PUB> or .  I've tried both and get the same error either way.

$ gradlew sign -PsigningKeyId=<PUB> -PsigningKey="$GPG_KEY" -PsigningPassword=...

> Error while evaluating property 'signatory' of task ':hibernate-core:signPublishedArtifactsPublication'
   > Could not read PGP secret key

I've also tried the form without passing a key-id - still same result.  So I am clearly not understanding something here.

$ gradlew --version

------------------------------------------------------------
Gradle 7.3.3
------------------------------------------------------------

Build time:   2021-12-22 12:37:54 UTC
Revision:     6f556c80f945dc54b50e0be633da6c62dbe8dc71

Kotlin:       1.5.31
Groovy:       3.0.9
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          11.0.6 (AdoptOpenJDK 11.0.6+10)
OS:           Linux 5.15.12-100.fc34.x86_64 amd64

[1] either https://docs.gradle.org/current/userguide/signing_plugin.html#sec:in-memory-keys or https://docs.gradle.org/current/userguide/signing_plugin.html#using_in_memory_ascii_armored_openpgp_subkeys


问:
How can I make my bot delete part of this json file
I'm trying to make my bot remove data from a json file after the command is sent but I'm having difficulty deleting the one piece of data from the json file. It'd be great if someone could help me out with this.

```<code>@client.command(name='redeem', pass_content=True)
async def redeem(message, code):
  with open('keys.json') as f:
    data = json.load(f)
    if code in data:
      ----delete some json data here
      role = message.guild.get_role(910056424812466176)
      await message.author.add_roles(role)
      await message.author.send("message here")
      hwidchannel = client.get_channel(909907655324205088)
      def check(m):
        print("message detected")
        if isinstance(m.channel,
        discord.channel.DMChannel):
          print("is dm")
          if  m.author.id == message.author.id:
            print("correct user")
            return hwidchannel == hwidchannel
      msg = await client.wait_for('message', check=check)
      await message.author.send('Please be patient as your purchase is reviewed.')
      await hwidchannel.send('Hwid is {.content}'.format(msg))
      await hwidchannel.send('Userid is {.author.id}'.format(msg))
    else:
      await message.author.send("Invalid Code")
</code>```

Json file:

```<code>{
  "3fswgtwdfe":"wasd",
  "29jyf382ff":"wasd"
}
</code>```

答:
The simplest take on this is:

```<code>data['urcode']=None
</code>```

But will probably cause some errors when using the data.
You can use the data.pop() instead:

```<code>data.pop("urcode")
</code>```

Then update the file:

```<code>with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)
    #Indent is optional, just makes the file look cleaner.
</code>```

Body:
I'm trying to make my bot remove data from a json file after the command is sent but I'm having difficulty deleting the one piece of data from the json file. It'd be great if someone could help me out with this.

@client.command(name='redeem', pass_content=True)
async def redeem(message, code):
  with open('keys.json') as f:
    data = json.load(f)
    if code in data:
      ----delete some json data here
      role = message.guild.get_role(910056424812466176)
      await message.author.add_roles(role)
      await message.author.send("message here")
      hwidchannel = client.get_channel(909907655324205088)
      def check(m):
        print("message detected")
        if isinstance(m.channel,
        discord.channel.DMChannel):
          print("is dm")
          if  m.author.id == message.author.id:
            print("correct user")
            return hwidchannel == hwidchannel
      msg = await client.wait_for('message', check=check)
      await message.author.send('Please be patient as your purchase is reviewed.')
      await hwidchannel.send('Hwid is {.content}'.format(msg))
      await hwidchannel.send('Userid is {.author.id}'.format(msg))
    else:
      await message.author.send("Invalid Code")

Json file:

{
  "3fswgtwdfe":"wasd",
  "29jyf382ff":"wasd"
}

Body:
The simplest take on this is:

data['urcode']=None

But will probably cause some errors when using the data.
You can use the data.pop() instead:

data.pop("urcode")

Then update the file:

with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)
    #Indent is optional, just makes the file look cleaner.


答:
You are trying to combine lists, but you want data frames. To understand the difference, see this post: What is difference between dataframe and list in R?. To fix it, store the objects as data frames rather than lists before combining.</p>
```<code>df1 = as.data.frame(11:20)
df1.Temp1 = as.data.frame(Predictedmodel_1$fitted)
df1.Temp2 = as.data.frame(Predictedmodel_2$fitted)
df1.Temp3 = as.data.frame(Predictedmodel_3$fitted)

df1 = cbind(df1,df1.Temp1,df1.Temp2,df1.Temp3)

colnames(df1) = c("Col1","col2","col3","col4")
</code>```

Title: Save fitted and predicted values to data frame in r

Body:
I am trying to extract the fitted and predicted values from the different classes of the object. But when I save them to a column in a data frame I got a column with NA. I tried to fix that by making the fitted value numeric, a data frame. But when it comes to saving the values in a data frame I still got the NA or errors. Adjusting the number of rows did neither helped.

This is my code:
library(forecast)

#generate time series
b=sin(runif(10, min=0, max=100))
plot(b,type="l")
#initiate data frame for fitted values
df1= data.frame(matrix(ncol =3, nrow=10))
colnames(df1)=c("month","Fit1", "Fit2", "Fit3")

#initiate data frame for predicted values
df2= data.frame(matrix(ncol =3, nrow=4))
colnames(df1)=c("month","Pred1", "Pred2","Pred3" )

#find model for time series
model_1= arima(b)
model_2=naive(b)
model_3=HoltWinters(ts(b, frequency=4))

#store fitted values in data frame
df1[,1]=1:10
df1[,2]=model_1$fitted
df1[,3]=model_2$fitted
df1[,4]=model_3$xhat

#find short term predicted values for 4 periods
Predictedmodel_1= forecast(model_1, 4)#
Predictedmodel_2= forecast(model_2, 4)#
Predictedmodel_3= forecast(model_3, 4)#

#store predicted values in data frame
df2[,1]=11:14
df2[,2]=Predictedmodel_1$fitted
df2[,3]=Predictedmodel_2$fitted
df2[,4]=Predictedmodel_3$fitted

Can somebody help me pls?

Body:
You are trying to combine lists, but you want data frames. To understand the difference, see this post: What is difference between dataframe and list in R?. To fix it, store the objects as data frames rather than lists before combining.

df1 = as.data.frame(11:20)
df1.Temp1 = as.data.frame(Predictedmodel_1$fitted)
df1.Temp2 = as.data.frame(Predictedmodel_2$fitted)
df1.Temp3 = as.data.frame(Predictedmodel_3$fitted)

df1 = cbind(df1,df1.Temp1,df1.Temp2,df1.Temp3)

colnames(df1) = c("Col1","col2","col3","col4")


问:
How to iterate through inputs with a while loop?
This problem has been posted before, but I'm having trouble translating what I've currently coded into a while loop as per professor instructions. The problem is:

```<code>Write a program that first gets a list of integers from input. The input begins
with an integer indicating the number of integers that follow. Then, get the
last value from the input, which indicates a threshold. Output all integers less
than or equal to that last threshold value.

Ex: If the input is:

5
50
60
140
200
75
100

The output is:

50,60,75

The 5 indicates that there are five integers in the list, namely 50,
60, 140, 200, and 75. The 100 indicates that the program should output all
integers less than or equal to 100, so the program outputs 50, 60, and 75.

For coding simplicity, follow every output value by a comma, including the last one.

Such functionality is common on sites like Amazon, where a user can filter results.
</code>```

My current code includes a "for" loop at the end:

```<code>make_string = []

while True:
  user_input = int(input())
  make_string.append(int(user_input))

  if len(make_string) > (int(make_string[0]) + 1):
    break

end_num = make_string[-1]

make_string.pop(0)
make_string.pop(-1)

for val in make_string:
  if val <= end_num:
    print(val, end=", ")

</code>```

Is there any way to translate that last for loop into a while loop to satisfy my professor's requirement?

答:
I just had the same problem. The answer is as follows...</p>
```<code>def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
   for value in user_values:
       if value <= upper_threshold:
           print(value, end="," )
def get_user_values():
   n = int(input())
   lst = []
   for i in range(n):
       lst.append(int(input()))
   return lst
if __name__ == '__main__':
   userValues = get_user_values()
   upperThreshold = int(input())
   output_ints_less_than_or_equal_to_threshold(userValues, upperThreshold)

</code>```

Body:
This problem has been posted before, but I'm having trouble translating what I've currently coded into a while loop as per professor instructions. The problem is:

Write a program that first gets a list of integers from input. The input begins
with an integer indicating the number of integers that follow. Then, get the
last value from the input, which indicates a threshold. Output all integers less
than or equal to that last threshold value.

Ex: If the input is:

5
50
60
140
200
75
100

The output is:

50,60,75

The 5 indicates that there are five integers in the list, namely 50,
60, 140, 200, and 75. The 100 indicates that the program should output all
integers less than or equal to 100, so the program outputs 50, 60, and 75.

For coding simplicity, follow every output value by a comma, including the last one.

Such functionality is common on sites like Amazon, where a user can filter results.

My current code includes a "for" loop at the end:

make_string = []

while True:
  user_input = int(input())
  make_string.append(int(user_input))

  if len(make_string) > (int(make_string[0]) + 1):
    break

end_num = make_string[-1]

make_string.pop(0)
make_string.pop(-1)

for val in make_string:
  if val <= end_num:
    print(val, end=", ")

Is there any way to translate that last for loop into a while loop to satisfy my professor's requirement?

Body:
I just had the same problem. The answer is as follows...

def output_ints_less_than_or_equal_to_threshold(user_values, upper_threshold):
   for value in user_values:
       if value <= upper_threshold:
           print(value, end="," )
def get_user_values():
   n = int(input())
   lst = []
   for i in range(n):
       lst.append(int(input()))
   return lst
if __name__ == '__main__':
   userValues = get_user_values()
   upperThreshold = int(input())
   output_ints_less_than_or_equal_to_threshold(userValues, upperThreshold)


问:
How to by pass Javascript check while hitting an URL in Postman or HttpLibrary?
I'm trying to hit an URL and upon hitting that I will hit consecutive URLs.

Both in Postman and Ruby (I'm using NET HTTP), I'm getting an error saying, "enable Javascript for website to function properly".

But in browser, everything works fine.
In browser, if I turn off javascript, I see the same error.

Question:
Is it possible to simulate same browser experience in Postman or Ruby NET:HTTP ?

答:
No, it's not possible. Not with NET::HTTP. You actually need to run the browser. But you can run it in a headless mode!

Fortunately, in Ruby there are some great gems that allow you to achieve that. Myself, I most often use Ferrum, which runs Chromium in the background and allows you to interface with the website using an extended Nokogiri API. Ferrum uses the CDP protocol to interface with Chromium and possibly Firefox.

In the past I have used Watir which basically wraps Selenium WebDriver with a nicer API and works with all the browsers. Your mileage may vary with this, I had a lot easier time with Ferrum and Ferrum provides a Nokogiri-compatible API, while Watir doesn't. On the other hand, Watir is a lot more mature.

I have tried puppeteer-ruby, which is mostly a port of the JavaScript puppeteer library. Like Ferrum, it also uses the CDP interface, but it may provide a better support than Ferrum for various features, because as a port of puppeteer, it contains a lot of knowledge that was put into puppeteer which is widely used. It's quite new, but very interesting.


问:
remove digits NOT between brackets - regex
I am trying to write a regular expression in python to remove digits except those between brackets
here is an example : "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."

I would like : "[Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from .."

答:
Can you try this regex r'(?<!\[)\d+(?!\])'?

st = "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."
st = re.sub(r'\[\D*\d+\D*\]|(?<!\[)\d+(?!\])', lambda x: x.group(0) if x.group(0).startswith('[') else '', st)

# [Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from ..
print(st)
```

(?<!\[) and (?!\]) are matches if \d+ NOT preceded by [ and NOT followed by ], respectively.

Body:
Can you try this regex r'(?<!\[)\d+(?!\])'?

st = "[Verse 1: Bankroll Fresh] Dope boy, '[9]5 Air Max on Came from 1952.."
st = re.sub(r'\[\D*\d+\D*\]|(?<!\[)\d+(?!\])', lambda x: x.group(0) if x.group(0).startswith('[') else '', st)

# [Verse 1: Bankroll Fresh] Dope boy, '[9] Air Max on Came from ..
print(st)

(?<!\[) and (?!\]) are matches if \d+ NOT preceded by [ and NOT followed by ], respectively.


问:
Find first non-zero value in each column of pandas DataFrame
What is a pandoric way to get a value and index of the first non-zero element in each column of a DataFrame (top to bottom)?

```<code>import pandas as pd

df = pd.DataFrame([[0, 0, 0],
                   [0, 10, 0],
                   [4, 0, 0],
                   [1, 2, 3]],
                  columns=['first', 'second', 'third'])

print(df.head())

#    first  second  third
# 0      0       0      0
# 1      0      10      0
# 2      4       0      0
# 3      1       2      3
</code>```

What I would like to achieve:

```<code>#        value  pos
# first      4    2
# second    10    1
# third      1    3
</code>```

答:
You can also use Numpy's nonzero function for this.

positions = [df[col].to_numpy().nonzero()[0][0] for col in df]
df_res = pd.DataFrame({'value': df.to_numpy()[(positions, range(3))],
                       'position': positions}, index=df.columns)
print(df_res)

        value  position
first       4         2
second     10         1
third       3         3
```

Body:
What is a pandoric way to get a value and index of the first non-zero element in each column of a DataFrame (top to bottom)?

import pandas as pd

df = pd.DataFrame([[0, 0, 0],
                   [0, 10, 0],
                   [4, 0, 0],
                   [1, 2, 3]],
                  columns=['first', 'second', 'third'])

print(df.head())

#    first  second  third
# 0      0       0      0
# 1      0      10      0
# 2      4       0      0
# 3      1       2      3

What I would like to achieve:

#        value  pos
# first      4    2
# second    10    1
# third      1    3