问:
How to count clicked buttons by adding each counted click button(only one on div) together
I need to count in JS two buttons if they clicked and then lower them to one couse I need confirmation of action only once in div. For example if Button1 and Button2 is clicked then I need to have the number 1. If Button1 and Button2 and Button11 and Button22 is clicked together I need to have the number 2.

Now I just need to add two counting to each other but I don't now how to finish it.
Anyone have any solution.

I have this code(http://jsfiddle.net/rjopn78x/253/)

$(document).ready(function() {
  $('#hej').removeClass('selected3').addClass('black');
});

$(document).ready(function() {
  $('itemitem').removeClass('green').addClass('item');
});

$( "button#jQueryColorChange" ).click(function() {
  $(this).addClass( "selected" );
  $(this).text("TRENING");
  $(this).addClass( "selected" );
});
$( "button#jQueryColorChange2" ).click(function() {
  $(this).addClass( "selected2" );
  $(this).text("ZNAM");
  $(this).addClass( "selected2" );
});

$(".Button1").click(function(){
           $('#itemitem').removeClass( "green" );
$('#itemitem').addClass( "orange" );
   $('item').removeClass( "green" );
   $('Button').removeClass( "selected3" );
   $(this).addClass( "Button" );
   $('#hej').addClass( "selected4" );
   $('Button').removeClass( "selected" );
});
$(".Button2").click(function(){
        $('#itemitem').removeClass( "orange" );
    $('#itemitem').addClass( "green" );
  $('item').removeClass( "orange" );
  $('Button').removeClass( "selected4" );
   $(this).addClass( "Button" );
   $('#hej').addClass( "selected3" );
   $('Button').removeClass( "selected2" );
});

$(document).ready(function() {
  $('#hejnowe').removeClass('selected5').addClass('black');
});

$(document).ready(function() {
  $('itemitem2').removeClass('green').addClass('item2');
});

$( "button#jQueryColorChange11" ).click(function() {
  $(this).addClass( "selected" );
  $(this).text("TRENING");
  $(this).addClass( "selected" );
});
$( "button#jQueryColorChange22" ).click(function() {
  $(this).addClass( "selected2" );
  $(this).text("ZNAM");
  $(this).addClass( "selected2" );
});

$(".Button11").click(function(){
           $('#itemitem2').removeClass( "green" );
$('#itemitem2').addClass( "orange" );
   $('item2').removeClass( "green" );
   $('Button').removeClass( "selected5" );
   $(this).addClass( "Button" );
   $('#hejnowe').addClass( "selected6" );
   $('Button').removeClass( "selected" );
});
$(".Button22").click(function(){
        $('#itemitem2').removeClass( "orange" );
    $('#itemitem2').addClass( "green" );
  $('item2').removeClass( "orange" );
  $('Button').removeClass( "selected6" );
   $(this).addClass( "Button" );
   $('#hejnowe').addClass( "selected5" );
   $('Button').removeClass( "selected2" );
});

var count = 0;
var counta = 0;
        var btn = document.getElementById("jQueryColorChange");
        var btna = document.getElementById("jQueryColorChange11");
        var disp = document.getElementById("display");
        var dispa = document.getElementById("display2");
        var dispaa =  count + counta;

  if(dispaa < 2){
  btn.onclick = function (){
            count++;
            if (count > 1) {
        return false;
    }
    disp.innerHTML = count;
    }
        btna.onclick = function (){
            counta++;
            if (counta > 1) {
        return false;
    }
    dispa.innerHTML = counta;
    }
     var dispaa =  count + counta;
    }
    $('#something').click( function() { alert(dispaa); });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.menu {
    /* To correctly align image, regardless of content height: */
    top: 15px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 300px;
    height:50px;
    background-color: blue;
      text-align: center;
  top: 0px;
}

div.menu2 {
    /* To correctly align image, regardless of content height: */
    top: 15px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 300px;
    height:50px;
    background-color: blue;
      text-align: center;
  top: 0px;
}

.Button {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:grey;
    color: yellow;
}

.Button1 {
  text-align: center;
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:orange;
    color: yellow;
}

.Button2 {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:green;
    color: yellow;
}

.nowe.selected3 {
    color: black;
    background:green;
    border: solid;
}

.nowe.selected4 {
    color: black;
    background:orange;
    border: solid;
}

.selected {
    color: black;
    background:orange;
    border: solid;
}
.selected2 {
    color: black;
    background:green;
    border: solid;
}

.item {
    /* To correctly align image, regardless of content height: */
    top: 0px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 294px;
}

.ite {
background-color: white;
}

.item.orange {
background-color: orange;
}

.item.green {
background-color: green;
}

div.item:hover {
  border: 3px red solid;}
}

img33 {
    width: 294px;
    height: 201px;
    background-color: grey;
}
.caption {
  text-align: center;
    /* Make the caption a block so it occupies its own line. */
    display: block;
    color: black;
}

.Button {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:grey;
    color: yellow;
}

.Button11 {
  text-align: center;
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:orange;
    color: yellow;
}

.Button22 {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:green;
    color: yellow;
}
.nowe2.selected5 {
    color: black;
    background:green;
    border: solid;
}

.nowe2.selected6 {
    color: black;
    background:orange;
    border: solid;
}

.selected {
    color: black;
    background:orange;
    border: solid;
}
.selected2 {
    color: black;
    background:green;
    border: solid;
}

.item2 {
    /* To correctly align image, regardless of content height: */
    top: 0px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 294px;
}

.item2.orange {
background-color: orange;
}

.item2.green {
background-color: green;
}

div.item2:hover {
  border: 3px red solid;}
}

img33 {
    width: 294px;
    height: 201px;
    background-color: grey;
}
.caption {
  text-align: center;
    /* Make the caption a block so it occupies its own line. */
    display: block;
    color: black;
}</code>```

0
0
Text

<button id="hej" class="nowe">GUY</button>

    Kaczyński łapie motyle --- catch[kacz] - łapać
<button class="Button1" id="jQueryColorChange";>TRENING</button>

<button class="Button2" id="jQueryColorChange2";>ZNAM</button>

<button id="hejnowe" class="nowe2">CATCH</button>

    Kaczyński łapie motyle --- catch[kacz] - łapać
<button class="Button11" id="jQueryColorChange11" onclick="return myFunction()";;>TRENING</button>

<button class="Button22" id="jQueryColorChange22" onclick="return myFunction()";>ZNAM</button>

```

答:
I found the solution:

```<code>var count = 0;
var counta = 0;
        var btn = document.getElementById("jQueryColorChange");
        var btna = document.getElementById("jQueryColorChange11");
        var disp = document.getElementById("display");
        var dispa = document.getElementById("display2");
        var di = document.getElementById("display3"); ///here

  btn.onclick = function (){
            count++;
            if (count > 1) {
        return false;
    }
    disp.innerHTML = count;
    di.innerHTML = Number(dispa.innerHTML) + Number(disp.innerHTML); ///here
    }
        btna.onclick = function (){
            counta++;
            if (counta > 1) {
        return false;
    }
    dispa.innerHTML = counta;
    di.innerHTML = Number(dispa.innerHTML) + Number(disp.innerHTML); //and here
    }
</code>```

Working example: http://jsfiddle.net/4szxcvan/4/
Thanks for attention :)

Here is possibility to store score in localStorage: https://jsfiddle.net/nbL9zkpu/1/

Body:
I need to count in JS two buttons if they clicked and then lower them to one couse I need confirmation of action only once in div. For example if Button1 and Button2 is clicked then I need to have the number 1. If Button1 and Button2 and Button11 and Button22 is clicked together I need to have the number 2.

Now I just need to add two counting to each other but I don't now how to finish it.
Anyone have any solution.

