问:
Why is my calculator not responding to my if statements?
Newbie programmer here. I'm finished with this project I was working on, and all of my if and else statements function properly, but only when they are placed at the very top of the code I'm writing.

For example, I started writing this code from if(number == 1) and worked my way down, but I eventually had to cut and paste them at the top, because when I entered a value that wasn't 1 (the first if statement, and thus the top statement that functions), the calculator failed to print anything at all when inputting a value for anything else except the top one. Because 4 is at the top, it works fine, but 1-3 don't work, and if I was to put 1 at the top then 2-4 would not print anything.

Here is a screeshot of the if statements on the bottom that do not print, and also have no debugging signs:

I'm sure it's a small issue that I managed to turn big.

```<code>#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int number;
    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;
    if(number <= 0)
    {
        cout<<"Integer is invalid, try again ";
        cin>> number;
    }
    if(number == 4)
    {
        cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
    }
     cin>> majxis;
     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     }
     cin>> minxis;
     area4= PI*minxis*majxis;
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }
    if(number == 3)
    {
        cout<<"\nWhat is the length of the top of the trapezoid? ";
    }
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     }
     cin>> bott;
     if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     }
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }
    if(number == 2)
    {
        cout<<"\nWhat is the length of the base of the triangle?";
    }
    cin>> trib;
    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    }
    cin>> trih;
    area2 = (0.5*trib)*trih;
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }
    if(number == 1)
    {
        cout<<"\nWhat is the radius of the circle?";
    }
    cin>> R1;
    area1 = PI*(R1 *R1);
    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }
}
</code>```

答:
There is a problem with your if statement..
as the well defined answer is already given, I am simplifying your code's readability and suggesting more better way to do this..

NOTE: Considering you're new bie.

Create Functions to handle different quadrilaterals

```<code>#include <iostream>
#include <iomanip>
using namespace std;

    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;

void handle_circle();
void handle_ellipse();
void handle_triangle();
void handle_trapizoid();

int main()
{
    int number;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;
    if(number <= 0)
    {
        cout<<"Integer is invalid, try again ";
        cin>> number;
    }
    if(number == 4)
    {
        handle_ellipse();
    }
    if(number == 3)
    {
        handle_trapizoid();
    }
    if(number == 2)
    {
        handle_triangle();
    }

    if(number == 1)
    {
        handle_circle();
    }
}

void handle_trapizoid()
{
         cout<<"\nWhat is the length of the top of the trapezoid? ";
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     cin>> bott;
     }

    if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     }
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }

}

void handle_ellipse()
{
     cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
     cin>> majxis;

     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     cin>> minxis;
     area4= PI*minxis*majxis;
     }
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }

}

void handle_triangle()
{
    cout<<"\nWhat is the length of the base of the triangle?";
    cin>> trib;

    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    cin>> trih;
    area2 = (0.5*trib)*trih;
    }
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }

}

void handle_circle()
{
    cout<<"\nWhat is the radius of the circle?";
    cin>> R1;
    area1 = PI*(R1 *R1);

    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }

}

</code>```

Also you can use switch statement as it is more faster than if statements

```<code>#include <iostream>
#include <iomanip>
using namespace std;

    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;

void handle_circle();
void handle_ellipse();
void handle_triangle();
void handle_trapizoid();

int main()
{
    int number;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;

    switch(number)
    {
        case 1:
        handle_circle();
        break;

        case 2:
        handle_triangle();
        break;

        case 3:
        handle_ellipse();
        break;

        case 4:
        handle_trapizoid();
        break;

        default:
        {
        cout<<"Integer is invalid, try again ";
        }
    }
}

void handle_trapizoid()
{
         cout<<"\nWhat is the length of the top of the trapezoid? ";
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     cin>> bott;
     }

    if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     }
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }

}

void handle_ellipse()
{
     cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
     cin>> majxis;

     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     cin>> minxis;
     area4= PI*minxis*majxis;
     }
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }

}

void handle_triangle()
{
    cout<<"\nWhat is the length of the base of the triangle?";
    cin>> trib;

    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    cin>> trih;
    area2 = (0.5*trib)*trih;
    }
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }

}

void handle_circle()
{
    cout<<"\nWhat is the radius of the circle?";
    cin>> R1;
    area1 = PI*(R1 *R1);

    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }

}
</code>```

Body:
Newbie programmer here. I'm finished with this project I was working on, and all of my if and else statements function properly, but only when they are placed at the very top of the code I'm writing.

For example, I started writing this code from if(number == 1) and worked my way down, but I eventually had to cut and paste them at the top, because when I entered a value that wasn't 1 (the first if statement, and thus the top statement that functions), the calculator failed to print anything at all when inputting a value for anything else except the top one. Because 4 is at the top, it works fine, but 1-3 don't work, and if I was to put 1 at the top then 2-4 would not print anything.

Here is a screeshot of the if statements on the bottom that do not print, and also have no debugging signs:

I'm sure it's a small issue that I managed to turn big.

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int number;
    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;
    if(number <= 0)
    {
        cout<<"Integer is invalid, try again ";
        cin>> number;
    }
    if(number == 4)
    {
        cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
    }
     cin>> majxis;
     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     }
     cin>> minxis;
     area4= PI*minxis*majxis;
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }
    if(number == 3)
    {
        cout<<"\nWhat is the length of the top of the trapezoid? ";
    }
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     }
     cin>> bott;
     if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     }
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }
    if(number == 2)
    {
        cout<<"\nWhat is the length of the base of the triangle?";
    }
    cin>> trib;
    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    }
    cin>> trih;
    area2 = (0.5*trib)*trih;
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }
    if(number == 1)
    {
        cout<<"\nWhat is the radius of the circle?";
    }
    cin>> R1;
    area1 = PI*(R1 *R1);
    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }
}

Body:
There is a problem with your if statement..
as the well defined answer is already given, I am simplifying your code's readability and suggesting more better way to do this..

NOTE: Considering you're new bie.

Create Functions to handle different quadrilaterals

#include <iostream>
#include <iomanip>
using namespace std;

    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;

void handle_circle();
void handle_ellipse();
void handle_triangle();
void handle_trapizoid();

int main()
{
    int number;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;
    if(number <= 0)
    {
        cout<<"Integer is invalid, try again ";
        cin>> number;
    }
    if(number == 4)
    {
        handle_ellipse();
    }
    if(number == 3)
    {
        handle_trapizoid();
    }
    if(number == 2)
    {
        handle_triangle();
    }

    if(number == 1)
    {
        handle_circle();
    }
}

void handle_trapizoid()
{
         cout<<"\nWhat is the length of the top of the trapezoid? ";
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     cin>> bott;
     }

    if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     }
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }

}

void handle_ellipse()
{
     cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
     cin>> majxis;

     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     cin>> minxis;
     area4= PI*minxis*majxis;
     }
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }

}

void handle_triangle()
{
    cout<<"\nWhat is the length of the base of the triangle?";
    cin>> trib;

    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    cin>> trih;
    area2 = (0.5*trib)*trih;
    }
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }

}

void handle_circle()
{
    cout<<"\nWhat is the radius of the circle?";
    cin>> R1;
    area1 = PI*(R1 *R1);

    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }

}

Also you can use switch statement as it is more faster than if statements

#include <iostream>
#include <iomanip>
using namespace std;

    float area1, area2, area3, area4;
    int R1;
    int trib;
    int trih;
    int top;
    int bott;
    int traph;
    int majxis;
    int minxis;
    const float PI= 3.14159;

void handle_circle();
void handle_ellipse();
void handle_triangle();
void handle_trapizoid();

int main()
{
    int number;
    cout<< "I'm starting my program ";
    cout<<"\n1.Circle";
    cout<<"\n2.triangle";
    cout<<"\n3.trapezoid";
    cout<<"\n4.ellipse ";
    cout<<"\nEnter the corresponding number of your choice(1-4):";
    cin>> number;

    switch(number)
    {
        case 1:
        handle_circle();
        break;

        case 2:
        handle_triangle();
        break;

        case 3:
        handle_ellipse();
        break;

        case 4:
        handle_trapizoid();
        break;

        default:
        {
        cout<<"Integer is invalid, try again ";
        }
    }
}

void handle_trapizoid()
{
         cout<<"\nWhat is the length of the top of the trapezoid? ";
     cin>> top;

     if(top <=0 )
     {
         cout<<"\n Invalid value for top length of trapezoid, try again";
     }
     else
     {
         cout<<"\nWhat is the length of the bottom of the trapezoid? ";
     cin>> bott;
     }

    if (bott <= 0)
     {
         cout<<"Invalid value for bottom length of trapezoid, try again: ";
     }
     else
     {
         cout<<"What is the height of the trapezoid? ";
     cin>>traph;
     area3 = (top+bott)*0.5+traph;
     }
     if (traph <= 0)
     {
         cout<<"Invalid value for height of trapezoid";
     }
     else
     {
         cout<<"The area of a trapezoid with a bottom of " << bott << "and a top of " << top << "is " << area3;
     }

}

