问:
How to move cloned Arc into Rust Warp callback?
I'm trying to code a simple Warp server.

type Cache = Arc<RwLock<HashMap<String, String>>>;
pub struct App {
    cache: Cache,
    // other fields
}

impl App {
    pub async fn new() -> App { /* App init */ }

    pub async fn run(self) {
      let filter = warp::path!("cache" / String)
         .and(warp::any().map(move || self.cache.clone()))
         .and_then(handler);

      tokio::join!(
            foo(self.cache),
            warp::serve(filter).run(self.server_socket)
      )
      unreachable!()
    }
}

async fn handler(id: String, cache: Cache) -> Result<impl warp::Reply, warp::Rejection> {
  /* does stuff */
}
async fn foo(cache: Cache) { /* does stuff */ }

```
<p>When I try to compile it I get this error</p>
```error[E0382]: use of moved value: `self.cache`
foo(self.cache),
    ^^^^^^^^^^ value used here after move
```
<p>Ok, no problem. Trying cloning <code>self.cache</code> and then moving it to the <code>filter</code>.</p>
<pre class="lang-rust prettyprint-override"><code>pub async fn run(self) {
  let cache = self.cache.clone(); // cloning cache
  let filter =
    warp::path!("cache" / String)
      .and(warp::any().map(move || cache))  // trying to move cache
      .and_then(handler);

  tokio::join!(
     foo(self.cache),
     warp::serve(filter).run(self.server_socket)
  )
  unreachable!()
}
</code>```

And now I get this error

```<code>error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`

.and(warp::any().map(move || cache))
                 --- ^^^^^^^------
                 |   |       |
                 |   |       closure is `FnOnce` because it moves the variable `cache` out of its environment
                 |   this closure implements `FnOnce`, not `Fn`
                 |   the requirement to implement `Fn` derives from here
                 required by a bound introduced by this call
</code>```

I didn't find any ways to move cloned cache into filter. The only way I got this to work was by cloning cache two times.

pub async fn run(self) {
  let cache = self.cache.clone(); // first cloning
  let filter =
    warp::path!("cache" / String)
      .and(warp::any().map(move || cache.clone()))  // second cloning
      .and_then(handler);

  tokio::join!(
     foo(self.cache),
     warp::serve(filter).run(self.server_socket)
  )
  unreachable!()
}
```

I clone cache two times but the first clone is used just to perform the second cloning so I think this is wrong way to solve this problem. How to avoid double cloning?

Body:
I'm trying to code a simple Warp server.

type Cache = Arc<RwLock<HashMap<String, String>>>;
pub struct App {
    cache: Cache,
    // other fields
}

impl App {
    pub async fn new() -> App { /* App init */ }

    pub async fn run(self) {
      let filter = warp::path!("cache" / String)
         .and(warp::any().map(move || self.cache.clone()))
         .and_then(handler);

      tokio::join!(
            foo(self.cache),
            warp::serve(filter).run(self.server_socket)
      )
      unreachable!()
    }
}

async fn handler(id: String, cache: Cache) -> Result<impl warp::Reply, warp::Rejection> {
  /* does stuff */
}
async fn foo(cache: Cache) { /* does stuff */ }

When I try to compile it I get this error

error[E0382]: use of moved value: `self.cache`
foo(self.cache),
    ^^^^^^^^^^ value used here after move

Ok, no problem. Trying cloning self.cache and then moving it to the filter.

pub async fn run(self) {
  let cache = self.cache.clone(); // cloning cache
  let filter =
    warp::path!("cache" / String)
      .and(warp::any().map(move || cache))  // trying to move cache
      .and_then(handler);

  tokio::join!(
     foo(self.cache),
     warp::serve(filter).run(self.server_socket)
  )
  unreachable!()
}

And now I get this error

error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`

.and(warp::any().map(move || cache))
                 --- ^^^^^^^------
                 |   |       |
                 |   |       closure is `FnOnce` because it moves the variable `cache` out of its environment
                 |   this closure implements `FnOnce`, not `Fn`
                 |   the requirement to implement `Fn` derives from here
                 required by a bound introduced by this call

I didn't find any ways to move cloned cache into filter. The only way I got this to work was by cloning cache two times.

pub async fn run(self) {
  let cache = self.cache.clone(); // first cloning
  let filter =
    warp::path!("cache" / String)
      .and(warp::any().map(move || cache.clone()))  // second cloning
      .and_then(handler);

  tokio::join!(
     foo(self.cache),
     warp::serve(filter).run(self.server_socket)
  )
  unreachable!()
}

I clone cache two times but the first clone is used just to perform the second cloning so I think this is wrong way to solve this problem. How to avoid double cloning?


来源: stackexchange

问:
Why doesn't the function return a value to another variable than the one used as operand?
I am making a gauss elimination program and the function that i use is applied on a matrix in the form of a static array that is a member of a struct MATRIX. I wanted to return the new eliminated row-echelon form of the matrix as a new struct variable. Let 1 be the matrix i set to eliminate, i want to make matrix 2 hold matrix's 1 row-echelon form.

This is the struct definition that holds a static amount of variables (i've set it to struct matrix MATRIX[10]):

```<code>struct matrix{
    float array[k][l];
    char line[k];
    char column[l];
    int inversity;
};
</code>```

And this is the function segment:

```<code>float gauss(struct matrix MATRIX[],int n){
    int row=0,flag=0;
    while(row<k){
        //LEFTMOST NON-ZERO COLUMN ID
        int j=0,cid,rid;
        flag=0;
        while((j<l)&&(flag!=1)){
            int i=row;
            //printf("i value is: %d\n",i);
            while((i<k)&&(flag!=1)){
                if(MATRIX[n].array[i][j]!=0){
                    flag=1;
                    cid=j;
                    rid=i;
                }
                i++;
            }
            j++;
        }//printf("Leftmost column with at least a non-zero char is: %d and its location is: %d,%d\n",cid,cid,rid);
    //SWAPPING WITH CEILING ROW
        if(flag!=0)
            for(int j=0; j<l; j++){
                    float temp=MATRIX[n].array[rid][j];
                    MATRIX[n].array[rid][j]=MATRIX[n].array[row][j];
                    MATRIX[n].array[row][j]=temp;
            }
        //printf("Swapping done:\n"); printmatrix(MATRIX,1);
    //SETTING LEAD 1
        float temp=MATRIX[n].array[row][cid];
            if(temp!=0){
                for(int j=0; j<l; j++){
                    MATRIX[n].array[row][j]/=temp;
                }
            }//printf("Set lead:\n"); printmatrix(MATRIX,1);
    //OPERATION SEGMENT
            for(int i=(row+1); i<k; i++){
                float temp=MATRIX[n].array[i][cid];
                //printf("temp is %.2f\n",temp);
                    for(int j=0; j<l; j++){
                        //printf("sub factor is %.2f\n",(-1*temp*MATRIX[n].array[row][j]));
                        MATRIX[n].array[i][j]+=(-1*temp*MATRIX[n].array[row][j]);
                    }//printmatrix(MATRIX,1);
            }//printf("Done operations:\n"); printmatrix(MATRIX,1);
            row++;
    }
    for(int i=0; i<k; i++)
        for(int j=0; j<l; j++)
            if(MATRIX[n].array[i][j]==(-1*0)) MATRIX[n].array[i][j]=0;
    printf("Done final operations:\n"); printmatrix(MATRIX,n);
    return MATRIX[n+1].array[k][l];
}
</code>```

After that i use the following to assign the new matrix to a new struct variable:

```<code>MATRIX[n+1].array[k][l]=gauss(MATRIX,rem);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am making a gauss elimination program and the function that i use is applied on a matrix in the form of a static array that is a member of a struct MATRIX. I wanted to return the new eliminated row-echelon form of the matrix as a new struct variable. Let 1 be the matrix i set to eliminate, i want to make matrix 2 hold matrix's 1 row-echelon form.