I have this code(http://jsfiddle.net/rjopn78x/253/)

$(document).ready(function() {
  $('#hej').removeClass('selected3').addClass('black');
});

$(document).ready(function() {
  $('itemitem').removeClass('green').addClass('item');
});

$( "button#jQueryColorChange" ).click(function() {
  $(this).addClass( "selected" );
  $(this).text("TRENING");
  $(this).addClass( "selected" );
});
$( "button#jQueryColorChange2" ).click(function() {
  $(this).addClass( "selected2" );
  $(this).text("ZNAM");
  $(this).addClass( "selected2" );
});

$(".Button1").click(function(){
           $('#itemitem').removeClass( "green" );
$('#itemitem').addClass( "orange" );
   $('item').removeClass( "green" );
   $('Button').removeClass( "selected3" );
   $(this).addClass( "Button" );
   $('#hej').addClass( "selected4" );
   $('Button').removeClass( "selected" );
});
$(".Button2").click(function(){
        $('#itemitem').removeClass( "orange" );
    $('#itemitem').addClass( "green" );
  $('item').removeClass( "orange" );
  $('Button').removeClass( "selected4" );
   $(this).addClass( "Button" );
   $('#hej').addClass( "selected3" );
   $('Button').removeClass( "selected2" );
});

$(document).ready(function() {
  $('#hejnowe').removeClass('selected5').addClass('black');
});

$(document).ready(function() {
  $('itemitem2').removeClass('green').addClass('item2');
});

$( "button#jQueryColorChange11" ).click(function() {
  $(this).addClass( "selected" );
  $(this).text("TRENING");
  $(this).addClass( "selected" );
});
$( "button#jQueryColorChange22" ).click(function() {
  $(this).addClass( "selected2" );
  $(this).text("ZNAM");
  $(this).addClass( "selected2" );
});

$(".Button11").click(function(){
           $('#itemitem2').removeClass( "green" );
$('#itemitem2').addClass( "orange" );
   $('item2').removeClass( "green" );
   $('Button').removeClass( "selected5" );
   $(this).addClass( "Button" );
   $('#hejnowe').addClass( "selected6" );
   $('Button').removeClass( "selected" );
});
$(".Button22").click(function(){
        $('#itemitem2').removeClass( "orange" );
    $('#itemitem2').addClass( "green" );
  $('item2').removeClass( "orange" );
  $('Button').removeClass( "selected6" );
   $(this).addClass( "Button" );
   $('#hejnowe').addClass( "selected5" );
   $('Button').removeClass( "selected2" );
});

var count = 0;
var counta = 0;
        var btn = document.getElementById("jQueryColorChange");
        var btna = document.getElementById("jQueryColorChange11");
        var disp = document.getElementById("display");
        var dispa = document.getElementById("display2");
        var dispaa =  count + counta;

  if(dispaa < 2){
  btn.onclick = function (){
            count++;
            if (count > 1) {
        return false;
    }
    disp.innerHTML = count;
    }
        btna.onclick = function (){
            counta++;
            if (counta > 1) {
        return false;
    }
    dispa.innerHTML = counta;
    }
     var dispaa =  count + counta;
    }
    $('#something').click( function() { alert(dispaa); });

div.menu {
    /* To correctly align image, regardless of content height: */
    top: 15px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 300px;
    height:50px;
    background-color: blue;
      text-align: center;
  top: 0px;
}

div.menu2 {
    /* To correctly align image, regardless of content height: */
    top: 15px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 300px;
    height:50px;
    background-color: blue;
      text-align: center;
  top: 0px;
}

.Button {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:grey;
    color: yellow;
}

.Button1 {
  text-align: center;
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:orange;
    color: yellow;
}

.Button2 {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:green;
    color: yellow;
}

.nowe.selected3 {
    color: black;
    background:green;
    border: solid;
}

.nowe.selected4 {
    color: black;
    background:orange;
    border: solid;
}

.selected {
    color: black;
    background:orange;
    border: solid;
}
.selected2 {
    color: black;
    background:green;
    border: solid;
}

.item {
    /* To correctly align image, regardless of content height: */
    top: 0px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 294px;
}

.ite {
background-color: white;
}

.item.orange {
background-color: orange;
}

.item.green {
background-color: green;
}

div.item:hover {
  border: 3px red solid;}
}

img33 {
    width: 294px;
    height: 201px;
    background-color: grey;
}
.caption {
  text-align: center;
    /* Make the caption a block so it occupies its own line. */
    display: block;
    color: black;
}

.Button {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:grey;
    color: yellow;
}

.Button11 {
  text-align: center;
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:orange;
    color: yellow;
}

.Button22 {
    font-size:13px;
    font-weight: bold;
    width: 160px;
    height: 25px;
    background:green;
    color: yellow;
}
.nowe2.selected5 {
    color: black;
    background:green;
    border: solid;
}

.nowe2.selected6 {
    color: black;
    background:orange;
    border: solid;
}

.selected {
    color: black;
    background:orange;
    border: solid;
}
.selected2 {
    color: black;
    background:green;
    border: solid;
}

.item2 {
    /* To correctly align image, regardless of content height: */
    top: 0px;
    display: inline-block;
    /* To horizontally center images and caption */
    /* The width of the container also implies margin around the images. */
    width: 294px;
}

.item2.orange {
background-color: orange;
}

.item2.green {
background-color: green;
}

div.item2:hover {
  border: 3px red solid;}
}

img33 {
    width: 294px;
    height: 201px;
    background-color: grey;
}
.caption {
  text-align: center;
    /* Make the caption a block so it occupies its own line. */
    display: block;
    color: black;
}

0
0
Text

<button id="hej" class="nowe">GUY</button>

    Kaczyński łapie motyle --- catch[kacz] - łapać
<button class="Button1" id="jQueryColorChange";>TRENING</button>

<button class="Button2" id="jQueryColorChange2";>ZNAM</button>

<button id="hejnowe" class="nowe2">CATCH</button>

    Kaczyński łapie motyle --- catch[kacz] - łapać
<button class="Button11" id="jQueryColorChange11" onclick="return myFunction()";;>TRENING</button>

<button class="Button22" id="jQueryColorChange22" onclick="return myFunction()";>ZNAM</button>

Body:
I found the solution:

var count = 0;
var counta = 0;
        var btn = document.getElementById("jQueryColorChange");
        var btna = document.getElementById("jQueryColorChange11");
        var disp = document.getElementById("display");
        var dispa = document.getElementById("display2");
        var di = document.getElementById("display3"); ///here

  btn.onclick = function (){
            count++;
            if (count > 1) {
        return false;
    }
    disp.innerHTML = count;
    di.innerHTML = Number(dispa.innerHTML) + Number(disp.innerHTML); ///here
    }
        btna.onclick = function (){
            counta++;
            if (counta > 1) {
        return false;
    }
    dispa.innerHTML = counta;
    di.innerHTML = Number(dispa.innerHTML) + Number(disp.innerHTML); //and here
    }

Working example: http://jsfiddle.net/4szxcvan/4/
Thanks for attention :)

Here is possibility to store score in localStorage: https://jsfiddle.net/nbL9zkpu/1/


来源: stackexchange

问:
git-askpass.exe: No such file or directory could not read Username for
I think I have done a fair share of research into this issue, but I have not been able to find a corresponding problem/solution.

What is trying to be achieved

Publish and push a solution from VS 2017 to Microsoft Visual Studio Team Services (VSTS).

Reproduceable Example

A new solution "GitExample" with the project "ExampleProject" has in been created (/w "Create new Git repository" checked).

In the Team Explorer window I select "Publish Git Repo" under the "Push to Visual  Studio Team Services" section. I choose my account and domain and press "Publish Repository".

Following error message is printed from Git.

```<code>Opening repositories:
c:\users\SampleUser\source\repos\PythonApplication4
Commit e3b04515 created locally in repository c:\users\SampleUser\source\repos\PythonApplication4
Error encountered while pushing branch to the remote repository: Git failed with a fatal error.
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
cannot spawn /C/Program Files/Microsoft Visual Studio/2017/Enterprise/Common7/IDE/CommonExtensions/Microsoft/TeamFoundation/Team Explorer/Git/mingw32/libexec/git-core/git-askpass.exe: No such file or directory
could not read Username for 'https://repodomain.visualstudio.com': terminal prompts disabled
Pushing to https://repodomain.visualstudio.com/_git/PythonApplication4

A new Git repository has been created for you in C:\Users\SampleUser\source\repos\GitExample.
Opening repositories:
C:\Users\SampleUser\source\repos\GitExample
Commit 5d8765b7 created locally in repository C:\Users\SampleUser\source\repos\GitExample
Opening repositories:
C:\Users\SampleUser\source\repos\GitExample
The calling thread cannot access this object because a different thread owns it.
Error encountered while pushing branch to the remote repository: Git failed with a fatal error.
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
cannot spawn /C/Program Files/Microsoft Visual Studio/2017/Enterprise/Common7/IDE/CommonExtensions/Microsoft/TeamFoundation/Team Explorer/Git/mingw32/libexec/git-core/git-askpass.exe: No such file or directory
could not read Username for 'https://repodomain.visualstudio.com': terminal prompts disabled
Pushing to https://repodomain.visualstudio.com/_git/GitExample
</code>```

The problem seems to reside with the Git Credential Manager for Windows. However, the Windows Credential Manager correctly lists git:repodomain.visualstudio.com with the correct User Name and Password combination.

What has been done:

Uninstall git for Windows and reinstall without Windows Credential Manager. Install Windows Credential Manager from GitHub repo.

Repair Visual Studio 2017 installation.

Delete and create Login in Credential Manager

I appreciate your time and effort looking into this.

答:
I solved this error in VS2019 by resetting the Git proxy:
Close VS.
Run CMD as administrator and execute this cmd:
git config --global http.proxy http://proxy:8080
Start VS</p>

ContentLicense: CC BY-SA 4.0

Body:
I think I have done a fair share of research into this issue, but I have not been able to find a corresponding problem/solution.

What is trying to be achieved

Publish and push a solution from VS 2017 to Microsoft Visual Studio Team Services (VSTS).

Reproduceable Example

A new solution "GitExample" with the project "ExampleProject" has in been created (/w "Create new Git repository" checked).

In the Team Explorer window I select "Publish Git Repo" under the "Push to Visual  Studio Team Services" section. I choose my account and domain and press "Publish Repository".

Following error message is printed from Git.

Opening repositories:
c:\users\SampleUser\source\repos\PythonApplication4
Commit e3b04515 created locally in repository c:\users\SampleUser\source\repos\PythonApplication4
Error encountered while pushing branch to the remote repository: Git failed with a fatal error.
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
cannot spawn /C/Program Files/Microsoft Visual Studio/2017/Enterprise/Common7/IDE/CommonExtensions/Microsoft/TeamFoundation/Team Explorer/Git/mingw32/libexec/git-core/git-askpass.exe: No such file or directory
could not read Username for 'https://repodomain.visualstudio.com': terminal prompts disabled
Pushing to https://repodomain.visualstudio.com/_git/PythonApplication4

A new Git repository has been created for you in C:\Users\SampleUser\source\repos\GitExample.
Opening repositories:
C:\Users\SampleUser\source\repos\GitExample
Commit 5d8765b7 created locally in repository C:\Users\SampleUser\source\repos\GitExample
Opening repositories:
C:\Users\SampleUser\source\repos\GitExample
The calling thread cannot access this object because a different thread owns it.
Error encountered while pushing branch to the remote repository: Git failed with a fatal error.
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
ArgumentNullException encountered.
   Value cannot be null.
