问:
Add files to empty commit on git?
I have been searching for this and i didn't found something clear to understand.

I have a new branch and have make changes on that branch. Then i have commited those changes but i forgot to add the files on that commit.
So my question is how can i add the files to the empty commit?

What i did:

```<code>git commit -m "this is my first commit"

git status
      modified: myFile.js
</code>```

So now i have the empty commit and i need to add the change myFile.js to that commit.

What should i do?

答:
First, you did not have an empty commit.

If you did not add first, that first commit did not complete successfully.

Second, "git commit" gives output similar to "git status" when there is nothing to commit, but without honoring the advise.statusHints configuration variable, which has been corrected with Git 2.25.1 (Feb. 2020).

See commit 5c4f55f (17 Dec 2019) by Heba Waly (HebaWaly).

(Merged by Junio C Hamano -- gitster -- in commit 9403e5d, 22 Jan 2020)

commit: honor advice.statusHints when rejecting an empty commit

Signed-off-by: Heba Waly

In ea9882b (commit: disable status hints when writing to COMMIT_EDITMSG, 2013-09-12, Git v1.8.5-rc0) the intent was to disable status hints when writing to COMMIT_EDITMSG, because giving the hints in the "git status" like output in the commit message template are too late to be useful (they say things like "'git add' to stage", but that is only possible after aborting the current "git commit" session).

But there is one case that the hints can be useful: When the current attempt to commit is rejected because no change is recorded in the index.

The message is given and "git commit" errors out, so the hints can immediately be followed by the user.

Teach the codepath to honor the configuration variable.

That means if you try and commit an empty commit, you will now see:

```<code>no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Title: Add files to empty commit on git?

Body:
I have been searching for this and i didn't found something clear to understand.

I have a new branch and have make changes on that branch. Then i have commited those changes but i forgot to add the files on that commit.
So my question is how can i add the files to the empty commit?

What i did:

git commit -m "this is my first commit"

git status
      modified: myFile.js

So now i have the empty commit and i need to add the change myFile.js to that commit.

What should i do?

Body:
First, you did not have an empty commit.

If you did not add first, that first commit did not complete successfully.

Second, "git commit" gives output similar to "git status" when there is nothing to commit, but without honoring the advise.statusHints configuration variable, which has been corrected with Git 2.25.1 (Feb. 2020).

See commit 5c4f55f (17 Dec 2019) by Heba Waly (HebaWaly).

(Merged by Junio C Hamano -- gitster -- in commit 9403e5d, 22 Jan 2020)

commit: honor advice.statusHints when rejecting an empty commit

Signed-off-by: Heba Waly

In ea9882b (commit: disable status hints when writing to COMMIT_EDITMSG, 2013-09-12, Git v1.8.5-rc0) the intent was to disable status hints when writing to COMMIT_EDITMSG, because giving the hints in the "git status" like output in the commit message template are too late to be useful (they say things like "'git add' to stage", but that is only possible after aborting the current "git commit" session).

But there is one case that the hints can be useful: When the current attempt to commit is rejected because no change is recorded in the index.

The message is given and "git commit" errors out, so the hints can immediately be followed by the user.

Teach the codepath to honor the configuration variable.

That means if you try and commit an empty commit, you will now see:

no changes added to commit (use "git add" and/or "git commit -a")


来源: stackexchange

问:
How to BEST extract information from multiple dataframes based on a series of if\else conditions and matching values? (Guidance needed!))
So I have three Dataframes, X, Y and Events. df_X has X Co-ordinates, df_Y has Y Co-ordinates and Events_df has a list of events that has happened (The Data is Basketball related). You'll see how they link together by looking below:

```<code>df_Event:

Seconds Passed   Event Type         Player
1.0              Passed The Ball    Steve
2.0              Received Pass      Michael
3.0              Touch              Michael
4.0              Passed The Ball    Michael
5.0              Received The Ball  George

df_X:

Seconds Passed  Steve   Michael   George
1.0             11.43   12.33     15.33
2.0             11.45   12.46     13.22
3.0             10.99   10.33     14.33
4.0             11.34   10.36     11.22
5.0             12.43   12.22     11.78

df_Y:

....

(The Same As Above Just With Different Numbers)
</code>```

I want to record patterns of events across time and then take the X, Y coordinates that correspond to the Seconds Passed columns across each Dataframes. So for example, if I wanted to know where a pass started and ended I would need the following information..

I want the following information in a new Dataframe labelled "Passes_df":

```<code>Passing Player   Receiving Player    X Coordinate PP   Y Coordinate PP  X Coordinate RP   Y Coordinate RP
Steve            Michael             11.43             ....             12.46             .....
</code>```

I know I could use the following:

```<code>Passes_df['Passing Player'] = df_Event['Player'].where(df_Event['Event'] == 'Pass').dropna()
Passes_df['Receiving Player'] = df_Event['Player'].shift(-1).where\
((df_Event['Event'] == 'Pass') & (df_Event['Event'].shift(-1) == 'Received Pass'))
</code>```

However, this seems way too long winded? Could I use a function that picks information from each source more fluently? Some help would be appreciated!

答:
If you want information about "how the ball moved" including dribbling you could do the following:

0: I simplified the input a bit:

```<code>d_e = {'seconds':[1,2,3,4,5], 'event' : ['passed', 'received', 'touch', 'passed', 'received'], 'player' : ['Steve', 'Michael','Michael','Michael','George']}
d_x = {'seconds':[1,2,3,4,5], 'Steve': [11.43, 11.45, 10.99, 11.34, 12.43], 'Michael':[12.33, 12.46, 10.33, 10.36, 12.22], 'George': [15.33, 13.22, 14.33, 11.22, 11.78]}
d_y = {'seconds':[1,2,3,4,5], 'Steve': [13.43, 13.45, 12.99, 12.34, 12.00], 'Michael':[9.33, 9.46, 10.53, 12.36, 12.72], 'George': [10.33, 10.22, 10.33, 11.72, 12.78]}
df_e = pd.DataFrame(d_e)
df_x = pd.DataFrame(d_x)
df_y = pd.DataFrame(d_y)
</code>```

1: Merge X and Y to tuples for coordinates:

Of course you don't have to use tuples and can stick with a solution like given by @ckedar, adjust keys later on accordingly.

```<code>df_merged = df_x.merge(df_y, on=['seconds']).set_index('seconds')
df_merged=df_merged.groupby(df_merged.columns.str.split('_').str[0],axis=1).agg(lambda x : tuple(x.tolist()))
</code>```

Result:

```<code>                 George         Michael           Steve
seconds
1        (15.33, 10.33)   (12.33, 9.33)  (11.43, 13.43)
2        (13.22, 10.22)   (12.46, 9.46)  (11.45, 13.45)
3        (14.33, 10.33)  (10.33, 10.53)  (10.99, 12.99)
4        (11.22, 11.72)  (10.36, 12.36)  (11.34, 12.34)
5        (11.78, 12.78)  (12.22, 12.72)   (12.43, 12.0)
</code>```

2: Put coordinates in Event dataframe:

```<code>df_e['coord'] = df_e.apply(lambda x : df_merged.loc[x['seconds']][x['player']]  ,axis=1)
</code>```

Result:

```<code>   seconds     event   player           coord
0        1    passed    Steve  (11.43, 13.43)
1        2  received  Michael   (12.46, 9.46)
2        3     touch  Michael  (10.33, 10.53)
3        4    passed  Michael  (10.36, 12.36)
4        5  received   George  (11.78, 12.78)
</code>```

3: Create new df with "from" and "to" information:

Here you would have to adjust to different keys, if you are not using tuples as coords, but rather X and Y.

```<code>df_new = pd.DataFrame(columns=['second', 'from', 'to', 'from_coord', 'to_coord'])
df_new[['second', 'from', 'from_coord']] = df_e[['seconds', 'player', 'coord']].iloc[:-1]
df_new[['to', 'to_coord']] = df_e[['player', 'coord']].iloc[1:].reset_index().drop('index',axis=1)
df_new = df_new.set_index('second')
</code>```

Result:

```<code>           from       to      from_coord        to_coord
second
1         Steve  Michael  (11.43, 13.43)   (12.46, 9.46)
2       Michael  Michael   (12.46, 9.46)  (10.33, 10.53)
3       Michael  Michael  (10.33, 10.53)  (10.36, 12.36)
4       Michael   George  (10.36, 12.36)  (11.78, 12.78)
</code>```

4 (optional): Now you can get passes and dribbling:

```<code>print('Passes:')
print(df_new[df_new['from'] != df_new['to']])
print('Dribbling:')
print(df_new[df_new['from'] == df_new['to']])
</code>```

Result:

```<code>Passes:
           from       to      from_coord        to_coord
second
1         Steve  Michael  (11.43, 13.43)   (12.46, 9.46)
4       Michael   George  (10.36, 12.36)  (11.78, 12.78)

Dribbling:
           from       to      from_coord        to_coord
second
2       Michael  Michael   (12.46, 9.46)  (10.33, 10.53)
3       Michael  Michael  (10.33, 10.53)  (10.36, 12.36)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
So I have three Dataframes, X, Y and Events. df_X has X Co-ordinates, df_Y has Y Co-ordinates and Events_df has a list of events that has happened (The Data is Basketball related). You'll see how they link together by looking below:

df_Event:

Seconds Passed   Event Type         Player
1.0              Passed The Ball    Steve
2.0              Received Pass      Michael
3.0              Touch              Michael
4.0              Passed The Ball    Michael
5.0              Received The Ball  George

df_X:

Seconds Passed  Steve   Michael   George
1.0             11.43   12.33     15.33
2.0             11.45   12.46     13.22
3.0             10.99   10.33     14.33
4.0             11.34   10.36     11.22
5.0             12.43   12.22     11.78

df_Y:

....

(The Same As Above Just With Different Numbers)

I want to record patterns of events across time and then take the X, Y coordinates that correspond to the Seconds Passed columns across each Dataframes. So for example, if I wanted to know where a pass started and ended I would need the following information..

I want the following information in a new Dataframe labelled "Passes_df":

Passing Player   Receiving Player    X Coordinate PP   Y Coordinate PP  X Coordinate RP   Y Coordinate RP
Steve            Michael             11.43             ....             12.46             .....

I know I could use the following:

Passes_df['Passing Player'] = df_Event['Player'].where(df_Event['Event'] == 'Pass').dropna()
Passes_df['Receiving Player'] = df_Event['Player'].shift(-1).where\
((df_Event['Event'] == 'Pass') & (df_Event['Event'].shift(-1) == 'Received Pass'))

However, this seems way too long winded? Could I use a function that picks information from each source more fluently? Some help would be appreciated!