This is the struct definition that holds a static amount of variables (i've set it to struct matrix MATRIX[10]):

struct matrix{
    float array[k][l];
    char line[k];
    char column[l];
    int inversity;
};

And this is the function segment:

float gauss(struct matrix MATRIX[],int n){
    int row=0,flag=0;
    while(row<k){
        //LEFTMOST NON-ZERO COLUMN ID
        int j=0,cid,rid;
        flag=0;
        while((j<l)&&(flag!=1)){
            int i=row;
            //printf("i value is: %d\n",i);
            while((i<k)&&(flag!=1)){
                if(MATRIX[n].array[i][j]!=0){
                    flag=1;
                    cid=j;
                    rid=i;
                }
                i++;
            }
            j++;
        }//printf("Leftmost column with at least a non-zero char is: %d and its location is: %d,%d\n",cid,cid,rid);
    //SWAPPING WITH CEILING ROW
        if(flag!=0)
            for(int j=0; j<l; j++){
                    float temp=MATRIX[n].array[rid][j];
                    MATRIX[n].array[rid][j]=MATRIX[n].array[row][j];
                    MATRIX[n].array[row][j]=temp;
            }
        //printf("Swapping done:\n"); printmatrix(MATRIX,1);
    //SETTING LEAD 1
        float temp=MATRIX[n].array[row][cid];
            if(temp!=0){
                for(int j=0; j<l; j++){
                    MATRIX[n].array[row][j]/=temp;
                }
            }//printf("Set lead:\n"); printmatrix(MATRIX,1);
    //OPERATION SEGMENT
            for(int i=(row+1); i<k; i++){
                float temp=MATRIX[n].array[i][cid];
                //printf("temp is %.2f\n",temp);
                    for(int j=0; j<l; j++){
                        //printf("sub factor is %.2f\n",(-1*temp*MATRIX[n].array[row][j]));
                        MATRIX[n].array[i][j]+=(-1*temp*MATRIX[n].array[row][j]);
                    }//printmatrix(MATRIX,1);
            }//printf("Done operations:\n"); printmatrix(MATRIX,1);
            row++;
    }
    for(int i=0; i<k; i++)
        for(int j=0; j<l; j++)
            if(MATRIX[n].array[i][j]==(-1*0)) MATRIX[n].array[i][j]=0;
    printf("Done final operations:\n"); printmatrix(MATRIX,n);
    return MATRIX[n+1].array[k][l];
}

After that i use the following to assign the new matrix to a new struct variable:

MATRIX[n+1].array[k][l]=gauss(MATRIX,rem);


问:
Retrieve thousands of files and folders without throttling
I'm trying to generate a nice big array for each user that contains all the files and folders the user owns as well as the users that each file/folder is shared with (e.g. users: ["John Doe": [{"name":"DemoDoc", "type": "file", "isShared": true, "sharedWithUsers": "bob@company.com", "joe@company.com"},{"name":"DemoFolder", "type": "folder", "isShared": false},...]]). I'll need to do this for a few hundred users. How should I do this with as few calls as possible?

The following is one approach per user:

Get Dropbox users (POST request):   https://api.dropboxapi.com/2/team/members/list

Loop through each member and grab their team_member_id

For each member (currently 364 members) get all their folders and files recursively: https://api.dropboxapi.com/2/files/list_folder

For each member folder, if it's shared get the members and add folder to user object if user is the owner of shared folder: https://api.dropboxapi.com/2/sharing/list_folder_members

If folder isn't shared then add folder to user object

If file check to see if user is owner of file: https://api.dropboxapi.com/2/sharing/list_file_members

If owner of file add file to user object

This approach could be thousands of http calls just for one user, which leads me to think this could be a very time expensive approach as well as the possibility of throttling.


问:
maven-dependency-plugin : "useSubDirectoryPerArtifact" parameter not affected by "useBaseVersion" parameter
I'm trying to unpack some dependencies with maven-dependency-plugin.

I want each dependency in its own directory named with the artifact Id and the artifact version

For example :

target/unpacked/artifactA-1.0-SNAPSHOT-war/contentA

target/unpacked/artifactB-2.0-SNAPSHOT-ear/contentB

My execution is like that :

```<code>                            <execution>
                                <id>unpack-applications</id>
                                <phase>generate-resources</phase>
                                <goals>
                                    <goal>unpack-dependencies</goal>
                                </goals>
                                <configuration>
                                    <includeArtifactIds>artifactA,artifactB</includeArtifactIds>
                                    <includeTypes>war,ear</includeTypes>
                                    <outputDirectory>target/unpacked</outputDirectory>
                                    <useSubDirectoryPerArtifact>true</useSubDirectoryPerArtifact>
                                    <useBaseVersion>true</useBaseVersion>
                              </configuration>
                            </execution>

</code>```

But most of the time, i got :

target/unpacked/artifactA-1.0-timestampXXX-war/contentA

target/unpacked/artifactB-2.0-timestampXXX-ear/contentB

If I change the goal to copy-dependency, I obtain something like that :

target/unpacked/artifactA-1.0-timestampXXX-war/artifactA-1.0-SNAPSHOT.war

target/unpacked/artifactB-2.0-timestampXXX-ear/artifactB-2.0-SNAPSHOT.ear

So it appears that the useSubDirectoryPerArtifact is not affected by the useBaseVersion option, only the artifact itself is.

Is there a way to workaround this without unpacking the artifact manually ?

Body:
I'm trying to unpack some dependencies with maven-dependency-plugin.

I want each dependency in its own directory named with the artifact Id and the artifact version

For example :

target/unpacked/artifactA-1.0-SNAPSHOT-war/contentA

target/unpacked/artifactB-2.0-SNAPSHOT-ear/contentB

My execution is like that :

                            <execution>
                                <id>unpack-applications</id>
                                <phase>generate-resources</phase>
                                <goals>
                                    <goal>unpack-dependencies</goal>
                                </goals>
                                <configuration>
                                    <includeArtifactIds>artifactA,artifactB</includeArtifactIds>
                                    <includeTypes>war,ear</includeTypes>
                                    <outputDirectory>target/unpacked</outputDirectory>
                                    <useSubDirectoryPerArtifact>true</useSubDirectoryPerArtifact>
                                    <useBaseVersion>true</useBaseVersion>
                              </configuration>
                            </execution>

But most of the time, i got :

target/unpacked/artifactA-1.0-timestampXXX-war/contentA

target/unpacked/artifactB-2.0-timestampXXX-ear/contentB

If I change the goal to copy-dependency, I obtain something like that :

target/unpacked/artifactA-1.0-timestampXXX-war/artifactA-1.0-SNAPSHOT.war

target/unpacked/artifactB-2.0-timestampXXX-ear/artifactB-2.0-SNAPSHOT.ear

So it appears that the useSubDirectoryPerArtifact is not affected by the useBaseVersion option, only the artifact itself is.

Is there a way to workaround this without unpacking the artifact manually ?


问:
Define variables globally with if statements in Gitlab CI CD
I want to set my variable $ENVIRONMENT to "int" if the $CI_COMMIT_BRANCH ist equal to "development". If the commit branch is equal to "main" I want to set the variable to the value "prod". This has to happen gloablly because every stage and job has to be able to access it.

I allready tried to set it within the job using rules but that didn't set the variable globally so it isn't really an option.

```<code>rules:
    - if: $CI_COMMIT_BRANCH == "development"
      variables:
        ENVIRONMENT: "int"
</code>```

Body:
I want to set my variable $ENVIRONMENT to "int" if the $CI_COMMIT_BRANCH ist equal to "development". If the commit branch is equal to "main" I want to set the variable to the value "prod". This has to happen gloablly because every stage and job has to be able to access it.

I allready tried to set it within the job using rules but that didn't set the variable globally so it isn't really an option.

rules:
    - if: $CI_COMMIT_BRANCH == "development"
      variables:
        ENVIRONMENT: "int"


问:
Multiple woff2 font files or a single ttf with multiple formats (converted to a woff2)? - which is faster
I have apparently found out that I can convert ttf variable font file from google fonts to a compressed woff2 file (50% reduced file) using this site:

https://cloudconvert.com/ttf-converter

I am wondering how this is possible, but nevertheless it seems to work on my website.

Also... With brotl the file sizes should be reduced by 30%, I am wondering if 3 request is worse than 1 bigger file

My question remains; which is faster for website woff2 load

have 3 x 20kb files

have 1 x 270kb file?


问:
Jquery datatable sorting icon not showing asc and desc when upgrade plugin from 1.10.21 to 1.13.1
We updated the our jquery.datatable.js 1.10.21 to 1.13.1, found that difference between both the plugins

jquery DT 1.13.1 contains below code

$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
if ( settings !== ctx ) { // need to check this this is the host
return;               // table, not a nested one
}

```<code>                var colIdx = column.idx;

                cell
                    .removeClass(
                        classes.sSortAsc +' '+
                        classes.sSortDesc
                    )
                    .addClass( columns[ colIdx ] == 'asc' ?
                        classes.sSortAsc : columns[ colIdx ] == 'desc' ?
                            classes.sSortDesc :
                            column.sSortingClass
                    );
            } );
        },
</code>```

and 1.10.21 contains below code
$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
if ( settings !== ctx ) { // need to check this this is the host
return;               // table, not a nested one
}

```<code>                var colIdx = column.idx;

                cell
                    .removeClass(
                        column.sSortingClass +' '+
                        classes.sSortAsc +' '+
                        classes.sSortDesc
                    )
                    .addClass( columns[ colIdx ] == 'asc' ?
                        classes.sSortAsc : columns[ colIdx ] == 'desc' ?
                            classes.sSortDesc :
                            column.sSortingClass
                    );
            } );
        },
</code>```

That why our sorting icon not showing asc and desc due to
cell.removeClass(column.sSortingClass +' '+ removed from 1.13.1 plugins.

Please suggest how to resolve the issue we are globally using the js for entire project .

Body:
We updated the our jquery.datatable.js 1.10.21 to 1.13.1, found that difference between both the plugins

jquery DT 1.13.1 contains below code

$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
if ( settings !== ctx ) { // need to check this this is the host
return;               // table, not a nested one
}

                var colIdx = column.idx;

                cell
                    .removeClass(
                        classes.sSortAsc +' '+
                        classes.sSortDesc
                    )
                    .addClass( columns[ colIdx ] == 'asc' ?
                        classes.sSortAsc : columns[ colIdx ] == 'desc' ?
                            classes.sSortDesc :
                            column.sSortingClass
                    );
            } );
        },

and 1.10.21 contains below code
$(settings.nTable).on( 'order.dt.DT', function ( e, ctx, sorting, columns ) {
if ( settings !== ctx ) { // need to check this this is the host
return;               // table, not a nested one
}

                var colIdx = column.idx;

                cell
                    .removeClass(
                        column.sSortingClass +' '+
                        classes.sSortAsc +' '+
                        classes.sSortDesc
                    )
                    .addClass( columns[ colIdx ] == 'asc' ?
                        classes.sSortAsc : columns[ colIdx ] == 'desc' ?
                            classes.sSortDesc :
                            column.sSortingClass
                    );
            } );
        },