Parameter name: path
cannot spawn /C/Program Files/Microsoft Visual Studio/2017/Enterprise/Common7/IDE/CommonExtensions/Microsoft/TeamFoundation/Team Explorer/Git/mingw32/libexec/git-core/git-askpass.exe: No such file or directory
could not read Username for 'https://repodomain.visualstudio.com': terminal prompts disabled
Pushing to https://repodomain.visualstudio.com/_git/GitExample

The problem seems to reside with the Git Credential Manager for Windows. However, the Windows Credential Manager correctly lists git:repodomain.visualstudio.com with the correct User Name and Password combination.

What has been done:

Uninstall git for Windows and reinstall without Windows Credential Manager. Install Windows Credential Manager from GitHub repo.

Repair Visual Studio 2017 installation.

Delete and create Login in Credential Manager

I appreciate your time and effort looking into this.


问:
Declaring variable without var sign in beginning?
I have seen class that states var _hello_kitty = array(); why they dont use $? i tried to make it public and static and it does not work without adding $i.e. public static $_hello_kitty = array();

now when i do add $ other functions who reference it by _hello_kitty stop working.

EDIT: OOOPS was my bad i somehow removed $ from there, i looped up original file and its there. but its still referencing like $this->_tpl_vars[$tpl_var] = &$value without $ and i cannot use self::_tpl_vars[$tpl_var];

now i did use self::$_tpl_vars[$tpl_var]; but now error comes up array_merge() [function.array-merge]: Argument #1 is not an array i

答:
In PHP, variables are prefixed with the dollar sign, which is the programming language's sigil. This is an important concept in computing, and it's the only way PHP is able to identify variables.

From wikipedia (which never, ever lies):

In the PHP language, which was largely inspired by Perl, “$” precedes
  any variable name. Names not prefixed by this are considered constants
  or functions.

and that's it.

ContentLicense: CC BY-SA 3.0


问:
Pandas: filter one dataframe by multiple, simultaneous column values of another dataframe
I have a filtered dataframe called correct_df and a raw dataframe example_df.

```<code>example_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_1', 'Test_2', 'Test_2', 'Test_2', 'Test_3', 'Test_3', 'Test_3'], 'A': [1, 2, 3, 1, 2, 3, 1, 2, 3]})
other_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_3', 'Test_3'], 'A': [1, 2, 1, 3]})
</code>```

Desired result:

I want the indexes of example_df where 'Test' and 'A' column values both match the combined row value of correct_df.

I have tried:

```<code>result = example_df.loc[ (example_df['Test'].isin(other_df['Test'])) & (example_df['A'].isin(other_df['A'])) ]
result

    Test    A
0   Test_1  1
1   Test_1  2
2   Test_1  3
6   Test_3  1
7   Test_3  2
8   Test_3  3
</code>```

But as these two conditions are separated, the resulting value only applies the conditions on single columns without chaining them i.e. A then also B, not A and B. How do I get the .loc of both column conditions?

答:
@jezrael's solution is absolutely perfect for your question. This is just another way (a little convoluted) to get the same outcome using numpy.

We can filter example_df directly using a boolean array which we can construct by checking if rows in example_df exist other_df. To do that we need to make example_df a 3D array and use numpy broadcasting to compare with other_df. Then use all and any to shrink it back to the 1D array msk:

```<code>msk = (example_df.to_numpy()[:, None]==other_df.to_numpy()).all(axis=2).any(axis=1)
out = example_df[msk]
</code>```

Output:

```<code>     Test  A
0  Test_1  1
1  Test_1  2
6  Test_3  1
8  Test_3  3
</code>```

Body:
I have a filtered dataframe called correct_df and a raw dataframe example_df.

example_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_1', 'Test_2', 'Test_2', 'Test_2', 'Test_3', 'Test_3', 'Test_3'], 'A': [1, 2, 3, 1, 2, 3, 1, 2, 3]})
other_df = pd.DataFrame({'Test': ['Test_1', 'Test_1', 'Test_3', 'Test_3'], 'A': [1, 2, 1, 3]})

Desired result:

I want the indexes of example_df where 'Test' and 'A' column values both match the combined row value of correct_df.

I have tried:

result = example_df.loc[ (example_df['Test'].isin(other_df['Test'])) & (example_df['A'].isin(other_df['A'])) ]
result

    Test    A
0   Test_1  1
1   Test_1  2
2   Test_1  3
6   Test_3  1
7   Test_3  2
8   Test_3  3

But as these two conditions are separated, the resulting value only applies the conditions on single columns without chaining them i.e. A then also B, not A and B. How do I get the .loc of both column conditions?

Body:
@jezrael's solution is absolutely perfect for your question. This is just another way (a little convoluted) to get the same outcome using numpy.

We can filter example_df directly using a boolean array which we can construct by checking if rows in example_df exist other_df. To do that we need to make example_df a 3D array and use numpy broadcasting to compare with other_df. Then use all and any to shrink it back to the 1D array msk:

msk = (example_df.to_numpy()[:, None]==other_df.to_numpy()).all(axis=2).any(axis=1)
out = example_df[msk]

Output:

     Test  A
0  Test_1  1
1  Test_1  2
6  Test_3  1
8  Test_3  3


问:
AWS S3 query list one Partition file
How to list all the files across domains in a S3 bucket is there any query in CLI or shell script to recursively return the dataset technical names under each origin in a bucket.

For example:

```<code>My bucket/domains/files
</code>```

答:
You can call list_objects_v2(), which will return a list of objects. If there are more than 1000 objects, you can use a paginator to easily loop through each object.

The API call will return a Key for each object, which consists of the Full Path of the object (eg folder1/object.txt).

Amazon S3 does not use 'folders' or 'subdirectories', so the listing will contain all objects. This is convenient because the complete listing can be easily obtained without needing to recurse through each subdirectory.

If you do need to recurse through the directories, you can use list_objects_v2(Delimiter='/',Prefix='folder1/') and it will only return a list of objects with that Prefix, which is effectively the same as a directory. It will also return a list of CommonPrefixes that are effectively the names of directories under that Prefix. However, recursing through the bucket this way will take many API calls and will be considerably slower.

Title: AWS S3 query list one Partition file

Body:
How to list all the files across domains in a S3 bucket is there any query in CLI or shell script to recursively return the dataset technical names under each origin in a bucket.

For example:

My bucket/domains/files


问:
react-sortable-tree - How to get the search API working
According to the API doc there needs to be a searchQuery prop which i've mentioned in my code but the search doesn't seem to be working

API doc doesn't explain how to implement it and the examples available online don't seem to be working on code sandbox.

The only article available which seems to explain search has incorrect code (duplicate props): https://frugalisminds.com/how-to-create-react-sortable-tree/

API Doc: https://www.npmjs.com/package/react-sortable-tree

Below is the code:

```<code>import React, { Component } from "react";
import SortableTree from "react-sortable-tree";
import "react-sortable-tree/style.css";

export default class Tree extends Component {
  constructor(props) {
    super(props);

    this.state = {
      treeData: [
        { title: "Chicken", children: [{ title: "Egg" }] },
        { title: "Fish", children: [{ title: "fingerline" }] },
      ],
      searchString: ""
    };
  }

  handleSearchOnChange = e => {
    this.setState({
      searchString: e.target.value,
    });
  };

  render() {
    return (
      <div style={{ height: 400 }}>
        <input
          type="search"
          onChange={this.handleSearchOnChange}
          className="form-control"
        />
        <SortableTree
          searchQuery={this.state.searchString}
          treeData={this.state.treeData}
          onChange={treeData => this.setState([...treeData])}
          isVirtualized={false}
        />
      </div>
    );
  }
}
</code>```

答:
missing a searchFocusOffset to highlight the found item and a searchMethod which can be custom defined inside render method as follows:</p>
```<code>import React, { Component } from "react";
import SortableTree from "react-sortable-tree";
import "react-sortable-tree/style.css"; // This only needs to be imported once in your app

export default class Tree extends Component {
  constructor(props) {
    super(props);

    this.state = {
      treeData: [
        { title: "Chicken", children: [{ title: "Egg" }] },
        { title: "Fish", children: [{ title: "fingerline" }] },
      ],
      searchString: ""
    };
  }

  render() {
    // Case insensitive search of `node.title`
    const customSearchMethod = ({ node, searchQuery }) =>
      searchQuery &&
      node.title.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1;

    return (
      <div style={{ height: 400 }}>
        <input
          type="search"
          onChange={event => this.setState({ searchString: event.target.value })}
          className="form-control"
        />
        <SortableTree
          searchMethod={customSearchMethod}
          searchQuery={this.state.searchString}
          searchFocusOffset={0}
          treeData={this.state.treeData}
          onChange={treeData => this.setState([...treeData])}
          isVirtualized={false}
        />
      </div>
    );
  }
}
</code>```

Body:
According to the API doc there needs to be a searchQuery prop which i've mentioned in my code but the search doesn't seem to be working

API doc doesn't explain how to implement it and the examples available online don't seem to be working on code sandbox.

The only article available which seems to explain search has incorrect code (duplicate props): https://frugalisminds.com/how-to-create-react-sortable-tree/

API Doc: https://www.npmjs.com/package/react-sortable-tree

Below is the code:

import React, { Component } from "react";
import SortableTree from "react-sortable-tree";
import "react-sortable-tree/style.css";

export default class Tree extends Component {
  constructor(props) {
    super(props);

    this.state = {
      treeData: [
        { title: "Chicken", children: [{ title: "Egg" }] },
        { title: "Fish", children: [{ title: "fingerline" }] },
      ],
      searchString: ""
    };
  }

  handleSearchOnChange = e => {
    this.setState({
      searchString: e.target.value,
    });
  };

  render() {
    return (

        <input
          type="search"
          onChange={this.handleSearchOnChange}
          className="form-control"
        />
        <SortableTree
          searchQuery={this.state.searchString}
          treeData={this.state.treeData}
          onChange={treeData => this.setState([...treeData])}
          isVirtualized={false}
        />

    );
  }
}