Body:
If you want information about "how the ball moved" including dribbling you could do the following:

0: I simplified the input a bit:

d_e = {'seconds':[1,2,3,4,5], 'event' : ['passed', 'received', 'touch', 'passed', 'received'], 'player' : ['Steve', 'Michael','Michael','Michael','George']}
d_x = {'seconds':[1,2,3,4,5], 'Steve': [11.43, 11.45, 10.99, 11.34, 12.43], 'Michael':[12.33, 12.46, 10.33, 10.36, 12.22], 'George': [15.33, 13.22, 14.33, 11.22, 11.78]}
d_y = {'seconds':[1,2,3,4,5], 'Steve': [13.43, 13.45, 12.99, 12.34, 12.00], 'Michael':[9.33, 9.46, 10.53, 12.36, 12.72], 'George': [10.33, 10.22, 10.33, 11.72, 12.78]}
df_e = pd.DataFrame(d_e)
df_x = pd.DataFrame(d_x)
df_y = pd.DataFrame(d_y)

1: Merge X and Y to tuples for coordinates:

Of course you don't have to use tuples and can stick with a solution like given by @ckedar, adjust keys later on accordingly.

df_merged = df_x.merge(df_y, on=['seconds']).set_index('seconds')
df_merged=df_merged.groupby(df_merged.columns.str.split('_').str[0],axis=1).agg(lambda x : tuple(x.tolist()))

Result:

                 George         Michael           Steve
seconds
1        (15.33, 10.33)   (12.33, 9.33)  (11.43, 13.43)
2        (13.22, 10.22)   (12.46, 9.46)  (11.45, 13.45)
3        (14.33, 10.33)  (10.33, 10.53)  (10.99, 12.99)
4        (11.22, 11.72)  (10.36, 12.36)  (11.34, 12.34)
5        (11.78, 12.78)  (12.22, 12.72)   (12.43, 12.0)

2: Put coordinates in Event dataframe:

df_e['coord'] = df_e.apply(lambda x : df_merged.loc[x['seconds']][x['player']]  ,axis=1)

Result:

   seconds     event   player           coord
0        1    passed    Steve  (11.43, 13.43)
1        2  received  Michael   (12.46, 9.46)
2        3     touch  Michael  (10.33, 10.53)
3        4    passed  Michael  (10.36, 12.36)
4        5  received   George  (11.78, 12.78)

3: Create new df with "from" and "to" information:

Here you would have to adjust to different keys, if you are not using tuples as coords, but rather X and Y.

df_new = pd.DataFrame(columns=['second', 'from', 'to', 'from_coord', 'to_coord'])
df_new[['second', 'from', 'from_coord']] = df_e[['seconds', 'player', 'coord']].iloc[:-1]
df_new[['to', 'to_coord']] = df_e[['player', 'coord']].iloc[1:].reset_index().drop('index',axis=1)
df_new = df_new.set_index('second')

Result:

           from       to      from_coord        to_coord
second
1         Steve  Michael  (11.43, 13.43)   (12.46, 9.46)
2       Michael  Michael   (12.46, 9.46)  (10.33, 10.53)
3       Michael  Michael  (10.33, 10.53)  (10.36, 12.36)
4       Michael   George  (10.36, 12.36)  (11.78, 12.78)

4 (optional): Now you can get passes and dribbling:

print('Passes:')
print(df_new[df_new['from'] != df_new['to']])
print('Dribbling:')
print(df_new[df_new['from'] == df_new['to']])

Result:

Passes:
           from       to      from_coord        to_coord
second
1         Steve  Michael  (11.43, 13.43)   (12.46, 9.46)
4       Michael   George  (10.36, 12.36)  (11.78, 12.78)

Dribbling:
           from       to      from_coord        to_coord
second
2       Michael  Michael   (12.46, 9.46)  (10.33, 10.53)
3       Michael  Michael  (10.33, 10.53)  (10.36, 12.36)


问:
In C++ is it possible to return an element of the class from a class member function?
In C++ is it possible to return an element of the class from a class member function?</p>

```<code>namespace translation2d
{
    class translation2d
    {
        public:
           double x;
          double y;

        public:
            translation2d()
            {
                x=0;
                y=0;
            }

        public:
            translation2d translateBy(translation2d other);
            //being interpreted as a constructor?
    }

    translation2d translation2d::translateBy(translation2d other)
    {//I need this member function to return an object of type translation2d
        x+=other.x;
        y+=other.y;
    }
};
</code>```

答:
6502's answer is correct, and the code is neat.

I just wanted to give a fix that minimises changes to your original code, for clarity:

```<code>translation2d translation2d::translateBy(translation2d other)
{
    translation2d copy = *this;

    copy.x += other.x;
    copy.y += other.y;

    return copy;
}
</code>```

The idea is to:

Create a copy of the "current" object so you don't impact the original (you don't want that)

Return that copy once you've adjusted it with data from other

Written another way, we can avoid copying the argument again since you already passed it by value:

```<code>translation2d translation2d::translateBy(translation2d copy)
{
    copy.x += this->x;
    copy.y += this->y;

    return copy;
}
</code>```

… though I'd expect the compiler to do this for you in reality, and I find this version of the code harder to read. See the last section of this answer for other ways to avoid the extra copy (assuming that you are inclined to worry about it).

An alternative version of this function would actually translate the current object rather than returning a new one:

```<code>translation2d& translation2d::translateBy(translation2d other)
{
    this->x += other.x;
    this->y += other.y;

    return *this;
}
</code>```

Notice that I still return something, rather than void; in this case I've followed the convention of returning a reference to the current object, which aids in chaining multiple modifications to the same object. You'll find this pattern a lot in operator overloading.

Technically the this-> is unnecessary, but it makes the function a bit easier to understand.

Note that 6502 changed the function to take other by const-reference, which is often a good idea and you should consider doing that too (though copying two doubles is so cheap that it may not be worth the indirection).

Body:
In C++ is it possible to return an element of the class from a class member function?

namespace translation2d
{
    class translation2d
    {
        public:
           double x;
          double y;

        public:
            translation2d()
            {
                x=0;
                y=0;
            }

        public:
            translation2d translateBy(translation2d other);
            //being interpreted as a constructor?
    }

    translation2d translation2d::translateBy(translation2d other)
    {//I need this member function to return an object of type translation2d
        x+=other.x;
        y+=other.y;
    }
};

Body:
6502's answer is correct, and the code is neat.

I just wanted to give a fix that minimises changes to your original code, for clarity:

translation2d translation2d::translateBy(translation2d other)
{
    translation2d copy = *this;

    copy.x += other.x;
    copy.y += other.y;

    return copy;
}

The idea is to:

Create a copy of the "current" object so you don't impact the original (you don't want that)

Return that copy once you've adjusted it with data from other

Written another way, we can avoid copying the argument again since you already passed it by value:

translation2d translation2d::translateBy(translation2d copy)
{
    copy.x += this->x;
    copy.y += this->y;

    return copy;
}

… though I'd expect the compiler to do this for you in reality, and I find this version of the code harder to read. See the last section of this answer for other ways to avoid the extra copy (assuming that you are inclined to worry about it).

An alternative version of this function would actually translate the current object rather than returning a new one:

translation2d& translation2d::translateBy(translation2d other)
{
    this->x += other.x;
    this->y += other.y;

    return *this;
}

Notice that I still return something, rather than void; in this case I've followed the convention of returning a reference to the current object, which aids in chaining multiple modifications to the same object. You'll find this pattern a lot in operator overloading.

Technically the this-> is unnecessary, but it makes the function a bit easier to understand.

Note that 6502 changed the function to take other by const-reference, which is often a good idea and you should consider doing that too (though copying two doubles is so cheap that it may not be worth the indirection).


问:
Add an image dynamically to this beautiful frame
Here is a beautifully animated border in pure CSS.

What if we want this animated borders as a frame and add an image as the content inside it.

When I add the image it just overlays the frame, But I want to put the image inside the frame, not over it.

I have tried my best but I can't find a solution without a hand.

Here is what I've tried (I need to add the image dynamically using javascript):

//addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

let image = document.createElement('img');
image.setAttribute("id", "shot");
var node = document.getElementsByClassName('content');
node[0].appendChild(image);
image.src = `${pictureSource}`;
let shot = document.getElementById("shot");

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box .content {
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}</code>```

```

答:
Add it as background of content:

addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

var node = document.getElementsByClassName('content');
node[0].style.background='url("'+pictureSource+'") center/cover'

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box .content {
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}</code>```

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

<p>If you want you can simplify the code of the animation like below:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>addimage(); // uncomment this to add the image to the frame
function addimage() {

  let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

  var node = document.getElementsByClassName('content');
  node[0].style.background = 'url("' + pictureSource + '") center/cover'

}</code>```

body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: black;
}

.box {
 border-radius: 10px;
  background:
    repeating-linear-gradient(-45deg, white 0 7.5px, hotpink 0 15px)
    0 0/21.21px 21.21px;  /* 21.21px = sqrt(2) * 15px */
  animation: animate 1s linear infinite;
}

.box .content {
  width: 300px;
  height: 300px;
  border-radius: 10px;
  box-shadow: 0 0 2px deeppink, 0 0 5px rgba(0, 0, 0, 1), inset 0 0 5px rgba(0, 0, 0, 1);
  margin:15px;
}