That why our sorting icon not showing asc and desc due to
cell.removeClass(column.sSortingClass +' '+ removed from 1.13.1 plugins.

Please suggest how to resolve the issue we are globally using the js for entire project .


问:
Getting error when I try create update query for php pdo
I have been struggling with this , I couldn't get the query to , when I click the link to the post I have getting the id of the post, but whenever I add that's update query I always end up with error 500 work please kindly assist I will so much appreciate</p>
```<code><?php
if(!isset($_GET['id'])) {
    header('Location: question.php');
    exit();
} else {
    $id = $_GET['id'];
}
//include database connection
   require_once('./includes/connection.php');
if(!is_numeric($id)) {
    header('Location: question.php');
}
$sql = "UPDATE posts SET title = :title, body = :body, category_id = :category_id WHERE post_id = :post_id";

// Prepare the query

$query = $db->prepare($sql);
$query->bindParam(':post_id', $id);
$query->execute();

?>
<?php include 'header.php';?>
<div><?php echo $id ?>

<?php include 'footer.php';?>
</code>```

Body:
I have been struggling with this , I couldn't get the query to , when I click the link to the post I have getting the id of the post, but whenever I add that's update query I always end up with error 500 work please kindly assist I will so much appreciate

<?php
if(!isset($_GET['id'])) {
    header('Location: question.php');
    exit();
} else {
    $id = $_GET['id'];
}
//include database connection
   require_once('./includes/connection.php');
if(!is_numeric($id)) {
    header('Location: question.php');
}
$sql = "UPDATE posts SET title = :title, body = :body, category_id = :category_id WHERE post_id = :post_id";

// Prepare the query

$query = $db->prepare($sql);
$query->bindParam(':post_id', $id);
$query->execute();

?>
<?php include 'header.php';?>

<?php echo $id ?>

<?php include 'footer.php';?>


问:
LSTM - Multi variate & timestep input with single variate output
Suppose I have a dataset with three variables (Var1, Var2, Var3) and a corresponding output value (Y). For these variables their values are recorded every four years.

Example of sequences:

index
sample_id
reference_year
Var1
Var2
Var3
Y

0
1086213
2015
7909.0
8094.0
9119.0
9

1
1086213
2016
7909.0
8073.0
9119.0
9

2
1086213
2017
7939.5
8083.5
9166.5
9

3
1086213
2018
7951.0
8064.0
9201.0
9

4
1086407
2015
10023.5
10606.0
12589.0
4

5
1086407
2016
10048.0
10645.0
12625.0
4

6
1086407
2017
10088.0
10737.0
12693.0
4

7
1086407
2018
10037.0
10659.0
12604.0
4

8
1090685
2015
8298.5
8556.0
9871.5
93

9
1090685
2016
8324.0
8886.0
10337.0
93

10
1090685
2017
8327.0
8785.0
10220.0
93

11
1090685
2018
8516.5
8929.5
10224.0
93

For training, I have ~122,000 / 4 = ~30,500 samples. I have a separate validation dataset (of about 18,000 samples).

My main question is: based on the four year sequence of Var1, Var2 and Var3, can I make an LSTM model that predicts the four year sequence of Y?

I'm using the PyTorch framework. I'm currently following Multivariate input LSTM in pytorch. However, I still have difficulties.

Create sequences:

```<code>in_seq1 = traindf.reset_index()['Var1']
in_seq2 = traindf.reset_index()['Var2']
in_seq3 = traindf.reset_index()['Var3']
out_seq = traindf.reset_index()['Y']

dataset = hstack((in_seq1, in_seq2, in_seq3, out_seq))
</code>```

Initialize and split dataset:

```<code># split a multivariate sequence into samples
def split_sequences(sequences, n_steps):
    X, y = list(), list()
    for i in range(len(sequences)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the dataset
        if end_ix > len(sequences):
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1]
        X.append(seq_x)
        y.append(seq_y)
    return array(X), array(y)

n_features = 4 # this is number of features (Var1, Var2, Var3 + Y)
n_timesteps = 4 # this is number of timesteps (2015, 2016, 2017, 2018)

# convert dataset into input/output
X, y = split_sequences(dataset, n_timesteps)
print(X.shape, y.shape)

# create NN
mv_net = MV_LSTM(n_features,n_timesteps)
criterion = torch.nn.MSELoss() # reduction='sum' created huge loss value
optimizer = torch.optim.Adam(mv_net.parameters(), lr=1e-1)

train_episodes = 500
batch_size = 16
</code>```

This gives me the error:

```<code>---> 11         seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1]
</code>```
```<code>IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
</code>```

I understand that my data is supposed to be multi-dimensional right?

EDIT: This error is fixed when using np.column_stack() instead of hstack(). Furthermore, I changed n_features to 3 instead of 4. However, when I run the training as per the answer in Multivariate input LSTM in pytorch the loss is nan and I get the idea that it doesn't work.

Am I on the right track or is this wrong? Is it possible to obtain a single sequence using a multi sequence as input?

Body:
Suppose I have a dataset with three variables (Var1, Var2, Var3) and a corresponding output value (Y). For these variables their values are recorded every four years.

Example of sequences:

index
sample_id
reference_year
Var1
Var2
Var3
Y

0
1086213
2015
7909.0
8094.0
9119.0
9

1
1086213
2016
7909.0
8073.0
9119.0
9

2
1086213
2017
7939.5
8083.5
9166.5
9

3
1086213
2018
7951.0
8064.0
9201.0
9

4
1086407
2015
10023.5
10606.0
12589.0
4

5
1086407
2016
10048.0
10645.0
12625.0
4

6
1086407
2017
10088.0
10737.0
12693.0
4

7
1086407
2018
10037.0
10659.0
12604.0
4

8
1090685
2015
8298.5
8556.0
9871.5
93

9
1090685
2016
8324.0
8886.0
10337.0
93

10
1090685
2017
8327.0
8785.0
10220.0
93

11
1090685
2018
8516.5
8929.5
10224.0
93

For training, I have ~122,000 / 4 = ~30,500 samples. I have a separate validation dataset (of about 18,000 samples).

My main question is: based on the four year sequence of Var1, Var2 and Var3, can I make an LSTM model that predicts the four year sequence of Y?

I'm using the PyTorch framework. I'm currently following Multivariate input LSTM in pytorch. However, I still have difficulties.

Create sequences:

in_seq1 = traindf.reset_index()['Var1']
in_seq2 = traindf.reset_index()['Var2']
in_seq3 = traindf.reset_index()['Var3']
out_seq = traindf.reset_index()['Y']

dataset = hstack((in_seq1, in_seq2, in_seq3, out_seq))

Initialize and split dataset:

# split a multivariate sequence into samples
def split_sequences(sequences, n_steps):
    X, y = list(), list()
    for i in range(len(sequences)):
        # find the end of this pattern
        end_ix = i + n_steps
        # check if we are beyond the dataset
        if end_ix > len(sequences):
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1]
        X.append(seq_x)
        y.append(seq_y)
    return array(X), array(y)

n_features = 4 # this is number of features (Var1, Var2, Var3 + Y)
n_timesteps = 4 # this is number of timesteps (2015, 2016, 2017, 2018)

# convert dataset into input/output
X, y = split_sequences(dataset, n_timesteps)
print(X.shape, y.shape)

# create NN
mv_net = MV_LSTM(n_features,n_timesteps)
criterion = torch.nn.MSELoss() # reduction='sum' created huge loss value
optimizer = torch.optim.Adam(mv_net.parameters(), lr=1e-1)

train_episodes = 500
batch_size = 16

This gives me the error:

---> 11         seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1]

IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed

I understand that my data is supposed to be multi-dimensional right?

EDIT: This error is fixed when using np.column_stack() instead of hstack(). Furthermore, I changed n_features to 3 instead of 4. However, when I run the training as per the answer in Multivariate input LSTM in pytorch the loss is nan and I get the idea that it doesn't work.

Am I on the right track or is this wrong? Is it possible to obtain a single sequence using a multi sequence as input?


问:
html2canvas jspdf after generate pdf it cutting my charts
0

when i download pdf of my resizable charts my export pdf file not looking well. when a page finish some chart length is more so it goes outside the page so i am seeing black line there how to fix thia? actually charts height and width is resizeable so i want when i export the whole charts the pdf should not looking broken. i am attatching screen shots and code. Thanks in advance.
i already post this question before but no one helped me.

can u please fix my codesandbox given example ?
https://codesandbox.io/s/customizable-react-dashboard-with-chart-fork-forked-15rfpq?file=/src/Content.js:1898-2587


问:
Android. Is it possible get cached bitmap with glide?
Is it possible to get cached bitmap by key with glide like in coil ?
For example my code with coil:

```<code>val bitmap =  imageLoader.memoryCache?.get(cacheKey) as? Bitmap?
</code>```

And my request to show page:

```<code> val request = ImageRequest.Builder(context)
                                .size(width, height)
                                .memoryCacheKey(cacheKey)
                                .data(bitmap)
                                .build()
</code>```

So if my bitmap != null I'm not render pdf page.

Now I want to do something similar with glide. But I didn't find a suitable way. Please let me know if this is possible with glide ?

Body:
Is it possible to get cached bitmap by key with glide like in coil ?
For example my code with coil:

val bitmap =  imageLoader.memoryCache?.get(cacheKey) as? Bitmap?

And my request to show page:

 val request = ImageRequest.Builder(context)
                                .size(width, height)
                                .memoryCacheKey(cacheKey)
                                .data(bitmap)
                                .build()

So if my bitmap != null I'm not render pdf page.

Now I want to do something similar with glide. But I didn't find a suitable way. Please let me know if this is possible with glide ?


问:
My XMLHttpRequest is removing the first character on send when it is a $
I've created the XMLHttpRequest and I'm sending it with post. I have a string that sometimes starts with multiple $, for example $$$ABCD. The request is in JavaScript and it's being sent to a function in C#.