void handle_ellipse()
{
     cout<<"\nWhat is the length of the semi-major axis of the ellipse? ";
     cin>> majxis;

     if(majxis <=0)
     {
         cout<<"Invalid value for the semi-major axis, try again: ";
     }
     else
     {
         cout<<"What is the length for the semi-minor axis of the ellipse? ";
     cin>> minxis;
     area4= PI*minxis*majxis;
     }
     if(minxis <=0)
     {
         cout<<"Invalid value for the semi-minor axis, try again: ";
     }
     else
     {
         cout<<"The area of an ellipse with a semi-major axis of " << majxis<< "and a semi-minor axis of " << minxis << "is " << area4;
     }

}

void handle_triangle()
{
    cout<<"\nWhat is the length of the base of the triangle?";
    cin>> trib;

    if(trib<=0)
    {
        cout<<"\nInvalid Base of triangle, try again:";
    }
    else
    {
        cout<<"\nWhat is the height of the triangle? ";
    cin>> trih;
    area2 = (0.5*trib)*trih;
    }
    if(trih<=0)
    {
        cout<<"\nInvalid height of triangle, try again:";
    }
    else
    {
        cout<<"\nThe area of a trangle with a base of " << trib << "and a height of "<< trih <<" is " << area2;
    }

}

void handle_circle()
{
    cout<<"\nWhat is the radius of the circle?";
    cin>> R1;
    area1 = PI*(R1 *R1);

    if( R1 <=0)
    {cout<<"\nRadius must be greater than 0, try again";
        cin>> R1;
    }
    else
    {
        cout<< "\nThe area of a circle with a radius of " << R1 << " is" << area1;
    }

}


来源: stackexchange

问:
Input element by user into 2D vector c++
I'a trying to implement an algorithm,  i want to input element by the user into 2D vector so that I have an element like this:

```<code>reference 1:
1 2 3
3 2 1
1 2 3
</code>```

so I want to know how to push_back the element into 2D vector

my problem here:

```<code>std::vector<vector<int>> d;
//std::vector<int> d;
cout<<"Enter the N number of ship and port:"<<endl;
cin>>in;
cout<<"\Enter preference etc..:\n";
for(i=0; i<in; i++){
cout<<"ship"<<i+1<<":"<<' ';
    for(j=0; j<in; j++){
    cin>>temp;
    d.push_back(temp);// I don't know how to push_back here!!
    }
}
</code>```

答:
```<code>vector<vector<int>> matrix; //declaring 2D vactor as matrix

int val;
cin>>val; //reading size of matrix in val

for(int i=0;i<val;i++){
    vector<int> temp; //make temp vector for storing val for every iteration
    for(int j=0;j<val;j++){
        int x;
        cin>>x;
        temp.emplace_back(x);
    }
    matrix.emplace_back(temp); // push back to matrix, temp vector's all value for every iteration
    temp.clear(); // clear temp vector for every iteration
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'a trying to implement an algorithm,  i want to input element by the user into 2D vector so that I have an element like this:

reference 1:
1 2 3
3 2 1
1 2 3

so I want to know how to push_back the element into 2D vector

my problem here:

std::vector<vector<int>> d;
//std::vector<int> d;
cout<<"Enter the N number of ship and port:"<<endl;
cin>>in;
cout<<"\Enter preference etc..:\n";
for(i=0; i<in; i++){
cout<<"ship"<<i+1<<":"<<' ';
    for(j=0; j<in; j++){
    cin>>temp;
    d.push_back(temp);// I don't know how to push_back here!!
    }
}

ContentLicense: CC BY-SA 4.0


问:
Stack multiple columns on top of eachother on Google Sheet?
I am using Google SpreadSheet, and I'm trying to import data from different sources together using a combination of query, importrange and curly brackets:

```<code>={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}
</code>```

But the result formula only returns SheetA data.

Since I only need 4 particular columns from SheetA and SheetB, I'd want the columns from both sheets to stack on top of eachother like this:

Col1
Col2
Col3
Col4

Data SheetA
Data SheetA
Data SheetA
Data SheetA

Data SheetB
Data SheetB
Data SheetB
Data SheetB

I tried running each =query(importrange) individually and combine them afterwards using {A:D;E:H} but it gives Result was not automatically expanded, please insert more rows error.

I tried looking for other similar threads but they were mostly about stacking different columns into one singular column. Can you help me with my case?

答:
Where you have 2 source files (Source1, Source2), and you want to use stack the data using IMPORTRANGE into another file (Combined)

There are 2 parts to this solution, and you can do Part 1 and Part 2 in any order.

Part 1

Give approvals to each of the imported ranges.

On a temporary sheet (that can be removed later) in the Combined file.

Use a standard IMPORTRANGE formula like this for Source1 (example, where you must replace "Source1_ID" with the ID of your Source1 file):

```<code>=IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source1_ID", "Sheet1!A2:D")
</code>```

After you have given approval, delete the formula from the cell, and do it again for Source2 (example, where you must replace "Source2_ID" with the ID of your Source2 file)

```<code>=IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source2_ID", "Sheet1!A2:D")
</code>```

Part 2

In the Combined file, go to the sheet where you want the combined data, and enter in the complete QUERY formula (example, where you must replace "Source1_ID" and "Source2_ID" with the ID's of both of your source files)

```<code>=QUERY({IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source1_ID", "Sheet1!A2:D"); IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source2_ID", "Sheet1!A2:D")}, "Select Col1, Col2, Col3, Col4 Where Col1 Is Not Null")
</code>```

Body:
I am using Google SpreadSheet, and I'm trying to import data from different sources together using a combination of query, importrange and curly brackets:

={Query(Importrange(SheetA),"select Col1,Col2,Col3,Col4 where Col1 is not null");
Query(Importrange(SheetB),"select Col1,Col2,Col3,Col4 where Col1 is not null")}

But the result formula only returns SheetA data.

Since I only need 4 particular columns from SheetA and SheetB, I'd want the columns from both sheets to stack on top of eachother like this:

Col1
Col2
Col3
Col4

Data SheetA
Data SheetA
Data SheetA
Data SheetA

Data SheetB
Data SheetB
Data SheetB
Data SheetB

I tried running each =query(importrange) individually and combine them afterwards using {A:D;E:H} but it gives Result was not automatically expanded, please insert more rows error.

I tried looking for other similar threads but they were mostly about stacking different columns into one singular column. Can you help me with my case?

Body:
Where you have 2 source files (Source1, Source2), and you want to use stack the data using IMPORTRANGE into another file (Combined)

There are 2 parts to this solution, and you can do Part 1 and Part 2 in any order.

Part 1

Give approvals to each of the imported ranges.

On a temporary sheet (that can be removed later) in the Combined file.

Use a standard IMPORTRANGE formula like this for Source1 (example, where you must replace "Source1_ID" with the ID of your Source1 file):

=IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source1_ID", "Sheet1!A2:D")

After you have given approval, delete the formula from the cell, and do it again for Source2 (example, where you must replace "Source2_ID" with the ID of your Source2 file)

=IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source2_ID", "Sheet1!A2:D")

Part 2

In the Combined file, go to the sheet where you want the combined data, and enter in the complete QUERY formula (example, where you must replace "Source1_ID" and "Source2_ID" with the ID's of both of your source files)

=QUERY({IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source1_ID", "Sheet1!A2:D"); IMPORTRANGE("https://docs.google.com/spreadsheets/d/Source2_ID", "Sheet1!A2:D")}, "Select Col1, Col2, Col3, Col4 Where Col1 Is Not Null")


问:
ToolTip is not closing with Select2
I am using jQuery UI ToolTip with Select2. My code is like below.

```<code>$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('<span class="tooltip" title="' + data_format.title + '">' + data_format.text + '</span>');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('<span class="tooltip" title="' + state.title + '">' + state.text + '('+ state.text1 +')</span>');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '<table> \
                        <tr> \
                        <td>Organisation</td> \
                        <td>'+text[2][1]+'</td> \
                        </tr> \
                        <tr> \
                        <td>Age</td> \
                        <td>'+ text[2][0]+'</td> \
                        </tr> \
                    </table>';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("<div>")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});

</code>```

After selection of a value ToolTip is not closing.

I am getting below error message in console.

$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('' + data_format.text + '');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('' + state.text + '('+ state.text1 +')');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '
 \

 \
                        Organisation	 \
                        '+text[2][1]+'	 \

 \

 \
                        Age	 \
                        '+ text[2][0]+'	 \

 \

';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("
")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>

<table style="text-align:left;min-width:800px;margin-top: 0 !important;">
                    <tbody><tr>
                    <th style="min-width:100px">Task +</th>
                    <th style="min-width:150px">Time</th>
                    <th style="min-width:180px">volunteers</th>
                    <th style="width:50%">Comment</th></tr><tr>
                    <td>test 1</td>
                    <td>09:00 - 12:00</td>
                    <td class="volunteer" id="1485"></td>
                    <td><p>hello</p>
</td>
                    </tr><tr>
                    <td>test2</td>
                    <td>09:00 - 12:00</td>
                    <td class="volunteer" id="1486"></td>
                    <td><p>test</p>
</td>
                    </tr></tbody></table></code>```