@keyframes animate {
  to {
    background-position: 21.21px 21.21px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <div class="content">

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

Body:
Here is a beautifully animated border in pure CSS.

What if we want this animated borders as a frame and add an image as the content inside it.

When I add the image it just overlays the frame, But I want to put the image inside the frame, not over it.

I have tried my best but I can't find a solution without a hand.

Here is what I've tried (I need to add the image dynamically using javascript):

//addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

let image = document.createElement('img');
image.setAttribute("id", "shot");
var node = document.getElementsByClassName('content');
node[0].appendChild(image);
image.src = `${pictureSource}`;
let shot = document.getElementById("shot");

}

html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box .content {
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}

Body:
Add it as background of content:

addimage(); // uncomment this to add the image to the frame
function addimage(){

let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

var node = document.getElementsByClassName('content');
node[0].style.background='url("'+pictureSource+'") center/cover'

}

html,
body,
.box .content {
 height: 100%;
 display: flex;
 align-items: center;
 justify-content: center;
 background-color: black;
}

.box {
 width: 300px;
 height: 300px;
 box-sizing: border-box;
 padding: 15px;
 position: relative;
 overflow: hidden;
}

.box::before {
 content: '';
 position: absolute;
 width: 150%;
 height: 150%;
 background: repeating-linear-gradient(
   white 0%,
   white 7.5px,
   hotpink 7.5px,
   hotpink 15px,
   white 15px,
   white 22.5px,
   hotpink 22.5px,
   hotpink 30px);
 transform: translateX(-20%) translateY(-20%) rotate(-45deg);
 animation: animate 20s linear infinite;
}

.box .content {
 position: relative;
 background-color: white;
 flex-direction: column;
 box-sizing: border-box;
 padding: 30px;
 text-align: center;
 font-family: sans-serif;
 z-index: 2;
}

.box,
.box .content {
 box-shadow: 0 0 2px deeppink,
    0 0 5px rgba(0, 0, 0, 1),
    inset 0 0 5px rgba(0, 0, 0, 1);
 border-radius: 10px;
}

.box .content h2 {
 color: deeppink;
}

.box .content p {
 color: dimgray;
}

@keyframes animate {
 from {
  background-position: 0;
 }

 to {
  background-position: 0 450px;
 }
}

<div class="box">
  <div class="content">

  </div>
</div>

If you want you can simplify the code of the animation like below:

addimage(); // uncomment this to add the image to the frame
function addimage() {

  let pictureSource = 'https://www.architectureartdesigns.com/wp-content/uploads/2013/03/ArchitectureArtdesigns-8.jpg';

  var node = document.getElementsByClassName('content');
  node[0].style.background = 'url("' + pictureSource + '") center/cover'

}

body {
  height: 100vh;
  margin:0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: black;
}

.box {
 border-radius: 10px;
  background:
    repeating-linear-gradient(-45deg, white 0 7.5px, hotpink 0 15px)
    0 0/21.21px 21.21px;  /* 21.21px = sqrt(2) * 15px */
  animation: animate 1s linear infinite;
}

.box .content {
  width: 300px;
  height: 300px;
  border-radius: 10px;
  box-shadow: 0 0 2px deeppink, 0 0 5px rgba(0, 0, 0, 1), inset 0 0 5px rgba(0, 0, 0, 1);
  margin:15px;
}

@keyframes animate {
  to {
    background-position: 21.21px 21.21px;
  }
}

<div class="box">
  <div class="content">

  </div>
</div>


问:
Python Loop for temperature
I am learning python for the first time and my assignment required me to:

Write a loop to print all elements in hourly_temperature. Separate
elements with a -> surrounded by spaces. Sample output for the given
program:

```<code>90 -> 92 -> 94 -> 95
</code>```

Note: 95 is followed by a space, then a newline.

After playing I had difficulty and found the coded answer as:

```<code>hourly_temperature = [90, 92, 94, 95]

Htemp = len(hourly_temperature)

#create list
temps = []

if Htemp >= 0:
    for i in hourly_temperature: #question on i and appends i
        temps.append(i)
        temps.append('->')
        Htemp -= 1
        continue
temps.pop()
for s in temps:    #question here
    print(s,'', end='')
    continue
print('')
</code>```

My question is regarding the for loops that I have notated with the #question.

I am wondering what the purpose is for the i and s to make the code work.

答:
i takes each value of hourly_temperature, as s takes the value of each element in temps.

This is a very complicated way to join values with a separator. Better to use str.join:

```<code>hourly_temperature = [90, 92, 94, 95]
print(' -> '.join(map(str, hourly_temperature)))
</code>```

Title: Python Loop for temperature

Body:
I am learning python for the first time and my assignment required me to:

Write a loop to print all elements in hourly_temperature. Separate
elements with a -> surrounded by spaces. Sample output for the given
program:

90 -> 92 -> 94 -> 95

Note: 95 is followed by a space, then a newline.

After playing I had difficulty and found the coded answer as:

hourly_temperature = [90, 92, 94, 95]

Htemp = len(hourly_temperature)

#create list
temps = []

if Htemp >= 0:
    for i in hourly_temperature: #question on i and appends i
        temps.append(i)
        temps.append('->')
        Htemp -= 1
        continue
temps.pop()
for s in temps:    #question here
    print(s,'', end='')
    continue
print('')

My question is regarding the for loops that I have notated with the #question.

I am wondering what the purpose is for the i and s to make the code work.

Body:
i takes each value of hourly_temperature, as s takes the value of each element in temps.

This is a very complicated way to join values with a separator. Better to use str.join:

hourly_temperature = [90, 92, 94, 95]
print(' -> '.join(map(str, hourly_temperature)))


问:
Changing state in onAppear breaks PageViewController
I'm struggling to understand why a PageViewController does not work as expected when there is a change to a @Published EnvironmentObject variable during .onAppear in its parent View.

If I comment out the .onAppear modifier in DetailView, then everything works fine - the slides swipe as expected of a PageViewController. But as soon as that modifier is back in, then the pages do not swipe correctly.

It's got to be something to do with the re-render due to state change, but I can't figure it out. I know that updateUIViewController is called on the state change, and this seems to change the array of viewControllers.

If anyone has a steer on how to solve this, I'll be really grateful to hear about it!

If you are running the code below, make sure to change your SceneDelegate:

```<code>let contentView = ContentView()
</code>```

to

```<code>let contentView = ContentView().environmentObject(Global())
</code>```

So here's a simple example of the issue:

import SwiftUI
import Foundation
import UIKit

struct Item: Hashable {
  var text: String
}

let testItems: [Item] = [
  Item(text: "I am item 1"),
  Item(text: "I am item 2"),
  Item(text: "I am item 3")
]

final class Global : ObservableObject {
  @Published var hideText: Bool = false
}

struct ContentView: View {

  @EnvironmentObject var global: Global

  var body: some View {

    NavigationView {
      VStack {
        List(testItems, id: \.self) { item in
          NavigationLink(destination: DetailView(item: item)) {
            Text(item.text)
          }
        }

        Text("I should vanish when detail view loads")
          .opacity(self.global.hideText ? 0 : 1)
      }
      .navigationBarTitle("Test")
    }
  }
}

struct DetailView: View {

  @EnvironmentObject var global: Global

  var item: Item
  var testViews: [Text] = [
    Text("Slide 1").font(.title),
    Text("Slide 2").font(.title),
    Text("Slide 3").font(.title),
  ]

  var body: some View {

    // The .onAppear modifier breaks the PageViewController
    // when it is commented out, the slides work as expected

    PageView(testViews)
      .onAppear {
        self.global.hideText = true
      }
  }
}

struct PageView<Page: View>: View {

  @State var currentPage = 0

  var viewControllers: [UIHostingController<Page>]

  init(_ views: [Page]) {
    self.viewControllers = views.map{ UIHostingController(rootView: $0) }
  }

  var body: some View {
    VStack(alignment: .center) {
      PageViewController(
        viewControllers: viewControllers,
        currentPageIndex: $currentPage
      )
    }
  }
}

struct PageViewController: UIViewControllerRepresentable {

  var viewControllers: [UIViewController]

  @Binding var currentPageIndex: Int

  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

  func makeUIViewController(context: Context) -> UIPageViewController {
    let pageViewController = UIPageViewController(
      transitionStyle: .scroll,
      navigationOrientation: .horizontal
    )

    pageViewController.view.backgroundColor = UIColor.clear
    pageViewController.dataSource = context.coordinator
    pageViewController.delegate = context.coordinator

    return pageViewController
  }

  func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
    pageViewController.setViewControllers([viewControllers[currentPageIndex]], direction: .forward, animated: true)
  }

  class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

    var parent: PageViewController

    init(_ pageViewController: PageViewController) {
      self.parent = pageViewController
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        // retrieves the index of the currently displayed view controller
        guard let index = parent.viewControllers.firstIndex(of: viewController) else {
          return nil
        }

        // shows the last view controller when the user swipes back from the first view controller
        if index == 0 {
          return parent.viewControllers.last
        }

        //show the view controller before the currently displayed view controller
        return parent.viewControllers[index - 1]
      }

      func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
          // retrieves the index of the currently displayed view controller
          guard let index = parent.viewControllers.firstIndex(of: viewController) else {
            print("View controller not found!!")
            return nil
          }
          // shows the first view controller when the user swipes further from the last view controller
          if index + 1 == parent.viewControllers.count {
            return parent.viewControllers.first
          }

          // show the view controller after the currently displayed view controller
          return parent.viewControllers[index + 1]
      }

      func pageViewController(_ pageViewController: UIPageViewController,
        didFinishAnimating finished: Bool,
        previousViewControllers: [UIViewController],
        transitionCompleted completed: Bool
      ) {
        if completed,
          let visibleViewController = pageViewController.viewControllers?.first,
          let index = parent.viewControllers.firstIndex(of: visibleViewController) {
            parent.currentPageIndex = index
          }
      }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
      .environmentObject(Global())
  }
}
```

答:
When you change EnvironmentObject variable during .onAppear in its parent view, it renders the view again and I guess values update with new objects.
If you set a breakpoint in your func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? method and get po in your console, you can see the memory address for the views are different and because of that it couldn't found the next view controller

```<code>parent:
(lldb) po parent
▿ PageViewController
  ▿ viewControllers : 3 elements
    ▿ 0 : <_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881e04b10>
    ▿ 1 : <_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881f13f70>
    ▿ 2 : <_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881f14dd0>

(lldb) po viewController
<_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881f186c0>
</code>```

as you can see, the view controller could not found in parent view controllers

For a solution, if you change your PageView to this, it solves the problem but It could be other solution too.

struct PageView: View {

  @State var currentPage = 0
  @State var viewControllers: [UIViewController]

  var body: some View {
    VStack(alignment: .center) {
      PageViewController(
        viewControllers: viewControllers,
        currentPageIndex: $currentPage
      )
    }
  }
}
```

change your viewControllers to be @State and pass it form parent view

Body:
I'm struggling to understand why a PageViewController does not work as expected when there is a change to a @Published EnvironmentObject variable during .onAppear in its parent View.

If I comment out the .onAppear modifier in DetailView, then everything works fine - the slides swipe as expected of a PageViewController. But as soon as that modifier is back in, then the pages do not swipe correctly.

It's got to be something to do with the re-render due to state change, but I can't figure it out. I know that updateUIViewController is called on the state change, and this seems to change the array of viewControllers.

If anyone has a steer on how to solve this, I'll be really grateful to hear about it!

If you are running the code below, make sure to change your SceneDelegate:

let contentView = ContentView()

to

let contentView = ContentView().environmentObject(Global())

So here's a simple example of the issue:

import SwiftUI
import Foundation
import UIKit

struct Item: Hashable {
  var text: String
}

let testItems: [Item] = [
  Item(text: "I am item 1"),
  Item(text: "I am item 2"),
  Item(text: "I am item 3")
]

final class Global : ObservableObject {
  @Published var hideText: Bool = false
}

struct ContentView: View {

  @EnvironmentObject var global: Global