When the string does not start with $$$, it shows up fine. However when it is $$$ABCD, it arrives as $$ABCD.

I check that the string is correct just before I call send in JavaScript.

Any help is appreciated.

Javascript

```<code>this.ChangeFilter = function (filter)
    {
Url = "NoNameHere.asmx/FunctionThatIsCalled";
        PostData = "ProfileName={0}&Filter={1}&userKey={2}";

        EventHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
        EventHttpRequest.onreadystatechange = VoidCallback;
        EventHttpRequest.open("post", Url, false);
        EventHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        EventHttpRequest.send(PostData.replace("{0}", sessionProfile)
                                        .replace("{1}", filter)
                                        .replace("{2}", userKey));
}

Filter here in JavaScript is $$$ABCD and correct

**C#**
public void FunctionThatIsCalled(string Profile Name, string Filter, string user Key)
    {}
</code>```

Filter shows up here in C# is $$ABCD, missing the first $ before I do anything

Body:
I've created the XMLHttpRequest and I'm sending it with post. I have a string that sometimes starts with multiple $, for example $$$ABCD. The request is in JavaScript and it's being sent to a function in C#.

When the string does not start with $$$, it shows up fine. However when it is $$$ABCD, it arrives as $$ABCD.

I check that the string is correct just before I call send in JavaScript.

Any help is appreciated.

Javascript

this.ChangeFilter = function (filter)
    {
Url = "NoNameHere.asmx/FunctionThatIsCalled";
        PostData = "ProfileName={0}&Filter={1}&userKey={2}";

        EventHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0");
        EventHttpRequest.onreadystatechange = VoidCallback;
        EventHttpRequest.open("post", Url, false);
        EventHttpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        EventHttpRequest.send(PostData.replace("{0}", sessionProfile)
                                        .replace("{1}", filter)
                                        .replace("{2}", userKey));
}

Filter here in JavaScript is $$$ABCD and correct

**C#**
public void FunctionThatIsCalled(string Profile Name, string Filter, string user Key)
    {}

Filter shows up here in C# is $$ABCD, missing the first $ before I do anything


问:
getting an error when trying to print out a structure
I want to store the inputs in a structure and then arrange them in alphabetical order and then print them out, but it is giving this error. I did not include the other half of the code as I don't think it is relevant</p>
```<code>./main.c:32:30: error: subscripted value is not an array, pointer, or vector
              Pupils[i].DM213[i] + Pupils[i].DM214 + Pupils[i].DM215)/8;
              ~~~~~~~~~~~~~~~^~
./main.c:34:50: error: use of undeclared identifier 'compare'
qsort(Pupils, PupilAmount, sizeof(struct Pupil), compare);
                                                 ^
2 errors generated.
make: *** [Makefile:10: main] Error 1
exit status 2
</code>```
```<code>#include <stdio.h>
int main(void) {
  //Aquires how many Pupils will be inputted
    int PupilAmount;
  printf("How many Pupils would you like to input?\n");
  scanf("%d", &PupilAmount);
//Creates structure and variable arrays for each module and Lastname
struct Pupil {
    char Lastnames[20];
    int DM210;
    int DM211;
    int DM212;
    int DM213;
    int DM214;
    int DM215;
};
//will run this process and obtain overall percentage results for as many Pupils are on file
    int arr[PupilAmount];
    printf("Would you like to read from a file? (y/n)\n");
    char input;
    scanf(" %c", &input);
    if (input == 'y') {
      FILE *fp;
      fp = fopen("input.txt", "r");
     struct Pupil Pupils[PupilAmount];
for (int i = 0; i < PupilAmount; i++) {
    fscanf(fp, "%19s %d %d %d %d %d %d",
           Pupils[i].Lastnames,
           &Pupils[i].DM210, &Pupils[i].DM211, &Pupils[i].DM212,
           &Pupils[i].DM213, &Pupils[i].DM214, &Pupils[i].DM215);
    arr[i] = (Pupils[i].DM210*2 + Pupils[i].DM211*2 + Pupils[i].DM212 +
              Pupils[i].DM213[i] + Pupils[i].DM214 + Pupils[i].DM215)/8;
//Sorts the Pupils in alphabetical order
qsort(Pupils, PupilAmount, sizeof(struct Pupil), compare);
//Prints the results

printf("Lastname  Overall Percentage Mark  DM210  DM211  DM212  DM213  DM214  DM215\n");

  for (int i = 0; i < PupilAmount; i++)
    printf("%s \t %12.1d \t %12.1d \t %4.1d \t %4.1d \t %4.1d \t %4.1d \t %4.1d \n"),Pupils[PupilAmount] ;}
fclose(fp);}
return 0;}
</code>```

Body:
I want to store the inputs in a structure and then arrange them in alphabetical order and then print them out, but it is giving this error. I did not include the other half of the code as I don't think it is relevant

./main.c:32:30: error: subscripted value is not an array, pointer, or vector
              Pupils[i].DM213[i] + Pupils[i].DM214 + Pupils[i].DM215)/8;
              ~~~~~~~~~~~~~~~^~
./main.c:34:50: error: use of undeclared identifier 'compare'
qsort(Pupils, PupilAmount, sizeof(struct Pupil), compare);
                                                 ^
2 errors generated.
make: *** [Makefile:10: main] Error 1
exit status 2

#include <stdio.h>
int main(void) {
  //Aquires how many Pupils will be inputted
    int PupilAmount;
  printf("How many Pupils would you like to input?\n");
  scanf("%d", &PupilAmount);
//Creates structure and variable arrays for each module and Lastname
struct Pupil {
    char Lastnames[20];
    int DM210;
    int DM211;
    int DM212;
    int DM213;
    int DM214;
    int DM215;
};
//will run this process and obtain overall percentage results for as many Pupils are on file
    int arr[PupilAmount];
    printf("Would you like to read from a file? (y/n)\n");
    char input;
    scanf(" %c", &input);
    if (input == 'y') {
      FILE *fp;
      fp = fopen("input.txt", "r");
     struct Pupil Pupils[PupilAmount];
for (int i = 0; i < PupilAmount; i++) {
    fscanf(fp, "%19s %d %d %d %d %d %d",
           Pupils[i].Lastnames,
           &Pupils[i].DM210, &Pupils[i].DM211, &Pupils[i].DM212,
           &Pupils[i].DM213, &Pupils[i].DM214, &Pupils[i].DM215);
    arr[i] = (Pupils[i].DM210*2 + Pupils[i].DM211*2 + Pupils[i].DM212 +
              Pupils[i].DM213[i] + Pupils[i].DM214 + Pupils[i].DM215)/8;
//Sorts the Pupils in alphabetical order
qsort(Pupils, PupilAmount, sizeof(struct Pupil), compare);
//Prints the results

printf("Lastname  Overall Percentage Mark  DM210  DM211  DM212  DM213  DM214  DM215\n");

  for (int i = 0; i < PupilAmount; i++)
    printf("%s \t %12.1d \t %12.1d \t %4.1d \t %4.1d \t %4.1d \t %4.1d \t %4.1d \n"),Pupils[PupilAmount] ;}
fclose(fp);}
return 0;}


问:
Spring Jdbc, how do I run an SQL script on start up of a project
I want to implement oauth2 authorization service using JdbcTemplate with Spring authorization server. I need to pre-initialize some database table for the Jdbc in order to create an authorization service. I looked through the example that they provided. They use EmbededDatabase and run the provided script like this.

```<code>    @Bean
    public EmbeddedDatabase embeddedDatabase() {
        // @formatter:off
        return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(EmbeddedDatabaseType.H2)
                .setScriptEncoding("UTF-8")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
                .build();
        // @formatter:on
    }
</code>```

but I want to be able to pre-initialize script like this on existing database that I have. how can I do that? I have my database at localhost:3306 with username root and password very_secure.

Body:
I want to implement oauth2 authorization service using JdbcTemplate with Spring authorization server. I need to pre-initialize some database table for the Jdbc in order to create an authorization service. I looked through the example that they provided. They use EmbededDatabase and run the provided script like this.

    @Bean
    public EmbeddedDatabase embeddedDatabase() {
        // @formatter:off
        return new EmbeddedDatabaseBuilder()
                .generateUniqueName(true)
                .setType(EmbeddedDatabaseType.H2)
                .setScriptEncoding("UTF-8")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/oauth2-authorization-consent-schema.sql")
                .addScript("org/springframework/security/oauth2/server/authorization/client/oauth2-registered-client-schema.sql")
                .build();
        // @formatter:on
    }

but I want to be able to pre-initialize script like this on existing database that I have. how can I do that? I have my database at localhost:3306 with username root and password very_secure.


问:
RN Flatlist pagingenabled and scrolllength
I am trying to create the following design using a FlatList

My first take was this:

```<code>    const SCREENWIDTH = 375
    const COMPONENTWIDTH = 325
    const OFFSET = (SCREENWIDTH - COMPONENTWIDTH) / 2

    <FlatList
    style={{flex: 1}}
    getItemLayout={(data, index) => ({
      length: COMPONENTWIDTH,
      offset: OFFSET + COMPONENTWIDTH * index,
      index,
    })}
    pagingEnabled
    horizontal
    contentContainerStyle={{ paddingLeft: OFFSET, paddingRight: OFFSET }}
    renderItem={({ item }) => (
    <View
            style={{
              width: COMPONENTWIDTH,
              height: 300,
            }}
          >
            <View
              style={{
                backgroundColor: colors.white,
                borderRadius: 20,
                flex: 1,
                marginLeft: 10,
                marginRight: 10,
              }}
            >
            </View>
          </View>)}
    />

</code>```

However paging seems to scroll SCREENWIDTH, not COMPONENTWIDTH