Body:
missing a searchFocusOffset to highlight the found item and a searchMethod which can be custom defined inside render method as follows:

import React, { Component } from "react";
import SortableTree from "react-sortable-tree";
import "react-sortable-tree/style.css"; // This only needs to be imported once in your app

export default class Tree extends Component {
  constructor(props) {
    super(props);

    this.state = {
      treeData: [
        { title: "Chicken", children: [{ title: "Egg" }] },
        { title: "Fish", children: [{ title: "fingerline" }] },
      ],
      searchString: ""
    };
  }

  render() {
    // Case insensitive search of `node.title`
    const customSearchMethod = ({ node, searchQuery }) =>
      searchQuery &&
      node.title.toLowerCase().indexOf(searchQuery.toLowerCase()) > -1;

    return (
      <div style={{ height: 400 }}>
        <input
          type="search"
          onChange={event => this.setState({ searchString: event.target.value })}
          className="form-control"
        />
        <SortableTree
          searchMethod={customSearchMethod}
          searchQuery={this.state.searchString}
          searchFocusOffset={0}
          treeData={this.state.treeData}
          onChange={treeData => this.setState([...treeData])}
          isVirtualized={false}
        />
      </div>
    );
  }
}


问:
Excel Count Number of Items if Same Year Across Multiple Worksheet Specific Cell
I have about 50 worksheets, each Worksheet contains specific cell (G11) in date format (dd-mmm-yy); other 5 worksheets used for other purpose.

What I need to do, first, to check cell G11 in the 50 worksheets match to current year and current month, then, count total number of G11 that meets current year and current month across all 50 worksheets. Finally, the counted number will be reflected in separate worksheet.

I had tried SUMPRODUCT or 3-D Reference, but I got return with #VALUE!. A2 is current mmm-yy; Sheet Name in 4 digit numbering:

```<code>=SUMPRODUCT(--(TEXT(INDIRECT("'"&Table[Sheet Name]&"'!$G$11"),"mmm-yy")=TEXT(A2,"mmm-yy")))
</code>```

答:
You could do:

```<code>=SUM(--(TEXT(N(INDIRECT("'"&Table[Sheet Name]&"'!$G$11")),"mmm-yy")=TEXT(A2,"mmm-yy")))
</code>```

or

```<code>=SUM(--(TEXT(N(INDIRECT(ADDRESS(11,7,,,Table[Sheet Name]))),"mmm-yy")=TEXT(A2,"mmm-yy")))
</code>```

If you have lower than Excel 2016, you have to do CTRL+SHIFT+ENTER to enter this formula.

Body:
I have about 50 worksheets, each Worksheet contains specific cell (G11) in date format (dd-mmm-yy); other 5 worksheets used for other purpose.

What I need to do, first, to check cell G11 in the 50 worksheets match to current year and current month, then, count total number of G11 that meets current year and current month across all 50 worksheets. Finally, the counted number will be reflected in separate worksheet.

I had tried SUMPRODUCT or 3-D Reference, but I got return with #VALUE!. A2 is current mmm-yy; Sheet Name in 4 digit numbering:

=SUMPRODUCT(--(TEXT(INDIRECT("'"&Table[Sheet Name]&"'!$G$11"),"mmm-yy")=TEXT(A2,"mmm-yy")))

Body:
You could do:

=SUM(--(TEXT(N(INDIRECT("'"&Table[Sheet Name]&"'!$G$11")),"mmm-yy")=TEXT(A2,"mmm-yy")))

or

=SUM(--(TEXT(N(INDIRECT(ADDRESS(11,7,,,Table[Sheet Name]))),"mmm-yy")=TEXT(A2,"mmm-yy")))

If you have lower than Excel 2016, you have to do CTRL+SHIFT+ENTER to enter this formula.


问:
How to run a loop to concatenate columns of multiple excel files(as separate dataframes) in a folder and merge and export into final dataframe
So basically , I want to run a loop to first import multiple excel files in a folder and convert them to separate data frames . Then I want to run a loop to concatenate specific columns of each data frame  and merge the new data  frames created as one . I tried a code but its not looping all the files in the folder.</p>
```<code>import glob
import pandas as pd
import os

x=input("enter file")
df=pd.read_excel(x)
df["Combin']=df.Pcode.str.cat(df.Icode)

filenames= glob.glob(r'C:\Desktop\*.xlsx')
for idx, fname in enumerate(filenames):
 df2=pd.read_excel(fname,sheet_name="PI",skiprows=4)
 df2[["Combin"]=df2.Pcode.str.cat(df2.Icode)
 merged=df.merge(df2,left_on='Combin', right_on='Combin', how='inner')
 df3=pd.read_excel(fname,sheet_name='PI')
 exc=df3.iat[0,19]
 merged ['Exchange']=exc
final=[[merged]]
excel_merged=pd.concat(final, ignore_index=True)
excel_merged.to_excel('output.xlsx')
</code>```

答:
Create empty list before loop and then use append for create list of DataFrames:

```<code>filenames= glob.glob(r'C:\Desktop\*.xlsx')

final = []
for idx, fname in enumerate(filenames):
    df2=pd.read_excel(fname,sheet_name="PI",skiprows=4)
    df2[["Combin"]=df2.Pcode.str.cat(df2.Icode)
    merged=df.merge(df2,left_on='Combin', right_on='Combin', how='inner')
    df3=pd.read_excel(fname,sheet_name='PI')
    exc=df3.iat[0,19]
    merged ['Exchange']=exc
    final.append(merged)

excel_merged=pd.concat(final, ignore_index=True)
excel_merged.to_excel('output.xlsx')
</code>```

Body:
So basically , I want to run a loop to first import multiple excel files in a folder and convert them to separate data frames . Then I want to run a loop to concatenate specific columns of each data frame  and merge the new data  frames created as one . I tried a code but its not looping all the files in the folder.

import glob
import pandas as pd
import os

x=input("enter file")
df=pd.read_excel(x)
df["Combin']=df.Pcode.str.cat(df.Icode)

filenames= glob.glob(r'C:\Desktop\*.xlsx')
for idx, fname in enumerate(filenames):
 df2=pd.read_excel(fname,sheet_name="PI",skiprows=4)
 df2[["Combin"]=df2.Pcode.str.cat(df2.Icode)
 merged=df.merge(df2,left_on='Combin', right_on='Combin', how='inner')
 df3=pd.read_excel(fname,sheet_name='PI')
 exc=df3.iat[0,19]
 merged ['Exchange']=exc
final=[[merged]]
excel_merged=pd.concat(final, ignore_index=True)
excel_merged.to_excel('output.xlsx')

Body:
Create empty list before loop and then use append for create list of DataFrames:

filenames= glob.glob(r'C:\Desktop\*.xlsx')

final = []
for idx, fname in enumerate(filenames):
    df2=pd.read_excel(fname,sheet_name="PI",skiprows=4)
    df2[["Combin"]=df2.Pcode.str.cat(df2.Icode)
    merged=df.merge(df2,left_on='Combin', right_on='Combin', how='inner')
    df3=pd.read_excel(fname,sheet_name='PI')
    exc=df3.iat[0,19]
    merged ['Exchange']=exc
    final.append(merged)

excel_merged=pd.concat(final, ignore_index=True)
excel_merged.to_excel('output.xlsx')


问:
Keyboard changing flex layout in react native with textInput
Layout overlapping on text input in react native as you can see in the images.
I have experimented with keyboardAvoidingView and keyboardAwareScrollView but I just cant fix it or I am implementing them incorrectly.

How to avoid keyboard from changing your flex layout? What's the industry standard? keyboardAvoidingView? I find that inconsistent or have not understood it conceptually. My approach usually is wrapping the entire code with either keyboardAwareScrollView or keyboardAvoidingView. Do I only do it over the textInput component?

```<code>const InterviewAlignment = ({navigation}) => {
  return (
    <View style={styles.container}>
      <View style={styles.header}>
      </View>
      <View style={styles.main}>
        <View
          style={{
            flex: 1,
            justifyContent: 'space-between',
          }}>
          <View
            style={{
              flex: 1,
              backgroundColor: 'red',
            }}>
          </View>
          <View style={styles.modeContainer}>
          </View>
          <View style={{flex: 1}}>
            <Text style={styles.text}>Link Address</Text>
            <TextInput
              style={styles.linkInput}
            />
          </View>
        </View>
        <View style={{flex: 1, backgroundColor: 'red'}}>

        </View>
        <View style={{flex: 1.5, backgroundColor: 'black'}}>
        </View>
      </View>
    </View>
  );
};

//RFValue is just a responsive wrapper

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: RFValue(16),
    minHeight: RFValue(56),
    backgroundColor: '#B1C59B',
  },
  text: {
    fontSize: RFValue(15),
    color: 'black',
  },
  main: {
    flex: 1,
    padding: 15,
  },
  modeContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    flex: 1,
    backgroundColor: 'yellow',
  },
  linkInput: {
    marginHorizontal: RFValue(40),
    padding: 0,
    paddingTop: 2,
    borderBottomWidth: RFValue(1),
    borderBottomColor: '#C4C4C4',
  },
});
</code>```

答: You can set height instead of flex in styling</p>

Body:
Layout overlapping on text input in react native as you can see in the images.
I have experimented with keyboardAvoidingView and keyboardAwareScrollView but I just cant fix it or I am implementing them incorrectly.

How to avoid keyboard from changing your flex layout? What's the industry standard? keyboardAvoidingView? I find that inconsistent or have not understood it conceptually. My approach usually is wrapping the entire code with either keyboardAwareScrollView or keyboardAvoidingView. Do I only do it over the textInput component?

const InterviewAlignment = ({navigation}) => {
  return (
    <View style={styles.container}>
      <View style={styles.header}>
      </View>
      <View style={styles.main}>
        <View
          style={{
            flex: 1,
            justifyContent: 'space-between',
          }}>
          <View
            style={{
              flex: 1,
              backgroundColor: 'red',
            }}>
          </View>
          <View style={styles.modeContainer}>
          </View>
          <View style={{flex: 1}}>
            <Text style={styles.text}>Link Address</Text>
            <TextInput
              style={styles.linkInput}
            />
          </View>
        </View>
        <View style={{flex: 1, backgroundColor: 'red'}}>

        </View>
        <View style={{flex: 1.5, backgroundColor: 'black'}}>
        </View>
      </View>
    </View>
  );
};

//RFValue is just a responsive wrapper

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: RFValue(16),
    minHeight: RFValue(56),
    backgroundColor: '#B1C59B',
  },
  text: {
    fontSize: RFValue(15),
    color: 'black',
  },
  main: {
    flex: 1,
    padding: 15,
  },
  modeContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    flex: 1,
    backgroundColor: 'yellow',
  },
  linkInput: {
    marginHorizontal: RFValue(40),
    padding: 0,
    paddingTop: 2,
    borderBottomWidth: RFValue(1),
    borderBottomColor: '#C4C4C4',
  },
});