  var body: some View {

    NavigationView {
      VStack {
        List(testItems, id: \.self) { item in
          NavigationLink(destination: DetailView(item: item)) {
            Text(item.text)
          }
        }

        Text("I should vanish when detail view loads")
          .opacity(self.global.hideText ? 0 : 1)
      }
      .navigationBarTitle("Test")
    }
  }
}

struct DetailView: View {

  @EnvironmentObject var global: Global

  var item: Item
  var testViews: [Text] = [
    Text("Slide 1").font(.title),
    Text("Slide 2").font(.title),
    Text("Slide 3").font(.title),
  ]

  var body: some View {

    // The .onAppear modifier breaks the PageViewController
    // when it is commented out, the slides work as expected

    PageView(testViews)
      .onAppear {
        self.global.hideText = true
      }
  }
}

struct PageView<Page: View>: View {

  @State var currentPage = 0

  var viewControllers: [UIHostingController<Page>]

  init(_ views: [Page]) {
    self.viewControllers = views.map{ UIHostingController(rootView: $0) }
  }

  var body: some View {
    VStack(alignment: .center) {
      PageViewController(
        viewControllers: viewControllers,
        currentPageIndex: $currentPage
      )
    }
  }
}

struct PageViewController: UIViewControllerRepresentable {

  var viewControllers: [UIViewController]

  @Binding var currentPageIndex: Int

  func makeCoordinator() -> Coordinator {
    Coordinator(self)
  }

  func makeUIViewController(context: Context) -> UIPageViewController {
    let pageViewController = UIPageViewController(
      transitionStyle: .scroll,
      navigationOrientation: .horizontal
    )

    pageViewController.view.backgroundColor = UIColor.clear
    pageViewController.dataSource = context.coordinator
    pageViewController.delegate = context.coordinator

    return pageViewController
  }

  func updateUIViewController(_ pageViewController: UIPageViewController, context: Context) {
    pageViewController.setViewControllers([viewControllers[currentPageIndex]], direction: .forward, animated: true)
  }

  class Coordinator: NSObject, UIPageViewControllerDataSource, UIPageViewControllerDelegate {

    var parent: PageViewController

    init(_ pageViewController: PageViewController) {
      self.parent = pageViewController
    }

    func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
        // retrieves the index of the currently displayed view controller
        guard let index = parent.viewControllers.firstIndex(of: viewController) else {
          return nil
        }

        // shows the last view controller when the user swipes back from the first view controller
        if index == 0 {
          return parent.viewControllers.last
        }

        //show the view controller before the currently displayed view controller
        return parent.viewControllers[index - 1]
      }

      func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
          // retrieves the index of the currently displayed view controller
          guard let index = parent.viewControllers.firstIndex(of: viewController) else {
            print("View controller not found!!")
            return nil
          }
          // shows the first view controller when the user swipes further from the last view controller
          if index + 1 == parent.viewControllers.count {
            return parent.viewControllers.first
          }

          // show the view controller after the currently displayed view controller
          return parent.viewControllers[index + 1]
      }

      func pageViewController(_ pageViewController: UIPageViewController,
        didFinishAnimating finished: Bool,
        previousViewControllers: [UIViewController],
        transitionCompleted completed: Bool
      ) {
        if completed,
          let visibleViewController = pageViewController.viewControllers?.first,
          let index = parent.viewControllers.firstIndex(of: visibleViewController) {
            parent.currentPageIndex = index
          }
      }
  }
}

struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    ContentView()
      .environmentObject(Global())
  }
}

Body:
When you change EnvironmentObject variable during .onAppear in its parent view, it renders the view again and I guess values update with new objects.
If you set a breakpoint in your func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? method and get po in your console, you can see the memory address for the views are different and because of that it couldn't found the next view controller

parent:
(lldb) po parent
▿ PageViewController
  ▿ viewControllers : 3 elements
    ▿ 0 : <_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881e04b10>
    ▿ 1 : <_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881f13f70>
    ▿ 2 : <_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881f14dd0>

(lldb) po viewController
<_TtGC7SwiftUI19UIHostingControllerVS_4Text_: 0x7fc881f186c0>

as you can see, the view controller could not found in parent view controllers

For a solution, if you change your PageView to this, it solves the problem but It could be other solution too.

struct PageView: View {

  @State var currentPage = 0
  @State var viewControllers: [UIViewController]

  var body: some View {
    VStack(alignment: .center) {
      PageViewController(
        viewControllers: viewControllers,
        currentPageIndex: $currentPage
      )
    }
  }
}

change your viewControllers to be @State and pass it form parent view


问:
Offset html scroll-behavior
I have the following layout:

html {
  scroll-behavior:smooth;
}

header {
  height: 234px;
  position: sticky;
  top: 0;
  padding: 24px;
  background-color: rgba(255,255,255,0.5);
  border-bottom: 1px solid #dedede;
}

nav {
  height: 88px;
  position: sticky;
  top: 234px;
  padding: 24px;
  background: #f5f5f5;
}