Any recomendations?

Body:
I am trying to create the following design using a FlatList

My first take was this:

    const SCREENWIDTH = 375
    const COMPONENTWIDTH = 325
    const OFFSET = (SCREENWIDTH - COMPONENTWIDTH) / 2

    <FlatList
    style={{flex: 1}}
    getItemLayout={(data, index) => ({
      length: COMPONENTWIDTH,
      offset: OFFSET + COMPONENTWIDTH * index,
      index,
    })}
    pagingEnabled
    horizontal
    contentContainerStyle={{ paddingLeft: OFFSET, paddingRight: OFFSET }}
    renderItem={({ item }) => (
    <View
            style={{
              width: COMPONENTWIDTH,
              height: 300,
            }}
          >
            <View
              style={{
                backgroundColor: colors.white,
                borderRadius: 20,
                flex: 1,
                marginLeft: 10,
                marginRight: 10,
              }}
            >
            </View>
          </View>)}
    />

However paging seems to scroll SCREENWIDTH, not COMPONENTWIDTH

Any recomendations?


问:
Error 'ValueError: Length of values (1) does not match length of index (54)' using pandas pd.to_numeric
I have the below dataframe:

```<code>                                          Financial KPI        Year                Value
0                                         Total Revenue         TTM             92478000
1                                         Total Revenue  12/31/2021             89113000
2                                         Total Revenue  12/31/2020             85528000
3                                         Total Revenue  12/31/2019             91244000
4                                         Total Revenue  12/31/2018             91247000
5   Net Income from Continuing & Discontinued Operation         TTM             27409000
6   Net Income from Continuing & Discontinued Operation  12/31/2021             31978000
7   Net Income from Continuing & Discontinued Operation  12/31/2020             17894000
8   Net Income from Continuing & Discontinued Operation  12/31/2019             27430000
9   Net Income from Continuing & Discontinued Operation  12/31/2018             28147000
10                                    Normalized Income         TTM             27409000
11                                    Normalized Income  12/31/2021             31978000
12                                    Normalized Income  12/31/2020             17894000
13                                    Normalized Income  12/31/2019             27430000
14                                    Normalized Income  12/31/2018             28147000
15                                            Basic EPS         TTM
16                                            Basic EPS  12/31/2021                 3.60
17                                            Basic EPS  12/31/2020                 1.88
18                                            Basic EPS  12/31/2019                 2.77
19                                            Basic EPS  12/31/2018                 2.64
20                                    Net_Profit_Margin         TTM   0.2963840048443954
21                                    Net_Profit_Margin  12/31/2021  0.35884775509746053
22                                    Net_Profit_Margin  12/31/2020  0.20921803386025628
23                                    Net_Profit_Margin  12/31/2019   0.3006225066853711
24                                    Net_Profit_Margin  12/31/2018  0.30847041546571397
25                                    Price To Earnings         TTM                9.125
26                                         Total Assets         TTM
27                                         Total Assets  12/31/2021           3169495000
28                                         Total Assets  12/31/2020           2819627000
29                                         Total Assets  12/31/2019           2434079000
30                                         Total Assets  12/31/2018           2354507000
31              Total Liabilities Net Minority Interest         TTM
32              Total Liabilities Net Minority Interest  12/31/2021           2899429000
33              Total Liabilities Net Minority Interest  12/31/2020           2546703000
34              Total Liabilities Net Minority Interest  12/31/2019           2169269000
35              Total Liabilities Net Minority Interest  12/31/2018           2089182000
36                 Total Equity Gross Minority Interest         TTM
37                 Total Equity Gross Minority Interest  12/31/2021            270066000
38                 Total Equity Gross Minority Interest  12/31/2020            272924000
39                 Total Equity Gross Minority Interest  12/31/2019            264810000
40                 Total Equity Gross Minority Interest  12/31/2018            265325000
41                                           Total Debt         TTM
42                                           Total Debt  12/31/2021            303870000
43                                           Total Debt  12/31/2020            282255000
44                                           Total Debt  12/31/2019            265060000
45                                           Total Debt  12/31/2018            249529000
46                   Current_Ratio (assets/liabilities)  12/31/2021    1.093144546736616
47                   Current_Ratio (assets/liabilities)  12/31/2020   1.1071675809860828
48                   Current_Ratio (assets/liabilities)  12/31/2019   1.1220733804797838
49                   Current_Ratio (assets/liabilities)  12/31/2018    1.126999466776949
50                                 Debt_to_Assets_Ratio  12/31/2021  0.09587331735812803
51                                 Debt_to_Assets_Ratio  12/31/2020  0.10010366619414554
52                                 Debt_to_Assets_Ratio  12/31/2019  0.10889539739671555
53                                 Debt_to_Assets_Ratio  12/31/2018  0.10597929842637971
</code>```

I'm trying to convert the values of column 'Value' from string to the float type with the following line:

```<code>df_global['Value'] = pd.to_numeric(['Value'], errors='coerce')
</code>```

However, with this line, I'm getting the error:

```<code>ValueError: Length of values (1) does not match length of index (54)
</code>```

Not sure why this is happening. To my understanding the to_numeric function should just convert all the values of that column to float. The index, without the column headers, go from 0 to 53 so why is it complaining? How can I prevent this.
Any help?

Body:
I have the below dataframe:

                                          Financial KPI        Year                Value
0                                         Total Revenue         TTM             92478000
1                                         Total Revenue  12/31/2021             89113000
2                                         Total Revenue  12/31/2020             85528000
3                                         Total Revenue  12/31/2019             91244000
4                                         Total Revenue  12/31/2018             91247000
5   Net Income from Continuing & Discontinued Operation         TTM             27409000
6   Net Income from Continuing & Discontinued Operation  12/31/2021             31978000
7   Net Income from Continuing & Discontinued Operation  12/31/2020             17894000
8   Net Income from Continuing & Discontinued Operation  12/31/2019             27430000
9   Net Income from Continuing & Discontinued Operation  12/31/2018             28147000
10                                    Normalized Income         TTM             27409000
11                                    Normalized Income  12/31/2021             31978000
12                                    Normalized Income  12/31/2020             17894000
13                                    Normalized Income  12/31/2019             27430000
14                                    Normalized Income  12/31/2018             28147000
15                                            Basic EPS         TTM
16                                            Basic EPS  12/31/2021                 3.60
17                                            Basic EPS  12/31/2020                 1.88
18                                            Basic EPS  12/31/2019                 2.77
19                                            Basic EPS  12/31/2018                 2.64
20                                    Net_Profit_Margin         TTM   0.2963840048443954
21                                    Net_Profit_Margin  12/31/2021  0.35884775509746053
22                                    Net_Profit_Margin  12/31/2020  0.20921803386025628
23                                    Net_Profit_Margin  12/31/2019   0.3006225066853711
24                                    Net_Profit_Margin  12/31/2018  0.30847041546571397
25                                    Price To Earnings         TTM                9.125
26                                         Total Assets         TTM
27                                         Total Assets  12/31/2021           3169495000
28                                         Total Assets  12/31/2020           2819627000
29                                         Total Assets  12/31/2019           2434079000
30                                         Total Assets  12/31/2018           2354507000
31              Total Liabilities Net Minority Interest         TTM
32              Total Liabilities Net Minority Interest  12/31/2021           2899429000
33              Total Liabilities Net Minority Interest  12/31/2020           2546703000
34              Total Liabilities Net Minority Interest  12/31/2019           2169269000
35              Total Liabilities Net Minority Interest  12/31/2018           2089182000
36                 Total Equity Gross Minority Interest         TTM
37                 Total Equity Gross Minority Interest  12/31/2021            270066000
38                 Total Equity Gross Minority Interest  12/31/2020            272924000
39                 Total Equity Gross Minority Interest  12/31/2019            264810000
40                 Total Equity Gross Minority Interest  12/31/2018            265325000
41                                           Total Debt         TTM
42                                           Total Debt  12/31/2021            303870000
43                                           Total Debt  12/31/2020            282255000
44                                           Total Debt  12/31/2019            265060000
45                                           Total Debt  12/31/2018            249529000
46                   Current_Ratio (assets/liabilities)  12/31/2021    1.093144546736616
47                   Current_Ratio (assets/liabilities)  12/31/2020   1.1071675809860828
48                   Current_Ratio (assets/liabilities)  12/31/2019   1.1220733804797838
49                   Current_Ratio (assets/liabilities)  12/31/2018    1.126999466776949
50                                 Debt_to_Assets_Ratio  12/31/2021  0.09587331735812803
51                                 Debt_to_Assets_Ratio  12/31/2020  0.10010366619414554
52                                 Debt_to_Assets_Ratio  12/31/2019  0.10889539739671555
53                                 Debt_to_Assets_Ratio  12/31/2018  0.10597929842637971

I'm trying to convert the values of column 'Value' from string to the float type with the following line:

df_global['Value'] = pd.to_numeric(['Value'], errors='coerce')

However, with this line, I'm getting the error:

ValueError: Length of values (1) does not match length of index (54)

Not sure why this is happening. To my understanding the to_numeric function should just convert all the values of that column to float. The index, without the column headers, go from 0 to 53 so why is it complaining? How can I prevent this.
Any help?


问:
MATLAB - Failed to initialize GPU BLAS library
I'm very new at Matlab. I'm running a function called inside a parfor loop (I have 4 CPUs / 4 Workers). In this function, I want to multiply two matrices named "M1" and "M2," using GPU in the following manner:

```<code>MyFunction()
    ...
    gpu_M1 = gpuArray(M1);
    ...
    for k = 1:v2
        ...
        gpu_M2T = gpuArray(M2');
        gpu_x = gpu_M1* gpu_M2T;
        x = gather(gpu_x);
        ...
    end
end % End of MyFunction()

% Part of the main program
...
parfor n = 1:v1
  MyFunction();
end
...
</code>```

Based on the outcomes in the Command Window, it seems to work fine during the first four iteration this function is called. However, while executing the following one (5th), I get the message "Failed to initialize GPU BLAS library." Does any of you know what this problem could be? I would appreciate your help. I'm running this code in Matlab R2022b. These are some details of my graphic card:
graphic card

```<code>

I read that perhaps the problem would be an out-of-memory problem, so after x = gather(gpu_x), I added the code "clear gpu_linesT," but it didn't work out. Indeed after doing that, I got an out-of-memory error. It seems that I created that error rather than fixing the previous one.
</code>```

Body:
I'm very new at Matlab. I'm running a function called inside a parfor loop (I have 4 CPUs / 4 Workers). In this function, I want to multiply two matrices named "M1" and "M2," using GPU in the following manner:

MyFunction()
    ...
    gpu_M1 = gpuArray(M1);
    ...
    for k = 1:v2
        ...
        gpu_M2T = gpuArray(M2');
        gpu_x = gpu_M1* gpu_M2T;
        x = gather(gpu_x);
        ...
    end
end % End of MyFunction()

% Part of the main program
...
parfor n = 1:v1
  MyFunction();
end
...

Based on the outcomes in the Command Window, it seems to work fine during the first four iteration this function is called. However, while executing the following one (5th), I get the message "Failed to initialize GPU BLAS library." Does any of you know what this problem could be? I would appreciate your help. I'm running this code in Matlab R2022b. These are some details of my graphic card:
graphic card

I read that perhaps the problem would be an out-of-memory problem, so after x = gather(gpu_x), I added the code "clear gpu_linesT," but it didn't work out. Indeed after doing that, I got an out-of-memory error. It seems that I created that error rather than fixing the previous one.


问:
Which is the best way to put a try-except-finally in delphi?

Possible Duplicate:

  Delphi Exception Handling - How to clean up properly?

  Use of Try/Finally/Catch Together in Delphi

I would like to know which is the best way to put try-except-finally in delphi? What I mean is in nested try block, which statement should come inside, for example, Example 1

```<code>// initialize / allocate resource (create objects etc.)
...
try
     try
        // use resource
        ...
     except
       // handle exception
       ...
     end;
finally
   // free resource / cleanup
   ...
end
</code>```

Example 2

```<code>    // initialize / allocate resource (create objects etc.)
...
try
     try
        // use resource
        ...
     finally
       // free resource / cleanup
       ...
     end;
except
   // handle exception
   ...
end
</code>```

Which is the best way to handle an exception in Delphi, Example 1 or Example 2. why?

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  Delphi Exception Handling - How to clean up properly?

  Use of Try/Finally/Catch Together in Delphi

I would like to know which is the best way to put try-except-finally in delphi? What I mean is in nested try block, which statement should come inside, for example, Example 1

// initialize / allocate resource (create objects etc.)
...
try
     try
        // use resource
        ...
     except
       // handle exception
       ...
     end;
finally
   // free resource / cleanup
   ...
end

Example 2

    // initialize / allocate resource (create objects etc.)
...
try
     try
        // use resource
        ...
     finally
       // free resource / cleanup
       ...
     end;
except
   // handle exception
   ...
end

Which is the best way to handle an exception in Delphi, Example 1 or Example 2. why?


问:
How to limit the form submission per day on kotlin
so here I am making a booking service application where later there will be a maximum user limit for inputting booking data. what I'm asking is how to provide quota limits to users for input per day. thnx

The limit here means to give the user a data input quota, so if the input quota is used up, the user cannot input data into the database again

below is the source code for inputting data to the database
`

```<code>val Modeldatabase = ModelDatabase(platnomor, tahunkendaraan, serieskendaraan, nama, alamat, nomorhp, tanggalservice, keluhane)
database.collection("Data Booking").document(nama).set(Modeldatabase)
    .addOnSuccessListener {
        pltnomor.text?.clear()
        thnkendaraan.text?.clear()
        srskendaraan.text?.clear()
        namapmlk.text?.clear()
        alamatpmlk.text?.clear()
        nohpe.text?.clear()
        tglbooking.text?.clear()
        keluhankerusakan.text?.clear()
        Toast.makeText(this, "Booking Sukses!", Toast.LENGTH_SHORT).show()
    }.addOnFailureListener{
        Toast.makeText(this, "Booking Gagal!", Toast.LENGTH_SHORT).show()
    }
</code>```

`

i hope to find a solution how to make max limit for input data

Body:
so here I am making a booking service application where later there will be a maximum user limit for inputting booking data. what I'm asking is how to provide quota limits to users for input per day. thnx

The limit here means to give the user a data input quota, so if the input quota is used up, the user cannot input data into the database again

below is the source code for inputting data to the database
`

val Modeldatabase = ModelDatabase(platnomor, tahunkendaraan, serieskendaraan, nama, alamat, nomorhp, tanggalservice, keluhane)
database.collection("Data Booking").document(nama).set(Modeldatabase)
    .addOnSuccessListener {
        pltnomor.text?.clear()
        thnkendaraan.text?.clear()
        srskendaraan.text?.clear()
        namapmlk.text?.clear()
        alamatpmlk.text?.clear()
        nohpe.text?.clear()
        tglbooking.text?.clear()
        keluhankerusakan.text?.clear()
        Toast.makeText(this, "Booking Sukses!", Toast.LENGTH_SHORT).show()
    }.addOnFailureListener{
        Toast.makeText(this, "Booking Gagal!", Toast.LENGTH_SHORT).show()
    }

`

i hope to find a solution how to make max limit for input data


问:
Python script to check the difference in days is 21
hi I want a python script to check the difference in number of days is 21 starting from a particular date. IF the difference is not 21 then break and fail the script.
So far i have below but not sure how do i put a loop for it:

```<code>from datetime import datetime
str_d1= '2022/11/24'
a= datetime.today()  #today is 15 dec
d1= datetime.strptime(str_d1, "%Y/%m/%d")
delta = a-d1
print(f'Difference is {delta.days} days')
print(a)
if delta.days % 21 ==0:
    print ('trigger')
</code>```

So suppose today is 15 dec and starting from 24th nov, the difference would be 21 days. but then I want to run this script after 15th dec as well and every time give a success after 21 days.
So I want to add this script in my Jenkins job so that it triggers another Jenkins job every 21 days.

Please help.

Body:
hi I want a python script to check the difference in number of days is 21 starting from a particular date. IF the difference is not 21 then break and fail the script.
So far i have below but not sure how do i put a loop for it:

from datetime import datetime
str_d1= '2022/11/24'
a= datetime.today()  #today is 15 dec
d1= datetime.strptime(str_d1, "%Y/%m/%d")
delta = a-d1
print(f'Difference is {delta.days} days')
print(a)
if delta.days % 21 ==0:
    print ('trigger')

So suppose today is 15 dec and starting from 24th nov, the difference would be 21 days. but then I want to run this script after 15th dec as well and every time give a success after 21 days.
So I want to add this script in my Jenkins job so that it triggers another Jenkins job every 21 days.

Please help.


问:
SpringBoot Multi-Project configuration
I have this project which contains two different ones, the first is an API interface, the second one, a webhook for recieving callbacks. What I want to achieve is to configure my webhook project to only recieve HTTPS requests, whilst my API interface can keep recieving HTTP requests. During my tests I realized that besides having multiple application.properties files, Spring defaults to only one and apply it's configurations to the whole project.
Does anyone know if it's possible to achieve that outcome? This is my project structure.

Application-webhook.properties:

Applicaion initializer:

Title: SpringBoot Multi-Project configuration


问:
scipy.interpolate.griddata not working as expected
I have a large dataset of temperatures throughout the US on a grid of 3km-3km:

The temps (temperature_data), latitudes and longitudes of each grid point are available where the lat/lon data are lats and lons, all with shape (1060,1800).

I also have a sub-regional high-resolution dataset I would like to extrapolate the temperatures_data from at each grid point. I have the latitudes and longitudes of these locations as rlats and rlons, each with shape (720,3840).

Reading around, I found the scipy.interpolate.griddata function, and used it as the following:

```<code>highres_temps = griddata((lats.flatten(),lons.flatten()),temperature_data.flatten(),(rlons,rlats),'nearest')
</code>```

The results give me in the new grid all have the same value:

```<code>print(np.amax(highres_temps))
print(np.amin(highres_temps))
28.175049
28.175049
</code>```

And if we zoom into the area of interest of highres_temps:

And zoom into the area of interest of temperature_data:

It is obvious the temps in temperature_data do not match with what should be extracted over the domain within rlats and rlons. Why might this be occurring?

Body:
I have a large dataset of temperatures throughout the US on a grid of 3km-3km:

The temps (temperature_data), latitudes and longitudes of each grid point are available where the lat/lon data are lats and lons, all with shape (1060,1800).

I also have a sub-regional high-resolution dataset I would like to extrapolate the temperatures_data from at each grid point. I have the latitudes and longitudes of these locations as rlats and rlons, each with shape (720,3840).

Reading around, I found the scipy.interpolate.griddata function, and used it as the following:

highres_temps = griddata((lats.flatten(),lons.flatten()),temperature_data.flatten(),(rlons,rlats),'nearest')

The results give me in the new grid all have the same value:

print(np.amax(highres_temps))
print(np.amin(highres_temps))
28.175049
28.175049

And if we zoom into the area of interest of highres_temps:

And zoom into the area of interest of temperature_data:

It is obvious the temps in temperature_data do not match with what should be extracted over the domain within rlats and rlons. Why might this be occurring?


问:
Format Document - Configure prettierrc like built in formatter of VSCode
I like to format documents with VSCode built-in features, which are convenient, don't depend on extensions, simplicity, and have suitable functionality of these built-in.

For example, this is a React Typescript project.

However, when the project keeps growing, I should not require everyone to add to their settings.json configuration like below because they are also working on other projects using other plenty format rules.

```<code>"[typescriptreact]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },
</code>```

So I want to configure the .prettierrc file to make the Prettier format properties approximately like the vscode.typescript-language-features format properties. I have looked for the vscode.typescript-language-features format properties but have not found it, could I achieve this solution? Or are there any other ways?

Body:
I like to format documents with VSCode built-in features, which are convenient, don't depend on extensions, simplicity, and have suitable functionality of these built-in.

For example, this is a React Typescript project.

However, when the project keeps growing, I should not require everyone to add to their settings.json configuration like below because they are also working on other projects using other plenty format rules.

"[typescriptreact]": {
        "editor.defaultFormatter": "vscode.typescript-language-features"
    },

So I want to configure the .prettierrc file to make the Prettier format properties approximately like the vscode.typescript-language-features format properties. I have looked for the vscode.typescript-language-features format properties but have not found it, could I achieve this solution? Or are there any other ways?


问:
Apply a color scale inside of a conditional that is based on a group variable
I'm trying to create a heatlane plot that has two or more groups of data in them. I guess these are actually two questions:

How can I set a color scale inside of a conditional?

Can I conditionally apply different color scales for more than two groups?

What I have so far:

import numpy as np
import pandas as pd

np.random.seed(42)

data = pd.DataFrame(
    {
        "id": range(1, 7),
        "value": np.random.random_sample(6),
        "group": ["A"] * 3 + ["B"] * 3,
    }
)

base = (
    alt.Chart(data)
    .encode(
        x=alt.X("id:O"),
        y=alt.Y("y2:Q", axis=None),
        y2=alt.Y2("y:Q"),
    )
    .transform_calculate(y="datum.value / 2", y2="-datum.value / 2")
)

(
    base.mark_bar(cornerRadius=3).encode(
        color=alt.condition(
            alt.datum.group == "A", alt.value("#0C676D"), alt.value("#E56399")
        )
    )
    + base.mark_bar(yOffset=-5, y2Offset=5).encode(
        color=alt.condition(
            alt.datum.group == "A", alt.value("#8AA5AE"), alt.value("#D9A4BE")
        )
    )
).properties(width=1200).configure_axis(grid=False).configure_view(strokeWidth=0)
```
<p>which yields a plot like this:</p>
<p><img src="https://i.stack.imgur.com/PAav9.png" alt="enter image description here" /></p>
<p>My problem is that when I change the condition like</p>
<pre class="lang-py prettyprint-override"><code>alt.condition(
    alt.datum.group == "A", alt.Color("value:Q", scale=alt.Scale(scheme="teals")), alt.value("#D9A4BE")
)
</code>```

I get a schema error

SchemaError: '#/definitions/FieldOrDatumDefWithCondition<MarkPropFieldDef,(Gradient|string|null)>' is not a 'uri-reference'

Failed validating 'format' in metaschema['properties']['$ref']:
    {'format': 'uri-reference', 'type': 'string'}

On schema['$ref']:
    '#/definitions/FieldOrDatumDefWithCondition<MarkPropFieldDef,(Gradient|string|null)>'
```

I'm also not sure at all how I should do conditional coloring based on more than two groups. I guess I could do color computations in Python and insert a value into the data frame but that seems undesirable approach.

Body:
I'm trying to create a heatlane plot that has two or more groups of data in them. I guess these are actually two questions:

How can I set a color scale inside of a conditional?

Can I conditionally apply different color scales for more than two groups?

What I have so far:

import numpy as np
import pandas as pd

np.random.seed(42)

data = pd.DataFrame(
    {
        "id": range(1, 7),
        "value": np.random.random_sample(6),
        "group": ["A"] * 3 + ["B"] * 3,
    }
)

base = (
    alt.Chart(data)
    .encode(
        x=alt.X("id:O"),
        y=alt.Y("y2:Q", axis=None),
        y2=alt.Y2("y:Q"),
    )
    .transform_calculate(y="datum.value / 2", y2="-datum.value / 2")
)

(
    base.mark_bar(cornerRadius=3).encode(
        color=alt.condition(
            alt.datum.group == "A", alt.value("#0C676D"), alt.value("#E56399")
        )
    )
    + base.mark_bar(yOffset=-5, y2Offset=5).encode(
        color=alt.condition(
            alt.datum.group == "A", alt.value("#8AA5AE"), alt.value("#D9A4BE")
        )
    )
).properties(width=1200).configure_axis(grid=False).configure_view(strokeWidth=0)

which yields a plot like this:

My problem is that when I change the condition like

alt.condition(
    alt.datum.group == "A", alt.Color("value:Q", scale=alt.Scale(scheme="teals")), alt.value("#D9A4BE")
)

I get a schema error

SchemaError: '#/definitions/FieldOrDatumDefWithCondition<MarkPropFieldDef,(Gradient|string|null)>' is not a 'uri-reference'

Failed validating 'format' in metaschema['properties']['$ref']:
    {'format': 'uri-reference', 'type': 'string'}

On schema['$ref']:
    '#/definitions/FieldOrDatumDefWithCondition<MarkPropFieldDef,(Gradient|string|null)>'

I'm also not sure at all how I should do conditional coloring based on more than two groups. I guess I could do color computations in Python and insert a value into the data frame but that seems undesirable approach.


问:
How can I set a default value of sanity document inside of sanity app?
I want to have a sanity app with animals. And I want an animal to have a field called "breed".
I want to set a default value for this field: "German shepherd". But I don't want to do this in code (using initialValue) because i want it to be adjusted manually in the app. Breed will be a document so I want to be able to add new breed, for example "German shepherd" in the sanity app, and then set is as default value for "breed" when creating new animal.

I tried to use initialValues but then I would have to hardcode an id of that breed instance


问:
Left joins return results in phpmyadmin but return nulls in php
I have two tables:
userfollow

```<code>`id` int(11) NOT NULL AUTO_INCREMENT,
`theuserid` int(11) NOT NULL,
`follower` int(11) NOT NULL,
`followstatus` int(11) NOT NULL,
</code>```

users

```<code>`users_id` int(11) NOT NULL AUTO_INCREMENT,
`users_username` int(11) NOT NULL,
etc...
</code>```

When I make this SQL query in phpmyadmin it works as intended:

```<code>SELECT *
FROM `userfollow`
    LEFT JOIN users on userfollow.theuserid = users.users_id
WHERE users_username = 'hello'
</code>```

However, in php this does not seem to work:

```<code>$stmt = $conn->prepare('SELECT *
                        FROM userfollow
                            LEFT JOIN users on userfollow.theuserid = users.users_id
                        WHERE users_username = ?');
</code>```

I am able to get the results from the users table in php but not from userfollow table. For example:

```<code>$userurl = $_GET['user'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('SELECT * FROM userfollow LEFT JOIN users on userfollow.theuserid = users.users_id WHERE users_username = ?');
$stmt->bind_param('s', $userurl);
$stmt->execute();

$result = $stmt->get_result();
while($row = $result->fetch_array()){
    $profilepageusername = $row['users_username'];
    $thestatus = $row['followstatus'];
</code>```

I am able to print out the username of the profile page but followstatus is null.
var_export($thestatus); returns a null.

It's worth pointing out that if I did the other way around the results would be the same, meaning that the query would return null results from the userfollow table:

```<code>SELECT *
FROM `users`
    LEFT JOIN userfollow on userfollow.theuserid = users.users_id
WHERE users_username = 'hello';
</code>```

This does not seem to work either. I've never had to use aliases before in php and to my knowledge the columns arent overwriting eachother or am I wrong? Any tips would be greatful thanks!

Body:
I have two tables:
userfollow

`id` int(11) NOT NULL AUTO_INCREMENT,
`theuserid` int(11) NOT NULL,
`follower` int(11) NOT NULL,
`followstatus` int(11) NOT NULL,

users

`users_id` int(11) NOT NULL AUTO_INCREMENT,
`users_username` int(11) NOT NULL,
etc...

When I make this SQL query in phpmyadmin it works as intended:

SELECT *
FROM `userfollow`
    LEFT JOIN users on userfollow.theuserid = users.users_id
WHERE users_username = 'hello'

However, in php this does not seem to work:

$stmt = $conn->prepare('SELECT *
                        FROM userfollow
                            LEFT JOIN users on userfollow.theuserid = users.users_id
                        WHERE users_username = ?');

I am able to get the results from the users table in php but not from userfollow table. For example:

$userurl = $_GET['user'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$stmt = $conn->prepare('SELECT * FROM userfollow LEFT JOIN users on userfollow.theuserid = users.users_id WHERE users_username = ?');
$stmt->bind_param('s', $userurl);
$stmt->execute();

$result = $stmt->get_result();
while($row = $result->fetch_array()){
    $profilepageusername = $row['users_username'];
    $thestatus = $row['followstatus'];

I am able to print out the username of the profile page but followstatus is null.
var_export($thestatus); returns a null.

It's worth pointing out that if I did the other way around the results would be the same, meaning that the query would return null results from the userfollow table:

SELECT *
FROM `users`
    LEFT JOIN userfollow on userfollow.theuserid = users.users_id
WHERE users_username = 'hello';

This does not seem to work either. I've never had to use aliases before in php and to my knowledge the columns arent overwriting eachother or am I wrong? Any tips would be greatful thanks!


问:
Serving static files with NGINX and DJANGO
I'm new to programming and I've managed to build my father a website where he can showcase his photography, I recently had to switch from shared hosting to my own VPS that uses ubuntu to give me more control and access to latest pips.

I've had everything working on local server regarding static files, everything uploads where it is meant to(for me it was static/media).

In production I've got my website running perfectly other than any css working for my templates or even admin panel and images not showing.

I have ran the following commands to get where I am, I will so share some code and screenshots of current configuration also. Image folders are also been created rather than images going into media folder. Images in browser have extensions image/image/test4 also.

```<code>DEBUG = False

sudo chown -R www-data:www-data /home/dave/mhprints/static

sudo chmod -R 777 /home/dave/mhprints/static

sudo chown -R www-data:www-data /home/dave/mhprints/staticfiles

sudo chmod -R 777 /home/dave/mhprints/staticfiles

sudo chmod -R 777 /var/www/staticfiles

sudo chmod -R 777 /var/www/staticfiles
</code>```

I have ImageField set with upload_to='media'

Current mapping of my project

Mapping of VAR folder

ROOTS AND URLS in settings.py

```<code>MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
     os.path.join(BASE_DIR, 'static')
    ]
CKEDITOR_UPLOAD_PATH = "uploads/"
</code>```

URLS.py

```<code>from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('mhpapp.urls')),
    path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

sites_enabled/mhprints file

```<code>server {
    listen 80;
    server_name my_ip;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static {
            root /var/www;
        }
    location /media {
            root /var/www/static;
        }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}
</code>```

I hope there is enough information here for some one to help me with this puzzle. I'm hoping its something simple I have over looked.

Body:
I'm new to programming and I've managed to build my father a website where he can showcase his photography, I recently had to switch from shared hosting to my own VPS that uses ubuntu to give me more control and access to latest pips.

I've had everything working on local server regarding static files, everything uploads where it is meant to(for me it was static/media).

In production I've got my website running perfectly other than any css working for my templates or even admin panel and images not showing.

I have ran the following commands to get where I am, I will so share some code and screenshots of current configuration also. Image folders are also been created rather than images going into media folder. Images in browser have extensions image/image/test4 also.

DEBUG = False

sudo chown -R www-data:www-data /home/dave/mhprints/static

sudo chmod -R 777 /home/dave/mhprints/static

sudo chown -R www-data:www-data /home/dave/mhprints/staticfiles

sudo chmod -R 777 /home/dave/mhprints/staticfiles

sudo chmod -R 777 /var/www/staticfiles

sudo chmod -R 777 /var/www/staticfiles

I have ImageField set with upload_to='media'

Current mapping of my project

Mapping of VAR folder

ROOTS AND URLS in settings.py

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
     os.path.join(BASE_DIR, 'static')
    ]
CKEDITOR_UPLOAD_PATH = "uploads/"

URLS.py

from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('mhpapp.urls')),
    path('ckeditor/', include('ckeditor_uploader.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

sites_enabled/mhprints file

server {
    listen 80;
    server_name my_ip;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static {
            root /var/www;
        }
    location /media {
            root /var/www/static;
        }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

I hope there is enough information here for some one to help me with this puzzle. I'm hoping its something simple I have over looked.


问:
How can I show JUnit and Integration test coverage under same Jenkins build through Jacoco?
I am executing JUnit and Integration Test and consolidating the report in jacoco.exec. However, is there a way to display these coverage reports separately ?</p>


问:
woocommerce cart amount remaining cost notification. Force refreshing notification after cart recalculation
I trying to write a function that display notification on cart page in WooCommerce if cart is not empty and cart amount is less than 40 USD in that way:

```<code>add_action( 'woocommerce_cart_collaterals', 'display_remaining_amount_message' );

function display_remaining_amount_message() {
  $cart_total = WC()->cart->get_displayed_subtotal();

  if ($cart_total > 0 && $cart_total < 40) {
    $difference = 40 - $cart_total;
    echo 'You need ' . $difference . ' USD more, to 40 USD cart amount.';
  }
}
</code>```

And everything works good, but when user is trying to add more products on cart page, and hit "recalcutate cart", he still see old remaining cost. I need to refresh the page to see correct remaining cost.

How to force reloading this notifications when cart is recalculated without page refresh?

Body:
I trying to write a function that display notification on cart page in WooCommerce if cart is not empty and cart amount is less than 40 USD in that way:

add_action( 'woocommerce_cart_collaterals', 'display_remaining_amount_message' );

function display_remaining_amount_message() {
  $cart_total = WC()->cart->get_displayed_subtotal();

  if ($cart_total > 0 && $cart_total < 40) {
    $difference = 40 - $cart_total;
    echo 'You need ' . $difference . ' USD more, to 40 USD cart amount.';
  }
}

And everything works good, but when user is trying to add more products on cart page, and hit "recalcutate cart", he still see old remaining cost. I need to refresh the page to see correct remaining cost.

How to force reloading this notifications when cart is recalculated without page refresh?


问:
How to get Bean from a main code to the SpringBootTest?
I have a SpringBootTest class:

```<code>
@SpringBootTest
class EntryData1 {

    @Autowired
    private ItemsDAO itemsDAO;

    @Test
    void contextLoads() {
        ClevertechTestTaskApplication.main(new String[]{"3-1","4-2"});
        System.out.println(itemsDAO.getList());
    }

}
</code>```

When I call itemsDAO.getList() in test I get {}, but when I write System.out.println(itemsDAO.getList()); in the main code I get a HashMap. So that means, test class make copy of ItemsDAO Bean, how can I use the main one?

Edit:

Now I have @SpringBootTest(args = {"1-3","4-2"}) and made in main method getter of args, to see, if String[] args getts anything. I got {} from getter, so it means nothing was sent to args

Body:
I have a SpringBootTest class:

@SpringBootTest
class EntryData1 {

    @Autowired
    private ItemsDAO itemsDAO;

    @Test
    void contextLoads() {
        ClevertechTestTaskApplication.main(new String[]{"3-1","4-2"});
        System.out.println(itemsDAO.getList());
    }

}

When I call itemsDAO.getList() in test I get {}, but when I write System.out.println(itemsDAO.getList()); in the main code I get a HashMap. So that means, test class make copy of ItemsDAO Bean, how can I use the main one?

Edit:

Now I have @SpringBootTest(args = {"1-3","4-2"}) and made in main method getter of args, to see, if String[] args getts anything. I got {} from getter, so it means nothing was sent to args


问:
Selenium with Java
I am getting this error while running script, it is not clicking on the element. I am eclipse with maven

org.openqa.selenium.ElementClickInterceptedException: element click intercepted

Your help is appreciated

when I click twice on the same element, it is working on the second click.

Note: when I run the same script on AVD, , it is working fine.

Tried JsClick as well.

Title: Selenium with Java


问:
Error by reunite Multiple tar.gz Files of Certain Size
Does anyone have experience with splitting tar.gz and what could have gone wrong here and why some files are damaged during splitting? I split one "testFile.tar.gz" file into parts not larger than 2 GB.
For example
testFile.tar.gz.001
testFile.tar.gz.002
testFile.tar.gz.003. I split the testFile.tar.gz file so that the input stream reads the data from testFile.tar.gz. and the output stream is written this data first in testFile.tar.gz.000 until it reaches the size of 2 GB, after this it is written in testFile.tar.gz001 and so on. I try to re-unite all parts with 7-zip. I mark all parts, then right-click the mouse and "7-Zip>unpack here".
I get the following error message

unexpected end of data,
the data cannot be opened as a [gzip] archive,

the data was opened as a [tar] archive

Data error: [path of corrupted file]


问:
How to properly hide MySQL credentials in a python project on replit.com?
I haven't posted in a while, but I need help with something. I have MySQL credentials that I need to use in a python project to connect to a database on PHPMyAdmin hosted by Freesqldatabase. this is the code I use to connect to it:

cnx = mysql.connector.connect(
                                user=*username*,
                                password=*password*,
                                host=*host*(sql9.freesqldatabase.com),
                                database=*database*)
```

I have the credentials and the credentials are correct, I just don't know how I could hide the credentials from the user that plays the repl project, since I uploaded it to the community on replit.

Basically, what happens is when the user plays the repl, the project is forked without the user knowing. This is an issue because I use the simplecrypt library to decrypt the data from a separate data.txt file, but the user could actually fork the repl and manipulate the script to get the data.

I have also tried the secret os.environ['key'] solution, but the os environment variables aren't forked with the project, so the user can't connect to the database through the repl project like they're supposed to.

I looked into this, and the only other solution I could find is to use a .env file, but that functionality is deprecated.

Is there any other way I could do this?

Body:
I haven't posted in a while, but I need help with something. I have MySQL credentials that I need to use in a python project to connect to a database on PHPMyAdmin hosted by Freesqldatabase. this is the code I use to connect to it:

cnx = mysql.connector.connect(
                                user=*username*,
                                password=*password*,
                                host=*host*(sql9.freesqldatabase.com),
                                database=*database*)

I have the credentials and the credentials are correct, I just don't know how I could hide the credentials from the user that plays the repl project, since I uploaded it to the community on replit.

Basically, what happens is when the user plays the repl, the project is forked without the user knowing. This is an issue because I use the simplecrypt library to decrypt the data from a separate data.txt file, but the user could actually fork the repl and manipulate the script to get the data.

I have also tried the secret os.environ['key'] solution, but the os environment variables aren't forked with the project, so the user can't connect to the database through the repl project like they're supposed to.

I looked into this, and the only other solution I could find is to use a .env file, but that functionality is deprecated.

Is there any other way I could do this?