问:
VBA Exctracting data value from a pivot table based on a date field
I have a pivot table which i update everyday.

I would like to set up an event that extracts the value of J-1 when it's a normal day of the week, and J-2 + J-3 when it is monday.

When the pivot table is refreshed, the new date of the day appears.

the pivot :
Pivot

The code I writed so far :

`

```<code>Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

Set Target = ThisWorkbook.Worksheets("TCD Global").PivotCaches("Tableau croisé dynamique4")

Dim New_cell As Range

Var field = Target.getfields("date début")
field = Format(field, "MMDDYYYY")

Select Case Weekday(field)
    Case vbMonday
       Cells("A16") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total CAT", field - 2)
       Cells("A17") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total CAT", field - 3)
       Cells("A18") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total  Hors CAT", field - 2)
       Cells("A19") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total Hors CAT", field - 3)

    Case Else
        Cells("A16") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total CAT", field - 1)
        Cells("A17") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total Hors CAT", field - 1)
End Sub
</code>```

`

Body:
I have a pivot table which i update everyday.

I would like to set up an event that extracts the value of J-1 when it's a normal day of the week, and J-2 + J-3 when it is monday.

When the pivot table is refreshed, the new date of the day appears.

the pivot :
Pivot

The code I writed so far :

`

Private Sub Worksheet_PivotTableUpdate(ByVal Target As PivotTable)

Set Target = ThisWorkbook.Worksheets("TCD Global").PivotCaches("Tableau croisé dynamique4")

Dim New_cell As Range

Var field = Target.getfields("date début")
field = Format(field, "MMDDYYYY")

Select Case Weekday(field)
    Case vbMonday
       Cells("A16") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total CAT", field - 2)
       Cells("A17") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total CAT", field - 3)
       Cells("A18") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total  Hors CAT", field - 2)
       Cells("A19") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total Hors CAT", field - 3)

    Case Else
        Cells("A16") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total CAT", field - 1)
        Cells("A17") = ThisWorkbook.Worksheets("TCD GLOBAL").Target.GetPivotData("Date début", "Total Hors CAT", field - 1)
End Sub

`


来源: stackexchange

问:
IONIC - ion-datetime time wheel doesn't dismiss when click on backdrop and neather the default buttons
```<code><sub><ng-template #INTERVALS>
    <ion-header>
        <ion-toolbar>
            <ion-col
                size="12"
                slot="start"
            >
                <ion-text class="ion-margin-start ion-text-size-20 ion-text-weight-500">{{ 'new_time_slot' | translate }}</ion-text>
            </ion-col>
        </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
        <form [formGroup]="intervalForm">
            <ion-item>
                <ion-label>{{ 'description' | translate }}</ion-label>
                <ion-input
                    formControlName="description"
                    slot="end"
                    class="ion-text-right"
                ></ion-input>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'price_list' | translate }}</ion-label>
                <ion-select formControlName="priceList">
                    <ion-select-option
                        *ngFor="let priceLevel of priceLevelList"
                        [value]="priceLevel?.name"
                    >
                        {{ priceLevel?.name }}
                    </ion-select-option>
                </ion-select>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'slot_color' | translate }}</ion-label>
                <ion-input></ion-input>
            </ion-item>
            <ion-item
                lines="none"
                class="ion-margin-top"
            >
                <ion-label class="ion-text-uppercase">{{ 'interval_time' | translate }}</ion-label>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'from' | translate }}</ion-label>
                <ion-datetime-button datetime="fromtime"></ion-datetime-button>
                <ion-popover [keepContentsMounted]="true">
                    <ng-template>
                        <ion-datetime
                            id="fromtime"
                            #fromtime
                            hourCycle="h23"
                            presentation="time"
                            value="{{ intervalFrom }}"
                            (ionChange)="timeChange('from', fromtime.value)"
                        >
                            <ion-buttons slot="buttons">
                                <ion-button
                                    color="primary"
                                    (click)="DismissClick()"
                                >
                                    Done
                                </ion-button>
                            </ion-buttons>
                        </ion-datetime>
                    </ng-template>
                </ion-popover>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'to' | translate }}</ion-label>
                <ion-datetime-button datetime="totime"></ion-datetime-button>
                <ion-popover [keepContentsMounted]="true">
                    <ng-template>
                        <ion-datetime
                            id="totime"
                            #totime
                            hourCycle="h23"
                            presentation="time"
                            min="{{ intervalFrom }}"
                            value="{{ intervalTo }}"
                            (ionChange)="timeChange('to', totime.value)"
                            [showDefaultButtons]="true"
                        ></ion-datetime>
                    </ng-template>
                </ion-popover>
            </ion-item>
        </form>
    </ion-content>
    <ion-footer class="ion-padding ion-no-border ion-text-right">
        <ion-button
            color="danger"
            (click)="modalCtrl.dismiss(data)"
        >
            {{ 'cancel' | translate }}
        </ion-button>
        <ion-button
            color="danger"
            (click)="onSubmit(intervalForm.value)"
        >
            {{ 'add' | translate }}
        </ion-button>
    </ion-footer>
</ng-template></sub>
</code>```

I simply copy the ion-datetime-button example showed on Ionic doc and added some customization for my purposes.

When i click on ion-datetime-button it show the time wheel correctly and i am able to change the time, but when i try to close it nothing happened and the wheel keep showing. It stacked all the page and until i refresh the page it doesn t dismiss. ANY HELP PLS ?

```<code></code>```

ContentLicense: CC BY-SA 4.0

Body:
<ng-template #INTERVALS>
    <ion-header>
        <ion-toolbar>
            <ion-col
                size="12"
                slot="start"
            >
                <ion-text class="ion-margin-start ion-text-size-20 ion-text-weight-500">{{ 'new_time_slot' | translate }}</ion-text>
            </ion-col>
        </ion-toolbar>
    </ion-header>
    <ion-content class="ion-padding">
        <form [formGroup]="intervalForm">
            <ion-item>
                <ion-label>{{ 'description' | translate }}</ion-label>
                <ion-input
                    formControlName="description"
                    slot="end"
                    class="ion-text-right"
                ></ion-input>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'price_list' | translate }}</ion-label>
                <ion-select formControlName="priceList">
                    <ion-select-option
                        *ngFor="let priceLevel of priceLevelList"
                        [value]="priceLevel?.name"
                    >
                        {{ priceLevel?.name }}
                    </ion-select-option>
                </ion-select>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'slot_color' | translate }}</ion-label>
                <ion-input></ion-input>
            </ion-item>
            <ion-item
                lines="none"
                class="ion-margin-top"
            >
                <ion-label class="ion-text-uppercase">{{ 'interval_time' | translate }}</ion-label>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'from' | translate }}</ion-label>
                <ion-datetime-button datetime="fromtime"></ion-datetime-button>
                <ion-popover [keepContentsMounted]="true">
                    <ng-template>
                        <ion-datetime
                            id="fromtime"
                            #fromtime
                            hourCycle="h23"
                            presentation="time"
                            value="{{ intervalFrom }}"
                            (ionChange)="timeChange('from', fromtime.value)"
                        >
                            <ion-buttons slot="buttons">
                                <ion-button
                                    color="primary"
                                    (click)="DismissClick()"
                                >
                                    Done
                                </ion-button>
                            </ion-buttons>
                        </ion-datetime>
                    </ng-template>
                </ion-popover>
            </ion-item>
            <ion-item>
                <ion-label>{{ 'to' | translate }}</ion-label>
                <ion-datetime-button datetime="totime"></ion-datetime-button>
                <ion-popover [keepContentsMounted]="true">
                    <ng-template>
                        <ion-datetime
                            id="totime"
                            #totime
                            hourCycle="h23"
                            presentation="time"
                            min="{{ intervalFrom }}"
                            value="{{ intervalTo }}"
                            (ionChange)="timeChange('to', totime.value)"
                            [showDefaultButtons]="true"
                        ></ion-datetime>
                    </ng-template>
                </ion-popover>
            </ion-item>
        </form>
    </ion-content>
    <ion-footer class="ion-padding ion-no-border ion-text-right">
        <ion-button
            color="danger"
            (click)="modalCtrl.dismiss(data)"
        >
            {{ 'cancel' | translate }}
        </ion-button>
        <ion-button
            color="danger"
            (click)="onSubmit(intervalForm.value)"
        >
            {{ 'add' | translate }}
        </ion-button>
    </ion-footer>
</ng-template>

I simply copy the ion-datetime-button example showed on Ionic doc and added some customization for my purposes.

When i click on ion-datetime-button it show the time wheel correctly and i am able to change the time, but when i try to close it nothing happened and the wheel keep showing. It stacked all the page and until i refresh the page it doesn t dismiss. ANY HELP PLS ?


问:
curl: (35) error:140943E8:SSL routines:ssl3_read_bytes while installing hyperledger fabric in WSL2
I am trying to install hyperledger fabric in WSL2 (ubuntu 18.04.5 LTS) on windows10 using the official documentation.

```<code>curl -sSLO https://raw.githubusercontent.com/hyperledger/fabric/main/scripts/install-fabric.sh && chmod +x install-fabric.sh
</code>```

But while using the above command I am getting curl: (35) error:140943E8:SSL routines:ssl3_read_bytes:reason(1000)

I have installed all the prerequisites.

Body:
I am trying to install hyperledger fabric in WSL2 (ubuntu 18.04.5 LTS) on windows10 using the official documentation.

curl -sSLO https://raw.githubusercontent.com/hyperledger/fabric/main/scripts/install-fabric.sh && chmod +x install-fabric.sh

But while using the above command I am getting curl: (35) error:140943E8:SSL routines:ssl3_read_bytes:reason(1000)

I have installed all the prerequisites.


问:
error function f_viz doesn't work in Rstudio / R
In Rstudio  / R  the function f_viz doesn't work. I have already downloaded factoextra packaging but it is mentionned : "Error: le package ‘ggplot2’ nécessaire pour ‘factoextra’, mais est introuvable".

And so I have tried to add ggplot2, but it still doesn't work. Anybody have an idea ?


问:
Loading OBJ model data using regexes?
I'm trying to write a class for loading a *.obj model, but I ran into a problem.

I'm fetching vertex data and vertex indexes from a *.obj file. For this I use regular expressions.

With prefix v:

Regex: v ([-+]?([0]\.[0-9]*|[1-9]*[0-9]*\.[0-9]*)) ([-+]? ([0]\.[0-9]*|[1-9]*[0-9]*\.[0-9]*)) ([-+]?([0]\.[0- 9]*|[1-9]*[0-9]*\.[0-9]*))
```
<p>With prefix <code>f</code>:</p>
<pre class="lang-none prettyprint-override"><code>Regex: f ([0-9]|[1-9][0-9]+)\/.*\/.* ([0-9]|[1-9][0-9]+)\ /.*\/.* ([0-9]|[1-9][0-9]+)\/.*\/.*
</code>```

All values are added to vectors:

```<code>std::vector<glm::fvec3> vertices_postion;
std::vector<GLint> vertices_postion_indicies;
</code>```

Next, the data is sent to OpenGL:

```<code>glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices_postion.size() * sizeof(glm::fvec3), &vertices_postion[0], GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vertices_postion_indicies.size() * sizeof(GLint), &vertices_postion_indicies[0], GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
</code>```

In terms of rendering:

```<code>glUseProgram(shader->getProgram());
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, vertices_postion_indicies.size(), GL_UNSIGNED_INT, (void*)0);
</code>```

The cube model was made in Autodesk Inventor and then exported to .OBJ format.

However, the rendering does not look correct, I think there are problems with the vertex rendering indexes.

Vertices:

v1: -5 v2: 0  v3: -5
v1: -5 v2: 0  v3: 5
v1: -5 v2: 10 v3: 5
v1: -5 v2: 10 v3: -5
v1: 5  v2: 0  v3: -5
v1: 5  v2: 10 v3: -5
v1: 5  v2: 0  v3: 5
v1: 5  v2: 10 v3: 5
```
<p>Vertex indices:</p>
<pre class="lang-none prettyprint-override"><code>1,2,4,4,2,3,5,1,6,6,1,4,7,5,8,8,5,6,2,7,3,3,7,8,2,1,7,7,1,5,8,6,3,3,6,4
</code>```

Picture:

Title: Loading OBJ model data using regexes?

Body:
I'm trying to write a class for loading a *.obj model, but I ran into a problem.

I'm fetching vertex data and vertex indexes from a *.obj file. For this I use regular expressions.

With prefix v:

Regex: v ([-+]?([0]\.[0-9]*|[1-9]*[0-9]*\.[0-9]*)) ([-+]? ([0]\.[0-9]*|[1-9]*[0-9]*\.[0-9]*)) ([-+]?([0]\.[0- 9]*|[1-9]*[0-9]*\.[0-9]*))

With prefix f:

Regex: f ([0-9]|[1-9][0-9]+)\/.*\/.* ([0-9]|[1-9][0-9]+)\ /.*\/.* ([0-9]|[1-9][0-9]+)\/.*\/.*

All values are added to vectors:

std::vector<glm::fvec3> vertices_postion;
std::vector<GLint> vertices_postion_indicies;

Next, the data is sent to OpenGL:

glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, vertices_postion.size() * sizeof(glm::fvec3), &vertices_postion[0], GL_STATIC_DRAW);

glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, vertices_postion_indicies.size() * sizeof(GLint), &vertices_postion_indicies[0], GL_STATIC_DRAW);

glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glEnableVertexAttribArray(0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

In terms of rendering:

glUseProgram(shader->getProgram());
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, vertices_postion_indicies.size(), GL_UNSIGNED_INT, (void*)0);

The cube model was made in Autodesk Inventor and then exported to .OBJ format.

However, the rendering does not look correct, I think there are problems with the vertex rendering indexes.

Vertices:

v1: -5 v2: 0  v3: -5
v1: -5 v2: 0  v3: 5
v1: -5 v2: 10 v3: 5
v1: -5 v2: 10 v3: -5
v1: 5  v2: 0  v3: -5
v1: 5  v2: 10 v3: -5
v1: 5  v2: 0  v3: 5
v1: 5  v2: 10 v3: 5

Vertex indices:

1,2,4,4,2,3,5,1,6,6,1,4,7,5,8,8,5,6,2,7,3,3,7,8,2,1,7,7,1,5,8,6,3,3,6,4

Picture:


问:
Value prediction without x_test dataset in LSTM Model
I done training my LSTM model and it brought a really good result. But, I wondering that is it only can predict the value in the x_test dataset? Like, I usually write model.predict(x_test). But what if I want to predict the actual future like it never happened for the testing set? What should I do?


问:
Event Bridge schedulers - Call my API gateway endpoint
I'm trying to use event bridge's new scheduler functionality:

I don't see the option "Call endpoint...", I did further reading and apparently is possible by sending a JSON but the format of that JSON is a big mystery and I can't find an example.

Is it possible to provide a working example of that, all that I tried is just not working.

EDIT:
This is an AWS cli example for something else:

aws scheduler create-schedule --schedule-expression "at(2022-11-20T13:00:00)" --name schedule-name \
--target '{"RoleArn": "role-arn", "Arn": "QUEUE_ARN", "Input": "TEST_PAYLOAD" }' \
--schedule-expression-timezone "America/Los_Angeles"
--flexible-time-window '{ "Mode": "OFF"}'```

The --target should be changed to call my API gateway endpoint but I can't figure out what are the required fields.

EDIT2:
Was suggested that (this question)  may provide a solution, but so far the accepted solution raises another question:

It appears you are right that the brand-new EventBridge Scheduler
console interface does not yet (?) support API Destinations.

I would like to do it in schedulers not rules, the way I see it schedulers is more adequate to what I'm trying to do, and I already have a solution using rules

Body:
I'm trying to use event bridge's new scheduler functionality:

I don't see the option "Call endpoint...", I did further reading and apparently is possible by sending a JSON but the format of that JSON is a big mystery and I can't find an example.

Is it possible to provide a working example of that, all that I tried is just not working.

EDIT:
This is an AWS cli example for something else:

aws scheduler create-schedule --schedule-expression "at(2022-11-20T13:00:00)" --name schedule-name \
--target '{"RoleArn": "role-arn", "Arn": "QUEUE_ARN", "Input": "TEST_PAYLOAD" }' \
--schedule-expression-timezone "America/Los_Angeles"
--flexible-time-window '{ "Mode": "OFF"}'

The --target should be changed to call my API gateway endpoint but I can't figure out what are the required fields.

EDIT2:
Was suggested that (this question)  may provide a solution, but so far the accepted solution raises another question:

It appears you are right that the brand-new EventBridge Scheduler
console interface does not yet (?) support API Destinations.

I would like to do it in schedulers not rules, the way I see it schedulers is more adequate to what I'm trying to do, and I already have a solution using rules


问:
kubectl keeps getting error when trying to list pods
After running this :

```<code>aws eks update-kubeconfig --region eu-west-1  --name my-cluster
</code>```

I tried to run kubectl get pods but I keep getting this error :

```<code>E1229 13:04:42.538976   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:42.873405   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:43.208848   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:43.561855   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:43.896372   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
error: You must be logged in to the server (the server has asked for the client to provide credentials)
</code>```

Mentioning here that aws is well configured and works fine.

Body:
After running this :

aws eks update-kubeconfig --region eu-west-1  --name my-cluster

I tried to run kubectl get pods but I keep getting this error :

E1229 13:04:42.538976   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:42.873405   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:43.208848   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:43.561855   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
E1229 13:04:43.896372   82870 memcache.go:238] couldn't get current server API group list: the server has asked for the client to provide credentials
error: You must be logged in to the server (the server has asked for the client to provide credentials)

Mentioning here that aws is well configured and works fine.


问:
Firebase authentication is taking over 10 minutes
I'm building an Android app using Java in Android Studio. I'm trying to implement authentication (login/register) using Firebase. However, both these operations are taking well over 10 minutes to perform. Is this issue code related or can it be something else? I have no idea what to look into. Any direction is much appreciated.

Code for login:

```<code>mAuth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(Login.this, "Login Successful.",
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();

            } else {
                // If sign in fails, display a message to the user.
                Toast.makeText(Login.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });
</code>```

Code for registration:

```<code>mAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            Log.d("FireB", "Completed");
            progressBar.setVisibility(View.GONE);
            if (task.isSuccessful()) {
                Log.d("FireB", ":D");
                Toast.makeText(Registration.this, "Account created.", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(), Login.class);
                startActivity(intent);
                finish();

            } else {
                // If sign in fails, display a message to the user.
                Log.d("FireB", "sowwy :((((");
                Toast.makeText(Registration.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });
</code>```

Body:
I'm building an Android app using Java in Android Studio. I'm trying to implement authentication (login/register) using Firebase. However, both these operations are taking well over 10 minutes to perform. Is this issue code related or can it be something else? I have no idea what to look into. Any direction is much appreciated.

Code for login:

mAuth.signInWithEmailAndPassword(email, password)
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            if (task.isSuccessful()) {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(Login.this, "Login Successful.",
                        Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();

            } else {
                // If sign in fails, display a message to the user.
                Toast.makeText(Login.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });

Code for registration:

mAuth.createUserWithEmailAndPassword(email, password)
    .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
        @Override
        public void onComplete(@NonNull Task<AuthResult> task) {
            Log.d("FireB", "Completed");
            progressBar.setVisibility(View.GONE);
            if (task.isSuccessful()) {
                Log.d("FireB", ":D");
                Toast.makeText(Registration.this, "Account created.", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(), Login.class);
                startActivity(intent);
                finish();

            } else {
                // If sign in fails, display a message to the user.
                Log.d("FireB", "sowwy :((((");
                Toast.makeText(Registration.this, "Authentication failed.",
                        Toast.LENGTH_SHORT).show();
            }
        }
    });


问:
Inserting/overwriting a table after a paragraph (specific location) in a word file with docx python?
Does anybody know how to create/update a table with the docx library in a word document at a specific location.
So e.g. after a paragraph with text 'test1'?

The idea is to check if paragraph exists in the document, overwrite the existsing table underneath if not create a new paragraph and underneath at a certain location (at certain header level).

I managed to add a paragraph after a specific paragraph but it does not seem to work with tables in the same way.

I can not seem to find a link between the paragraph objects and creating a table object underneath that paragraph object or identifying the existing table object based on the paragraph.

A bit of context on the code, the code is first reading xaml files and writing this data in a word document. The first time the code is run it will create all subheadings and text/tables. With a second run the code will be updating the text/table values as the subheadings already exist.

e.g.
template:

02_BusinessProcess

00_Dispatcher

01_Initialization

after first run:

02_BusinessProcess
1.1 Xamlfilename
Text
Table

00_Dispatcher
2.1 Xamlfilenam
Text

01_Initialization

after second run:

02_BusinessProcess
1.1 Xamlfilename
Updated Text
Updated Table

00_Dispatcher
2.1 Xamlfilenam
Updated Text

01_Initialization

I want to add in the tables between these lines(newly created paragraphs).

```<code>paragraph1 = insert_paragraph_after(paragraph, xaml_obt.xamlfilename, style=document.styles['Heading 3'])
                        paragraph_annseq = insert_paragraph_after(paragraph1, xaml_obt.ann_seq, style=document.styles['No Spacing'])
                        paragraph_var = insert_paragraph_after(paragraph_annseq, "Variables - " + xaml_obt.xamlfilename,style=document.styles['Heading 4'])
                        paragraph_in_arg = insert_paragraph_after(paragraph_var, "In_Agruments - "  + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        paragraph_io_arg = insert_paragraph_after(paragraph_in_arg, "In_Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        insert_paragraph_after(paragraph_io_arg, "Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
</code>```

Or update the table in this spot if the paragraph exists in the document:

```<code>                if paragraph.style.name.startswith('Heading'):
                    if paragraph.text == xaml_obt.xamlfilename:
                        new_para = document.paragraphs[i + 1]
                        new_para.text = xaml_obt.ann_seq + "\n\n"
                        style = document.styles['No Spacing']
                        new_para.style = style
                        new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT

</code>```

Here is the complete code:

```<code>from tkinter import Tk, filedialog
import os
import json
from xml.etree import ElementTree as ET
import docx
from docx.oxml.xmlchemy import OxmlElement
from docx.text.paragraph import Paragraph
from docx.enum.text import WD_ALIGN_PARAGRAPH
import time
import win32com.client
import pandas as pd

class xamlinfo(object):
    def __init__(self, name: object) -> object:
        self.aut_block = str
        self.xamlfilepath = str
        self.xamlfilename = str
        self.xaml_read = None
        self.toplevelnaming = str
        self.ann_seq = str
        self.in_arguments = pd.DataFrame(columns=['Name', 'Type', 'Annotation'])
        self.out_arguments = pd.DataFrame(columns=['Name', 'Type', 'Annotation'])
        self.io_agruments = pd.DataFrame(columns=['Name', 'Type', 'Annotation'])
        self.variables = pd.DataFrame(columns=['Name', 'Annotation'])

def selectfolder():
    root = Tk()  # pointing root to Tk() to use it as Tk() in program.
    root.withdraw()
    root.attributes('-topmost', True)
    open_file = filedialog.askdirectory()
    open_file = os.path.normpath(open_file)
    print("Following filepath selected: ",open_file)
    return open_file

def assignxamlobjects(listxamls, path):
    if os.path.exists(path):
        for root,dirs,files in os.walk(path):
            for file in files:
                xaml_obt = xamlinfo(os.path.basename(file))
                xaml_obt.aut_block = os.path.basename(path)
                xaml_obt.xamlfilename = file
                xaml_obt.xamlfilepath = os.path.join(root,file)
                tree = ET.parse(xaml_obt.xamlfilepath)
                treeroot = tree.getroot()
                xaml_obt.xaml_read = treeroot
                top_sequence = treeroot.find(".//{*}Sequence")
                xaml_obt.toplevelnaming = top_sequence.attrib["DisplayName"]
                annotation = ""
                annotationelements = [x for x in top_sequence.attrib if "annotationtext" in x.lower()]
                if (len(annotationelements) > 0):
                    annotation = top_sequence.attrib[annotationelements[0]]
                xaml_obt.ann_seq = annotation
                listofelements = treeroot.findall(".//{*}Property")
                for element in listofelements:
                    if "InArgument" in element.attrib["Type"]:
                        annotation = ""
                        annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                        if (len(annotationelements) > 0):
                            annotation = element.attrib[annotationelements[0]]
                        xaml_obt.in_arguments = xaml_obt.in_arguments.append({0:str(element.attrib["Name"]), 1:str(element.attrib["Type"]).replace("InArgument",""),2: annotation})
                    if "InOutArgument" in element.attrib["Type"]:
                        annotation = ""
                        annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                        if (len(annotationelements) > 0):
                            annotation = element.attrib[annotationelements[0]]
                        xaml_obt.io_agruments = xaml_obt.io_agruments.append({0:str(element.attrib["Name"]), 1:str(element.attrib["Type"]).replace("InOutArgument",""),2: annotation})
                    if "OutArgument" in element.attrib["Type"]:
                        annotation = ""
                        annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                        if (len(annotationelements) > 0):
                            annotation = element.attrib[annotationelements[0]]
                        xaml_obt.out_arguments =  xaml_obt.out_arguments.append({0:str(element.attrib["Name"]), 1:str(element.attrib["Type"]).replace("OutArgument",""),2: annotation})
                listofelements = treeroot.findall(".//{*}Variable")
                for element in listofelements:
                    annotation = ""
                    annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                    if (len(annotationelements) > 0):
                        annotation = element.attrib[annotationelements[0]]
                    xaml_obt.variables = xaml_obt.variables.append({0:str(element.attrib["Name"]),1:annotation})
                listxamls.append(xaml_obt)
    else:
        print("The following path does not exists, please amend your project structure: "+path)
    return listxamls

def getworkflowinfo(openfile):
    jsonpath = os.path.join(openfile,"project.json")
    procestrans_path = os.path.join(openfile,"process","02_BusinessProcess")
    dispatcher_path = os.path.join(openfile,"process","00_Dispatcher")
    init_path = os.path.join(openfile,"process","01_Initialization")
    process_path = os.path.join(openfile,"Process")
    listxamls = []
    listxamls = assignxamlobjects(listxamls, path=procestrans_path)
    listxamls = assignxamlobjects(listxamls, path=dispatcher_path)
    listxamls = assignxamlobjects(listxamls, path=init_path)
    listxamls = assignxamlobjects(listxamls, path=process_path)
    with open(jsonpath) as f:
        uipathjson = json.load(f)
    return uipathjson, listxamls

def insert_paragraph_after(paragraph, text, style):
    new_p = OxmlElement('w:p')
    paragraph._p.addnext(new_p)
    new_para = Paragraph(new_p, paragraph._parent)
    if text:
        new_para.add_run(text)
    if style is not None:
        new_para.style = style
    paragraph1 = new_para
    return paragraph1

def fillxamldata(document, listofxamls):
    print("Starting to update workflow information.")
    for xaml_obt in listofxamls:
        paraexists = False
        for paragraph in document.paragraphs:
            if paragraph.text == xaml_obt.xamlfilename:
                paraexists = True
        if paraexists is True:
            for i, paragraph in enumerate(document.paragraphs):
                # Check if the paragraph is a heading
                if paragraph.style.name.startswith('Heading'):
                    if paragraph.text == xaml_obt.xamlfilename:
                        new_para = document.paragraphs[i + 1]
                        new_para.text = xaml_obt.ann_seq + "\n\n"
                        style = document.styles['No Spacing']
                        new_para.style = style
                        new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT
        else:
            for paragraph in document.paragraphs:
                # Check if the paragraph is a heading
                if paragraph.style.name.startswith('Heading'):
                    if paragraph.text == xaml_obt.aut_block:
                        paragraph1 = insert_paragraph_after(paragraph, xaml_obt.xamlfilename, style=document.styles['Heading 3'])
                        paragraph_annseq = insert_paragraph_after(paragraph1, xaml_obt.ann_seq, style=document.styles['No Spacing'])
                        paragraph_var = insert_paragraph_after(paragraph_annseq, "Variables - " + xaml_obt.xamlfilename,style=document.styles['Heading 4'])
                        paragraph_in_arg = insert_paragraph_after(paragraph_var, "In_Agruments - "  + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        paragraph_io_arg = insert_paragraph_after(paragraph_in_arg, "In_Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        insert_paragraph_after(paragraph_io_arg, "Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
    print("Workflow information updated successfully.\n")
    return

def filldependencies(document, jsonUI):
    print("Starting to fill dependencies.")
    dict_depend = jsonUI['dependencies']
    text = ""
    for i in dict_depend:
        text = text + i+": "+ dict_depend[i]+"\n"
    for i, paragraph in enumerate(document.paragraphs): # Loop through all the paragraphs in the Word file
        if paragraph.style.name.startswith('Heading'): # Check if the paragraph is a heading
             if 'dependencies' == paragraph.text.lower():
                new_para = document.paragraphs[i+1]
                new_para.text = text
                style = document.styles['No Spacing']
                new_para.style = style
                new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT
    print("Dependencies updated successfully.\n")
    return

def fillgeneralinfo(document, jsonUI):
    print("Starting to fill process info.")
    text = ("Process name: "+"\t\t\t"+ jsonUI['name'] + "\n" +
    "Process description:"+"\t\t" + jsonUI['description'] +"\n" +
    "UIpath Studio version:"+"\t\t"+ jsonUI['studioVersion'] + "\n" +
    "Project version:"+"\t\t\t" + jsonUI['projectVersion'] + "\n")
    for i, paragraph in enumerate(document.paragraphs): # Loop through all the paragraphs in the Word file
        if paragraph.style.name.startswith('Heading'): # Check if the paragraph is a heading
             if 'general info' == paragraph.text.lower():
                new_para = document.paragraphs[i+1]
                new_para.text = text
                style = document.styles['No Spacing']
                new_para.style = style
                new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT
    print("Process info successfully updated.\n")
    return

def fillworddata(path, listofxamls):
    print("You seleceted the following SDD file: "+path+"\n")
    document = docx.Document(path)
    with open(path, "w") as doc:
        fillxamldata(document, listofxamls)
        filldependencies(document, jsonUI)
        fillgeneralinfo(document, jsonUI)
    document.save(path)
    return

def startmessage():
    print("###############################################################\n"+
          "                           SDD_AUT                             \n"+
          "###############################################################\n")

starttimer = time.time()
startmessage()
openfile = selectfolder()
jsonUI, listxamls = getworkflowinfo(openfile)
correct_proc = input("The information for process | " + jsonUI['name'] + " | has been read.\n"+
      "Do you want to continue? (y/n)\n")
if correct_proc.lower() == 'y':
    sdd_doc = filedialog.askopenfilename(title='Select a file')
    fillworddata(path=sdd_doc, listofxamls=listxamls)
    print("Process has been executed successfully!")
else:
    print("The process has been terminated as the incorrect project was selected.")
endtimer = time.time()
duration = endtimer - starttimer
print("Process took: " + str(duration))

</code>```

Body:
Does anybody know how to create/update a table with the docx library in a word document at a specific location.
So e.g. after a paragraph with text 'test1'?

The idea is to check if paragraph exists in the document, overwrite the existsing table underneath if not create a new paragraph and underneath at a certain location (at certain header level).

I managed to add a paragraph after a specific paragraph but it does not seem to work with tables in the same way.

I can not seem to find a link between the paragraph objects and creating a table object underneath that paragraph object or identifying the existing table object based on the paragraph.

A bit of context on the code, the code is first reading xaml files and writing this data in a word document. The first time the code is run it will create all subheadings and text/tables. With a second run the code will be updating the text/table values as the subheadings already exist.

e.g.
template:

02_BusinessProcess

00_Dispatcher

01_Initialization

after first run:

02_BusinessProcess
1.1 Xamlfilename
Text
Table

00_Dispatcher
2.1 Xamlfilenam
Text

01_Initialization

after second run:

02_BusinessProcess
1.1 Xamlfilename
Updated Text
Updated Table

00_Dispatcher
2.1 Xamlfilenam
Updated Text

01_Initialization

I want to add in the tables between these lines(newly created paragraphs).

paragraph1 = insert_paragraph_after(paragraph, xaml_obt.xamlfilename, style=document.styles['Heading 3'])
                        paragraph_annseq = insert_paragraph_after(paragraph1, xaml_obt.ann_seq, style=document.styles['No Spacing'])
                        paragraph_var = insert_paragraph_after(paragraph_annseq, "Variables - " + xaml_obt.xamlfilename,style=document.styles['Heading 4'])
                        paragraph_in_arg = insert_paragraph_after(paragraph_var, "In_Agruments - "  + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        paragraph_io_arg = insert_paragraph_after(paragraph_in_arg, "In_Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        insert_paragraph_after(paragraph_io_arg, "Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])

Or update the table in this spot if the paragraph exists in the document:

                if paragraph.style.name.startswith('Heading'):
                    if paragraph.text == xaml_obt.xamlfilename:
                        new_para = document.paragraphs[i + 1]
                        new_para.text = xaml_obt.ann_seq + "\n\n"
                        style = document.styles['No Spacing']
                        new_para.style = style
                        new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT

Here is the complete code:

from tkinter import Tk, filedialog
import os
import json
from xml.etree import ElementTree as ET
import docx
from docx.oxml.xmlchemy import OxmlElement
from docx.text.paragraph import Paragraph
from docx.enum.text import WD_ALIGN_PARAGRAPH
import time
import win32com.client
import pandas as pd

class xamlinfo(object):
    def __init__(self, name: object) -> object:
        self.aut_block = str
        self.xamlfilepath = str
        self.xamlfilename = str
        self.xaml_read = None
        self.toplevelnaming = str
        self.ann_seq = str
        self.in_arguments = pd.DataFrame(columns=['Name', 'Type', 'Annotation'])
        self.out_arguments = pd.DataFrame(columns=['Name', 'Type', 'Annotation'])
        self.io_agruments = pd.DataFrame(columns=['Name', 'Type', 'Annotation'])
        self.variables = pd.DataFrame(columns=['Name', 'Annotation'])

def selectfolder():
    root = Tk()  # pointing root to Tk() to use it as Tk() in program.
    root.withdraw()
    root.attributes('-topmost', True)
    open_file = filedialog.askdirectory()
    open_file = os.path.normpath(open_file)
    print("Following filepath selected: ",open_file)
    return open_file

def assignxamlobjects(listxamls, path):
    if os.path.exists(path):
        for root,dirs,files in os.walk(path):
            for file in files:
                xaml_obt = xamlinfo(os.path.basename(file))
                xaml_obt.aut_block = os.path.basename(path)
                xaml_obt.xamlfilename = file
                xaml_obt.xamlfilepath = os.path.join(root,file)
                tree = ET.parse(xaml_obt.xamlfilepath)
                treeroot = tree.getroot()
                xaml_obt.xaml_read = treeroot
                top_sequence = treeroot.find(".//{*}Sequence")
                xaml_obt.toplevelnaming = top_sequence.attrib["DisplayName"]
                annotation = ""
                annotationelements = [x for x in top_sequence.attrib if "annotationtext" in x.lower()]
                if (len(annotationelements) > 0):
                    annotation = top_sequence.attrib[annotationelements[0]]
                xaml_obt.ann_seq = annotation
                listofelements = treeroot.findall(".//{*}Property")
                for element in listofelements:
                    if "InArgument" in element.attrib["Type"]:
                        annotation = ""
                        annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                        if (len(annotationelements) > 0):
                            annotation = element.attrib[annotationelements[0]]
                        xaml_obt.in_arguments = xaml_obt.in_arguments.append({0:str(element.attrib["Name"]), 1:str(element.attrib["Type"]).replace("InArgument",""),2: annotation})
                    if "InOutArgument" in element.attrib["Type"]:
                        annotation = ""
                        annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                        if (len(annotationelements) > 0):
                            annotation = element.attrib[annotationelements[0]]
                        xaml_obt.io_agruments = xaml_obt.io_agruments.append({0:str(element.attrib["Name"]), 1:str(element.attrib["Type"]).replace("InOutArgument",""),2: annotation})
                    if "OutArgument" in element.attrib["Type"]:
                        annotation = ""
                        annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                        if (len(annotationelements) > 0):
                            annotation = element.attrib[annotationelements[0]]
                        xaml_obt.out_arguments =  xaml_obt.out_arguments.append({0:str(element.attrib["Name"]), 1:str(element.attrib["Type"]).replace("OutArgument",""),2: annotation})
                listofelements = treeroot.findall(".//{*}Variable")
                for element in listofelements:
                    annotation = ""
                    annotationelements = [x for x in element.attrib if "annotationtext" in x.lower()]
                    if (len(annotationelements) > 0):
                        annotation = element.attrib[annotationelements[0]]
                    xaml_obt.variables = xaml_obt.variables.append({0:str(element.attrib["Name"]),1:annotation})
                listxamls.append(xaml_obt)
    else:
        print("The following path does not exists, please amend your project structure: "+path)
    return listxamls

def getworkflowinfo(openfile):
    jsonpath = os.path.join(openfile,"project.json")
    procestrans_path = os.path.join(openfile,"process","02_BusinessProcess")
    dispatcher_path = os.path.join(openfile,"process","00_Dispatcher")
    init_path = os.path.join(openfile,"process","01_Initialization")
    process_path = os.path.join(openfile,"Process")
    listxamls = []
    listxamls = assignxamlobjects(listxamls, path=procestrans_path)
    listxamls = assignxamlobjects(listxamls, path=dispatcher_path)
    listxamls = assignxamlobjects(listxamls, path=init_path)
    listxamls = assignxamlobjects(listxamls, path=process_path)
    with open(jsonpath) as f:
        uipathjson = json.load(f)
    return uipathjson, listxamls

def insert_paragraph_after(paragraph, text, style):
    new_p = OxmlElement('w:p')
    paragraph._p.addnext(new_p)
    new_para = Paragraph(new_p, paragraph._parent)
    if text:
        new_para.add_run(text)
    if style is not None:
        new_para.style = style
    paragraph1 = new_para
    return paragraph1

def fillxamldata(document, listofxamls):
    print("Starting to update workflow information.")
    for xaml_obt in listofxamls:
        paraexists = False
        for paragraph in document.paragraphs:
            if paragraph.text == xaml_obt.xamlfilename:
                paraexists = True
        if paraexists is True:
            for i, paragraph in enumerate(document.paragraphs):
                # Check if the paragraph is a heading
                if paragraph.style.name.startswith('Heading'):
                    if paragraph.text == xaml_obt.xamlfilename:
                        new_para = document.paragraphs[i + 1]
                        new_para.text = xaml_obt.ann_seq + "\n\n"
                        style = document.styles['No Spacing']
                        new_para.style = style
                        new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT
        else:
            for paragraph in document.paragraphs:
                # Check if the paragraph is a heading
                if paragraph.style.name.startswith('Heading'):
                    if paragraph.text == xaml_obt.aut_block:
                        paragraph1 = insert_paragraph_after(paragraph, xaml_obt.xamlfilename, style=document.styles['Heading 3'])
                        paragraph_annseq = insert_paragraph_after(paragraph1, xaml_obt.ann_seq, style=document.styles['No Spacing'])
                        paragraph_var = insert_paragraph_after(paragraph_annseq, "Variables - " + xaml_obt.xamlfilename,style=document.styles['Heading 4'])
                        paragraph_in_arg = insert_paragraph_after(paragraph_var, "In_Agruments - "  + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        paragraph_io_arg = insert_paragraph_after(paragraph_in_arg, "In_Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
                        insert_paragraph_after(paragraph_io_arg, "Out_Agruments - " + xaml_obt.xamlfilename, style=document.styles['Heading 4'])
    print("Workflow information updated successfully.\n")
    return

def filldependencies(document, jsonUI):
    print("Starting to fill dependencies.")
    dict_depend = jsonUI['dependencies']
    text = ""
    for i in dict_depend:
        text = text + i+": "+ dict_depend[i]+"\n"
    for i, paragraph in enumerate(document.paragraphs): # Loop through all the paragraphs in the Word file
        if paragraph.style.name.startswith('Heading'): # Check if the paragraph is a heading
             if 'dependencies' == paragraph.text.lower():
                new_para = document.paragraphs[i+1]
                new_para.text = text
                style = document.styles['No Spacing']
                new_para.style = style
                new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT
    print("Dependencies updated successfully.\n")
    return

def fillgeneralinfo(document, jsonUI):
    print("Starting to fill process info.")
    text = ("Process name: "+"\t\t\t"+ jsonUI['name'] + "\n" +
    "Process description:"+"\t\t" + jsonUI['description'] +"\n" +
    "UIpath Studio version:"+"\t\t"+ jsonUI['studioVersion'] + "\n" +
    "Project version:"+"\t\t\t" + jsonUI['projectVersion'] + "\n")
    for i, paragraph in enumerate(document.paragraphs): # Loop through all the paragraphs in the Word file
        if paragraph.style.name.startswith('Heading'): # Check if the paragraph is a heading
             if 'general info' == paragraph.text.lower():
                new_para = document.paragraphs[i+1]
                new_para.text = text
                style = document.styles['No Spacing']
                new_para.style = style
                new_para.alignment = WD_ALIGN_PARAGRAPH.LEFT
    print("Process info successfully updated.\n")
    return

def fillworddata(path, listofxamls):
    print("You seleceted the following SDD file: "+path+"\n")
    document = docx.Document(path)
    with open(path, "w") as doc:
        fillxamldata(document, listofxamls)
        filldependencies(document, jsonUI)
        fillgeneralinfo(document, jsonUI)
    document.save(path)
    return

def startmessage():
    print("###############################################################\n"+
          "                           SDD_AUT                             \n"+
          "###############################################################\n")

starttimer = time.time()
startmessage()
openfile = selectfolder()
jsonUI, listxamls = getworkflowinfo(openfile)
correct_proc = input("The information for process | " + jsonUI['name'] + " | has been read.\n"+
      "Do you want to continue? (y/n)\n")
if correct_proc.lower() == 'y':
    sdd_doc = filedialog.askopenfilename(title='Select a file')
    fillworddata(path=sdd_doc, listofxamls=listxamls)
    print("Process has been executed successfully!")
else:
    print("The process has been terminated as the incorrect project was selected.")
endtimer = time.time()
duration = endtimer - starttimer
print("Process took: " + str(duration))


问:
GADAppOpenAd automatically play video
GADAppOpenAd automatically play video after loading the ads, although not yet call present function.

and will give an error in the console after disabling the ads:

```<code>-[AVPlayerViewController exitFullScreenAnimated:completionHandler:] failed with error View needs to be loaded before you can call
-[AVPlayerViewController (0x10a878a00) exitFullScreenAnimated:completionHandler:]!
</code>```

I can't do anything next.
Has anyone encountered a similar situation, I just met a few days ago.

Title: GADAppOpenAd automatically play video

Body:
GADAppOpenAd automatically play video after loading the ads, although not yet call present function.

and will give an error in the console after disabling the ads:

-[AVPlayerViewController exitFullScreenAnimated:completionHandler:] failed with error View needs to be loaded before you can call
-[AVPlayerViewController (0x10a878a00) exitFullScreenAnimated:completionHandler:]!

I can't do anything next.
Has anyone encountered a similar situation, I just met a few days ago.


问:
Unity setting localEulerAngles causes unexpected result
I have the following code:

```<code>if (Input.GetKeyDown(KeyCode.A))
{
    var rot = switchTransform.localEulerAngles;
    Debug.Log(rot);
    rot.x = 150;
    switchTransform.localEulerAngles = rot;
}
</code>```

When I click 'A', the switchTransform switches from (30, 0, 0) to (150, 0, 0) in the inspector and (30, 0, 0) to (30, 180, 180) in the console.

It works correctly if I write it like this:

```<code>angle = 150f;
if (Mathf.Abs(angle) <= 180 && Mathf.Abs(angle) > float.Epsilon)
{
    angle = 180 - angle;
}
if (Input.GetKeyDown(KeyCode.A))
{
    var rot = switchTransform.localEulerAngles;
    rot.x = angle;
    switchTransform.localEulerAngles = rot;
}
</code>```

Why does it happen, and is there a better way to work around it?

This is the switch transform, as you can see it has unusual pivot.

Body:
I have the following code:

if (Input.GetKeyDown(KeyCode.A))
{
    var rot = switchTransform.localEulerAngles;
    Debug.Log(rot);
    rot.x = 150;
    switchTransform.localEulerAngles = rot;
}

When I click 'A', the switchTransform switches from (30, 0, 0) to (150, 0, 0) in the inspector and (30, 0, 0) to (30, 180, 180) in the console.

It works correctly if I write it like this:

angle = 150f;
if (Mathf.Abs(angle) <= 180 && Mathf.Abs(angle) > float.Epsilon)
{
    angle = 180 - angle;
}
if (Input.GetKeyDown(KeyCode.A))
{
    var rot = switchTransform.localEulerAngles;
    rot.x = angle;
    switchTransform.localEulerAngles = rot;
}

Why does it happen, and is there a better way to work around it?

This is the switch transform, as you can see it has unusual pivot.


问:
How do I manage PR and CI pipelines in Git Flow strategy?
If I deploy to prod from the latest release branch forked from dev how can I integrate PR to review code?

Also, if I would like to run a test integration pipeline automatically when a pull request is done to link the result to the pull request and improve the code review process is it possible with this kind of branch strategy?

At the moment I have the following branch strategy:

master

test

dev

features

Features are detached from dev, then merged in dev when they are ready.
When a set of features are ready I create a PR from dev to test and my test pipeline runs and shows the result inside the PR to improve the code review process.

When code is merged into a test after PR a pipeline ships it to the test environment and another test pipeline runs to test APIs from the outside.
Then code is merged to prod and shipped to prod.


问:
I cannot install dayjs library on new angular app
I'm new to angular and I'm currently making some tutorials and I ran onto some dependency tree issue when I try to install dayjs library. I looked for an answer and I assume that the library should be updated.

I run the following command :
npm install --save angular-dayjs dayjs
and the result I got is

```<code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: test-app@0.0.0
npm ERR! Found: @angular/common@13.1.3
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^11.2.7" from angular-dayjs@0.0.4
npm ERR! node_modules/angular-dayjs
npm ERR!   angular-dayjs@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
</code>```

I assume that the author of the library should rebuild the it against latest angular/common but
is there any chance to solve this issue on my own?
Thank you in advance!

Body:
I'm new to angular and I'm currently making some tutorials and I ran onto some dependency tree issue when I try to install dayjs library. I looked for an answer and I assume that the library should be updated.

I run the following command :
npm install --save angular-dayjs dayjs
and the result I got is

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: test-app@0.0.0
npm ERR! Found: @angular/common@13.1.3
npm ERR! node_modules/@angular/common
npm ERR!   @angular/common@"~13.1.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer @angular/common@"^11.2.7" from angular-dayjs@0.0.4
npm ERR! node_modules/angular-dayjs
npm ERR!   angular-dayjs@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

I assume that the author of the library should rebuild the it against latest angular/common but
is there any chance to solve this issue on my own?
Thank you in advance!


问:
SharedPreferences getInstance Error Flutter
I'm in testing and I got this error when I'm calling await SharedPreferences.getInstance();

The error :

```<code>Unexpected character (at character 477)
...b\\\",\\\"body\\\":\\\"ab\\\"}\"]}"}\":\\\"Description\\\",\\\"datePost\...
</code>```

The test :

```<code>test("Test getInstance", () async {
    await SharedPreferences.getInstance();
  });
</code>```

I can't clear it because I can't get the instance. (I know that I can call setMockInitialValues, but before that work perfectly).

Any suggest ?

Body:
I'm in testing and I got this error when I'm calling await SharedPreferences.getInstance();

The error :

Unexpected character (at character 477)
...b\\\",\\\"body\\\":\\\"ab\\\"}\"]}"}\":\\\"Description\\\",\\\"datePost\...

The test :

test("Test getInstance", () async {
    await SharedPreferences.getInstance();
  });

I can't clear it because I can't get the instance. (I know that I can call setMockInitialValues, but before that work perfectly).

Any suggest ?


问:
How to dynamically break pages when converting HTML to PDF
On my back-end application, I'm making a PDF using HTML content. The content is dynamic so I can't place manual page breaks for specific sections of the content. For example, if there is a paragraph with a heading and it does not fit into the remaining space on the current page That whole paragraph should go to the next page. I am using the html-pdf-node package to generate the PDFs. Is there a way I can dynamically add the page breaks to the html. Following is my PDF generating code:

```<code>import * as PDFDocument from 'pdfkit';
import * as pdfDoc from 'html-pdf-node';
import * as fs from 'fs';

export const createPdfFromHtml = async (content: string, pdfPath: string): Promise<string> => {
    const doc = new PDFDocument();

    doc.pipe(fs.createWriteStream(pdfPath));
    doc.end();

    const options: pdfDoc.Options = {
        format: 'A4',
        // width: 595,
        // height: 842,
        path: pdfPath,
        margin: {
            top: 30,
            bottom: 30,
            left: 30,
            right: 30,
        },
    };

    const file = { content };

    await pdfDoc.generatePdf(file, options);
    return 'pdf generated';
};
</code>```

Body:
On my back-end application, I'm making a PDF using HTML content. The content is dynamic so I can't place manual page breaks for specific sections of the content. For example, if there is a paragraph with a heading and it does not fit into the remaining space on the current page That whole paragraph should go to the next page. I am using the html-pdf-node package to generate the PDFs. Is there a way I can dynamically add the page breaks to the html. Following is my PDF generating code:

import * as PDFDocument from 'pdfkit';
import * as pdfDoc from 'html-pdf-node';
import * as fs from 'fs';

export const createPdfFromHtml = async (content: string, pdfPath: string): Promise<string> => {
    const doc = new PDFDocument();

    doc.pipe(fs.createWriteStream(pdfPath));
    doc.end();

    const options: pdfDoc.Options = {
        format: 'A4',
        // width: 595,
        // height: 842,
        path: pdfPath,
        margin: {
            top: 30,
            bottom: 30,
            left: 30,
            right: 30,
        },
    };

    const file = { content };

    await pdfDoc.generatePdf(file, options);
    return 'pdf generated';
};


问:
How to make TdxBarButton always visible in TdxBarManager.Bars[i], even when user is removed this button (made invisible) previous time?
I am using DevExpress TdxBarManager for Delphi, which is very complex component. It contains set of TdxBarButton's (or its descendants) - commands. And it also contains set of TdxBars - panels in which those commands are placed.

During the design time the developer creates TdxBarButton instance, assings properties to it in the object inspector and then drags-and-drops it on the TdxBar instance.

During the runtime the user can call 'Add or Remove Buttons' and this opens the dialog, in which the user can opt to make some buttons from this bar invisible. The visible/invisible button selection is preserved in the user registry.

My question is - how can I press the TdxBarButton to be always visible? Even when the user has opted to make it invisible. I know that dxBarButton has Visible property whose possible values include ivAlways, but this value ir preserved and resetting it does not make the invisible button visible again.

I am currently developing using Delphi 6, but I guess the same applies to TdxBarManager in the more recent Delphi as well like Delphi 2009 or Delphi Sydney.


问:
Angular Unit Test shows error warnings of kind NG0304 "component is not a known element" even after the component stubs have been declared
I am writing unit tests for an Angular component that uses multiple child components which are used with @ViewChild({}) in the following way:

Template:

...
<app-app-form></app-app-form>
<app-terms-form></app-terms-form>
...
```
<p>Model:</p>
<pre class="lang-js prettyprint-override"><code>...
@ViewChild(AppFormComponent, {static: true}) protected appForm: AppFormComponent;
@ViewChild(TermsFormComponent, {static: true}) protected termsForm: TermsFormComponent;
...
</code>```

In total I use six such components. For testing purposes I declared component stubs in this way:

@Component({
  selector: 'app-terms-form',
  template: '',
  providers: [
    { provide: TermsFormComponent, useClass: TermsFormStubComponent }
  ]
})
class TermsFormStubComponent implements Partial<IFormComp<any>> {
...
}
```
<p>When I run my tests I get error warning messages for all used child components although I declared them in the TestBed:</p>
```ERROR: 'NG0304: 'app-terms-form' is not a known element (used in the 'CreateLicenseComponent' component template):
1. If 'app-terms-form' is an Angular component, then verify that it is a part of an @NgModule where this component is declared.
```
<p>I want my tests to not display any error warnings for things that I deem already fixed but I can not figure out how to stop it. The TestBed is configured with all the necessary components.</p>
<pre class="lang-js prettyprint-override"><code>beforeEach(async () => {
    ...
    await TestBed.configureTestingModule({
      imports: [ ... ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ], // doesn't resolve the error warnings NG0304
      declarations: [
        CreateLicenseComponent,
        OrderFormStubComponent,
        DeviceFormStubComponent,
        AppFormStubComponent,
        TermsFormStubComponent,
        DnFormStubComponent,
        ExpiresFormStubComponent
      ],
      providers: [ ... ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(CreateLicenseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
</code>```

As you can see I already added CUSTOM_ELEMENTS_SCHEMA and NO_ERRORS_SCHEMA, also tried each individually. But it doesn't work. And I should not have to add them in the first place because all needed elements are in the "declarations" array. I still get the error warnings for all six child components

My tests run all successfully and through debugging I already confirmed that the component stubs are available. I could just ignore these error warnings but they are nevertheless annoying in particular because I am going to add more components like the showcased one. Does anyone have an idea how to cleanly solve this problem?

```<code></code>```

Body:
I am writing unit tests for an Angular component that uses multiple child components which are used with @ViewChild({}) in the following way:

Template:

...
<app-app-form></app-app-form>
<app-terms-form></app-terms-form>
...

Model:

...
@ViewChild(AppFormComponent, {static: true}) protected appForm: AppFormComponent;
@ViewChild(TermsFormComponent, {static: true}) protected termsForm: TermsFormComponent;
...

In total I use six such components. For testing purposes I declared component stubs in this way:

@Component({
  selector: 'app-terms-form',
  template: '',
  providers: [
    { provide: TermsFormComponent, useClass: TermsFormStubComponent }
  ]
})
class TermsFormStubComponent implements Partial<IFormComp<any>> {
...
}

When I run my tests I get error warning messages for all used child components although I declared them in the TestBed:

ERROR: 'NG0304: 'app-terms-form' is not a known element (used in the 'CreateLicenseComponent' component template):
1. If 'app-terms-form' is an Angular component, then verify that it is a part of an @NgModule where this component is declared.

I want my tests to not display any error warnings for things that I deem already fixed but I can not figure out how to stop it. The TestBed is configured with all the necessary components.

beforeEach(async () => {
    ...
    await TestBed.configureTestingModule({
      imports: [ ... ],
      schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ], // doesn't resolve the error warnings NG0304
      declarations: [
        CreateLicenseComponent,
        OrderFormStubComponent,
        DeviceFormStubComponent,
        AppFormStubComponent,
        TermsFormStubComponent,
        DnFormStubComponent,
        ExpiresFormStubComponent
      ],
      providers: [ ... ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(CreateLicenseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

As you can see I already added CUSTOM_ELEMENTS_SCHEMA and NO_ERRORS_SCHEMA, also tried each individually. But it doesn't work. And I should not have to add them in the first place because all needed elements are in the "declarations" array. I still get the error warnings for all six child components

My tests run all successfully and through debugging I already confirmed that the component stubs are available. I could just ignore these error warnings but they are nevertheless annoying in particular because I am going to add more components like the showcased one. Does anyone have an idea how to cleanly solve this problem?


问:
How to Create an API server based on Network Traffic Output
I have a phone that I want to install my custom app, but the only way to install apps is via the phone app store so what I want to do is to create a fake server that would respond like the app store API server and then DNS spoofing to my fake server and install my custom app
I captured the network traffic and I have it in a har file now I need to create a fake server based on that traffic the question is if there is a tool that can automatically do this?

I tried to rewrite from scratch a new server in node.js and express but I fell into to much trouble because I'm not so familiar with express


问:
relation between C++ operators new/delete and malloc/free

Possible Duplicate:

  What is the difference between new/delete and malloc/free?

Can anyone please tell me the relation between the c++ operators like new/delete etc and the functions in libc i.e malloc/free. Though just tested it positive that a call to new/free actually lands up to malloc and free respectively. So that means libstdc++ inherently requires libc.

ContentLicense: CC BY-SA 3.0


问:
Version number of new entity is equal to 1 after first save
I'm really confused about saving new entity to repository.

Firstly I check repo.findAll() to see element inside, and lets say there is one element there.
Then,  I save entity like SomEntity(id=1, version=0, name="SomeName") to repository.
Next I check again repo.findAll() and I get 2 elements and my new saved entity is like SomEntity(id=1, version=1, name="SomeName").

I do not get it. Why version is 1? Why not 0?

I tried to debug inside some spring modules, but it's really hard to debug it. I could only observe that inside SimpleJpaRepository:

```<code>@Transactional
public <S extends T> S save(S entity) {
   Assert.notNull(entity, "Entity must not be null.");
   if (this.entityInformation.isNew(entity)) {
       this.em.persist(entity);
       return entity;
   } else {
       return this.em.merge(entity);
   }
}

</code>```

it goes to this.em.merge(entity) as it contains already id.

I could see that if if I run line transaction.save(entity) in return I get entity with version 0, but if I run repo.findAll() I see that entity with version 1.

Could someone explain me this?

Body:
I'm really confused about saving new entity to repository.

Firstly I check repo.findAll() to see element inside, and lets say there is one element there.
Then,  I save entity like SomEntity(id=1, version=0, name="SomeName") to repository.
Next I check again repo.findAll() and I get 2 elements and my new saved entity is like SomEntity(id=1, version=1, name="SomeName").

I do not get it. Why version is 1? Why not 0?

I tried to debug inside some spring modules, but it's really hard to debug it. I could only observe that inside SimpleJpaRepository:

@Transactional
public <S extends T> S save(S entity) {
   Assert.notNull(entity, "Entity must not be null.");
   if (this.entityInformation.isNew(entity)) {
       this.em.persist(entity);
       return entity;
   } else {
       return this.em.merge(entity);
   }
}

it goes to this.em.merge(entity) as it contains already id.

I could see that if if I run line transaction.save(entity) in return I get entity with version 0, but if I run repo.findAll() I see that entity with version 1.

Could someone explain me this?


问:
Firebase Cloud Messaging Error: Service messaging is not available
I have firebase installed (previously working with Auth, Firestore, Storage, with no problems) but when I want to implement messaging I have this error message:

Error: Service messaging is not available

Working with Next.js.

This is my firebase.js config file:

```<code>import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getMessaging } from "firebase/messaging";

const firebaseConfig = {
  apiKey: "--------------------",
  authDomain: "------------------",
  projectId: "--------------------",
  storageBucket: "--------------------",
  messagingSenderId: "------------------------",
  appId: "---------------------------",
  measurementId: "--------------------",
};

const app = initializeApp(firebaseConfig);

export const auth = getAuth();

export const db = getFirestore(app);

export const messaging = getMessaging(app);
</code>```

I have already reinstalled firebase with version 9.15.0

Body:
I have firebase installed (previously working with Auth, Firestore, Storage, with no problems) but when I want to implement messaging I have this error message:

Error: Service messaging is not available

Working with Next.js.

This is my firebase.js config file:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getMessaging } from "firebase/messaging";

const firebaseConfig = {
  apiKey: "--------------------",
  authDomain: "------------------",
  projectId: "--------------------",
  storageBucket: "--------------------",
  messagingSenderId: "------------------------",
  appId: "---------------------------",
  measurementId: "--------------------",
};

const app = initializeApp(firebaseConfig);

export const auth = getAuth();

export const db = getFirestore(app);

export const messaging = getMessaging(app);

I have already reinstalled firebase with version 9.15.0


问:
Partition csv data to parquet through Glue Visual Editor, all data types getting converting to string only. but Double, Float, Long, etc Not working
I am trying to Partition csv data to parquet through AWS Glue -(Visual Editor), so all data types getting converted into string only. Double,Int,Float,Long, etc Not working properly. so i am not perform SQL like operation on that data because is all type of data is string only.

Data is stored properly in s3 -CSV format

when data store in parquet all data is have only string type.

So what will be the reason for that ??

But my expectation is result will be store in proper format and with proper datatype. so i can perform SQL like operation on that data using AWS Athena-crawler.


问:
how to split the screen in glut codeblocks for multiplayer in c
I have a project that requires me to make a game of two players at the same time while controlling the game characters via the keyboard and the mouse. To start, I need to know how to separate the screen so that the game is repeated in two halves with the difference in scores and other things

I searched a lot, but I did not find anything in the C language, so I hope someone can help me here

note:

-The game must be in 3D


问:
How to list blobs and read content using Spring Boot Starter for Azure Storage
Ive been using this guide here https://learn.microsoft.com/en-us/azure/developer/java/spring-framework/configure-spring-boot-starter-java-app-with-azure-storage

The examples here work nicely. But i want to know how i can use this setup to do other stuff. The example to read a file is only hardcoded to one file. The other example is to write to the same file.

I need some docs/examples on listing the blobs. And then dynamically reading whichever i want.


问:
Trying to access array offset on value of type bool in
```<code>    if ( is_array( $args[0] ) && isset( $_wp_theme_features['$post-thumbnails'] ) ) {
                $args[0] = array_unique( array_merge( $_wp_theme_features['$post-thumbnails'][0], $args[0] ) );
            }

</code>```

I don't know how to fix it. Could someone please help me?

I don't know this, just trying to fix with help.

Body:
    if ( is_array( $args[0] ) && isset( $_wp_theme_features['$post-thumbnails'] ) ) {
                $args[0] = array_unique( array_merge( $_wp_theme_features['$post-thumbnails'][0], $args[0] ) );
            }

I don't know how to fix it. Could someone please help me?

I don't know this, just trying to fix with help.


问:
specific sending of a data to another user in django
I code a plateform project in django, a user can create an announce and a another user can reserv this announce.I would like that when User-A books on an announce of user-b, User-B receives the notification on the site, on a page notification, but I don't know how to do that. I tried something.

My views.py :

```<code>@login_required
def view_annonce(request, annonce_id):
    message = ""
    annonce = get_object_or_404(models.Offre, id=annonce_id)
    if request.GET.get('contact') == 'contact':
        print('user clicked summary')
        if request.user.point_number < 10:
            message = "You can't reserv this announce"

        else :
            request.user.point_number = request.user.point_number -10
            request.user.save()
            return redirect("home")
    context={
        "annonce": annonce,
    }
    return render(request, 'blog/view_annonce.html', context=context)

@login_required
def notif_page(request):

    return render(request, 'blog/notifications.html')

</code>```

urls.py :

```<code>path('offre/<int:annonce_id>', blog.views.view_annonce, name="view_offre"),
path("offre/<int:annonce_id>/edit", blog.views.edit_annonce, name='edit_offre'),
path("notif/", blog.views.notif_page, name="notif"),
</code>```

my models.py :

```<code>class User(AbstractUser):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(max_length=30, null=True)
    profile_photo = models.ImageField(verbose_name='Photo de profile')
    point_number = models.IntegerField(default=20)
    ville = models.CharField(max_length=50)

</code>```

Body:
I code a plateform project in django, a user can create an announce and a another user can reserv this announce.I would like that when User-A books on an announce of user-b, User-B receives the notification on the site, on a page notification, but I don't know how to do that. I tried something.

My views.py :

@login_required
def view_annonce(request, annonce_id):
    message = ""
    annonce = get_object_or_404(models.Offre, id=annonce_id)
    if request.GET.get('contact') == 'contact':
        print('user clicked summary')
        if request.user.point_number < 10:
            message = "You can't reserv this announce"

        else :
            request.user.point_number = request.user.point_number -10
            request.user.save()
            return redirect("home")
    context={
        "annonce": annonce,
    }
    return render(request, 'blog/view_annonce.html', context=context)

@login_required
def notif_page(request):

    return render(request, 'blog/notifications.html')

urls.py :

path('offre/<int:annonce_id>', blog.views.view_annonce, name="view_offre"),
path("offre/<int:annonce_id>/edit", blog.views.edit_annonce, name='edit_offre'),
path("notif/", blog.views.notif_page, name="notif"),

my models.py :

class User(AbstractUser):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(max_length=30, null=True)
    profile_photo = models.ImageField(verbose_name='Photo de profile')
    point_number = models.IntegerField(default=20)
    ville = models.CharField(max_length=50)


问:
mouseover event not working when entering from child
In the js code below mouseover event listeners are added to the div elements. This is visualized by a change in the border style.

I am trying to make it so that the mouseover event only fires when the mouse enters from externally, and not when re-entering from one of the child paragraphs.

In other words you can see when moving the cursor from a parent div to one of its children, the cursor is no longer considered over the parent, and when the cursor moves off the child and back onto the parent the mouseover event is called again. I am trying to prevent this event call. Rather it should only trigger when the mouse moves into the div from externally.

side note: I am aware of the :hover css selector but am looking for a javascript solution.

```<code><style>
    div, p {
        margin: 8px;
        padding: 8px;
        display: inline-block;
        border: 1px dashed grey;
    }
</style>
<div>
    <p></p>
    <p></p>
    <p></p>
</div>

<div>
    <p></p>
    <p></p>
    <p></p>
    <p></p>
</div>

<script>
    let rootDivs = document.querySelectorAll("body > div");
    for (let rootDiv of rootDivs) {
        rootDiv.addEventListener("mouseover", function(event) {
            if (event.target === rootDiv) {
                event.target.style.borderColor = "green";
                event.target.style.borderStyle = "solid";
            }
        });

        rootDiv.addEventListener("mouseout", function(event) {
            if (event.target === rootDiv) {
                event.target.style.borderColor = "grey";
                event.target.style.borderStyle = "dashed";

            }
        });
    }
</script>
</code>```


问:
How can I generate the data so that there is only one mode?
I want to make the mode of a set of data and for this I use the function "max". How can I indicate that if there is more than one value that is the maximum it repeats the operation, and that therefore, this message does not come out: "In sub(object$syntax$docexpr, val, chunk[pos[1L]]) :argument 'replacement' has length > 1 and only the first element will be used".
I want the dataset to have only one mode.

That is, I want to take the maximum value of a vector, but if there is more than one maximum value, I want to re-generate the data, until I get a data set where there is only one maximum value.

```<code><<echo=FALSE, results=hide>>=
## DATA GENERATION

create_table <- function() {
   n_a <- sample(10:25,1)
  n_b <- 50-n_a
  n_c <- sample(10:25,1)
  n_d <- 50-n_c
  A <- rmultinom(1, n_a, prob=c(0.1, 0.2, 0.3, 0.4))
  F <- rmultinom(1, n_b, prob=c(0.2, 0.1, 0.4, 0.3))
  I <- rmultinom(1, n_c, prob=c(0.3, 0.4, 0.2, 0.1))
  P <- rmultinom(1, n_d, prob=c(0.4, 0.3, 0.1, 0.2))
  matrix(c(A, F, I, P), nrow = 4,
         dimnames = list(c("7", "8", "9", "10"),
           c("3", "4", "5", "6")))
}

public <- create_table()

variant <- sample(1:2, 1)
margins <- list(1, 2, NULL)
prop_public <- round(100*prop.table(public, margins[[variant]]), digits = 2)

while (length(prop_public) != length(unique(prop_public))) {
  public <- create_table()
  prop_public <- round(100*prop.table(public, margins[[variant]]), digits = 2)
}

## QUESTION/ANSWER GENERATION

public
prop_public

states = list(c("7", "8", "9", "10"),
           c("3", "4", "5", "6"))

q3 <- switch (variant,
  paste0("¿Cuál es la calificación más frecuente en Física"),
  paste0("¿Cuál es la calificación más frecuente en la asignatura optativa? " )
)

w1<- public[1,"3"]+public[2,"3"]+public[3,"3"]+public[4,"3"]

w2<- public[1,"4"]+public[2,"4"]+public[3,"4"]+public[4,"4"]

w3<- public[1,"5"]+public[2,"5"]+public[3,"5"]+public[4,"5"]

w4<- public[1,"6"]+public[2,"6"]+public[3,"6"]+public[4,"6"]

v <- max(c(w1, w2, w3, w4))

grupos =  c("3", "4", "5" , "6")
ans <- grupos[c(w1==v, w2==v, w3==v, w4==v)]
c(w1,w2,w3,w4)

v1<-public["7",1]+public["7",2]+public["7",3]+public["7",4]

v2<-public["8",1]+public["8",2]+public["8",3]+public["8",4]

v3<- public["9",1]+public["9",2]+public["9",3]+public["9",4]

v4<- public["10",1]+public["10",2]+public["10",3]+public["10",4]

h1 <- max(c(v1, v2, v3, v4))

grupos1 = c("7", "8", "9", "10")
ans1 <- grupos1[c(v1==h1, v2==h1, v3==h1, v4==h1)]
c(v1,v2,v3,v4)

sol <- switch (variant, ans, ans1 )
</code>```

Body:
I want to make the mode of a set of data and for this I use the function "max". How can I indicate that if there is more than one value that is the maximum it repeats the operation, and that therefore, this message does not come out: "In sub(object$syntax$docexpr, val, chunk[pos[1L]]) :argument 'replacement' has length > 1 and only the first element will be used".
I want the dataset to have only one mode.

That is, I want to take the maximum value of a vector, but if there is more than one maximum value, I want to re-generate the data, until I get a data set where there is only one maximum value.

<<echo=FALSE, results=hide>>=
## DATA GENERATION

create_table <- function() {
   n_a <- sample(10:25,1)
  n_b <- 50-n_a
  n_c <- sample(10:25,1)
  n_d <- 50-n_c
  A <- rmultinom(1, n_a, prob=c(0.1, 0.2, 0.3, 0.4))
  F <- rmultinom(1, n_b, prob=c(0.2, 0.1, 0.4, 0.3))
  I <- rmultinom(1, n_c, prob=c(0.3, 0.4, 0.2, 0.1))
  P <- rmultinom(1, n_d, prob=c(0.4, 0.3, 0.1, 0.2))
  matrix(c(A, F, I, P), nrow = 4,
         dimnames = list(c("7", "8", "9", "10"),
           c("3", "4", "5", "6")))
}

public <- create_table()

variant <- sample(1:2, 1)
margins <- list(1, 2, NULL)
prop_public <- round(100*prop.table(public, margins[[variant]]), digits = 2)

while (length(prop_public) != length(unique(prop_public))) {
  public <- create_table()
  prop_public <- round(100*prop.table(public, margins[[variant]]), digits = 2)
}

## QUESTION/ANSWER GENERATION

public
prop_public

states = list(c("7", "8", "9", "10"),
           c("3", "4", "5", "6"))

q3 <- switch (variant,
  paste0("¿Cuál es la calificación más frecuente en Física"),
  paste0("¿Cuál es la calificación más frecuente en la asignatura optativa? " )
)

w1<- public[1,"3"]+public[2,"3"]+public[3,"3"]+public[4,"3"]

w2<- public[1,"4"]+public[2,"4"]+public[3,"4"]+public[4,"4"]

w3<- public[1,"5"]+public[2,"5"]+public[3,"5"]+public[4,"5"]

w4<- public[1,"6"]+public[2,"6"]+public[3,"6"]+public[4,"6"]

v <- max(c(w1, w2, w3, w4))

grupos =  c("3", "4", "5" , "6")
ans <- grupos[c(w1==v, w2==v, w3==v, w4==v)]
c(w1,w2,w3,w4)

v1<-public["7",1]+public["7",2]+public["7",3]+public["7",4]

v2<-public["8",1]+public["8",2]+public["8",3]+public["8",4]

v3<- public["9",1]+public["9",2]+public["9",3]+public["9",4]

v4<- public["10",1]+public["10",2]+public["10",3]+public["10",4]

h1 <- max(c(v1, v2, v3, v4))

grupos1 = c("7", "8", "9", "10")
ans1 <- grupos1[c(v1==h1, v2==h1, v3==h1, v4==h1)]
c(v1,v2,v3,v4)

sol <- switch (variant, ans, ans1 )


问:
How to resolve InvalidArgumentException in Selenium+Python for Shadow DOM elements

while automation shadow dom elements I'm getting invalid argument exception

When I'm automation shadow dom elements with this code am getting this error

can anyone please give me a solution how to resolve this issue?

Thankyou....


问:
Hibernate query.stream() connection leak
I am using Spring Data JPA 2.7.6 with Hibernate 5.6.14, PostgreSQL driver 42.5.1 and HikariCP 4.0.3.

Inside a custom repository fragment implementation, I have a utility method that turns any given query into an "exists"-predicate. It used to look like this:

    //using javax.persistence.Query
    private boolean exists(Query query) {
        query.setMaxResults(1);
        final List<?> result = query.getResultList();
        return !result.isEmpty();
    }
```
<p>This worked perfectly, both inside and outside of transactions.</p>
<p>Now it got changed to use streams like this:</p>
<pre class="lang-java prettyprint-override"><code>    //using org.hibernate.query.Query
    private boolean exists(Query<?> query) {
        query.setMaxResults(1);
        try (Stream<?> result = query.stream()) {
            return result.findFirst()
                    .isPresent();
        }
    }
</code>```

This works fine when called inside a transaction but causes connection leaks when called without one.

Usefulness of the streams code aside (I reverted the change), I would like to understand why this causes a leak to avoid similar issues in other contexts.

I would have expected the stream to get closed when exiting the try-block, and therefore no issues with the connection. Hibernate javadoc says

You should call Stream.close() after processing the stream so that the underlying resources are deallocated right away.

which the try-block should guarantee.

Body:
I am using Spring Data JPA 2.7.6 with Hibernate 5.6.14, PostgreSQL driver 42.5.1 and HikariCP 4.0.3.

Inside a custom repository fragment implementation, I have a utility method that turns any given query into an "exists"-predicate. It used to look like this:

    //using javax.persistence.Query
    private boolean exists(Query query) {
        query.setMaxResults(1);
        final List<?> result = query.getResultList();
        return !result.isEmpty();
    }

This worked perfectly, both inside and outside of transactions.

Now it got changed to use streams like this:

    //using org.hibernate.query.Query
    private boolean exists(Query<?> query) {
        query.setMaxResults(1);
        try (Stream<?> result = query.stream()) {
            return result.findFirst()
                    .isPresent();
        }
    }

This works fine when called inside a transaction but causes connection leaks when called without one.

Usefulness of the streams code aside (I reverted the change), I would like to understand why this causes a leak to avoid similar issues in other contexts.

I would have expected the stream to get closed when exiting the try-block, and therefore no issues with the connection. Hibernate javadoc says

You should call Stream.close() after processing the stream so that the underlying resources are deallocated right away.

which the try-block should guarantee.


问:
operator= calls other operator= repeatedly
I have 2 classes HttpRequest and RequestParser both implementing the operator=. Each have a variable referencing to HttpRequest and RequestParser as so:

```<code>class HttpRequest : public Message {
    private:
        std::string _method;
        std::string _path;
        bool _requestReceived;

        RequestParser _parser;

        ...

HttpRequest &HttpRequest::operator=(HttpRequest const &rhs) {
    if (this != &rhs) {
        _method = rhs._method;
        _path = rhs._path;
        _parser = rhs._parser;
    }
}
</code>```
```<code>class RequestParser {
    private:
        std::stringstream _inReceive;
        bool _headersReceived;

        HttpRequest &_request;

        ...
RequestParser &RequestParser::operator=(RequestParser const &rhs) {
    if (this != &rhs) {
        _inReceive << rhs._inReceive.str();
        _headersReceived = rhs._headersReceived;
        _request = rhs._request;
    }
}
</code>```

The problem is that they each call operator= repeatedly.

```<code>    #28 0x5641ead38f57 in RequestParser::operator=(RequestParser const&) srcs/http/RequestParser.cpp:98
    #29 0x5641ead368f1 in HttpRequest::operator=(HttpRequest const&) srcs/http/HttpRequest.cpp:64
    #30 0x5641ead38f57 in RequestParser::operator=(RequestParser const&) srcs/http/RequestParser.cpp:98
    #31 0x5641ead368f1 in HttpRequest::operator=(HttpRequest const&) srcs/http/HttpRequest.cpp:64
    #32 0x5641ead38f57 in RequestParser::operator=(RequestParser const&) srcs/http/RequestParser.cpp:98
</code>```

I have no idea how to fix this.

Body:
I have 2 classes HttpRequest and RequestParser both implementing the operator=. Each have a variable referencing to HttpRequest and RequestParser as so:

class HttpRequest : public Message {
    private:
        std::string _method;
        std::string _path;
        bool _requestReceived;

        RequestParser _parser;

        ...

HttpRequest &HttpRequest::operator=(HttpRequest const &rhs) {
    if (this != &rhs) {
        _method = rhs._method;
        _path = rhs._path;
        _parser = rhs._parser;
    }
}

class RequestParser {
    private:
        std::stringstream _inReceive;
        bool _headersReceived;

        HttpRequest &_request;

        ...
RequestParser &RequestParser::operator=(RequestParser const &rhs) {
    if (this != &rhs) {
        _inReceive << rhs._inReceive.str();
        _headersReceived = rhs._headersReceived;
        _request = rhs._request;
    }
}

The problem is that they each call operator= repeatedly.

    #28 0x5641ead38f57 in RequestParser::operator=(RequestParser const&) srcs/http/RequestParser.cpp:98
    #29 0x5641ead368f1 in HttpRequest::operator=(HttpRequest const&) srcs/http/HttpRequest.cpp:64
    #30 0x5641ead38f57 in RequestParser::operator=(RequestParser const&) srcs/http/RequestParser.cpp:98
    #31 0x5641ead368f1 in HttpRequest::operator=(HttpRequest const&) srcs/http/HttpRequest.cpp:64
    #32 0x5641ead38f57 in RequestParser::operator=(RequestParser const&) srcs/http/RequestParser.cpp:98

I have no idea how to fix this.


问:
storing a GPG key in AWS KMS
I have a series of files in AWS S3, encrypted with a GPG public key. I want to store the private key in AWS KMS, so I can programmatically decrypt them.

I have followed AWS docs for BYOK (https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys.html) but cannot encrypt my private key with the AWS wrapping key as it's "unable to load private key" when I follow step 2 of https://docs.aws.amazon.com/kms/latest/developerguide/importing-keys-encrypt-key-material.html.

Title: storing a GPG key in AWS KMS


问:
Mock SQS of aws-sdk using sinon and chai in node.js
I have a code snippet like below:

```<code>const aws=require('aws-sdk');
aws.config.update({region:'us-east-1'});
const sqs=new aws.SQS();
</code>```

which later used in my code like below:

```<code>export const sendMessageQ=async (params:any)=>{
    return await sqs.sendMessage(params).promise();
}
</code>```

for this method in my spec.ts file I am writing the test case as below:

```<code>import chai,{expect} from 'chai';
import sinon from 'sinon';
chai.use(require('sinon-chai'));

describe("queue-test",()=>{
   let awsSQS: sinon.SinonStub;
  beforEach(async ()=>{
      awsSQS=sinon.stub(aws,'SQS').returns({
              sendMessage(){
                   return {
                      promise(){
                         return Promise.resolve();
                      }
                   }
              }
          })

      });
  it("check SQS",async ()=>{
      const output=await sendMessageQ({});
      expect(output).to.be.eq(some_output); ///some_output is I am creating like same as real sqs
                                          ///response
  });

})
</code>```

But here I am facing an issue like sendMessage is throwing the error QueryUrl does not exist or you do not have access to it. Now I am stubbing the sendMessage method but it is trying to call the original one. The stubbing is not working properly. I tried different approaches as well but it is not working.

Body:
I have a code snippet like below:

const aws=require('aws-sdk');
aws.config.update({region:'us-east-1'});
const sqs=new aws.SQS();

which later used in my code like below:

export const sendMessageQ=async (params:any)=>{
    return await sqs.sendMessage(params).promise();
}

for this method in my spec.ts file I am writing the test case as below:

import chai,{expect} from 'chai';
import sinon from 'sinon';
chai.use(require('sinon-chai'));

describe("queue-test",()=>{
   let awsSQS: sinon.SinonStub;
  beforEach(async ()=>{
      awsSQS=sinon.stub(aws,'SQS').returns({
              sendMessage(){
                   return {
                      promise(){
                         return Promise.resolve();
                      }
                   }
              }
          })

      });
  it("check SQS",async ()=>{
      const output=await sendMessageQ({});
      expect(output).to.be.eq(some_output); ///some_output is I am creating like same as real sqs
                                          ///response
  });

})

But here I am facing an issue like sendMessage is throwing the error QueryUrl does not exist or you do not have access to it. Now I am stubbing the sendMessage method but it is trying to call the original one. The stubbing is not working properly. I tried different approaches as well but it is not working.


问:
Thread-local-storage (__thread) used on a static class member
I'm trying thread-local-storage with a C++ class:

```<code>struct TestTLS
{
    TestTLS()
    {
        TestTLS::g_tls_val = 1;
    }

    int getTls()
    {
        return TestTLS::g_tls_val;
    }

    void setTls(int v)
    {
        TestTLS::g_tls_val = v;
    }

private:
    static __thread int g_tls_val;

};
</code>```

and then:

```<code>TestTLS tls;
int ff = tls.getTls();
tls.setTls(3);
int ee = tls.getTls();
</code>```

But I'm getting the following errors:

```<code>Undefined symbols for architecture arm64:
  "TestTLS::g_tls_val", referenced from:
      TestTLS::getTls() in main.o
      TestTLS::setTls(int) in main.o
      TestTLS::TestTLS() in main.o
</code>```

What am I doing wrong there?

Body:
I'm trying thread-local-storage with a C++ class:

struct TestTLS
{
    TestTLS()
    {
        TestTLS::g_tls_val = 1;
    }

    int getTls()
    {
        return TestTLS::g_tls_val;
    }

    void setTls(int v)
    {
        TestTLS::g_tls_val = v;
    }

private:
    static __thread int g_tls_val;

};

and then:

TestTLS tls;
int ff = tls.getTls();
tls.setTls(3);
int ee = tls.getTls();

But I'm getting the following errors:

Undefined symbols for architecture arm64:
  "TestTLS::g_tls_val", referenced from:
      TestTLS::getTls() in main.o
      TestTLS::setTls(int) in main.o
      TestTLS::TestTLS() in main.o

What am I doing wrong there?