section {
  height: 100vh;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <p>I'm the header</p>
</header>

<section>
  <p>I'm a video</p>
</section>

<nav>
  Section 1
  Section 2
  Section 3
</nav>

<section id="1">
  <p>I'm section 1</p>
</section>

<section id="2">
  <p>I'm section 2</p>
</section>

<section id="3">
  <p>I'm section 3</p>
</section></code>```

As you can see, I have the main header at the top of the page with position: sticky;. I then have a  further down the page which sticks underneath the main header. You can then click the links to scroll to each
.

When clicking on each link in the , each
 scrolls to the very top the page.

Is there a way to offset the top position? In this case, I'd need to offset from the top by 322px ( and  heights combined).

I've tried adding a :before pseudo element to each
 with a height of 322px, but this doesn't work.

答:
How about adding:

```<code>section {
  padding-top: 370px;
}
</code>```

 +  are actually 370px. 234px + 88px + 2x24px of padding. 2, not 4 because padding is collapsed between them.

Title: Offset html scroll-behavior

Body:
I have the following layout:

html {
  scroll-behavior:smooth;
}

header {
  height: 234px;
  position: sticky;
  top: 0;
  padding: 24px;
  background-color: rgba(255,255,255,0.5);
  border-bottom: 1px solid #dedede;
}

nav {
  height: 88px;
  position: sticky;
  top: 234px;
  padding: 24px;
  background: #f5f5f5;
}

section {
  height: 100vh;
  text-align: center;
}

I'm the header

I'm a video

  Section 1
  Section 2
  Section 3

I'm section 1

I'm section 2

I'm section 3

As you can see, I have the main header at the top of the page with position: sticky;. I then have a  further down the page which sticks underneath the main header. You can then click the links to scroll to each
.

When clicking on each link in the , each
 scrolls to the very top the page.

Is there a way to offset the top position? In this case, I'd need to offset from the top by 322px ( and  heights combined).

I've tried adding a :before pseudo element to each
 with a height of 322px, but this doesn't work.

Body:
How about adding:

section {
  padding-top: 370px;
}

<header> + <nav> are actually 370px. 234px + 88px + 2x24px of padding. 2, not 4 because padding is collapsed between them.


问:
lxml searching for tags when namespaces are present
I'm a little confused about navigating an xml document that has namespaces with lxml.etree. I've seen a few threads  on this topic (1, 2) as well as the lxml docs but still haven't figured out the answer.

```<code>xml = """<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<sbml xmlns="http://www.sbml.org/sbml/level2" level="2" metaid="metaid_0000001" version="1">
    <model id="Teusink2000_Glycolysis" metaid="metaid_0000002" name="Teusink2000_Glycolysis">
        <annotation>
        </annotation>
    </model>
</sbml>"""
from lxml import etree
utf8_parser = etree.XMLParser(encoding='utf-8')
xml = etree.fromstring(xml.encode('utf-8'), parser=utf8_parser)
</code>```

Searching for the root element doesn't seem to work, but I guess thats because its the root element and therefore you don't really need to search for it

```<code>print(xml.nsmap)
print(xml.findall('sbml'))
print(xml.findall('sbml', namespaces=xml.nsmap))
print(xml.findall('sbml', namespaces={'': 'http://www.sbml.org/sbml/level2'}))
</code>```

produces

```<code>{None: 'http://www.sbml.org/sbml/level2'}
[]
[]
[]
</code>```

Searching for the model element however, does work provided you give it a namespace

```<code>print(xml.findall('model'))
print(xml.findall('model', namespaces=xml.nsmap))
print(xml.findall('model', namespaces={'': 'http://www.sbml.org/sbml/level2'}))
</code>```

produces

```<code>[]
[<Element {http://www.sbml.org/sbml/level2}model at 0x2125d7c0888>]
[<Element {http://www.sbml.org/sbml/level2}model at 0x2125d7c0448>]
</code>```

But, searching for the annotation element does not work as I expect.

```<code>print(xml.findall('annotation'))
print(xml.findall('annotation', namespaces=xml.nsmap))
print(xml.findall('annotation', namespaces={'': 'http://www.sbml.org/sbml/level2'}))
</code>```

produces

```<code>[]
[]
[]
</code>```

Could anybody point out what I'm missing here?

答:
Your syntax is wrong. You can only search for the current level using annotation. If you want to search the whole tree, you need to use print(xml.findall('.//annotation', namespaces=xml.nsmap)).

```<code>print(xml.findall('.//annotation', namespaces=xml.nsmap))
# [<Element {http://www.sbml.org/sbml/level2}annotation at 0x7fbcb9a14308>]
</code>```

Body:
I'm a little confused about navigating an xml document that has namespaces with lxml.etree. I've seen a few threads  on this topic (1, 2) as well as the lxml docs but still haven't figured out the answer.

xml = """<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<sbml xmlns="http://www.sbml.org/sbml/level2" level="2" metaid="metaid_0000001" version="1">
    <model id="Teusink2000_Glycolysis" metaid="metaid_0000002" name="Teusink2000_Glycolysis">
        <annotation>
        </annotation>
    </model>
</sbml>"""
from lxml import etree
utf8_parser = etree.XMLParser(encoding='utf-8')
xml = etree.fromstring(xml.encode('utf-8'), parser=utf8_parser)

Searching for the root element doesn't seem to work, but I guess thats because its the root element and therefore you don't really need to search for it

print(xml.nsmap)
print(xml.findall('sbml'))
print(xml.findall('sbml', namespaces=xml.nsmap))
print(xml.findall('sbml', namespaces={'': 'http://www.sbml.org/sbml/level2'}))

produces

{None: 'http://www.sbml.org/sbml/level2'}
[]
[]
[]

Searching for the model element however, does work provided you give it a namespace

print(xml.findall('model'))
print(xml.findall('model', namespaces=xml.nsmap))
print(xml.findall('model', namespaces={'': 'http://www.sbml.org/sbml/level2'}))

produces

[]
[<Element {http://www.sbml.org/sbml/level2}model at 0x2125d7c0888>]
[<Element {http://www.sbml.org/sbml/level2}model at 0x2125d7c0448>]

But, searching for the annotation element does not work as I expect.

print(xml.findall('annotation'))
print(xml.findall('annotation', namespaces=xml.nsmap))
print(xml.findall('annotation', namespaces={'': 'http://www.sbml.org/sbml/level2'}))

produces

[]
[]
[]

Could anybody point out what I'm missing here?

Body:
Your syntax is wrong. You can only search for the current level using annotation. If you want to search the whole tree, you need to use print(xml.findall('.//annotation', namespaces=xml.nsmap)).

print(xml.findall('.//annotation', namespaces=xml.nsmap))
# [<Element {http://www.sbml.org/sbml/level2}annotation at 0x7fbcb9a14308>]


答:
The i and the s are going to be variables that represent the next value in the list every time the loop iterates. You need them to actually access each item.

You should try to rewrite your answer to only use one loop and avoid creating the second list temps

You should also be able to do this without using Htemp, pop(), or continue.

Title: Python Loop for temperature


问:
Get name and value with PHP
I have this simple form:

HTML:

```<code><input type="checkbox" name="product[]" value="20$" /> book
<input type="checkbox" name="product[]" value="30$" /> plane
</code>```

PHP:

```
<code>
$product = $_POST['product'];
foreach($product as $value) {
    echo $value;
}
</code>
```

Note:

The user can choose one or two ... products.

Question:

I want to know if there is a solution to get the name too, like adding an ID class or something ..

Basically I cant get the name attribute because I didn't sent it with the form.

答:
Add the missing information to your POST-parameters:

```<code><input type="checkbox" name="product[book]" value="20$" /> book
<input type="checkbox" name="product[plane]" value="30$" /> plane
</code>```

You can iterate over it like this:

```<code>foreach ($_POST['product'] as $name => $value) {
    // ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get name and value with PHP

Body:
I have this simple form:

HTML:

<input type="checkbox" name="product[]" value="20$" /> book
<input type="checkbox" name="product[]" value="30$" /> plane

PHP:

$product = $_POST['product'];
foreach($product as $value) {
    echo $value;
}

Note:

The user can choose one or two ... products.

Question:

I want to know if there is a solution to get the name too, like adding an ID class or something ..

Basically I cant get the name attribute because I didn't sent it with the form.

Body:
Add the missing information to your POST-parameters:

<input type="checkbox" name="product[book]" value="20$" /> book
<input type="checkbox" name="product[plane]" value="30$" /> plane

You can iterate over it like this:

foreach ($_POST['product'] as $name => $value) {
    // ...
}


问:
How do I communicate between/connect two tomcat servers
I am working on a project where I have two servers (tomcat), Server A gives initial snapshot of information from DB(MySQL) to the frontend. Server B to serve updates to server A, both servers need to communicate. How do I connect them? Thank you very much for your help. </p>

答: There are many ways two Tomcat instances running on the same host could be set up to communicate with each other.  It's quite common to implement a REST service in the "server" Tomcat instance and have the "client" Tomcat instance send the REST request to the other instance.  It's common to use either the Jersey or CXF framework to implement a JAX-RS REST service, or you could use the Spring framework to implement a more general web request handler.</p>


问:
Node.js seems to not free memory after loop
```<code>const axios = require('axios');
const JSDOM = require('jsdom').JSDOM;

axios.get('https://facebook.com')
    .then(response => {
        let i=1;
        while (true) {
            console.log(i++);
            const dom = new JSDOM(response.data);
            dom.window.close();
        }
    });
</code>```

The above will run (on my machine) 440 times, then crash with the following:

```<code><--- Last few GCs --->

[13411:0x5dc70d0]    63566 ms: Mark-sweep 2042.3 (2051.1) -> 2041.3 (2051.1) MB, 2407.4 / 0.0 ms  (average mu = 0.123, current mu = 0.027) allocation failure scavenge might not succeed
[13411:0x5dc70d0]    67327 ms: Mark-sweep 2042.0 (2051.1) -> 2041.1 (2050.9) MB, 3745.2 / 0.0 ms  (average mu = 0.055, current mu = 0.004) allocation failure scavenge might not succeed

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x145cc79]
    1: StubFrame [pc: 0x145dab5]
Security context: 0x0d2e98240921 <JSObject>
    2: /* anonymous */ [0x374dcc798739] [/pathtomyproject/node_modules/parse5/lib/tokenizer/index.js:~644] [pc=0x323d7cd98d24](this=0x10b528b73279 <Tokenizer map = 0x242f38ec5c11>,95)
    3: getNextToken [0x374dcc799419] [/pathtomyproject/node_modules/parse5/lib/tokenizer/i...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20200215.163602.13411.0.001.json
Node.js report completed
 1: 0xa9d570 node::Abort() [node]
 2: 0xa9f832 node::OnFatalError(char const*, char const*) [node]
 3: 0xc0758e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xc07909 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xdb5e15  [node]
 6: 0xdb64a6 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xdc4d19 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [node]
 8: 0xdc5b55 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xdc862c v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
10: 0xd8f204 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]
11: 0x10dc52e v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x145cc79  [node]
Aborted (core dumped)
</code>```

So I guess even after reassigning dom on each iteration, the previous values are still being stored on the heap. Why is this and how do I prevent it?

答:
Garbage collection in V8 is done when your code is not running and is in between doing things.  Your while(true) loop runs forever and thus you never give V8 a change to do garbage collection.

For a lot of additional reasons, you never do a forever running loop in Javascript (unless you have an await inside the loop) because nodejs is a largely single-threaded event driven system and when you are busy cranking on a while(true) loop, NO events can ever get processed so lots of things can't get done in nodejs.

Why is this and how do I prevent it?

Garbage collectors are often designed to let your code run and not interfere with their execution and then, in a moment when your code isn't doing anything and has finished with its internal state for what it was doing, the garbage collector examines the state of objects in the heap to find objects that are no longer in use.

You prevent this by not going in a tight loop like this without ever providing any slack time that the GC can run.  As explained above, a tight loop like this prevents any other events in nodejs from running anyway so it's generally a bad reason for other reasons too.

Note, that your code not only creates 444 dom instances and all the objects associated with those instances, but it doesn't provide any ability to clean up all the temporary variables/strings that were used in the creation of that dom instance which could be substantial when parsing HTML so the total memory usage is significantly higher than just the 444 finished dom instances.  If, you insert any type of breathing room into the loop, then the GC will get a chance to clean things up that are no longer being used.

Body:
const axios = require('axios');
const JSDOM = require('jsdom').JSDOM;

axios.get('https://facebook.com')
    .then(response => {
        let i=1;
        while (true) {
            console.log(i++);
            const dom = new JSDOM(response.data);
            dom.window.close();
        }
    });

The above will run (on my machine) 440 times, then crash with the following:

<--- Last few GCs --->

[13411:0x5dc70d0]    63566 ms: Mark-sweep 2042.3 (2051.1) -> 2041.3 (2051.1) MB, 2407.4 / 0.0 ms  (average mu = 0.123, current mu = 0.027) allocation failure scavenge might not succeed
[13411:0x5dc70d0]    67327 ms: Mark-sweep 2042.0 (2051.1) -> 2041.1 (2050.9) MB, 3745.2 / 0.0 ms  (average mu = 0.055, current mu = 0.004) allocation failure scavenge might not succeed

<--- JS stacktrace --->

==== JS stack trace =========================================

    0: ExitFrame [pc: 0x145cc79]
    1: StubFrame [pc: 0x145dab5]
Security context: 0x0d2e98240921 <JSObject>
    2: /* anonymous */ [0x374dcc798739] [/pathtomyproject/node_modules/parse5/lib/tokenizer/index.js:~644] [pc=0x323d7cd98d24](this=0x10b528b73279 <Tokenizer map = 0x242f38ec5c11>,95)
    3: getNextToken [0x374dcc799419] [/pathtomyproject/node_modules/parse5/lib/tokenizer/i...

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Writing Node.js report to file: report.20200215.163602.13411.0.001.json
Node.js report completed
 1: 0xa9d570 node::Abort() [node]
 2: 0xa9f832 node::OnFatalError(char const*, char const*) [node]
 3: 0xc0758e v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, bool) [node]
 4: 0xc07909 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [node]
 5: 0xdb5e15  [node]
 6: 0xdb64a6 v8::internal::Heap::RecomputeLimits(v8::internal::GarbageCollector) [node]
 7: 0xdc4d19 v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [node]
 8: 0xdc5b55 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [node]
 9: 0xdc862c v8::internal::Heap::AllocateRawWithRetryOrFailSlowPath(int, v8::internal::AllocationType, v8::internal::AllocationOrigin, v8::internal::AllocationAlignment) [node]
10: 0xd8f204 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationType, v8::internal::AllocationOrigin) [node]
11: 0x10dc52e v8::internal::Runtime_AllocateInYoungGeneration(int, unsigned long*, v8::internal::Isolate*) [node]
12: 0x145cc79  [node]
Aborted (core dumped)

So I guess even after reassigning dom on each iteration, the previous values are still being stored on the heap. Why is this and how do I prevent it?


问:
How to know the version of pip itself
Which shell command gives me the actual version of pip I am using?

pip gives with pip show all version of modules that are installed but excludes itself.

答:
```<code>`pip -v` or `pip --v`
</code>```

However note, if you are using macos catelina which has the zsh (z shell) it might give you a whole bunch of things, so the best option is to try install the version or start as -- pip3

Title: How to know the version of pip itself

Body:
`pip -v` or `pip --v`

However note, if you are using macos catelina which has the zsh (z shell) it might give you a whole bunch of things, so the best option is to try install the version or start as -- pip3


问:
Delphi XML validation with XSD
I'm using Delphi 10.2 update 3.
I followed these instructions to validate a generated xml document.

What effect does the attribute noNamespaceSchemaLocation have on XML parsing?

Validate XML using Windows DOM and TXMLDocument: doesn't work on some computers

schema validation with msxml in delphi

But I have an error.
"The attribute 'noNamespaceSchemaLocation' on the element 'jegyzek_adatok' is not defined in the DTD/Schema."

Preparing the xml document:

```<code>const
  cSchemaLocation = 'noNamespaceSchemaLocation';

procedure PreparePostBookXMLDocument(ARootNode: IXMLNode);
var
  xDoc: IXMLDocument;
begin
  if ARootNode.OwnerDocument = nil then Exit;

  xDoc := ARootNode.OwnerDocument;
  xDoc.Version := '1.0';
  xDoc.Encoding := 'windows-1250';
  xDoc.Options := xDoc.Options + [doNodeAutoIndent];
  ARootNode.Attributes['xmlns:xsi'] := 'http://www.w3.org/2001/XMLSchema-instance';
  ARootNode.Attributes['xsi:' + cSchemaLocation] := 'https://www.posta.hu/static/internet/download/level_ver8_ugyfeleknek_8p4.xsd';
end;
</code>```

The validation:

```<code>function ValidatePostBookXMLDocument(ARootNode: IXMLNode): IResult;
var
  xDocument: IXMLDocument;
  xMsxmlDoc: IXMLDOMDocument3;
  xXSDDocument: IXMLDOMDocument3;
  xSchemaCache: IXMLDOMSchemaCollection;
  xSchemaLocation: string;
  xError: IXMLDOMParseError;
begin
  Result := ERRUnknown;
  try
    if ARootNode = nil then Exit;

    xDocument := ARootNode.OwnerDocument;
    if xDocument = nil then Exit;

    xMsxmlDoc := ((xDocument.DOMDocument as IXMLDOMNodeRef).GetXMLDOMNode as IXMLDOMDocument3);

    xSchemaLocation := ARootNode.AttributeNodes.FindNode(cSchemaLocation).Text;
    xXSDDocument := CoDOMDocument60.Create;
    xXSDDocument.async := False;
    xXSDDocument.validateOnParse := True;
    if not xXSDDocument.load(xSchemaLocation) then Exit(MakeErrorResult(ohFileError, 'A validációhoz szükséges séma fájlt nem sikerült betölteni!'));

    xSchemaCache := CoXMLSchemaCache60.Create;
    xSchemaCache.add('', xXSDDocument);
    xMsxmlDoc.schemas := xSchemaCache;
    xError := xMsxmlDoc.validate;
    case xError.errorCode of
      S_OK: Result := Success;
      else Exit(MakeErrorResult(ohError, xError.reason));
    end;
  except
    on E:Exception do Result := HandleException;
  end;
end;
</code>```

The generated xml file, is valid via https://www.freeformatter.com/xml-validator-xsd.html#.

The XSD (https://www.posta.hu/static/internet/download/level_ver8_ugyfeleknek_8p4.xsd):

My generated xml (on my google drive):

Can somebody help me?

答:
I don't know the specific XML parser you're using in Delphi. However, to answer the general questions:

the attribute xsi:noNamespaceSchemaLocation declares where to find an XSD schema for the document (specifically, a schema for elements in no namespace)

it has no effect unless you invoke XSD schema validation. Some parsers may interpret the presence of this attribute as a signal to invoke schema validation, but that's fairly unusual.

when validating against an XSD schema, this attribute is always valid provided that its value is a valid URI. The schema doesn't need to explicitly permit this attribute.

when validating against a DTD, this attribute is INVALID unless the DTD is written to explicitly allow it.

I suspect that you are running the parser with DTD validation enabled and that the DTD does not permit this attribute to be present. But that's a bit of a guess.

Title: Delphi XML validation with XSD

Body:
I'm using Delphi 10.2 update 3.
I followed these instructions to validate a generated xml document.

What effect does the attribute noNamespaceSchemaLocation have on XML parsing?

Validate XML using Windows DOM and TXMLDocument: doesn't work on some computers

schema validation with msxml in delphi

But I have an error.
"The attribute 'noNamespaceSchemaLocation' on the element 'jegyzek_adatok' is not defined in the DTD/Schema."

Preparing the xml document:

const
  cSchemaLocation = 'noNamespaceSchemaLocation';

procedure PreparePostBookXMLDocument(ARootNode: IXMLNode);
var
  xDoc: IXMLDocument;
begin
  if ARootNode.OwnerDocument = nil then Exit;

  xDoc := ARootNode.OwnerDocument;
  xDoc.Version := '1.0';
  xDoc.Encoding := 'windows-1250';
  xDoc.Options := xDoc.Options + [doNodeAutoIndent];
  ARootNode.Attributes['xmlns:xsi'] := 'http://www.w3.org/2001/XMLSchema-instance';
  ARootNode.Attributes['xsi:' + cSchemaLocation] := 'https://www.posta.hu/static/internet/download/level_ver8_ugyfeleknek_8p4.xsd';
end;

The validation:

function ValidatePostBookXMLDocument(ARootNode: IXMLNode): IResult;
var
  xDocument: IXMLDocument;
  xMsxmlDoc: IXMLDOMDocument3;
  xXSDDocument: IXMLDOMDocument3;
  xSchemaCache: IXMLDOMSchemaCollection;
  xSchemaLocation: string;
  xError: IXMLDOMParseError;
begin
  Result := ERRUnknown;
  try
    if ARootNode = nil then Exit;

    xDocument := ARootNode.OwnerDocument;
    if xDocument = nil then Exit;

    xMsxmlDoc := ((xDocument.DOMDocument as IXMLDOMNodeRef).GetXMLDOMNode as IXMLDOMDocument3);

    xSchemaLocation := ARootNode.AttributeNodes.FindNode(cSchemaLocation).Text;
    xXSDDocument := CoDOMDocument60.Create;
    xXSDDocument.async := False;
    xXSDDocument.validateOnParse := True;
    if not xXSDDocument.load(xSchemaLocation) then Exit(MakeErrorResult(ohFileError, 'A validációhoz szükséges séma fájlt nem sikerült betölteni!'));

    xSchemaCache := CoXMLSchemaCache60.Create;
    xSchemaCache.add('', xXSDDocument);
    xMsxmlDoc.schemas := xSchemaCache;
    xError := xMsxmlDoc.validate;
    case xError.errorCode of
      S_OK: Result := Success;
      else Exit(MakeErrorResult(ohError, xError.reason));
    end;
  except
    on E:Exception do Result := HandleException;
  end;
end;

The generated xml file, is valid via https://www.freeformatter.com/xml-validator-xsd.html#.

The XSD (https://www.posta.hu/static/internet/download/level_ver8_ugyfeleknek_8p4.xsd):

My generated xml (on my google drive):

Can somebody help me?


问:
bash script to rename files based on a calculation
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

```<code>#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done
</code>```

答:
```<code>for oldpath in */*/*
do
    x=$(basename "$oldpath" .png)
    zoom_y=$(dirname "$oldpath")
    y=$(basename "$zoom_y")
    ozoom=$(dirname "$zoom_y")
    nzoom=$(echo "2^$zoom-$y-1" | bc)
    mv "$oldpath" $nzoom/$y/$x.png
done
</code>```

This avoids using sed.  I like basename and dirname.  However, you can also use bash (and Korn) shell notations such as:

```<code>y=${zoom_y#*/}
ozoom=${zoom_y%/*}
</code>```

You might be able to do it all without invoking basename or dirname at all.

Body:
I have a file system containing PNG images.  The layout of the filesystem is: ZOOM/X/Y.png where ZOOM, X, and Y are all integers.

I need to change the names of the PNG files.  Basically, I need to convert Y from its current value to 2^ZOOM-Y-1.  I've written a bash script to accomplish this task.  However, I suspect it can be optimized substantially.  (I also suspect that I may have been better off writing it in Perl, but that is another story.)

Here is the script.  Is this about as good as it gets?  Or can the performance be optimized?  Are there tools I can use that would profile the script for me and tell me where I'm spending all my execution time?

#!/bin/bash

tiles=`ls -d */*/*`

for oldPath in $tiles
do
   oldY=`basename -s .png $oldPath`
   zoomX=`dirname $oldPath`
   zoom=`echo $zoomX | sed 's#\([^\]\)/.*#\1#'`
   newY=`echo 2^$zoom-$oldY-1|bc`
   mv ${zoomX}/${oldY}.png ${zoomX}/${newY}.png
done

Body:
for oldpath in */*/*
do
    x=$(basename "$oldpath" .png)
    zoom_y=$(dirname "$oldpath")
    y=$(basename "$zoom_y")
    ozoom=$(dirname "$zoom_y")
    nzoom=$(echo "2^$zoom-$y-1" | bc)
    mv "$oldpath" $nzoom/$y/$x.png
done

This avoids using sed.  I like basename and dirname.  However, you can also use bash (and Korn) shell notations such as:

y=${zoom_y#*/}
ozoom=${zoom_y%/*}

You might be able to do it all without invoking basename or dirname at all.


问:
PHP method signature has no parameters method call has one parameter no warning
Hello I am trying to make a simple class that has a method with no parameters. With method call I am putting in one parameter to fail a test but the test passes. And if I run the code in browser everything runs with no warning. I am on a development environment so php should detect such violations.

This is the method signature

```<code>    public function getServiceDetail(): ServiceDetail
    {
        ...
    }
</code>```

This is the call

```<code>...

$this->repository->getServiceDetail(1);

...
</code>```

The result of the above is just fine I get the detail from the logic that is in the method no warnings or errors.

Edit: If I put wrong type into signature of the method I get the proper error since I have strict_types on.

答:
PHP doesn't care about that because all php functions are variadic by nature. This is why func_get_args exists. Anything you hand to a php function/method is assumed valid unless otherwise explicitly defined as invalid. In other words, you must define a prototype and the call must then explicitly defy that prototype for it be considered invalid.

For example:

```<code>function foo(Array $bar, String $baz) {
    var_dump(func_get_args());
}

foo([1], "quix", new stdclass); // is perfectly legal in php
</code>```

You get

```
array(3) {
  [0]=>
  array(1) {
    [0]=>
    int(1)
  }
  [1]=>
  string(4) "quix"
  [2]=>
  object(stdClass)#1 (0) {
  }
}
```

From the manual:

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.

Body:
Hello I am trying to make a simple class that has a method with no parameters. With method call I am putting in one parameter to fail a test but the test passes. And if I run the code in browser everything runs with no warning. I am on a development environment so php should detect such violations.

This is the method signature

    public function getServiceDetail(): ServiceDetail
    {
        ...
    }

This is the call

...

$this->repository->getServiceDetail(1);

...

The result of the above is just fine I get the detail from the logic that is in the method no warnings or errors.

Edit: If I put wrong type into signature of the method I get the proper error since I have strict_types on.

Body:
PHP doesn't care about that because all php functions are variadic by nature. This is why func_get_args exists. Anything you hand to a php function/method is assumed valid unless otherwise explicitly defined as invalid. In other words, you must define a prototype and the call must then explicitly defy that prototype for it be considered invalid.

For example:

function foo(Array $bar, String $baz) {
    var_dump(func_get_args());
}

foo([1], "quix", new stdclass); // is perfectly legal in php

You get

array(3) {
  [0]=>
  array(1) {
    [0]=>
    int(1)
  }
  [1]=>
  string(4) "quix"
  [2]=>
  object(stdClass)#1 (0) {
  }
}

From the manual:

PHP has support for variable-length argument lists in user-defined functions. This is implemented using the ... token in PHP 5.6 and later, and using the func_num_args(), func_get_arg(), and func_get_args() functions in PHP 5.5 and earlier.


问:
Is it possible to assign a pod of StatefulSet to a specific node of a Kubernetes cluster?
I have a 5 node cluster(1-master/4-worker). Is it possible to configure a StatefulSet where I can make a pod(s) to run on a given node knowing it has sufficient capacity rather Kubernetes Scheduler making this decision?

Lets say, my StatefulSet create 4 pods(replicas: 4) as myapp-0,myapp-1,myapp-2 and myapp-3. Now what I am looking for is:

myapp-0 pod-- get scheduled over---> worker-1

myapp-1 pod-- get scheduled over---> worker-2

myapp-2 pod-- get scheduled over---> worker-3

myapp-3 pod-- get scheduled over---> worker-4

Please let me know if it can be achieved somehow? Because if I add a toleration to pods of a StatefulSet, it will be same for all the pods and all of them will get scheduled over a single node matching the taint.

Thanks, J

答:
take a look to this guideline https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
however, what you are looking for is the nodeSelector directive that should be placed in the pod spec.


问:
How to get previous/next row when ordering by date/time then ID in MySQL?
I have table like

```<code>SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...
</code>```

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

答:
Method #1 (requires MySQL 8+):

SQL

```<code>-- Previous ID
WITH cte_desc AS (SELECT * FROM `table` ORDER BY `date` DESC, id DESC),
     cte_r AS (SELECT * FROM `table` WHERE id = @r_id)
SELECT id AS prev_id
FROM cte_desc
WHERE `date` < (SELECT `date` FROM cte_r)
   OR `date` = (SELECT `date` FROM cte_r) AND id < (SELECT id FROM cte_r)
LIMIT 1;

-- Next ID
WITH cte_asc AS (SELECT * FROM `table` ORDER BY `date`, id),
     cte_r AS (SELECT * FROM `table` WHERE id = @r_id)
SELECT id AS next_id
FROM cte_asc
WHERE `date` > (SELECT `date` FROM cte_r)
   OR `date` = (SELECT `date` FROM cte_r) AND id > (SELECT id FROM cte_r)
LIMIT 1;
</code>```

where @r_id is set to the ID of the row you want to find the previous/next for = 8 in your example.

Explanation

Two Common Table Expressions are defined: cte_desc sorts the table and cte_r gets the current row. The query part then finds the top row for which either the date value is strictly less than that of the chosen row or for which it is equal but the id is strictly less.

Online Demo

Dbfiddle demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5380e374f24243d578db28b9f89b9c8c

Method #2 (for earlier MySQL versions)

Similar to above - just slightly longer when there is no CTE support:

SQL

```<code>-- Previous ID
SELECT id AS prev_id
FROM (SELECT * FROM `table` ORDER BY `date` DESC, id DESC) sub
WHERE `date` < (SELECT `date` FROM `table` WHERE id = @r_id)
   OR `date` = (SELECT `date` FROM `table` WHERE id = @r_id)
      AND id < (SELECT id FROM `table` WHERE id = @r_id)
LIMIT 1;

-- Next ID
SELECT id AS next_id
FROM (SELECT * FROM `table` ORDER BY `date`, id) sub
WHERE `date` > (SELECT `date` FROM `table` WHERE id = @r_id)
   OR `date` = (SELECT `date` FROM `table` WHERE id = @r_id)
      AND id > (SELECT id FROM `table` WHERE id = @r_id)
LIMIT 1;
</code>```

Online Demo

Rextester demo: https://rextester.com/MTW78358

Method #3 (Slower? See first comments):

```<code>-- Previous ID
SELECT id AS prev_id
FROM `table`
WHERE CONCAT(`date`, LPAD(id, 8, '0')) =
(SELECT MAX(CONCAT(`date`, LPAD(id, 8, '0')))
 FROM `table`
 WHERE CONCAT(`date`, LPAD(id, 8, '0')) < (SELECT CONCAT(`date`, LPAD(id, 8, '0'))
                                           FROM `table`
                                           WHERE id = @r_id));
-- Next ID
SELECT id AS next_id
FROM `table`
WHERE CONCAT(`date`, LPAD(id, 8, '0')) =
(SELECT MIN(CONCAT(`date`, LPAD(id, 8, '0')))
 FROM `table`
 WHERE CONCAT(`date`, LPAD(id, 8, '0')) > (SELECT CONCAT(`date`, LPAD(id, 8, '0'))
                                           FROM `table`
                                           WHERE id = @r_id));
</code>```

Online Demo

Rextester demo: https://rextester.com/BSQQL24519

Explanation

The ordering is by date/time then by ID so to simplify the searching, these are concatenated into a single string - but there is the usual snag of a string ordering placing e.g. 10 after 1 rather than after 9. To overcome this, the IDs are padded with zeros up to the number of digits of the maximum integer in MySQL (4294967295) - using the LPAD function. Having done this groundwork, the previous row can then be found by looking for the largest one that is less than the one for the current id value using MAX and a subselect.

Body:
I have table like

SELECT id, name, date FROM `table` ORDER BY `date` DESC, id DESC
...
10  |a|2020-01-08 20:40:00
9   |b|2020-01-08 20:40:00
8   |c|2020-01-08 20:40:00
500 |d|2020-01-06 22:49:00
7   |e|2020-01-06 22:00:00
...

How to get next and previous of a record. (ex: i have info of a record with id = 8 then how to get a next record is 9 and a previous record is 500)

Body:
Method #1 (requires MySQL 8+):

SQL

-- Previous ID
WITH cte_desc AS (SELECT * FROM `table` ORDER BY `date` DESC, id DESC),
     cte_r AS (SELECT * FROM `table` WHERE id = @r_id)
SELECT id AS prev_id
FROM cte_desc
WHERE `date` < (SELECT `date` FROM cte_r)
   OR `date` = (SELECT `date` FROM cte_r) AND id < (SELECT id FROM cte_r)
LIMIT 1;

-- Next ID
WITH cte_asc AS (SELECT * FROM `table` ORDER BY `date`, id),
     cte_r AS (SELECT * FROM `table` WHERE id = @r_id)
SELECT id AS next_id
FROM cte_asc
WHERE `date` > (SELECT `date` FROM cte_r)
   OR `date` = (SELECT `date` FROM cte_r) AND id > (SELECT id FROM cte_r)
LIMIT 1;

where @r_id is set to the ID of the row you want to find the previous/next for = 8 in your example.

Explanation

Two Common Table Expressions are defined: cte_desc sorts the table and cte_r gets the current row. The query part then finds the top row for which either the date value is strictly less than that of the chosen row or for which it is equal but the id is strictly less.

Online Demo

Dbfiddle demo: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5380e374f24243d578db28b9f89b9c8c

Method #2 (for earlier MySQL versions)

Similar to above - just slightly longer when there is no CTE support:

SQL

-- Previous ID
SELECT id AS prev_id
FROM (SELECT * FROM `table` ORDER BY `date` DESC, id DESC) sub
WHERE `date` < (SELECT `date` FROM `table` WHERE id = @r_id)
   OR `date` = (SELECT `date` FROM `table` WHERE id = @r_id)
      AND id < (SELECT id FROM `table` WHERE id = @r_id)
LIMIT 1;

-- Next ID
SELECT id AS next_id
FROM (SELECT * FROM `table` ORDER BY `date`, id) sub
WHERE `date` > (SELECT `date` FROM `table` WHERE id = @r_id)
   OR `date` = (SELECT `date` FROM `table` WHERE id = @r_id)
      AND id > (SELECT id FROM `table` WHERE id = @r_id)
LIMIT 1;

Online Demo

Rextester demo: https://rextester.com/MTW78358

Method #3 (Slower? See first comments):

-- Previous ID
SELECT id AS prev_id
FROM `table`
WHERE CONCAT(`date`, LPAD(id, 8, '0')) =
(SELECT MAX(CONCAT(`date`, LPAD(id, 8, '0')))
 FROM `table`
 WHERE CONCAT(`date`, LPAD(id, 8, '0')) < (SELECT CONCAT(`date`, LPAD(id, 8, '0'))
                                           FROM `table`
                                           WHERE id = @r_id));
-- Next ID
SELECT id AS next_id
FROM `table`
WHERE CONCAT(`date`, LPAD(id, 8, '0')) =
(SELECT MIN(CONCAT(`date`, LPAD(id, 8, '0')))
 FROM `table`
 WHERE CONCAT(`date`, LPAD(id, 8, '0')) > (SELECT CONCAT(`date`, LPAD(id, 8, '0'))
                                           FROM `table`
                                           WHERE id = @r_id));

Online Demo

Rextester demo: https://rextester.com/BSQQL24519

Explanation

The ordering is by date/time then by ID so to simplify the searching, these are concatenated into a single string - but there is the usual snag of a string ordering placing e.g. 10 after 1 rather than after 9. To overcome this, the IDs are padded with zeros up to the number of digits of the maximum integer in MySQL (4294967295) - using the LPAD function. Having done this groundwork, the previous row can then be found by looking for the largest one that is less than the one for the current id value using MAX and a subselect.


问:
Group Data using two columns and merge the third column into a single row
I have the data in this form

I want this as Ouput using R

Body:
Maybe you can try the base R code below using aggregate + replace

x <- aggregate(roll.no ~ ., df, FUN = function(v) paste0(v,collapse = "|"))
dfout <- within(x[order(x$subject,x$center),],
                subject <-replace(subject,duplicated(subject),""))

such that

> dfout
  subject center     roll.no
1     100   2500 700|701|702
4           2501         703
2     101   2500         701
5           2501         705
3     102   2500         707
6           2502     701|700

DATA

df <- structure(list(subject = c(100, 100, 100, 100, 101, 101, 102,
102, 102), center = c(2500, 2500, 2500, 2501, 2500, 2501, 2502,
2500, 2502), roll.no = c(700, 701, 702, 703, 701, 705, 701, 707,
700)), class = "data.frame", row.names = c(NA, -9L))


问:
Spring TransactionalTemplate does not roll back on exception

Problem Statement

My goal is to:

Read CSV file row --> Convert to DTO object (This step is not related to my question, included for the sake of completeness)

Collect 'n' DTO objects --> Call save()/update() service methods. (Under the same transactional context)

Expected: When one save()/update() call fails --> Rollback the whole batch.

Actual: When one save()/update() call fails --> Spring commits the record for previous call(s).

Implementation

Below is my code implementation. (Omitted helper methods and non-relevant attributes for brevity)

Importer Class:

Groups List(Patient) and calls save()/update() depending upon the operation type.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.github.swapnil.hims.bo.importer.BulkImporter;
import com.github.swapnil.hims.bo.importer.Importer;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.service.PatientService;

@Component
public class PatientImporter extends Importer implements BulkImporter {
    @Autowired
    private PatientService patientSvc;

    private final TransactionTemplate txTmpl;

    public PatientImporter(PlatformTransactionManager transactionManager) {
        this.txTmpl = new TransactionTemplate(transactionManager);
    }

    @Override
    public PatientDetail rowToObject(CSVRecord record) {
        // Convert row to DTO object.
        return patientDetail;
    }

    @Override
    public void saveToDb(List<Object> patients) {
        List<PatientDetail> patientList = patients.stream().map(patient -> (PatientDetail) patient)
                .collect(Collectors.toList());
        saveAll(patientList, this.importType, BATCH_SIZE);
    }

    private void saveAll(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        txTmpl.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                createPatients(patients, action, batchSize);
            }
        });
    }

    private void createPatients(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        int startAt = 0;
        while (true) {
            List<PatientDetail> patientBatch = patients.stream().skip(startAt).limit(batchSize)
                    .collect(Collectors.toList());

            for (PatientDetail patient : patientBatch) {
                if (action == Importer.Type.CREATE) {
                    patientSvc.save(patient);
                } else {
                    patientSvc.update(patient);
                }
            }

            if (patientBatch.size() != batchSize) {
                break;
            }

            startAt += batchSize;
        }
    }
}
```

<p><strong>PatientService Class:</strong></p>

<blockquote>
  <p>Repository/Service class for Patient.</p>
</blockquote>

<pre class="lang-java prettyprint-override"><code>import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.swapnil.hims.dao.PatientDao;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.entities.Patient;
import com.github.swapnil.hims.exception.PatientException;
import com.github.swapnil.hims.service.PatientService;

@Service
public class PatientServiceImpl implements PatientService {
    private final static Log logger = LogFactory.getLog(PatientServiceImpl.class);

    @Autowired
    private PatientDao patientDao;

    @Override
    @Transactional
    public void save(PatientDetail patientDetail) {
        patientDao.save(getPatient(patientDetail));
    }

    @Override
    @Transactional
    public void update(Long id, PatientDetail patientDetail) {
        patientDao.save(getPatient(id, patientDetail));
    }

    @Override
    public void update(PatientDetail patientDetail) {
        update(patientDetail.getIdentifier(), patientDetail);
    }

    private Patient getPatient(PatientDetail patientDetail) {
        if (StringUtils.isEmpty(patientDetail.getPatientId())) {
            throw new PatientException("Patient ID is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getName())) {
            throw new PatientException("Patient name is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getEmail())) {
            throw new PatientException("Patient e-mail is required!");
        }

        Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId());
        if (dbPatient != null) {
            throw new PatientException(String.format("Patient with the same pid '%s' already exists!", dbPatient.getPatientId()));
        }

        return patientDetail.toPatient();
    }

    private Patient getPatient(Long id, PatientDetail patientDetail) {
        Patient patient = patientDao.findById(id);

        if (patient == null) {
            throw new PatientException("Patient with id " + id + " does not exists.");
        }

        patient.setName(StringUtils.isEmpty(patientDetail.getName()) ? patient.getName() : patientDetail.getName());
        patient.setCity(StringUtils.isEmpty(patientDetail.getCity()) ? patient.getCity() : patientDetail.getCity());
        patient.setAddress(StringUtils.isEmpty(patientDetail.getAddress()) ? patient.getAddress() : patientDetail.getAddress());
        patient.setEmail(StringUtils.isEmpty(patientDetail.getEmail()) ? patient.getEmail() : patientDetail.getEmail());
        patient.setContactNumber(patientDetail.getContactNumber() != null ? patient.getContactNumber() : patientDetail.getContactNumber());
        patient.setPatientId(StringUtils.isEmpty(patientDetail.getPatientId()) ? patient.getPatientId() : patientDetail.getPatientId());

        return patient;
    }
}
</code>```

PatientDao.java

import org.springframework.data.jpa.repository.JpaRepository;

import com.github.swapnil.hims.entities.Patient;

public interface PatientDao extends JpaRepository<Patient, String> {
    public Patient findById(Long id);

    public void deleteById(Long id);

    public Patient findByPatientId(String patientId);
}
```

I tried:

try {createPatients(patients, action, batchSize);} catch() {status.setRollbackOnly()}

Setting PropagationBehaviour to PROPAGATION_REQUIRED.

I cannot understand what I'm missing here, I've invested loads of time in solving this and would really, really appreciate any help. I'm using MySQL v8.0.16.

(GitHub repo URL)

EDIT

While debugging, I found that Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId()); call causes the hibernate to flush the session and commit the previous object to DB. I'm not sure how to prevent this though. I tried some things but didn't work, I'll keep looking and update this.

答: In order to rollback the whole batch, you need to annotate the 'saveToDb' method in Patient importer with @Transactional as well.</p>

Body:
Problem Statement

My goal is to:

Read CSV file row --> Convert to DTO object (This step is not related to my question, included for the sake of completeness)

Collect 'n' DTO objects --> Call save()/update() service methods. (Under the same transactional context)

Expected: When one save()/update() call fails --> Rollback the whole batch.

Actual: When one save()/update() call fails --> Spring commits the record for previous call(s).

Implementation

Below is my code implementation. (Omitted helper methods and non-relevant attributes for brevity)

Importer Class:

Groups List(Patient) and calls save()/update() depending upon the operation type.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.github.swapnil.hims.bo.importer.BulkImporter;
import com.github.swapnil.hims.bo.importer.Importer;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.service.PatientService;

@Component
public class PatientImporter extends Importer implements BulkImporter {
    @Autowired
    private PatientService patientSvc;

    private final TransactionTemplate txTmpl;

    public PatientImporter(PlatformTransactionManager transactionManager) {
        this.txTmpl = new TransactionTemplate(transactionManager);
    }

    @Override
    public PatientDetail rowToObject(CSVRecord record) {
        // Convert row to DTO object.
        return patientDetail;
    }

    @Override
    public void saveToDb(List<Object> patients) {
        List<PatientDetail> patientList = patients.stream().map(patient -> (PatientDetail) patient)
                .collect(Collectors.toList());
        saveAll(patientList, this.importType, BATCH_SIZE);
    }

    private void saveAll(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        txTmpl.execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                createPatients(patients, action, batchSize);
            }
        });
    }

    private void createPatients(List<PatientDetail> patients, Importer.Type action, Integer batchSize) {
        int startAt = 0;
        while (true) {
            List<PatientDetail> patientBatch = patients.stream().skip(startAt).limit(batchSize)
                    .collect(Collectors.toList());

            for (PatientDetail patient : patientBatch) {
                if (action == Importer.Type.CREATE) {
                    patientSvc.save(patient);
                } else {
                    patientSvc.update(patient);
                }
            }

            if (patientBatch.size() != batchSize) {
                break;
            }

            startAt += batchSize;
        }
    }
}

PatientService Class:

Repository/Service class for Patient.

import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.swapnil.hims.dao.PatientDao;
import com.github.swapnil.hims.dto.PatientDetail;
import com.github.swapnil.hims.entities.Patient;
import com.github.swapnil.hims.exception.PatientException;
import com.github.swapnil.hims.service.PatientService;

@Service
public class PatientServiceImpl implements PatientService {
    private final static Log logger = LogFactory.getLog(PatientServiceImpl.class);

    @Autowired
    private PatientDao patientDao;

    @Override
    @Transactional
    public void save(PatientDetail patientDetail) {
        patientDao.save(getPatient(patientDetail));
    }

    @Override
    @Transactional
    public void update(Long id, PatientDetail patientDetail) {
        patientDao.save(getPatient(id, patientDetail));
    }

    @Override
    public void update(PatientDetail patientDetail) {
        update(patientDetail.getIdentifier(), patientDetail);
    }

    private Patient getPatient(PatientDetail patientDetail) {
        if (StringUtils.isEmpty(patientDetail.getPatientId())) {
            throw new PatientException("Patient ID is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getName())) {
            throw new PatientException("Patient name is required!");
        }

        if (StringUtils.isEmpty(patientDetail.getEmail())) {
            throw new PatientException("Patient e-mail is required!");
        }

        Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId());
        if (dbPatient != null) {
            throw new PatientException(String.format("Patient with the same pid '%s' already exists!", dbPatient.getPatientId()));
        }

        return patientDetail.toPatient();
    }

    private Patient getPatient(Long id, PatientDetail patientDetail) {
        Patient patient = patientDao.findById(id);

        if (patient == null) {
            throw new PatientException("Patient with id " + id + " does not exists.");
        }

        patient.setName(StringUtils.isEmpty(patientDetail.getName()) ? patient.getName() : patientDetail.getName());
        patient.setCity(StringUtils.isEmpty(patientDetail.getCity()) ? patient.getCity() : patientDetail.getCity());
        patient.setAddress(StringUtils.isEmpty(patientDetail.getAddress()) ? patient.getAddress() : patientDetail.getAddress());
        patient.setEmail(StringUtils.isEmpty(patientDetail.getEmail()) ? patient.getEmail() : patientDetail.getEmail());
        patient.setContactNumber(patientDetail.getContactNumber() != null ? patient.getContactNumber() : patientDetail.getContactNumber());
        patient.setPatientId(StringUtils.isEmpty(patientDetail.getPatientId()) ? patient.getPatientId() : patientDetail.getPatientId());

        return patient;
    }
}

PatientDao.java

import org.springframework.data.jpa.repository.JpaRepository;

import com.github.swapnil.hims.entities.Patient;

public interface PatientDao extends JpaRepository<Patient, String> {
    public Patient findById(Long id);

    public void deleteById(Long id);

    public Patient findByPatientId(String patientId);
}

I tried:

try {createPatients(patients, action, batchSize);} catch() {status.setRollbackOnly()}

Setting PropagationBehaviour to PROPAGATION_REQUIRED.

I cannot understand what I'm missing here, I've invested loads of time in solving this and would really, really appreciate any help. I'm using MySQL v8.0.16.

(GitHub repo URL)

EDIT

While debugging, I found that Patient dbPatient = patientDao.findByPatientId(patientDetail.getPatientId()); call causes the hibernate to flush the session and commit the previous object to DB. I'm not sure how to prevent this though. I tried some things but didn't work, I'll keep looking and update this.