Three state of the issue.

First state when I click on td and select2 drop down is displaying.

Second state when I hove over a value of select2 drop down and ToolTip is displaying.

Third state when I click on a value of select2 and that value is selected but Tooltip still displaying. I need to close, remove or destroy the ToolTip. I can see an error message in console also.

I am trying to replicate my issue here. But I am not so expert about jsfiddle that's why I couldn't do it properly.

答:
You are creating tooltip on only one option and trying to close tooltips on all the options. So other options without tooltip are throwing the error cannot call methods on tooltip prior to initialization; attempted to call method 'close'

I've fixed it on JSFiddle

 $('.js-data-example-ajax').on("select2:close", e =>
    closeTooltips()
  );
  $('.js-data-example-ajax').on("select2:selecting", e =>
    closeTooltips()
  );

function closeTooltips() {
  $('.select2-results__option').each(function() {
    try {
      $(this).tooltip('close');
    } catch (e) {}
  });
}

```

Note: You may have to handle more select2 events.On JsFiddle it takes time for tooltip to showup don't know why. Keep hovering over elements.

Title: ToolTip is not closing with Select2

Body:
I am using jQuery UI ToolTip with Select2. My code is like below.

$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('' + data_format.text + '');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('' + state.text + '('+ state.text1 +')');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '
 \

 \
                        Organisation	 \
                        '+text[2][1]+'	 \

 \

 \
                        Age	 \
                        '+ text[2][0]+'	 \

 \

';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("
")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});

After selection of a value ToolTip is not closing.

I am getting below error message in console.

$(".volunteer").on("click", function (event) {

    function templateSelection(data_format) {
        if (!data_format.id) { return data_format.text; }
        var output = $('' + data_format.text + '');
        return output;
    };

    function resultfucntion(state) {
        if (!state.id) { return state.text;}
        var $state = $('' + state.text + '('+ state.text1 +')');
        return $state;
    };

    var orga_id = $('#orga').val();

    var cellEle = $(this);

    // Populate select element
    cellEle.html(`<select multiple="multiple"></select>`);

    // Initialise select2
    let selectEle = cellEle.children("select").select2({
        ajax: {
            url: "/wp-admin/admin-ajax.php",
            data: function (params) {
                return {
                    action: 'get_data',
                    search: params.term,
                    orga_id: orga_id,
                };
            },
            processResults: function (data) {
                var options = [];
                if (data) {
                    $.each(data, function (index, text) {
                    var user_data = '
 \

 \
                        Organisation	 \
                        '+text[2][1]+'	 \

 \

 \
                        Age	 \
                        '+ text[2][0]+'	 \

 \

';
                        options.push({ id: index, text: text[0], text1: text[1], title: user_data });
                    });
                }
                return {
                    results: options,
                    more: false
                };
            },
        },
        templateSelection: templateSelection,
        templateResult: resultfucntion,
    });
});

selectEle.on("select2:opening", function (e) {
  $(document).on("mouseenter", ".select2-results__option", function () {
    $(this).tooltip({
      position: {
        my: "center bottom-20",
        at: "center top",
        using: function (position, feedback) {
          $(this).css(position);
          var txt = $(this).text();
          $(this).html(txt);
          $("
")
            .addClass("arrow")
            .addClass(feedback.vertical)
            .addClass(feedback.horizontal)
            .appendTo(this);
        },
      },
    });
  });
});

selectEle.on("select2:closing", function (e) {
    $('.select2-results__option').tooltip('close');  // This code is not working.
    $('.select2-results__option .tooltip').tooltip('close');  // This code is not working.
});

selectEle.on("select2:select", function () {
    $(".select2-results__option").tooltip("close");   // This code is not working.
    $(".select2-results__option .tooltip").tooltip("close");  // This code is not working.
});

                    Task +
                    Time
                    volunteers
                    Comment

                    test 1
                    09:00 - 12:00

hello

                    test2
                    09:00 - 12:00

test

Three state of the issue.

First state when I click on td and select2 drop down is displaying.

Second state when I hove over a value of select2 drop down and ToolTip is displaying.

Third state when I click on a value of select2 and that value is selected but Tooltip still displaying. I need to close, remove or destroy the ToolTip. I can see an error message in console also.

I am trying to replicate my issue here. But I am not so expert about jsfiddle that's why I couldn't do it properly.

Body:
You are creating tooltip on only one option and trying to close tooltips on all the options. So other options without tooltip are throwing the error cannot call methods on tooltip prior to initialization; attempted to call method 'close'

I've fixed it on JSFiddle

 $('.js-data-example-ajax').on("select2:close", e =>
    closeTooltips()
  );
  $('.js-data-example-ajax').on("select2:selecting", e =>
    closeTooltips()
  );

function closeTooltips() {
  $('.select2-results__option').each(function() {
    try {
      $(this).tooltip('close');
    } catch (e) {}
  });
}

Note: You may have to handle more select2 events.On JsFiddle it takes time for tooltip to showup don't know why. Keep hovering over elements.


问:
How can you use parameterized statements with DB2 Text Search?
I've tried this:

```<code>select * from ourschema.mytable
    where contains(mysearchablefield, @searchTerms) = 1;
</code>```

Where @searchTerms was set to "search terms"

Unfortunately, it only produced an error:

```<code>ERROR [42610] [IBM][DB2/NT] SQL0418N A statement contains a use of a parameter marker that is not valid. SQLSTATE=42610
</code>```

Is there a way to use parameterized queries for text search with DB2?  If not, is there a document which describes the syntax in detail for manual (ugh) escaping of the search terms (quotes, etc)?

答:
Instead of @field you need to use "?". Everything is basically the same.

Okay, here is a live code sample.

```<code>            sqlStmt = "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
            "DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
            "EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
            "COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 1 AS SORTORDER " +
            "FROM QMFILES/NVMASTP " +
            "WHERE VCLOSEDATE = 0 AND " +
            "DEPT_CODE LIKE @DEPT_CODE1 AND " +
            "DIVISION_CODE LIKE @DIVISION_CODE1 AND " +
            "COMPLAINT_DATE BETWEEN @FROM_COMPLAINT_DATE1 AND @TO_COMPLAINT_DATE1 " +
            statusQry +
            "UNION " +
            "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
            "DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
            "EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
            "COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 2 AS SORTORDER " +
            "FROM QMFILES/NVMASTP " +
            "WHERE VCLOSEDATE <> 0 AND " +
            "DEPT_CODE LIKE @DEPT_CODE2 AND " +
            "DIVISION_CODE LIKE @DIVISION_CODE2 AND " +
            "COMPLAINT_DATE BETWEEN @FROM_COMPLAINT_DATE2 AND @TO_COMPLAINT_DATE2 " +
            statusQry +
            "ORDER BY DEPT_CODE, DIVISION_CODE, COMPLAINT_CODE, SORTORDER";

        iDB2Command cmd = new iDB2Command(sqlStmt, conn);
        conn.Open();
        cmd.DeriveParameters();
        conn.Close();
        cmd.Parameters["@DEPT_CODE1"].Value = dept;
        cmd.Parameters["@DIVISION_CODE1"].Value = serviceArea;
        cmd.Parameters["@DEPT_CODE2"].Value = dept;
        cmd.Parameters["@DIVISION_CODE2"].Value = serviceArea;
        cmd.Parameters["@FROM_COMPLAINT_DATE1"].Value = Convert.ToDecimal(fromDateString);
        cmd.Parameters["@TO_COMPLAINT_DATE1"].Value = Convert.ToDecimal(toDateString);
        cmd.Parameters["@FROM_COMPLAINT_DATE2"].Value = Convert.ToDecimal(fromDateString);
        cmd.Parameters["@TO_COMPLAINT_DATE2"].Value = Convert.ToDecimal(toDateString);