问:
Azure ad graph api
I'm testing Azure Graph API.

and I'm trying to find an API that allows me to retrieve only users that are assigned to a specific app I created.

In app registration page, I gave a user.read.all permission, but the get user API gives me all users that are in the AD and not only that are assigned to the app I created. Should I change the permissions? or to access an another API?

Does anybody know what to do?

Thanks

答:
As a workaround you can use the below graph API to get the list of users.

```<code>https://graph.microsoft.com/v1.0/servicePrincipals/{ObjectID}/appRoleAssignedTo
</code>```

Note: The above graph API gives the Object Types User and Service
Principle as well

As discussed in the MS Q &A Platform This endpoint currently does not support filters based on appRoleId. In fact, except that the id parameter can be filtered, the three parameters appRoleId, principalId, and resourceId do not support filtering. Similar issues have been raised before.

Title: Azure ad graph api

Body:
As a workaround you can use the below graph API to get the list of users.

https://graph.microsoft.com/v1.0/servicePrincipals/{ObjectID}/appRoleAssignedTo

Note: The above graph API gives the Object Types User and Service
Principle as well

As discussed in the MS Q &A Platform This endpoint currently does not support filters based on appRoleId. In fact, except that the id parameter can be filtered, the three parameters appRoleId, principalId, and resourceId do not support filtering. Similar issues have been raised before.


问:
How many times do I need to run cdk bookstrap?
I am trying to understand how cdk bootstrap works. I have read the doc: https://github.com/aws/aws-cdk/blob/master/design/cdk-bootstrap.md and tried to run the command in my AWS account. I can see a new cf stack is created CDKToolkit which includes s3 bucket, iam roles etc.

My question is whether I need to run this command for every cdk project I have? Or is it just one time execution?
If I have projects using different cdk version v1 and v2, do I use the same cf stack? Will it cause version conflicts?

答:
It's typically a one time thing per account per region. The infrastructure in that stack is shared among your CDK apps.

There was a change in format a while ago that required an update of the stack, but since then it has remained largely unchanged.

The docs on bootstrap are probably more helpful than the Github Link: CDK Bootstrapping.

Each CloudFormation stack created by a CDK app only belongs to one CDK app, they shouldn't be shared. The outputs can be referenced from other apps, but each stack should belong to one app.

That's why you can mix and match CDK versions across different stacks. Usually each CDK app maps to one or more CloudFormation stacks.


问:
AttributeError: 'Member' object has no attribute 'avatar_url_as'
i am making an image command and it didnt work. I am using Pillow but i don't think its the problem. Please help me

Here is the code:

```<code>@commands.command()
async def chad(self, ctx, user: nextcord.Member = None):
    if user == None:
        user = ctx.author

    chad = Image.open(os.path.join("Modules", "Images", "chad.jpg"))
    useravatar = user.avatar_url_as(size=128)
    avatar_data = BytesIO(await useravatar.read())
    pfp = Image.open(avatar_data)
    pfp = pfp.resize((81,81))

    chad.paste (pfp, (282,247))
    chad.save("chad_done.jpg")

    await ctx.send(file = nextcord.File("chad_done.jpg"))`
</code>```

答:
In short:

nextcord.Member object hasn't avatar_url_as method

Probably you looking for nextcord.Member.avatar

Or nextcord.Member.display_avatar

Body:
i am making an image command and it didnt work. I am using Pillow but i don't think its the problem. Please help me

Here is the code:

@commands.command()
async def chad(self, ctx, user: nextcord.Member = None):
    if user == None:
        user = ctx.author

    chad = Image.open(os.path.join("Modules", "Images", "chad.jpg"))
    useravatar = user.avatar_url_as(size=128)
    avatar_data = BytesIO(await useravatar.read())
    pfp = Image.open(avatar_data)
    pfp = pfp.resize((81,81))

    chad.paste (pfp, (282,247))
    chad.save("chad_done.jpg")

    await ctx.send(file = nextcord.File("chad_done.jpg"))`


问:
Android Studio stuck on loading devices
I'm currently running Android Studio Bumblebee 2021.1.1 in windows 10.
The problem I have is each time I start android studio the device list is stuck in loading devices.

I tried these solutions

android studio device list stuck on loading/51101178

android device list showing in android studio got stuck/65177069

The soulutions provided in the threads sometimes work and sometimes don't but the real problem is even if I did fix it in the run time,  The next time I open android studio it's still there.

I already tried updating android studio to latest version, reinstalling android studio, deleting all the caches and plugins and resetting it to default. Completely Deleting Sdk folder and downloading again. But nothing helped I don't know where this problem could be originate from

答: This is a temporary solution. Open terminal and type adb devices. Once your device starts showing up in terminal, it will start showing up in loading devices too.

Title: Android Studio stuck on loading devices


问:
Override element.style in CSS
I have a react component using React-qr-scanner but I cannot seem to override the element.style. I want to remove the border because it's too big.

```<code>.qrScanner {
  border: 1px solid rgba(0, 0, 0, 0.3) !important;
  box-shadow: rgba(244, 248, 0, 0.5) 0px 0px 0px 5px inset;
}
</code>```

I'm calling it by

```<code><QrReader
            delay={3000}
            onError={handleError}
            onScan={handleScan}
            // chooseDeviceId={()=>selected}
            style={{width: '250px', heigth: '200px'}}
            className={'qrScanner'}
          />
</code>```

I want to override it using CSS.

答: You can't. Style takes precedence over CSS. You'll have to hack or fork the plugin.</p>

Title: Override element.style in CSS

Body:
I have a react component using React-qr-scanner but I cannot seem to override the element.style. I want to remove the border because it's too big.

.qrScanner {
  border: 1px solid rgba(0, 0, 0, 0.3) !important;
  box-shadow: rgba(244, 248, 0, 0.5) 0px 0px 0px 5px inset;
}

I'm calling it by

<QrReader
            delay={3000}
            onError={handleError}
            onScan={handleScan}
            // chooseDeviceId={()=>selected}
            style={{width: '250px', heigth: '200px'}}
            className={'qrScanner'}
          />

I want to override it using CSS.


问:
Entity manager error on the server?
Hi I have developed my java application on glassfish server with EJB 3.0 persistance. On my local machine the application was running fine and was persisting the data perfectly. However, When I deployed it on the linux server, whenever I persist any data it gives me this EJB exception error:

```<code>Caused by: Java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManagerFactory.
</code>```

And here is my persistence.xml file:

```<code><?xml version="1.0" encoding="UTF-8" ?>
  <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="MyPU" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/security</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="eclipselink.ddl-generation" value="create-tables" />
        </properties>
    </persistence-unit>
  </persistence>
</code>```

what could possbily cause this?

PS: Im using Glassfish 3.1.43, EJB 3.0

答: What database are you using? I would verify that the user you have configured in the connection pool has the privilege to create tables.</p>

Title: Entity manager error on the server?

Body:
Hi I have developed my java application on glassfish server with EJB 3.0 persistance. On my local machine the application was running fine and was persisting the data perfectly. However, When I deployed it on the linux server, whenever I persist any data it gives me this EJB exception error:

Caused by: Java.lang.IllegalStateException: Attempting to execute an operation on a closed EntityManagerFactory.

And here is my persistence.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
  <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="MyPU" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/security</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="eclipselink.ddl-generation" value="create-tables" />
        </properties>
    </persistence-unit>
  </persistence>

what could possbily cause this?

PS: Im using Glassfish 3.1.43, EJB 3.0


问:
How to use requests.Sessions() to deliver a package to a URL with no 'action' attribute in the HTML in Python
I want to use requests.Sessions() to deliver my login information to a website. Once logged in I want to navigate to a second URL that can only be accessed once logged in. In order to scrape data from the second URL.

I am new to scraping and don't really have any experience with HTML

I am working in collaboratory if that makes any difference.

This is my code and the outputs:

```<code>import requests

page = requests.get("https://app.gristanalytics.com/Account/Login")
page
</code>```

<Response [200]>

```<code>page.status_code
</code>```

200

```<code>from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())
</code>```

This is the output:

```<code><!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport"/>
  <link href="/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="/lib/fontawesome/css/all.min.css" rel="stylesheet"/>
  <link href="/lib/datetimepicker/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
  <link href="/lib/vue-multiselect/vue-multiselect.min.css" rel="stylesheet"/>
  <link href="/css/site.css" rel="stylesheet"/>
  <title>
   Log in - Grist
  </title>
 </head>
 <body>
  <div>
   <div class="text-center loginbox">
    <form method="post" style="width:100%;max-width:350px;padding:15px;margin:0 auto;">
     <img alt="" class="mb-4" src="/images/grist_logo_m_black.png"/>
     <h1 class="h3 mb-3 font-weight-normal">
      Please sign in
     </h1>
     <div class="text-danger validation-summary-valid" data-valmsg-summary="true">
      <ul>
       <li style="display:none">
       </li>
      </ul>
     </div>
     <label class="sr-only" for="inputEmail">
      Email address
     </label>
     <input autofocus="" class="form-control my-1" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" placeholder="Email address" required="" type="email" value=""/>
     <label class="sr-only" for="inputPassword">
      Password
     </label>
     <input class="form-control my-1" data-val="true" data-val-required="The Password field is required." id="Input_Password" name="Input.Password" placeholder="Password" required="" type="password"/>
     <div class="checkbox my-3">
      <label>
       <input data-val="true" data-val-required="The Remember me? field is required." id="Input_RememberMe" name="Input.RememberMe" type="checkbox" value="true"/>
       Remember me
      </label>
      <p>
       <a href="/Account/ForgotPassword">
        Forgot your password?
       </a>
      </p>
     </div>
     <button class="btn btn-lg btn-primary btn-block" type="submit">
      Sign in
     </button>
     <p class="mt-5 mb-3 text-muted">
      © 2018-2022
     </p>
     <input name="__RequestVerificationToken" type="hidden" value="CfDJ8CxpSY-tCd5Ou0L0wqhntPACCikaoFBOUQLV0RgCaVUJgt9wRSd3p9aVswNuSLU6OPRKsbIm-qvOyZyZErcEm-E__Q2tPauexh3z_T02Oh5TZCpeY12PsUsERY3INO5LUBBmWXeUR6nG5BFHnnNdW70">
      <input name="Input.RememberMe" type="hidden" value="false"/>
     </input>
    </form>
   </div>
  </div>
  <script src="/lib/jquery-validation/dist/Jquery.validate.min.js">
  </script>
  <script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js">
  </script>
 </body>
</html>
</code>```

At this point I believe that the field names that I want to deliver the payload are:
name="Input.Email" and name="Input.Password"

However I note that there is no action attribute in the HTML code, so I plan to send the payload to the original URL as you will see below.

```<code>payload = {
    'Input.Email':  'MyEmail', #yes in practice this is my actual information instead of this placeholder
    'Input.Password': 'MyPassword', #same here real password used instead
}
with requests.Session() as session:
  post = session.post('https://app.gristanalytics.com/Account/Login', data=payload)
  r = session.get('https://app.gristanalytics.com/Data/Brewhouse')
soup = BeautifulSoup(r.content, 'html.parser')
print(soup.prettify())
</code>```

The output of this is:

```<code><!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport"/>
  <link href="/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="/lib/fontawesome/css/all.min.css" rel="stylesheet"/>
  <link href="/lib/datetimepicker/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
  <link href="/lib/vue-multiselect/vue-multiselect.min.css" rel="stylesheet"/>
  <link href="/css/site.css" rel="stylesheet"/>
  <title>
   Log in - Grist
  </title>
 </head>
 <body>
  <div>
   <div class="text-center loginbox">
    <form method="post" style="width:100%;max-width:350px;padding:15px;margin:0 auto;">
     <img alt="" class="mb-4" src="/images/grist_logo_m_black.png"/>
     <h1 class="h3 mb-3 font-weight-normal">
      Please sign in
     </h1>
     <div class="text-danger validation-summary-valid" data-valmsg-summary="true">
      <ul>
       <li style="display:none">
       </li>
      </ul>
     </div>
     <label class="sr-only" for="inputEmail">
      Email address
     </label>
     <input autofocus="" class="form-control my-1" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" placeholder="Email address" required="" type="email" value=""/>
     <label class="sr-only" for="inputPassword">
      Password
     </label>
     <input class="form-control my-1" data-val="true" data-val-required="The Password field is required." id="Input_Password" name="Input.Password" placeholder="Password" required="" type="password"/>
     <div class="checkbox my-3">
      <label>
       <input data-val="true" data-val-required="The Remember me? field is required." id="Input_RememberMe" name="Input.RememberMe" type="checkbox" value="true"/>
       Remember me
      </label>
      <p>
       <a href="/Account/ForgotPassword">
        Forgot your password?
       </a>
      </p>
     </div>
     <button class="btn btn-lg btn-primary btn-block" type="submit">
      Sign in
     </button>
     <p class="mt-5 mb-3 text-muted">
      © 2018-2022
     </p>
     <input name="__RequestVerificationToken" type="hidden" value="CfDJ8CxpSY-tCd5Ou0L0wqhntPAwaiYOz80Q50p5gOcDk9qSF-gR4JJpzNGOdSKiQOzcVPp8hBKgDaEwXOrbFnpgdYXkedfcnLQlXIJ1Z7HnIi5vKZybNd6VSKk_Xs5Az444e3Oug-u1UFcxq_OLX1Iu0wU">
      <input name="Input.RememberMe" type="hidden" value="false"/>
     </input>
    </form>
   </div>
  </div>
  <script src="/lib/jquery-validation/dist/Jquery.validate.min.js">
  </script>
  <script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js">
  </script>
 </body>
</html>
</code>```

Which is the same HTML as the first time, it is clear that I am not logged in, and as a result I can't get to the HTML code of the URL I want.

I have tried other variations for the payload field names including:

inputEmail (from for=)

Input_Email (from id=)

email (from type=)

sample code for variation 1 would be

```<code>payload = {
    'inputEmail':  'MyEmail', #yes in practice this is my actual information instead of this placeholder
    'inputPassword': 'MyPassword', #same here real password used instead
}
</code>```

I get no error or warning messages when running this code so I'm a bit stuck as to what to do.

答:
The following code helped me to login and get me where I wanted to go!

Big thank you to @bushcat69 for the help he provided, I probably wouldn't have looked seriously at the verification token without them.

As well as the following [1, 2]  stack exchange posts for additional information that I used.

```<code>with requests.Session() as session:
  read = session.get('https://app.gristanalytics.com/Account/Login')
  soup = BeautifulSoup(read.content, 'html.parser')
  token = soup.select_one('[name="__RequestVerificationToken"]').get('value')
  payload = {
    'Input.Email':  'MyEmail@email.com',
    'Input.Password': 'MyPassword',
    '__RequestVerificationToken': token,
    'Input.RememberMe': 'false'
}
  post = session.post('https://app.gristanalytics.com/Account/Login', data=payload)
  r = session.get('https://app.gristanalytics.com/Data/Brewhouse')
  tastySoup = BeautifulSoup(r.content, 'html.parser')
  print(tastySoup.prettify())
</code>```

I am now having issues where it seems that some of the content that I want to scrape is working through Ajax / javascript which I don't know how to get. If you're having similar issues look into my future questions, I will also leave a comment here with the stackexchange/whatever website if I find content that helps me figure it out.

Body:
I want to use requests.Sessions() to deliver my login information to a website. Once logged in I want to navigate to a second URL that can only be accessed once logged in. In order to scrape data from the second URL.

I am new to scraping and don't really have any experience with HTML

I am working in collaboratory if that makes any difference.

This is my code and the outputs:

import requests

page = requests.get("https://app.gristanalytics.com/Account/Login")
page

<Response [200]>

page.status_code

200

from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')
print(soup.prettify())

This is the output:

<!DOCTYPE html>

  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport"/>
  <link href="/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="/lib/fontawesome/css/all.min.css" rel="stylesheet"/>
  <link href="/lib/datetimepicker/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
  <link href="/lib/vue-multiselect/vue-multiselect.min.css" rel="stylesheet"/>
  <link href="/css/site.css" rel="stylesheet"/>
  <title>
   Log in - Grist
  </title>

    <form method="post" style="width:100%;max-width:350px;padding:15px;margin:0 auto;">

      Please sign in

      Email address

     <input autofocus="" class="form-control my-1" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" placeholder="Email address" required="" type="email" value=""/>

      Password

     <input class="form-control my-1" data-val="true" data-val-required="The Password field is required." id="Input_Password" name="Input.Password" placeholder="Password" required="" type="password"/>

       <input data-val="true" data-val-required="The Remember me? field is required." id="Input_RememberMe" name="Input.RememberMe" type="checkbox" value="true"/>
       Remember me

        Forgot your password?

     <button class="btn btn-lg btn-primary btn-block" type="submit">
      Sign in
     </button>

      © 2018-2022

     <input name="__RequestVerificationToken" type="hidden" value="CfDJ8CxpSY-tCd5Ou0L0wqhntPACCikaoFBOUQLV0RgCaVUJgt9wRSd3p9aVswNuSLU6OPRKsbIm-qvOyZyZErcEm-E__Q2tPauexh3z_T02Oh5TZCpeY12PsUsERY3INO5LUBBmWXeUR6nG5BFHnnNdW70">
      <input name="Input.RememberMe" type="hidden" value="false"/>
     </input>
    </form>

At this point I believe that the field names that I want to deliver the payload are:
name="Input.Email" and name="Input.Password"

However I note that there is no action attribute in the HTML code, so I plan to send the payload to the original URL as you will see below.

payload = {
    'Input.Email':  'MyEmail', #yes in practice this is my actual information instead of this placeholder
    'Input.Password': 'MyPassword', #same here real password used instead
}
with requests.Session() as session:
  post = session.post('https://app.gristanalytics.com/Account/Login', data=payload)
  r = session.get('https://app.gristanalytics.com/Data/Brewhouse')
soup = BeautifulSoup(r.content, 'html.parser')
print(soup.prettify())

The output of this is:

<!DOCTYPE html>

  <meta charset="utf-8"/>
  <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport"/>
  <link href="/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"/>
  <link href="/lib/fontawesome/css/all.min.css" rel="stylesheet"/>
  <link href="/lib/datetimepicker/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
  <link href="/lib/vue-multiselect/vue-multiselect.min.css" rel="stylesheet"/>
  <link href="/css/site.css" rel="stylesheet"/>
  <title>
   Log in - Grist
  </title>

    <form method="post" style="width:100%;max-width:350px;padding:15px;margin:0 auto;">

      Please sign in

      Email address

     <input autofocus="" class="form-control my-1" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" placeholder="Email address" required="" type="email" value=""/>

      Password

     <input class="form-control my-1" data-val="true" data-val-required="The Password field is required." id="Input_Password" name="Input.Password" placeholder="Password" required="" type="password"/>

       <input data-val="true" data-val-required="The Remember me? field is required." id="Input_RememberMe" name="Input.RememberMe" type="checkbox" value="true"/>
       Remember me

        Forgot your password?

     <button class="btn btn-lg btn-primary btn-block" type="submit">
      Sign in
     </button>

      © 2018-2022

     <input name="__RequestVerificationToken" type="hidden" value="CfDJ8CxpSY-tCd5Ou0L0wqhntPAwaiYOz80Q50p5gOcDk9qSF-gR4JJpzNGOdSKiQOzcVPp8hBKgDaEwXOrbFnpgdYXkedfcnLQlXIJ1Z7HnIi5vKZybNd6VSKk_Xs5Az444e3Oug-u1UFcxq_OLX1Iu0wU">
      <input name="Input.RememberMe" type="hidden" value="false"/>
     </input>
    </form>

Which is the same HTML as the first time, it is clear that I am not logged in, and as a result I can't get to the HTML code of the URL I want.

I have tried other variations for the payload field names including:

inputEmail (from for=)

Input_Email (from id=)

email (from type=)

sample code for variation 1 would be

payload = {
    'inputEmail':  'MyEmail', #yes in practice this is my actual information instead of this placeholder
    'inputPassword': 'MyPassword', #same here real password used instead
}

I get no error or warning messages when running this code so I'm a bit stuck as to what to do.

Body:
The following code helped me to login and get me where I wanted to go!

Big thank you to @bushcat69 for the help he provided, I probably wouldn't have looked seriously at the verification token without them.

As well as the following [1, 2]  stack exchange posts for additional information that I used.

with requests.Session() as session:
  read = session.get('https://app.gristanalytics.com/Account/Login')
  soup = BeautifulSoup(read.content, 'html.parser')
  token = soup.select_one('[name="__RequestVerificationToken"]').get('value')
  payload = {
    'Input.Email':  'MyEmail@email.com',
    'Input.Password': 'MyPassword',
    '__RequestVerificationToken': token,
    'Input.RememberMe': 'false'
}
  post = session.post('https://app.gristanalytics.com/Account/Login', data=payload)
  r = session.get('https://app.gristanalytics.com/Data/Brewhouse')
  tastySoup = BeautifulSoup(r.content, 'html.parser')
  print(tastySoup.prettify())

I am now having issues where it seems that some of the content that I want to scrape is working through Ajax / javascript which I don't know how to get. If you're having similar issues look into my future questions, I will also leave a comment here with the stackexchange/whatever website if I find content that helps me figure it out.


问:
how to simplify if elseif statement to get particular search data from laravel MySQL database
I am collecting all the data like id, name, date, empid from the controller in variable data

```<code>$data = $request->all();

</code>```

now i want to select all the rows from the mysql table base on the input value i receive from request like this.

if no value is given then select all from DB

```<code>if ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

           $country =  country::get();

</code>```

if only certain input value is given

```<code>elseif ($data['keyvalue'] !== '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] !=='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] !=='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] !=='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();

}

</code>```

and if all input value is given

```<code>elseif ($data['keyvalue'] !== '' && $data['datefrom'] !=='' && $data['dateto'] !=='' && $data['prepid'] !=='' ){

           $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();
}

</code>```

everything working fine i just want to simplify this code..

答:
You could do it like this:

$country = null;

if ($value0 !== null)
{
    $country = $country ?? Country::where('query0 here');
}
else if ($value1 !== null)
{
    $country = $country ?? Country::where('query1 here');
}
...
// end of your else ifs
// you do not need to check if all of the value exist because
// the query when all of the value exist and the partial value
// exist combined is just the same

$country = $country ?? $country->get();

```

Body:
I am collecting all the data like id, name, date, empid from the controller in variable data

$data = $request->all();

now i want to select all the rows from the mysql table base on the input value i receive from request like this.

if no value is given then select all from DB

if ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

           $country =  country::get();

if only certain input value is given

elseif ($data['keyvalue'] !== '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] !=='' && $data['dateto'] =='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] !=='' && $data['prepid'] =='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->orderBy('sr_id')
                    ->get();

}elseif ($data['keyvalue'] == '' && $data['datefrom'] =='' && $data['dateto'] =='' && $data['prepid'] !=='' ){

            $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();

}

and if all input value is given

elseif ($data['keyvalue'] !== '' && $data['datefrom'] !=='' && $data['dateto'] !=='' && $data['prepid'] !=='' ){

           $country = country::where('sr_status','LIKE','%'.$data['status'].'%')
                    ->whereDate('created_at','>=',$data['datefrom'])
                    ->whereDate('created_at','<=',$data['dateto'])
                    ->Where('sr_name','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('tel_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('country_code','LIKE','%'.$data['keyvalue'].'%')
                    ->orWhere('currency_name','LIKE','%'.$data['keyvalue'].'%')
                    ->Where('prep_emp','LIKE','%'.$data['prepid'].'%')
                    ->orderBy('sr_id')
                    ->get();
}

everything working fine i just want to simplify this code..


问:
How to prevent jwt token from getting stolen from the mobile phone and misused?
I have a web api and mobile app.

I'm using Oauth (openidconnect). When user invokes the login endpoint, the Oauth flow is triggered which eventually results in the jwt id token being received by the api server (from the auth server).

Assume that the jwt id token is sent to the mobile app by the app server (in the api response), so that the api remains stateless, and subsequent api requests can pass the jwt id token into the endpoint so that the api knows who the caller is.

How to prevent this jwt from being stolen from the mobile phone and misused?

答:
Because JWTs are used to identify the client, if one is stolen or compromised, an attacker has full access to the user’s account in the same way they would if the attacker had instead compromised the user’s username and password.

For instance, if an attacker gets ahold of your JWT, they could start sending requests to the server identifying themselves as you and do things like make service changes, user account updates, etc. Once an attacker has your JWT it is game over.

BUT, there is one thing that makes a stolen JWT slightly less bad than a stolen username and password: timing. Because JWTs can be configured to automatically expire after a set amount of time (a minute, an hour, a day, whatever), attackers can only use your JWT to access the service until it expires.

In theory, that sounds great, right? One of the ways token authentication is said to make authentication more “secure” is via short-lived tokens. That’s one of the core reasons token-based authentication has really taken off in recent years: you can automatically expire tokens and mitigate the risk of relying on forever-cached “stateless” tokens.

In the security world, after all, relying on cached data to make sensitive decisions like who can log into a service and what they can do is considered a bad thing. Because tokens are stateless and allow for some speed improvements over traditional session authentication, the only way in which they can remain somewhat “secure” is by limiting their lifespan so they don’t cause too much harm when compromised.

The only problem here is that if an attacker was able to steal your token in the first place, they’re likely able to do it once you get a new token as well. The most common ways this happens is by man-in-the-middling (MITM) your connection or getting access to the client or server directly. And unfortunately, in these scenarios, even the shortest-lived JWTs won’t help you at all.

In general, tokens should be treated like passwords and protected as such. They should never be publicly shared and should be kept in secure data stores. For browser-based applications, this means never storing your tokens in HTML5 Local Storage and instead storing tokens in server-side cookies that are not accessible to JavaScript.

In general, token-based authentication does not provide any additional security over typical session-based authentication relying on opaque session identifiers. While there are certainly a good number of use cases for token-based authentication, knowing how the technology works and where your weak spots are is essential.

Another interesting thing to consider is that in some cases, a stolen JWT can actually be worse than a stolen username and password.

Let’s pretend, for a moment, that your username and password have been compromised. In this scenario, if the app you’re logging into is protected with multi-factor authentication, an attacker needs to bypass additional identity proofing mechanisms in order to gain access to your account.

While guessing or brute-forcing a username and password is a very realistic scenario, being able to compromise a user’s mutli-factor authentication setup can be quite difficult. Bypassing factors like app-based authorization, SMS verification, face ID, touch ID, etc., is a significantly more challenging than guessing a user’s password.

Because of this, a compromised JWT can actually be a greater security risk than a compromised username and password. Imagine the scenario above where the app a user logs into is protected by multi-factor authentication. Once the user logs in and verifies themselves via multi-factor, they are assigned a JWT to prove who they are. If that JWT is stolen, the attacker no longer needs to bypass MFA directly (like they would have to if they only had the user’s username and password)—they can now directly make requests as the user without additional identity proofing. Quite a big risk.


问:
Sending DM with embeds using discord.py
I have tried many things but I can't get discord.py to send a message with embeds. But I have gotten it to send a normal message when a command is typed using this code.

```<code>@client.event
async def on_message(message):
  msg = message.content

  if msg.startswith('$helpme'):
    await message.author.send("this text would be sent via dm, but with no embeds...")
</code>```

It would be a help menu which the bot would the dm the user when $helpme is typed. Problem is I can't get it to send this embed code.

```<code>  embed=discord.Embed(title=" Help", description="I am here to help!", color=0x0000ff)
  embed.set_author(name="Meerdus", icon_url="https://cdn.discordapp.com/attachments/834885490451808286/939646209092616312/M.png")
  embed.add_field(name="$helpme", value="Shows this menu!", inline=False)
  embed.add_field(name="$kick", value="Kick a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$ban", value="Ban a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$unban", value="Unban a member if you have Administrator permissions.", inline=False)
  embed.add_field(name="$lock", value="Lock a channel if you have the permission to manage channels!", inline=False)
  embed.add_field(name="$meme", value="Display a random clean meme! :)", inline=False)
  embed.add_field(name="$doggo", value="Show a random dog picture and dog fact!", inline=False)
  embed.add_field(name="$kitty", value="Show a random cat picture and cat fact!", inline=False)
  embed.add_field(name="$birdy", value="Show a random bird picture and bird fact!", inline=False)
  embed.add_field(name="$randomnum", value="Display a random number between 1 and 100!", inline=False)
  embed.add_field(name="$tictactoe", value="Play tictactoe with two people by specifing <command> <yourusername> <secondplayersusername>", inline=False)
  embed.add_field(name="DONT ACTUALLY ENTER THE <>", value="You have to enter the things said inside them.", inline=False)
  await ctx.send(embed=embed)
</code>```

答:
I believe the issue is it needs to be await message.author.send() not await ctx.send() since in the code snippet that works it is in the on_message() event listener. ctx.send() is how you would do it in a Bot command. The syntaxation is completely fine.

For example in my own discord bot you can see I send the help embed inside a cog the exact same way as the second snippet which is completely functional.

Title: Sending DM with embeds using discord.py

Body:
I have tried many things but I can't get discord.py to send a message with embeds. But I have gotten it to send a normal message when a command is typed using this code.

@client.event
async def on_message(message):
  msg = message.content

  if msg.startswith('$helpme'):
    await message.author.send("this text would be sent via dm, but with no embeds...")

It would be a help menu which the bot would the dm the user when $helpme is typed. Problem is I can't get it to send this embed code.

  embed=discord.Embed(title=" Help", description="I am here to help!", color=0x0000ff)
  embed.set_author(name="Meerdus", icon_url="https://cdn.discordapp.com/attachments/834885490451808286/939646209092616312/M.png")
  embed.add_field(name="$helpme", value="Shows this menu!", inline=False)
  embed.add_field(name="$kick", value="Kick a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$ban", value="Ban a member if you have Administrator permissions!", inline=False)
  embed.add_field(name="$unban", value="Unban a member if you have Administrator permissions.", inline=False)
  embed.add_field(name="$lock", value="Lock a channel if you have the permission to manage channels!", inline=False)
  embed.add_field(name="$meme", value="Display a random clean meme! :)", inline=False)
  embed.add_field(name="$doggo", value="Show a random dog picture and dog fact!", inline=False)
  embed.add_field(name="$kitty", value="Show a random cat picture and cat fact!", inline=False)
  embed.add_field(name="$birdy", value="Show a random bird picture and bird fact!", inline=False)
  embed.add_field(name="$randomnum", value="Display a random number between 1 and 100!", inline=False)
  embed.add_field(name="$tictactoe", value="Play tictactoe with two people by specifing <command> <yourusername> <secondplayersusername>", inline=False)
  embed.add_field(name="DONT ACTUALLY ENTER THE <>", value="You have to enter the things said inside them.", inline=False)
  await ctx.send(embed=embed)


问:
Find pk in queryset Django
I have a problem in obtaining a single id from a queryset. I post my models and views in order to be more clear:
models.py

```<code>class MissionEntry(models.Model):
    student = models.ForeignKey(
        Student, on_delete=models.DO_NOTHING, blank=True, null=True)
    mission = models.ForeignKey(
        Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
    log_entry = models.ForeignKey(
        LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True)
    learning_objective = models.ForeignKey(
        LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
    grade = models.CharField(
        max_length=10, choices=GRADING_VALUE, blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    debriefing = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.mission) + ' ' + str(self.log_entry)

    class Meta:
        verbose_name_plural = 'Mission Entries'

class MissionEntryStatus(models.Model):
    mission = models.ForeignKey(
        Mission, on_delete=models.PROTECT, null=True, blank=True)
    student = models.ForeignKey(Student, on_delete=models.PROTECT)
    is_completed = models.BooleanField(default=False)
    is_failed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class StudentMission(models.Model):
    mission = models.ForeignKey(Mission, on_delete=models.PROTECT)
    student_training_course = models.ForeignKey(
        StudentTrainingCourse, on_delete=models.PROTECT)
    mission_status = models.ForeignKey(
        MissionEntryStatus, on_delete=models.PROTECT, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['mission__name']

    def __str__(self):
        return self.mission.name

class LogEntry(models.Model):
    aircraft = models.ForeignKey(Aircraft, on_delete=models.DO_NOTHING)
    adep = models.ForeignKey(
        Aerodrome, on_delete=models.PROTECT, related_name='adep')
    ades = models.ForeignKey(
        Aerodrome, on_delete=models.PROTECT, related_name='ades')
    date = models.DateField()
    etd = models.TimeField()
    ata = models.TimeField()
    eet = models.TimeField()
    function_type = models.ForeignKey(FunctionType, on_delete=models.PROTECT)
    student = models.ForeignKey(
        Student, on_delete=models.PROTECT, blank=True, null=True)
    instructor = models.ForeignKey(
        Instructor, on_delete=models.PROTECT, blank=True, null=True)
    student_mission = models.ForeignKey(
        'mission.StudentMission', on_delete=models.PROTECT, null=True, blank=True)
    note = models.TextField(null=True, blank=True)
    cross_country = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
</code>```

views.py

```<code>def student_mission_list(request, pk):
    student = Student.objects.get(id=pk)
    student_training_course = StudentTrainingCourse.objects.filter(
        student_id=student.id)
    missions = StudentMission.objects.filter(
        student_training_course_id__in=student_training_course)
    mission_entry = MissionEntry.objects.filter(student_id=student)
    log_entry = LogEntry.objects.filter(student_mission_id__in=missions)
    print(log_entry)
    context = {
        'student': student,
        'missions': missions,
        'mission_entry': mission_entry,
    }
    return render(request, 'mission/student_mission_list.html', context)
</code>```

In fact, what I need to do, is to obtain a single value for the log_entry. The problem is that, obviously, I am retrieving multiple values of log_entry. But I would like to get the single pk of the log_entry.
Any suggestion? Should I remodel the models.py file?

答:
try this:</p>
```<code>log_entry = LogEntry.objects.get(student_mission_id__in=missions)
print(log_entry.id)
</code>```

Title: Find pk in queryset Django

Body:
I have a problem in obtaining a single id from a queryset. I post my models and views in order to be more clear:
models.py

class MissionEntry(models.Model):
    student = models.ForeignKey(
        Student, on_delete=models.DO_NOTHING, blank=True, null=True)
    mission = models.ForeignKey(
        Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
    log_entry = models.ForeignKey(
        LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True)
    learning_objective = models.ForeignKey(
        LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
    grade = models.CharField(
        max_length=10, choices=GRADING_VALUE, blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    debriefing = models.TextField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return str(self.mission) + ' ' + str(self.log_entry)

    class Meta:
        verbose_name_plural = 'Mission Entries'

class MissionEntryStatus(models.Model):
    mission = models.ForeignKey(
        Mission, on_delete=models.PROTECT, null=True, blank=True)
    student = models.ForeignKey(Student, on_delete=models.PROTECT)
    is_completed = models.BooleanField(default=False)
    is_failed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class StudentMission(models.Model):
    mission = models.ForeignKey(Mission, on_delete=models.PROTECT)
    student_training_course = models.ForeignKey(
        StudentTrainingCourse, on_delete=models.PROTECT)
    mission_status = models.ForeignKey(
        MissionEntryStatus, on_delete=models.PROTECT, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['mission__name']

    def __str__(self):
        return self.mission.name

class LogEntry(models.Model):
    aircraft = models.ForeignKey(Aircraft, on_delete=models.DO_NOTHING)
    adep = models.ForeignKey(
        Aerodrome, on_delete=models.PROTECT, related_name='adep')
    ades = models.ForeignKey(
        Aerodrome, on_delete=models.PROTECT, related_name='ades')
    date = models.DateField()
    etd = models.TimeField()
    ata = models.TimeField()
    eet = models.TimeField()
    function_type = models.ForeignKey(FunctionType, on_delete=models.PROTECT)
    student = models.ForeignKey(
        Student, on_delete=models.PROTECT, blank=True, null=True)
    instructor = models.ForeignKey(
        Instructor, on_delete=models.PROTECT, blank=True, null=True)
    student_mission = models.ForeignKey(
        'mission.StudentMission', on_delete=models.PROTECT, null=True, blank=True)
    note = models.TextField(null=True, blank=True)
    cross_country = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

views.py

def student_mission_list(request, pk):
    student = Student.objects.get(id=pk)
    student_training_course = StudentTrainingCourse.objects.filter(
        student_id=student.id)
    missions = StudentMission.objects.filter(
        student_training_course_id__in=student_training_course)
    mission_entry = MissionEntry.objects.filter(student_id=student)
    log_entry = LogEntry.objects.filter(student_mission_id__in=missions)
    print(log_entry)
    context = {
        'student': student,
        'missions': missions,
        'mission_entry': mission_entry,
    }
    return render(request, 'mission/student_mission_list.html', context)

In fact, what I need to do, is to obtain a single value for the log_entry. The problem is that, obviously, I am retrieving multiple values of log_entry. But I would like to get the single pk of the log_entry.
Any suggestion? Should I remodel the models.py file?

Body:
try this:

log_entry = LogEntry.objects.get(student_mission_id__in=missions)
print(log_entry.id)