</code>```

I hope this helps you out more.

OwnerDisplayName: jsight

Body:
I've tried this:

select * from ourschema.mytable
    where contains(mysearchablefield, @searchTerms) = 1;

Where @searchTerms was set to "search terms"

Unfortunately, it only produced an error:

ERROR [42610] [IBM][DB2/NT] SQL0418N A statement contains a use of a parameter marker that is not valid. SQLSTATE=42610

Is there a way to use parameterized queries for text search with DB2?  If not, is there a document which describes the syntax in detail for manual (ugh) escaping of the search terms (quotes, etc)?

Body:
Instead of @field you need to use "?". Everything is basically the same.

Okay, here is a live code sample.

            sqlStmt = "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
            "DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
            "EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
            "COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 1 AS SORTORDER " +
            "FROM QMFILES/NVMASTP " +
            "WHERE VCLOSEDATE = 0 AND " +
            "DEPT_CODE LIKE @DEPT_CODE1 AND " +
            "DIVISION_CODE LIKE @DIVISION_CODE1 AND " +
            "COMPLAINT_DATE BETWEEN @FROM_COMPLAINT_DATE1 AND @TO_COMPLAINT_DATE1 " +
            statusQry +
            "UNION " +
            "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
            "DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
            "EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
            "COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 2 AS SORTORDER " +
            "FROM QMFILES/NVMASTP " +
            "WHERE VCLOSEDATE <> 0 AND " +
            "DEPT_CODE LIKE @DEPT_CODE2 AND " +
            "DIVISION_CODE LIKE @DIVISION_CODE2 AND " +
            "COMPLAINT_DATE BETWEEN @FROM_COMPLAINT_DATE2 AND @TO_COMPLAINT_DATE2 " +
            statusQry +
            "ORDER BY DEPT_CODE, DIVISION_CODE, COMPLAINT_CODE, SORTORDER";

        iDB2Command cmd = new iDB2Command(sqlStmt, conn);
        conn.Open();
        cmd.DeriveParameters();
        conn.Close();
        cmd.Parameters["@DEPT_CODE1"].Value = dept;
        cmd.Parameters["@DIVISION_CODE1"].Value = serviceArea;
        cmd.Parameters["@DEPT_CODE2"].Value = dept;
        cmd.Parameters["@DIVISION_CODE2"].Value = serviceArea;
        cmd.Parameters["@FROM_COMPLAINT_DATE1"].Value = Convert.ToDecimal(fromDateString);
        cmd.Parameters["@TO_COMPLAINT_DATE1"].Value = Convert.ToDecimal(toDateString);
        cmd.Parameters["@FROM_COMPLAINT_DATE2"].Value = Convert.ToDecimal(fromDateString);
        cmd.Parameters["@TO_COMPLAINT_DATE2"].Value = Convert.ToDecimal(toDateString);

I hope this helps you out more.

OwnerDisplayName: Mike Wills

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mike Wills


问:
PDDL syntax error, ':DURATIVE-ACTIONS' : domain definition expected
I was modeling a domain file with durative actions. I am using the PDDL plugin for VS Code. The code does not have any syntax error problems. The Planner from HTTP://solver.planning.domains/solve return an error

/tmp/solver_planning_domains_tmp_41rdIKx0z0gCb/domain.pddl: syntax error in line 5, ':DURATIVE-ACTIONS': domain definition expected Failed to parse the problem -- list index out of range

The complete domain file big to post here, so the related part of code is:
I appreciated your help.

```<code>(define (domain test)

(:requirements :strips :typing :fluents :durative-actions :duration-inequalities :negative-preconditions :equality )
(:types
    getbot - robot
    wp0 wp1 charging_station object_location - location
    a1 a2 a3 - area
    bat1 charger - power
    gripper
    obj- object
)

(:predicates
    ;General predicates
    (robot-at ?rb - robot ?l - location)
    (location-situated ?l - location ?a - area)    ;location situated in which area

    ;Gripper related predicates
    (object-found ?o - object)
    (object-at ?o - object ?obj_loc - location)
    (object-placed ?o - object ?obj_loc - location)
    (gripper-empty ?rb - robot ?gr - gripper)
    (holding-object ?rb - robot ?o - object)
</code>```

Thank you in advance

答: The planner on that server doesn't support durative actions.</p>

Body:
I was modeling a domain file with durative actions. I am using the PDDL plugin for VS Code. The code does not have any syntax error problems. The Planner from HTTP://solver.planning.domains/solve return an error

/tmp/solver_planning_domains_tmp_41rdIKx0z0gCb/domain.pddl: syntax error in line 5, ':DURATIVE-ACTIONS': domain definition expected Failed to parse the problem -- list index out of range

The complete domain file big to post here, so the related part of code is:
I appreciated your help.

(define (domain test)

(:requirements :strips :typing :fluents :durative-actions :duration-inequalities :negative-preconditions :equality )
(:types
    getbot - robot
    wp0 wp1 charging_station object_location - location
    a1 a2 a3 - area
    bat1 charger - power
    gripper
    obj- object
)

(:predicates
    ;General predicates
    (robot-at ?rb - robot ?l - location)
    (location-situated ?l - location ?a - area)    ;location situated in which area

    ;Gripper related predicates
    (object-found ?o - object)
    (object-at ?o - object ?obj_loc - location)
    (object-placed ?o - object ?obj_loc - location)
    (gripper-empty ?rb - robot ?gr - gripper)
    (holding-object ?rb - robot ?o - object)

Thank you in advance


问:
Is there a R function that allows you to insert a variable inside a command?
For example:
Imagine I have an object named "cors" which contains a string only ("Spain" for example). I would like then for "cors" to be replaced in the expression (1) below by "Spain", resulting in the expression (2):

```<code>#(1)
DF <- DF %>% filter(str_detect(Country, "Germany|cors", negate = TRUE))
</code>```
```<code>#(2)
DF <- DF %>% filter(str_detect(Country, "Germany|Spain", negate = TRUE))
</code>```

P.S: I know that in MATLAB this could be handled with the "eval()" command, though in R it apparently has a completely different applicability.

答:
If we have an object, then place it outside the quotes and use paste/str_c to create the string

```<code>library(dplyr)
library(stringr)
cors <- "Spain"
pat <- str_c(c("Germany", cors),  collapse = "|")
DF %>%
    filter(str_detect(Country, pat, negate = TRUE))
</code>```

Or another option is to string interpolate with glue (assuming cors object have only a single string element)

```<code>DF %>%
    filter(str_detect(Country, glue::glue("Germany|{cors}"), negate = TRUE))
</code>```

Or this can be done in base R with grepl

```<code>pat <- paste(c("Germany", cors), collapse = "|")
subset(DF, !grepl(pat, Country))
</code>```

Body:
For example:
Imagine I have an object named "cors" which contains a string only ("Spain" for example). I would like then for "cors" to be replaced in the expression (1) below by "Spain", resulting in the expression (2):

#(1)
DF <- DF %>% filter(str_detect(Country, "Germany|cors", negate = TRUE))

#(2)
DF <- DF %>% filter(str_detect(Country, "Germany|Spain", negate = TRUE))

P.S: I know that in MATLAB this could be handled with the "eval()" command, though in R it apparently has a completely different applicability.

Body:
If we have an object, then place it outside the quotes and use paste/str_c to create the string

library(dplyr)
library(stringr)
cors <- "Spain"
pat <- str_c(c("Germany", cors),  collapse = "|")
DF %>%
    filter(str_detect(Country, pat, negate = TRUE))

Or another option is to string interpolate with glue (assuming cors object have only a single string element)

DF %>%
    filter(str_detect(Country, glue::glue("Germany|{cors}"), negate = TRUE))

Or this can be done in base R with grepl

pat <- paste(c("Germany", cors), collapse = "|")
subset(DF, !grepl(pat, Country))


问:
 tags showing different behaviour
When I'm using
 tags to create horizontal rows then the behavior is not uniform i.e. all the
s (in my case) are displaying alternate background color.

Also, I've tested in Chrome and opera and the zoom level was 100% at the time of testing.

For reference, below is the image:-

hr{
    border-style: none;
    width: 10%;
    height: 2px;
    background-color: rgba(0, 0, 0, 0.253) ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr></code>```

答:
Turn background-color:transparent and border:0 - to remove default properties as set by browser, and use either of (border-top, border-bottom) to have consistant height. Also, refer to: Why are half of my
s being styled differently than the others?

hr{
    border:0;
    width: 10%;
    height: 2px;
    background-color: transparent;
    border-top:1px solid #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr></code>```

Title: <hr> tags showing different behaviour

Body:
Turn background-color:transparent and border:0 - to remove default properties as set by browser, and use either of (border-top, border-bottom) to have consistant height. Also, refer to: Why are half of my <hr>s being styled differently than the others?

hr{
    border:0;
    width: 10%;
    height: 2px;
    background-color: transparent;
    border-top:1px solid #000;
}

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>
<br>

<hr>


问:
Godot 3.4: Quest System Task Advancement
So I managed to solve my previous problem about not being able to modify a dictionary(stupid me), but now im more or less stuck on the concept of task advancement.

So I have a quest system(dictionary), with sub-dictionaries such as "tasks"
I want a single function to advance the quest, and I'm thinking something like this:

```<code>if not all_tasks in Quest are complete:
   find the first task that has a "completed" bool value of false
   change bool value to true
else: (all tasks have "completed" value of true)
   complete quest instead.
</code>```

And I'm thinking it will have to be an array of tasks.
But I'm not sure how to implement this and I keep getting stuck on the logic. It's way easier to write it out logically than to actually implement it in code.

So, what do you think? Is this a valid way of going about this? is there a better way?
If this is a good way, how would I go about finding the first task in the array that is not complete, and then complete it?

答:
```<code>func advanceQuest(questName: String):
if PlayerData.playerData.quests_active.has(questName):

    var taskList = []

    if PlayerData.playerData.quests_active.get(questName).get("taskType") == 0:
        for task in PlayerData.playerData.quests_active.get(questName).get("tasks"):
            if PlayerData.playerData.quests_active.get(questName).get("tasks").get(task).get("completed") == false:
                taskList.append(task)
        if taskList != []:
            PlayerData.playerData.quests_active[questName]["tasks"][taskList[0]]["completed"] = true
        else:
            completeQuest(questName)

    else:
        #Syncronous Task Type
        pass
else:
</code>```

Got it!!!!!

Body:
So I managed to solve my previous problem about not being able to modify a dictionary(stupid me), but now im more or less stuck on the concept of task advancement.

So I have a quest system(dictionary), with sub-dictionaries such as "tasks"
I want a single function to advance the quest, and I'm thinking something like this:

if not all_tasks in Quest are complete:
   find the first task that has a "completed" bool value of false
   change bool value to true
else: (all tasks have "completed" value of true)
   complete quest instead.

And I'm thinking it will have to be an array of tasks.
But I'm not sure how to implement this and I keep getting stuck on the logic. It's way easier to write it out logically than to actually implement it in code.

So, what do you think? Is this a valid way of going about this? is there a better way?
If this is a good way, how would I go about finding the first task in the array that is not complete, and then complete it?

Body:
func advanceQuest(questName: String):
if PlayerData.playerData.quests_active.has(questName):

    var taskList = []

    if PlayerData.playerData.quests_active.get(questName).get("taskType") == 0:
        for task in PlayerData.playerData.quests_active.get(questName).get("tasks"):
            if PlayerData.playerData.quests_active.get(questName).get("tasks").get(task).get("completed") == false:
                taskList.append(task)
        if taskList != []:
            PlayerData.playerData.quests_active[questName]["tasks"][taskList[0]]["completed"] = true
        else:
            completeQuest(questName)

    else:
        #Syncronous Task Type
        pass
else:

Got it!!!!!


问:
What does a function in a django model do?
i wrote this function in django model that would help send and get messages but tbh i do not understand what the code exactly does because the tutorial teacher didn't explain anything about the code and for days now i have been trying to figure out what the code does with no solutions yet.
I do not just want to copy and paste code from a tutorial, i want to also understand what each code does so that's why i would appreciate anyhelp.

The code

```<code>def get_messages(user):
        messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last')
        users = []
        for message in messages:
            users.append({
                'user': User.objects.get(pk=message['recipient']),
                'last': message['last'],
                'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count()
                })
        return users
</code>```

complete models.py

```<code>class Message(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
    sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user')
    recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user')
    body = models.TextField(max_length=1000, blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)
    is_read = models.BooleanField(default=False)

    def send_message(from_user, to_user, body):
        sender_message = Message(
            user=from_user,
            sender=from_user,
            recipient=to_user,
            body=body,
            is_read=True)
        sender_message.save()

        recipient_message = Message(
            user=to_user,
            sender=from_user,
            body=body,
            recipient=from_user,)
        recipient_message.save()
        return sender_message

    def get_messages(user):
        messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last')
        users = []
        for message in messages:
            users.append({
                'user': User.objects.get(pk=message['recipient']),
                'last': message['last'],
                'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count()
                })
        return users
</code>```

views.py if needed

```<code>def Inbox(request):
    messages = Message.get_messages(user=request.user)
    active_direct = None
    directs = None

    if messages:
        message = messages[0]
        active_direct = message['user'].username
        directs = Message.objects.filter(user=request.user, recipient=message['user'])
        directs.update(is_read=True)
        for message in messages:
            if message['user'].username == active_direct:
                message['unread'] = 0
</code>```

答:
Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last')

This will select all Messages for a specific user, of those Message object you are selecting the recipient value and the max date. This is equal to the following in SQL:

```<code>SELECT
    "messages"."recipient",
    MAX("messages"."date") AS "last"
FROM
    "messages"
WHERE
    "messages"."recipient" = x
GROUP BY
    "messages"."recipient",
    "messages"."date"
ORDER BY
    "messages"."date" DESC
</code>```

Then in the loop the user objects is retrieved by the recipient value:

'user': User.objects.get(pk=message['recipient']),

Unread will be set to the amount of messages that this user has sent to the given recipient but are still unread.

'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count()

Tip: if you ever have a django query, you can just call see the SQL query by doing the following: print(Message.objects.filter(...).query)

Body:
i wrote this function in django model that would help send and get messages but tbh i do not understand what the code exactly does because the tutorial teacher didn't explain anything about the code and for days now i have been trying to figure out what the code does with no solutions yet.
I do not just want to copy and paste code from a tutorial, i want to also understand what each code does so that's why i would appreciate anyhelp.

The code

def get_messages(user):
        messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last')
        users = []
        for message in messages:
            users.append({
                'user': User.objects.get(pk=message['recipient']),
                'last': message['last'],
                'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count()
                })
        return users

complete models.py

class Message(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user')
    sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user')
    recipient = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user')
    body = models.TextField(max_length=1000, blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)
    is_read = models.BooleanField(default=False)

    def send_message(from_user, to_user, body):
        sender_message = Message(
            user=from_user,
            sender=from_user,
            recipient=to_user,
            body=body,
            is_read=True)
        sender_message.save()

        recipient_message = Message(
            user=to_user,
            sender=from_user,
            body=body,
            recipient=from_user,)
        recipient_message.save()
        return sender_message

    def get_messages(user):
        messages = Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last')
        users = []
        for message in messages:
            users.append({
                'user': User.objects.get(pk=message['recipient']),
                'last': message['last'],
                'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count()
                })
        return users

views.py if needed

def Inbox(request):
    messages = Message.get_messages(user=request.user)
    active_direct = None
    directs = None

    if messages:
        message = messages[0]
        active_direct = message['user'].username
        directs = Message.objects.filter(user=request.user, recipient=message['user'])
        directs.update(is_read=True)
        for message in messages:
            if message['user'].username == active_direct:
                message['unread'] = 0

Body:
Message.objects.filter(user=user).values('recipient').annotate(last=Max('date')).order_by('-last')

This will select all Messages for a specific user, of those Message object you are selecting the recipient value and the max date. This is equal to the following in SQL:

SELECT
    "messages"."recipient",
    MAX("messages"."date") AS "last"
FROM
    "messages"
WHERE
    "messages"."recipient" = x
GROUP BY
    "messages"."recipient",
    "messages"."date"
ORDER BY
    "messages"."date" DESC

Then in the loop the user objects is retrieved by the recipient value:

'user': User.objects.get(pk=message['recipient']),

Unread will be set to the amount of messages that this user has sent to the given recipient but are still unread.

'unread': Message.objects.filter(user=user, recipient__pk=message['recipient'], is_read=False).count()

Tip: if you ever have a django query, you can just call see the SQL query by doing the following: print(Message.objects.filter(...).query)


问:
How to load a web page in the background in a Chrome extension?
I'm writing a Chrome extension that will add some information to a page, based on content from another webpage (on another domain).

This is done by asking the background service worker to load the page, then pass the relevant information back to the content script.

It's important that the page is loaded as if the user opened a tab with that page, so it'll use the user's login and other context (locale, etc).

content.js:

```<code>chrome.runtime.sendMessage('some-query', function(response) {
  console.log(response)
})
</code>```

background.js:

```<code>chrome.runtime.onMessage.addListener((message, sender, reply) => {
  loadInBackground(message, reply)
  return true
})

function loadInBackground(query, reply) {
  console.log('searching for', query)
  let url = new URL("https://some.site.com/search")
  url.searchParams.append("query", query)
  // How to load the page?
  reply('data-from-loaded-page')
}
</code>```

I've tried using fetch, but that gives a CORS error and even if it didn't, I don't expect it to use the state as if loaded in a tab. So, what hidden Chrome API can I use to do this? I've looked at all of these but I can't find the API I need.

答:
To use fetch in an extension script, add that URL or "<all_urls>" to host permissions.

But there's a bigger problem: the site's scripts won't run with fetch, so there'll be nothing useful to extract on many modern pages that construct themselves dynamically.

The only workaround for extensions in such cases is to open that site in a new tab or iframe because Chrome extensions don't have a WebView like Chrome Apps did, so extensions can't fully imitate a normal page load process. Note that Chrome Apps will soon cease to exist in Chrome.

The problem with opening the site in a new tab is that it will be visible to the user. You can reduce the annoyance by opening a new non-focused window (chrome.windows.create), but that will also produce some visual effect for many users depending on their desktop environment.

Thus, the only inconspicuous workaround is to create an iframe pointing to the remote page.

Create a web_accessible_resources-exposed iframe in the original web page because MV3 extensions don't have DOM in the background script. You won't need a background script at all for this task. The iframe can be "hidden" from the page inside a closed ShadowDOM. This iframe will have full access to all granted chrome API.

Optionally register a DNR rule to strip the deny header.

Add a child iframe with src pointing to the site you want to fetch.

Extract the data using executeScript with a frameId obtained via webRequest.

Send the data to the main content script.

manifest.json:

  "host_permissions": ["<all_urls>"],
  "permissions": ["declarativeNetRequestWithHostAccess", "scripting", "webRequest"],
  "web_accessible_resources": [{
    "resources": ["iframer.html"],
    "matches": ["<all_urls>"]
  }],
```
<p>main content script:</p>
<pre class="lang-js prettyprint-override"><code>(async () => {
  const data = await getRemoteSiteData('https://www.example.com', ['body']);
  console.log(data);
})();

function getRemoteSiteData(url, selectors) {
  const id = Math.random().toString(36).slice(2);
  const iframe = document.createElement('iframe');
  const el = document.createElement('div');
  const root = el.attachShadow({mode: 'closed'});
  root.appendChild(document.createElement('style')).textContent =
    ':host { display: none !important }';
  root.appendChild(iframe);
  iframe.src = chrome.runtime.getURL('iframer.html#' + id);
  document.body.appendChild(el);
  return new Promise(resolve => {
    chrome.runtime.onMessage.addListener(function _(msg, sender, sendResponse) {
      if (msg.id !== id) return;
      if (msg.init) {
        sendResponse({url, selectors, frameId: sender.frameId});
      } else {
        el.remove();
        chrome.runtime.onMessage.removeListener(_);
        resolve(msg.result);
      }
    });
  });
}
</code>```

iframer.html:

```
<p>iframer.js:</p>
<pre class="lang-js prettyprint-override"><code>(async () => {
  const id = location.hash.slice(1);
  const tabId = (await chrome.tabs.getCurrent()).id;
  const job = await chrome.tabs.sendMessage(tabId, {id, init: true});
  const iframe = document.createElement('iframe');
  let webFrameId;
  chrome.webRequest.onBeforeRequest.addListener(function _(info) {
    chrome.webRequest.onBeforeRequest.removeListener(_);
    webFrameId = info.frameId;
  }, {tabId, types: ['sub_frame']});
  iframe.src = job.url;
  document.body.appendChild(iframe);
  await new Promise(onload => Object.assign(iframe, {onload}));
  const data = await chrome.scripting.executeScript({
    target: {tabId, frameIds: [webFrameId]},
    args: [job.selectors],
    func: selectors => selectors.map(sel =>
      Array.from(document.querySelectorAll(sel),
        el => el.textContent)),
  })
  const {result} = data.find(d => d.frameId === webFrameId);
  await chrome.tabs.sendMessage(tabId, {id, result}, {frameId: job.frameId});
})();
</code>```

WARNING! An http:// URL cannot be loaded on a https:// site. You will see an error about mixed content being blocked in devtools console. The only workaround is to replace step 1 above with opening a new tab/window for the remote site and run a content script there, e.g. the original content script sends a message to the background script, which uses chrome.tabs.create + chrome.scripting.executeScript.

WARNING! Some sites use JS to stop loading in iframes by checking window == window.top.

This check can't be spoofed if it's done in an inline script element.

Body:
I'm writing a Chrome extension that will add some information to a page, based on content from another webpage (on another domain).

This is done by asking the background service worker to load the page, then pass the relevant information back to the content script.

It's important that the page is loaded as if the user opened a tab with that page, so it'll use the user's login and other context (locale, etc).

content.js:

chrome.runtime.sendMessage('some-query', function(response) {
  console.log(response)
})

background.js:

chrome.runtime.onMessage.addListener((message, sender, reply) => {
  loadInBackground(message, reply)
  return true
})

function loadInBackground(query, reply) {
  console.log('searching for', query)
  let url = new URL("https://some.site.com/search")
  url.searchParams.append("query", query)
  // How to load the page?
  reply('data-from-loaded-page')
}

I've tried using fetch, but that gives a CORS error and even if it didn't, I don't expect it to use the state as if loaded in a tab. So, what hidden Chrome API can I use to do this? I've looked at all of these but I can't find the API I need.

Body:
To use fetch in an extension script, add that URL or "<all_urls>" to host permissions.

But there's a bigger problem: the site's scripts won't run with fetch, so there'll be nothing useful to extract on many modern pages that construct themselves dynamically.

The only workaround for extensions in such cases is to open that site in a new tab or iframe because Chrome extensions don't have a WebView like Chrome Apps did, so extensions can't fully imitate a normal page load process. Note that Chrome Apps will soon cease to exist in Chrome.

The problem with opening the site in a new tab is that it will be visible to the user. You can reduce the annoyance by opening a new non-focused window (chrome.windows.create), but that will also produce some visual effect for many users depending on their desktop environment.

Thus, the only inconspicuous workaround is to create an iframe pointing to the remote page.

Create a web_accessible_resources-exposed iframe in the original web page because MV3 extensions don't have DOM in the background script. You won't need a background script at all for this task. The iframe can be "hidden" from the page inside a closed ShadowDOM. This iframe will have full access to all granted chrome API.

Optionally register a DNR rule to strip the deny header.

Add a child iframe with src pointing to the site you want to fetch.

Extract the data using executeScript with a frameId obtained via webRequest.

Send the data to the main content script.

manifest.json:

  "host_permissions": ["<all_urls>"],
  "permissions": ["declarativeNetRequestWithHostAccess", "scripting", "webRequest"],
  "web_accessible_resources": [{
    "resources": ["iframer.html"],
    "matches": ["<all_urls>"]
  }],

main content script:

(async () => {
  const data = await getRemoteSiteData('https://www.example.com', ['body']);
  console.log(data);
})();

function getRemoteSiteData(url, selectors) {
  const id = Math.random().toString(36).slice(2);
  const iframe = document.createElement('iframe');
  const el = document.createElement('div');
  const root = el.attachShadow({mode: 'closed'});
  root.appendChild(document.createElement('style')).textContent =
    ':host { display: none !important }';
  root.appendChild(iframe);
  iframe.src = chrome.runtime.getURL('iframer.html#' + id);
  document.body.appendChild(el);
  return new Promise(resolve => {
    chrome.runtime.onMessage.addListener(function _(msg, sender, sendResponse) {
      if (msg.id !== id) return;
      if (msg.init) {
        sendResponse({url, selectors, frameId: sender.frameId});
      } else {
        el.remove();
        chrome.runtime.onMessage.removeListener(_);
        resolve(msg.result);
      }
    });
  });
}

iframer.html:

<script src=iframer.js></script>

iframer.js:

(async () => {
  const id = location.hash.slice(1);
  const tabId = (await chrome.tabs.getCurrent()).id;
  const job = await chrome.tabs.sendMessage(tabId, {id, init: true});
  const iframe = document.createElement('iframe');
  let webFrameId;
  chrome.webRequest.onBeforeRequest.addListener(function _(info) {
    chrome.webRequest.onBeforeRequest.removeListener(_);
    webFrameId = info.frameId;
  }, {tabId, types: ['sub_frame']});
  iframe.src = job.url;
  document.body.appendChild(iframe);
  await new Promise(onload => Object.assign(iframe, {onload}));
  const data = await chrome.scripting.executeScript({
    target: {tabId, frameIds: [webFrameId]},
    args: [job.selectors],
    func: selectors => selectors.map(sel =>
      Array.from(document.querySelectorAll(sel),
        el => el.textContent)),
  })
  const {result} = data.find(d => d.frameId === webFrameId);
  await chrome.tabs.sendMessage(tabId, {id, result}, {frameId: job.frameId});
})();

WARNING! An http:// URL cannot be loaded on a https:// site. You will see an error about mixed content being blocked in devtools console. The only workaround is to replace step 1 above with opening a new tab/window for the remote site and run a content script there, e.g. the original content script sends a message to the background script, which uses chrome.tabs.create + chrome.scripting.executeScript.

WARNING! Some sites use JS to stop loading in iframes by checking window == window.top.

This check can't be spoofed if it's done in an inline script element.


问:
Creating a shared drive with a service account
Is it possible to create a shared drive with a service account ?.

Since there is no UI for service account to create file/folders i need some way /APIs support to create shared drives.

I can create children (files and folders) under a service account but not sure how to create a shared drive with a service account.

Best Regards,
Saurav

答:
Since there is no UI for service account to create file/folders i need some way /APIs support to create shared drives.

Service accounts are used for accessing Google drive via the google drive api. The File.create method would allow you to create a folder and files if you like.

If you create them from the service account they will be created on the service accounts Google drive account.

You can set the parents directory as well when creating it and this will allow you to create it in another directory for example one on your presonal drive account.

I cant say that I have tried but the drives create method will let you create a shared drive. It should work just fine from a service account.


问:
Junit5: WebMvcTest returns 404. Probably because I'm not mocking underlyng method?
Preamble: I'm learning Java, Spring Boot and overall... TDD with Java/Spring Boot.

Used versions:

Spring Boot 2.6.3

Java 17

Junit5

This is my controller:

@RestController
@RequestMapping("/api/v1/login")
public class LoginController {

    @Autowired
    private JwtAuthentication jwtAuthentication;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailService jwtUserDetailService;

    @PostMapping
    public ResponseEntity<?> createAuthenticationToken(@RequestBody UserEntity userEntity) throws Exception {
        jwtAuthentication.authenticate(userEntity.getUsername(), userEntity.getPassword());
        final UserDetails userDetails = jwtUserDetailService.loadUserByUsername(userEntity.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new JwtResponse(token));
    }
}
```
<p>Relevant <code>autowired</code> is the <code>JwtAuthentication</code>:</p>
<pre class="lang-java prettyprint-override"><code>@Component
public class JwtAuthentication {

    @Autowired
    private AuthenticationManager authenticationManager;

    private static final long serialVersionUID = -20220210203900L;

    public void authenticate(String username, String password) throws BadCredentialsException {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (BadCredentialsException e) {
            throw new BadCredentialsException("INVALID_CREDENTIALS", e);
        }
    }
}
</code>```

I wrote the test for JwtAuthentication itself without issues, now I need to test the Controller.

This is my test:

@ExtendWith(SpringExtension.class)
@WebMvcTest(LoginControllerTest.class)
class LoginControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private JwtAuthentication jwtAuthentication;

    @Test
    void testCanLogin() throws Exception {

        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("username");
        userEntity.setPassword("password");

        mvc.perform(post("/api/v1/login/").contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(userEntity))).andExpect(status().isOk());
    }
}
```
<p>But I get 404 instead of 200.</p>
<p>I read that reason is missing mocking underlying methods. That, in reality, these tests on Controller doesn't launch entire configuration (and so on). Cannot find the answer atm, here on S.O..</p>
<p>So, I think the solution need to be add a "simple" <code>when</code> in test:</p>
<pre class="lang-java prettyprint-override"><code>@Test
void testCanLogin() throws Exception {

UserEntity userEntity = new UserEntity();
userEntity.setUsername("username");
userEntity.setPassword("password");

// I think I need some code here:
// pseudocode    when(jwtAuthentication.authenticate("username", "password").then .... I DON'T KNOW HERE!

mvc.perform(post("/api/v1/login/").contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(userEntity))).andExpect(status().isOk());
    }
</code>```

答:
404 is because of no controllers to handle the request.

It is because you specify a wrong controller in @WebMvcTest such that the controller that you want to test is not included in the spring container. So change to the following should fix the problem :

@WebMvcTest(LoginController.class)
class LoginControllerTest {

    @MockBean
    private JwtAuthentication jwtAuthentication;

    @MockBean
    private JwtTokenUtil jwtTokenUtil;

    @MockBean
    private JwtUserDetailService jwtUserDetailService;

}
```

Also note the following points :

I remove @ExtendWith(SpringExtension.class) as @WebMvcTest already included it

@WebMvcTest will only enable the beans related to web layers (see this) which  JwtTokenUtil and JwtUserDetailService does not belong to it. So you have to use @MockBean to mock them.

Body:
Preamble: I'm learning Java, Spring Boot and overall... TDD with Java/Spring Boot.

Used versions:

Spring Boot 2.6.3

Java 17

Junit5

This is my controller:

@RestController
@RequestMapping("/api/v1/login")
public class LoginController {

    @Autowired
    private JwtAuthentication jwtAuthentication;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailService jwtUserDetailService;

    @PostMapping
    public ResponseEntity<?> createAuthenticationToken(@RequestBody UserEntity userEntity) throws Exception {
        jwtAuthentication.authenticate(userEntity.getUsername(), userEntity.getPassword());
        final UserDetails userDetails = jwtUserDetailService.loadUserByUsername(userEntity.getUsername());
        final String token = jwtTokenUtil.generateToken(userDetails);
        return ResponseEntity.ok(new JwtResponse(token));
    }
}

Relevant autowired is the JwtAuthentication:

@Component
public class JwtAuthentication {

    @Autowired
    private AuthenticationManager authenticationManager;

    private static final long serialVersionUID = -20220210203900L;

    public void authenticate(String username, String password) throws BadCredentialsException {
        try {
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (BadCredentialsException e) {
            throw new BadCredentialsException("INVALID_CREDENTIALS", e);
        }
    }
}

I wrote the test for JwtAuthentication itself without issues, now I need to test the Controller.

This is my test:

@ExtendWith(SpringExtension.class)
@WebMvcTest(LoginControllerTest.class)
class LoginControllerTest {

    @Autowired
    private MockMvc mvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private JwtAuthentication jwtAuthentication;

    @Test
    void testCanLogin() throws Exception {

        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("username");
        userEntity.setPassword("password");

        mvc.perform(post("/api/v1/login/").contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(userEntity))).andExpect(status().isOk());
    }
}

But I get 404 instead of 200.

I read that reason is missing mocking underlying methods. That, in reality, these tests on Controller doesn't launch entire configuration (and so on). Cannot find the answer atm, here on S.O..

So, I think the solution need to be add a "simple" when in test:

@Test
void testCanLogin() throws Exception {

UserEntity userEntity = new UserEntity();
userEntity.setUsername("username");
userEntity.setPassword("password");

// I think I need some code here:
// pseudocode    when(jwtAuthentication.authenticate("username", "password").then .... I DON'T KNOW HERE!

mvc.perform(post("/api/v1/login/").contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(userEntity))).andExpect(status().isOk());
    }

Body:
404 is because of no controllers to handle the request.

It is because you specify a wrong controller in @WebMvcTest such that the controller that you want to test is not included in the spring container. So change to the following should fix the problem :

@WebMvcTest(LoginController.class)
class LoginControllerTest {

    @MockBean
    private JwtAuthentication jwtAuthentication;

    @MockBean
    private JwtTokenUtil jwtTokenUtil;

    @MockBean
    private JwtUserDetailService jwtUserDetailService;

}

Also note the following points :

I remove @ExtendWith(SpringExtension.class) as @WebMvcTest already included it

@WebMvcTest will only enable the beans related to web layers (see this) which  JwtTokenUtil and JwtUserDetailService does not belong to it. So you have to use @MockBean to mock them.


问:
Why won't Visual Studio debugger properly evaluate expressions that involve generic type arguments?
In the following code:

```<code>        private static void Main(string[] args)
        {
            var listy = new List<DateTime> { DateTime.Now };
            MyMethod(listy);
        }

        static void MyMethod<T>(List<T> myList)
        {
            // put breakpoint here
        }
</code>```

If I break in the debugger, open QuickWatch on "myList", I see:

```<code>myList
   [0]
   Raw View
</code>```

If I select the "[0]" node and click Add Watch, the expression that is added to Watch:

(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.DateTime>(myList)).Items[0]

This expression seems correct, and yet, the watch window shows the following error:

The best overloaded method match for
  'System.Collections.Generic.Mscorlib_CollectionDebugView.Mscorlib_CollectionDebugView(System.Collections.Generic.ICollection)'
  has some invalid arguments

This seems like a bug in the debugger. Why does this happen? And is it documented anywhere?

答:
Looks that way. I've been able to replicate the error. Mscorlib_CollectionDebugView<T> has only one constructor accepting ICollection<T> and List<T> implements ICollection<T>. Also, explicitly casting to ICollection<T> works:

```<code>(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.DateTime>((ICollection<DateTime>)myList)).Items[0]
</code>```

Body:
In the following code:

        private static void Main(string[] args)
        {
            var listy = new List<DateTime> { DateTime.Now };
            MyMethod(listy);
        }

        static void MyMethod<T>(List<T> myList)
        {
            // put breakpoint here
        }

If I break in the debugger, open QuickWatch on "myList", I see:

myList
   [0]
   Raw View

If I select the "[0]" node and click Add Watch, the expression that is added to Watch:

(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.DateTime>(myList)).Items[0]

This expression seems correct, and yet, the watch window shows the following error:

The best overloaded method match for
  'System.Collections.Generic.Mscorlib_CollectionDebugView.Mscorlib_CollectionDebugView(System.Collections.Generic.ICollection)'
  has some invalid arguments

This seems like a bug in the debugger. Why does this happen? And is it documented anywhere?

Body:
Looks that way. I've been able to replicate the error. Mscorlib_CollectionDebugView<T> has only one constructor accepting ICollection<T> and List<T> implements ICollection<T>. Also, explicitly casting to ICollection<T> works:

(new System.Collections.Generic.Mscorlib_CollectionDebugView<System.DateTime>((ICollection<DateTime>)myList)).Items[0]


问:
Split vs Strip in Python to remove redundant white space
May I ask do I need to use strip() before split() to remove any redundant space in Python (and turn into a list after)?
For example:

```<code>string1 = '   a      b '
</code>```

I want the result:

```<code>#list1=[a,b]
</code>```

When I test I found out that list1=string1.split() is enough. But somehow my teacher say string1.strip().split() is needed. Maybe he is wrong?

答:
I tried using:

```<code>string1 = '   a      b '
list1 = string1.strip().split()
print(list1)
</code>```

and

```<code>string1 = '   a      b '
list1 = string1.split()
print(list1)
</code>```

And they give the same result.

So using strip() isn't necessarily needed, as it will only remove the spaces at the start (leading whitespaces) and spaces at the end (trailing whitespaces).

Body:
May I ask do I need to use strip() before split() to remove any redundant space in Python (and turn into a list after)?
For example:

string1 = '   a      b '

I want the result:

#list1=[a,b]

When I test I found out that list1=string1.split() is enough. But somehow my teacher say string1.strip().split() is needed. Maybe he is wrong?

Body:
I tried using:

string1 = '   a      b '
list1 = string1.strip().split()
print(list1)

and

string1 = '   a      b '
list1 = string1.split()
print(list1)

And they give the same result.

So using strip() isn't necessarily needed, as it will only remove the spaces at the start (leading whitespaces) and spaces at the end (trailing whitespaces).


问:
Output .docx document using repository in palantir foundry
Since the foundry documentation is rather patchy and didn't really provide an answer:
Is it somehow possible to use a foundry code repository (python-docx library is available and used) and a df as input to produce word documents (.docx) as output?
I thought that maybe using a composition of the transform input/output and py-docx document.save() functionality may work but I couldn't come up with a proper solution.

    from pyspark.sql import functions as F
    from transforms.api import transform, transform_df, Input, Output
    import os, docx
    import pandas as pd

    @transform(
        output = Output("some_folder/"),
        source_df = Input(""),
    )

    def compute(source_df, output):
        df = source_df.dataframe()
        test = df.toPandas()
        document = docx.Document()
        doc.add_paragraph(str(test.loc[1,1])
        document.save('test.docx')
        output.write_dataframe(df)

```

This code ofc does't work, but would appreciate a working solution (in an ideal world it would be possible to have multiple .docx as output).

答:
Your best bet is to use spark to distribute the file generation over executors. This transformation generates a word doc for each row and stores in a dataset container, which is recommended over using Compass (Foundry's folder system). Browse to the dataset to download the underlying files

```<code># from pyspark.sql import functions as F
from transforms.api import transform, Output
import pandas as pd
import docx

'''
# ====================================================== #
# === [DISTRIBUTED GENERATION OF FILESYSTEM OUTPUTS] === #
# ====================================================== #

Description
-----------
Generates a spark dataframes containing docx files with strings contained in a source spark dataframe

Strategy
--------
1. Create dummy spark dataframe with primary key and random text
2. Use a udf to open filesystem and write a docx with the contents of text column above

'''

@transform(
    output=Output("ri.foundry.main.dataset.7e0f243f-e97f-4e05-84b3-ebcc4b4a2a1c")
)
def compute(ctx, output):
    # gen data
    pdf = pd.DataFrame({'name': ['docx_1', 'docx_2'], 'content': ['doc1 content', 'doc2 content']})
    data = ctx.spark_session.createDataFrame(pdf)

    # function to write files
    def strings_to_doc(df, transform_output):
        rdd = df.rdd

        def generate_files(row):
            filename = row['name'] + '.docx'

            with transform_output.filesystem().open(filename, 'wb') as worddoc:
                doc = docx.Document()
                doc.add_heading(row['name'])
                doc.add_paragraph(row['content'])
                doc.save(worddoc)

        rdd.foreach(generate_files)

    return strings_to_doc(data, output)
</code>```

A pandas udf will also work if you prefer the input to a pandas dataframe but you are forced define a schema which is inconvinient for your usage.

Body:
Since the foundry documentation is rather patchy and didn't really provide an answer:
Is it somehow possible to use a foundry code repository (python-docx library is available and used) and a df as input to produce word documents (.docx) as output?
I thought that maybe using a composition of the transform input/output and py-docx document.save() functionality may work but I couldn't come up with a proper solution.

    from pyspark.sql import functions as F
    from transforms.api import transform, transform_df, Input, Output
    import os, docx
    import pandas as pd

    @transform(
        output = Output("some_folder/"),
        source_df = Input(""),
    )

    def compute(source_df, output):
        df = source_df.dataframe()
        test = df.toPandas()
        document = docx.Document()
        doc.add_paragraph(str(test.loc[1,1])
        document.save('test.docx')
        output.write_dataframe(df)

This code ofc does't work, but would appreciate a working solution (in an ideal world it would be possible to have multiple .docx as output).

Body:
Your best bet is to use spark to distribute the file generation over executors. This transformation generates a word doc for each row and stores in a dataset container, which is recommended over using Compass (Foundry's folder system). Browse to the dataset to download the underlying files

# from pyspark.sql import functions as F
from transforms.api import transform, Output
import pandas as pd
import docx

'''
# ====================================================== #
# === [DISTRIBUTED GENERATION OF FILESYSTEM OUTPUTS] === #
# ====================================================== #

Description
-----------
Generates a spark dataframes containing docx files with strings contained in a source spark dataframe

Strategy
--------
1. Create dummy spark dataframe with primary key and random text
2. Use a udf to open filesystem and write a docx with the contents of text column above

'''

@transform(
    output=Output("ri.foundry.main.dataset.7e0f243f-e97f-4e05-84b3-ebcc4b4a2a1c")
)
def compute(ctx, output):
    # gen data
    pdf = pd.DataFrame({'name': ['docx_1', 'docx_2'], 'content': ['doc1 content', 'doc2 content']})
    data = ctx.spark_session.createDataFrame(pdf)

    # function to write files
    def strings_to_doc(df, transform_output):
        rdd = df.rdd

        def generate_files(row):
            filename = row['name'] + '.docx'

            with transform_output.filesystem().open(filename, 'wb') as worddoc:
                doc = docx.Document()
                doc.add_heading(row['name'])
                doc.add_paragraph(row['content'])
                doc.save(worddoc)

        rdd.foreach(generate_files)

    return strings_to_doc(data, output)

A pandas udf will also work if you prefer the input to a pandas dataframe but you are forced define a schema which is inconvinient for your usage.


问:
How can I avoid app names in inapp item titles returned from Google Play getSkuDetails?
I'd like the use the getSkuDetails() call from the In-app Billing v3 API to dynamically display a list of inapp purchase options with properly translated titles and relevant price.

However, the "title" property from getSkuDetails() seems to always be of the form "<item title> (app name)", which is less than useful. How can I get only the item title itself without the app name without hacking the string?

答:
I found that in development builds, I'd get a value like My product (com.test.myapp (unreviewed)). Here's a version of the regex that handles the nested parentheses and keeps other parentheses in your product name intact:

```<code>const removeAppNameFromProductTitle = (title: string) => {
  const regex = /( \([^()]*\)$)|( \([^)]*\)\)$)/im;
  return title.replace(regex, '');
};
</code>```

The code is in TypeScript (React Native), but I'm sure you can adapt. Here's a gist with test cases: https://gist.github.com/thmsobrmlr/732ecf958f600ec38e89c4e8ff57f3dd.

Body:
I found that in development builds, I'd get a value like My product (com.test.myapp (unreviewed)). Here's a version of the regex that handles the nested parentheses and keeps other parentheses in your product name intact:

const removeAppNameFromProductTitle = (title: string) => {
  const regex = /( \([^()]*\)$)|( \([^)]*\)\)$)/im;
  return title.replace(regex, '');
};

The code is in TypeScript (React Native), but I'm sure you can adapt. Here's a gist with test cases: https://gist.github.com/thmsobrmlr/732ecf958f600ec38e89c4e8ff57f3dd.


问:
One file keeps opening in visual studio IDE
I'm using Visual Studio 2010

In one solution I have A.XAML file and it keeps opening every time I start solution. It also opens at some random time - I have no exact explanation.

It's very annoying. Why would VS open specific file by itself?

答:
What worked for me was running Visual Studio installer and choosing the repair option.
I had a whole solution that always opened a few seconds after I open any other solution. I didn't want to delete the solution so I thought I should try repairing Visual Studio (using VS2019). Haven't had any issue since.

Seems like an 'intense' option but it was what worked.