问:
How to make item number's with adaptive in html/css ordered list with block children element of list item?

Targets

Make ordered list as custom as :before pseudo element styling allowed (AFAIK arbitrary shape is impossible).

The spacing between container content edge (even with border when left padding is 0) and item number (designated as l) also between number and item (designated as m) must be adjustable.

The item number with must be adaptive due to increasing digits count.

li could has children block elements as div, p, figure, etc.

Problem

Below solution without positioning satisfies to first three requirements.

ol {
  counter-reset: section;
}
ol li:before {
  content: "";
  display: inline-block;
  counter-increment: section;
  content: counters(section, ".") " ";
  margin-left: 4px;
  margin-right: 10px;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol + li {
  margin-top: 6px;
}
```

<p> Fiddle</p>

<p><img src="https://i.stack.imgur.com/JT2ct.png" alt="enter image description here"></p>

<p>But what about fourth requirement? Let's try to add child elements to <code>li</code>:</p>

<pre class="lang-css prettyprint-override"><code><ol>
  <li>Alpha</li>
  <li>
    <ol>
      <li>
        <p>Lorem ipsum</p>
        <p>Duis aute</p>
      </li>
    </ol>
  </li>
</ol>
</code>```

Conceptually, :before pseudo element must take the one column (space below it must be empty until next li).
Currently, I know just one solution: positioning.

ol {
  counter-reset: section;
}
ol li {
  position: relative;
}
ol li:before {
  position: absolute;
  left: 0;
  counter-increment: section;
  content: counters(section, ".") " ";
  display: inline-block;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol li + li {
  margin-top: 12px;
}
ol li > li {
  padding-left: 30px;
}
ol li > li > ol > li {
  padding-left: 44px;
}
```

Fillde

In addition to ugliness, this solution reaches just first and fourth target:

Second target We can not control neither l not m anymore: we can control just total spacing l + m + o.

Third target No adaptivity: the l + m + o is actual only for initial digits count.

For the fouth target, vertical spacing adjusting is required, but it no too hard.

Could you suggest some alternative solutions? Does CSS flexibility ends here?

答:
Here is an idea using CSS grid where I will tweak your initial code a little:

ol {
  counter-reset: section;
  list-style:none;
  margin:0;
  padding:0;
}
ol li {
  display:grid; /* added this */
  grid-template-columns:auto 1fr; /* auto for the bullet and 1fr for the content*/
  align-items:baseline; /* keep all the text aligned */
}

ol li:before {
  content: "";
  /* make sure the bullet span many rows os it's kept on the first column
     and the content will placed on the second column
   */
  grid-row:span 1000;
  counter-increment: section;
  content: counters(section, ".") " ";
  margin-left: 4px;
  margin-bottom:3px;
  margin-right: 10px;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol + li {
  margin-top: 6px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Alpha</li>
  <li>
    <ol>
      <p>Something</p>
      <li>
        <p>Lorem ipsum</p>
        <p>Duis aute</p>
      </li>
    </ol>
  </li>
  <li>Charlie</li>
  <li>Delta</li>
  <li>Echo</li>
  <li>Foxtrotg</li>
  <li>Golf</li>
  <li>Hotel</li>
  <li>India</li>
  <li>Juliet</li>
</ol></code>```

Or like below:

ol {
  counter-reset: section;
  list-style:none;
  margin:0;
  padding:0;
}
ol li {
  display:grid; /* added this */
  grid-template-columns:auto 1fr; /* auto for the bullet and 1fr for the content*/
  align-items:baseline; /* keep all the text aligned */
}
ol li > * {
  grid-column:2; /* all the content in the second column and keep only the bullet in the first*/
}
ol li:before {
  content: "";
  counter-increment: section;
  content: counters(section, ".") " ";
  margin-left: 4px;
  margin-bottom:3px;
  margin-right: 10px;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol + li {
  margin-top: 6px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
  <li>Alpha</li>
  <li>
    <ol>
      <p>Something</p>
      <li>
        <p>Lorem ipsum</p>
        <p>Duis aute</p>
      </li>
    </ol>
  </li>
  <li>Charlie</li>
  <li>Delta</li>
  <li>Echo</li>
  <li>Foxtrotg</li>
  <li>Golf</li>
  <li>Hotel</li>
  <li>India</li>
  <li>Juliet</li>
</ol></code>```

Body:
Targets

Make ordered list as custom as :before pseudo element styling allowed (AFAIK arbitrary shape is impossible).

The spacing between container content edge (even with border when left padding is 0) and item number (designated as l) also between number and item (designated as m) must be adjustable.

The item number with must be adaptive due to increasing digits count.

li could has children block elements as div, p, figure, etc.

Problem

Below solution without positioning satisfies to first three requirements.

ol {
  counter-reset: section;
}
ol li:before {
  content: "";
  display: inline-block;
  counter-increment: section;
  content: counters(section, ".") " ";
  margin-left: 4px;
  margin-right: 10px;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol + li {
  margin-top: 6px;
}

 Fiddle

But what about fourth requirement? Let's try to add child elements to li:

Alpha

Lorem ipsum

Duis aute

Conceptually, :before pseudo element must take the one column (space below it must be empty until next li).
Currently, I know just one solution: positioning.

ol {
  counter-reset: section;
}
ol li {
  position: relative;
}
ol li:before {
  position: absolute;
  left: 0;
  counter-increment: section;
  content: counters(section, ".") " ";
  display: inline-block;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol li + li {
  margin-top: 12px;
}
ol li > li {
  padding-left: 30px;
}
ol li > li > ol > li {
  padding-left: 44px;
}

Fillde

In addition to ugliness, this solution reaches just first and fourth target:

Second target We can not control neither l not m anymore: we can control just total spacing l + m + o.

Third target No adaptivity: the l + m + o is actual only for initial digits count.

For the fouth target, vertical spacing adjusting is required, but it no too hard.

Could you suggest some alternative solutions? Does CSS flexibility ends here?

Body:
Here is an idea using CSS grid where I will tweak your initial code a little:

ol {
  counter-reset: section;
  list-style:none;
  margin:0;
  padding:0;
}
ol li {
  display:grid; /* added this */
  grid-template-columns:auto 1fr; /* auto for the bullet and 1fr for the content*/
  align-items:baseline; /* keep all the text aligned */
}

ol li:before {
  content: "";
  /* make sure the bullet span many rows os it's kept on the first column
     and the content will placed on the second column
   */
  grid-row:span 1000;
  counter-increment: section;
  content: counters(section, ".") " ";
  margin-left: 4px;
  margin-bottom:3px;
  margin-right: 10px;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol + li {
  margin-top: 6px;
}

<ol>
  <li>Alpha</li>
  <li>
    <ol>
      <p>Something</p>
      <li>
        <p>Lorem ipsum</p>
        <p>Duis aute</p>
      </li>
    </ol>
  </li>
  <li>Charlie</li>
  <li>Delta</li>
  <li>Echo</li>
  <li>Foxtrotg</li>
  <li>Golf</li>
  <li>Hotel</li>
  <li>India</li>
  <li>Juliet</li>
</ol>

Or like below:

ol {
  counter-reset: section;
  list-style:none;
  margin:0;
  padding:0;
}
ol li {
  display:grid; /* added this */
  grid-template-columns:auto 1fr; /* auto for the bullet and 1fr for the content*/
  align-items:baseline; /* keep all the text aligned */
}
ol li > * {
  grid-column:2; /* all the content in the second column and keep only the bullet in the first*/
}
ol li:before {
  content: "";
  counter-increment: section;
  content: counters(section, ".") " ";
  margin-left: 4px;
  margin-bottom:3px;
  margin-right: 10px;
  padding: 4px 6px;
  background: lightblue;
  border: 1px solid skyblue;
  border-radius: 4px;
}
ol + li {
  margin-top: 6px;
}

<ol>
  <li>Alpha</li>
  <li>
    <ol>
      <p>Something</p>
      <li>
        <p>Lorem ipsum</p>
        <p>Duis aute</p>
      </li>
    </ol>
  </li>
  <li>Charlie</li>
  <li>Delta</li>
  <li>Echo</li>
  <li>Foxtrotg</li>
  <li>Golf</li>
  <li>Hotel</li>
  <li>India</li>
  <li>Juliet</li>
</ol>


来源: stackexchange

问:
Check in file the data match the syntax
i have a scenario where i want to check the below details in files match the syntax

Syntax : NAME/SURNAME/COUNTRY

Note : every record in file should match the syntax. if one records does not match then should display
failed or success

File data

```<code>Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/
</code>```

As you can see the file data the last record does not match according to the syntax
then should display failed

My code

```<code> for i in `cat /demo/Student.txt`
      do
      check=`echo $i | cut -d '/' -f3`
      if [[ -z $check ]];
      then
        echo failed syntax does not match NAME/SURNAME/COUNTRY
        exit 1
      fi
    done
</code>```

答:
Maybe use awk

```<code>#check value in third column, using / as a delimiter
check="$(awk -F"/" '{print $3}' /demo/Student.txt)"

#check if third column is empty
if [ "$check" == "" ]; then
    echo "failed syntax..."
    exit 1
fi
</code>```

You can run this check on the three columns (change print $3 to $1 and $2)
Probably not the most efficient solution, since I am also fairly new to shell scripting, but I think it should work.

ContentLicense: CC BY-SA 4.0

Title: Check in file the data match the syntax

Body:
i have a scenario where i want to check the below details in files match the syntax

Syntax : NAME/SURNAME/COUNTRY

Note : every record in file should match the syntax. if one records does not match then should display
failed or success

File data

Ajay/abc/india
Avik/bcs/delhi
Viraj/xyz/

As you can see the file data the last record does not match according to the syntax
then should display failed

My code

 for i in `cat /demo/Student.txt`
      do
      check=`echo $i | cut -d '/' -f3`
      if [[ -z $check ]];
      then
        echo failed syntax does not match NAME/SURNAME/COUNTRY
        exit 1
      fi
    done

Body:
Maybe use awk

#check value in third column, using / as a delimiter
check="$(awk -F"/" '{print $3}' /demo/Student.txt)"

#check if third column is empty
if [ "$check" == "" ]; then
    echo "failed syntax..."
    exit 1
fi

You can run this check on the three columns (change print $3 to $1 and $2)
Probably not the most efficient solution, since I am also fairly new to shell scripting, but I think it should work.


问:
How to jump back to the top of the code after if statement C language
I'm trying to make my program to start again from the beginning after user has selected an option from a menu.
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu What would you like to do? and not to just restart just the if statement.

Should I add a for loop inside of the if statement to accomplish this? thanks for the help.

```<code> printf("What would you like to do?\n");
    printf("      1 - Donate\n");
    printf("      2 - Invest\n");
    printf("      3 - Print balance\n");
    printf("      4 - Exit\n");
    printf("\n");

    //scans menu choice
    scanf("%d", &menu_option);

    if(menu_option==1)
    {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
    }
</code>```

答:
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu

just do

```<code>for(;;) {
  printf("      1 - Donate\n");
  printf("      2 - Invest\n");
  printf("      3 - Print balance\n");
  printf("      4 - Exit\n");
  printf("\n");

  //scans menu choice
  scanf("%d", &menu_option);

  if(menu_option==1)
  {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
    // NO BREAK
  }
  else {
    .... management of other cases
    break;
  }
}
</code>```

or if you prefer

```<code>do {
  printf("      1 - Donate\n");
  printf("      2 - Invest\n");
  printf("      3 - Print balance\n");
  printf("      4 - Exit\n");
  printf("\n");

  //scans menu choice
  scanf("%d", &menu_option);

  if(menu_option==1)
  {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
  }
  // ... management of other cases
} while (menu_option==1);
</code>```

But are you sure you do not want to redo also in cases 2 and 3 ? In that case replace while (menu_option==1); by while (menu_option != 4); or in the first proposal do the break only when menu_option is 4

I also encourage you to check the return value of scanf("%d", &menu_option); to be sure a valid integer was given in input and menu_option was set

Body:
I'm trying to make my program to start again from the beginning after user has selected an option from a menu.
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu What would you like to do? and not to just restart just the if statement.

Should I add a for loop inside of the if statement to accomplish this? thanks for the help.

 printf("What would you like to do?\n");
    printf("      1 - Donate\n");
    printf("      2 - Invest\n");
    printf("      3 - Print balance\n");
    printf("      4 - Exit\n");
    printf("\n");

    //scans menu choice
    scanf("%d", &menu_option);

    if(menu_option==1)
    {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
    }

Body:
When the user selects 1 and then enters the amount of the donation I want the program to start again and show the menu

just do

for(;;) {
  printf("      1 - Donate\n");
  printf("      2 - Invest\n");
  printf("      3 - Print balance\n");
  printf("      4 - Exit\n");
  printf("\n");

  //scans menu choice
  scanf("%d", &menu_option);

  if(menu_option==1)
  {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
    // NO BREAK
  }
  else {
    .... management of other cases
    break;
  }
}

or if you prefer

do {
  printf("      1 - Donate\n");
  printf("      2 - Invest\n");
  printf("      3 - Print balance\n");
  printf("      4 - Exit\n");
  printf("\n");

  //scans menu choice
  scanf("%d", &menu_option);

  if(menu_option==1)
  {
    printf("How much do you want to donate?\n");
    scanf("%lf", &donation);
    donations_made++;
    current_Balance = initial_Balance + donation;
  }
  // ... management of other cases
} while (menu_option==1);

But are you sure you do not want to redo also in cases 2 and 3 ? In that case replace while (menu_option==1); by while (menu_option != 4); or in the first proposal do the break only when menu_option is 4

I also encourage you to check the return value of scanf("%d", &menu_option); to be sure a valid integer was given in input and menu_option was set


问:
How to detect if javascript is executing on page
Is there a way to detect if javascript is executing a script using either JQuery, javascript, WebDriver, or C# (like a browser API or something)?

For example, say I'm on a webpage and I just selected a U.S. State (let's say California) from a picklist, and some javascript is now loading a second picklist with all the cities found in California.  How can I detect if javascript is executing, and when it has finished?

I'm running into problems with WebDriver since it doesn't know how to wait for a script to stop executing aside from pausing for a few seconds.

答: I think you can do something if JavaScript is not Enabled ,like adding tags Do Whatever You Want so you can invalidate or something ,be creative .

ContentLicense: CC BY-SA 3.0

Body: I think you can do something if JavaScript is not Enabled ,like adding tags <noscript>Do Whatever You Want</noscript> so you can invalidate or something ,be creative .


问:
Did anyone find solution for Trying to get property 'pivot' of non-object?
I tried to make relation btw organizer and user using pivot table, but when i tried to display the output its showing me error.
OrganizeController.php

```<code>public function show($id)
{
    $organize = Organize::find($id);

    return dd($organize->pivot->name);
}
</code>```

Organize.php

```<code>namespace App;

use App\OrganizeUser;

use Illuminate\Database\Eloquent\Model;

class Organize extends Model
{
    public function user()
    {
        return $this->belongsToMany(User::class)->withPivot('user_id');
    }
}
</code>```

答:
Try this: </p>

```<code>public function show($id){
    $organize = Organize::find($id);
    $organize->user()->get();
}
</code>```

Body:
I tried to make relation btw organizer and user using pivot table, but when i tried to display the output its showing me error.
OrganizeController.php

public function show($id)
{
    $organize = Organize::find($id);

    return dd($organize->pivot->name);
}

Organize.php

namespace App;

use App\OrganizeUser;

use Illuminate\Database\Eloquent\Model;

class Organize extends Model
{
    public function user()
    {
        return $this->belongsToMany(User::class)->withPivot('user_id');
    }
}

Body:
Try this:

public function show($id){
    $organize = Organize::find($id);
    $organize->user()->get();
}


问:
SSIS Execute Process Task with Python- Exit code was "1"
I am trying to run a Python script from the SSIS Execute Process Task. I am getting the following error. I've tried looking around stackoverflow, but cannot seem to find a suitable answer to my problem.

```<code>SSIS package "C:\Users\Q300L\source\repos\TestScript\Package.dtsx" starting.
Error: 0xC0029151 at Execute Process Task, Execute Process Task: In Executing "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe" "C:\Users\Q300L\Desktop\GGTT.py" at "", The process exit code was "1" while the expected was "0".
Task failed: Execute Process Task
Warning: 0x80019002 at Package: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED.  The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "C:\Users\Q300L\source\repos\TestScript\Package.dtsx" finished: Failure.
</code>```

Process details.

My Python script is a simple web scraping that takes the SPY companies from a wikipedia table.

```<code>import csv
import requests
import pandas as pd
from bs4 import BeautifulSoup

website_url = requests.get("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies").text

soup = BeautifulSoup(website_url, 'html.parser')

My_table = soup.find('table', attrs={"id":"constituents"})

counter_ = 0

df = pd.DataFrame(columns=["symbol", "security", "SEC_fillings", "GICS_Sector", "Headquarters_Location", "Date_first_added", "CIK", "Founded"])

for tr in My_table.find_all('tr'):
    counter_ += 1
    tds = tr.find_all('td')
    if not tds:
        continue
    tmp_list = []
    for td in tds[:8]:
        tmp_list.append(td.text.strip())
    df.loc[counter_] = tmp_list

df.to_csv("C:/Users/Q300L/Desktop/Rich/Staging/SPY.csv", encoding='utf-8', index=False)
</code>```

But the code gives me the error mentioned above. The code runs fine in both IDLE and Visual Studio Code. And succesfully creates a file with the scraped data.

I did try run a more simple task of creating a file with SSIS Execute Process Task, to get a minimum viable product up and running. The below code runs just fine, when executing my SSIS package:

```<code>import csv
with open('C:/Users/Q300L/Desktop/innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
    writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
    writer.writerow([3, "Guido van Rossum", "Python Programming"])
</code>```

I also tried to make a simple python script with import csv and nothing else. Which runs fine, when I then add the next import requests it starts to complain, and throws the same error.

I'm hoping some may point me in the right direction. Thanks!

答:
Try to change the property FailTaskIfReturnCodeIsNotSuccessValue to false.

I too got similar error and python program was to print hello world. By changing above property the error resolved. Hope this will help.

Body:
I am trying to run a Python script from the SSIS Execute Process Task. I am getting the following error. I've tried looking around stackoverflow, but cannot seem to find a suitable answer to my problem.

SSIS package "C:\Users\Q300L\source\repos\TestScript\Package.dtsx" starting.
Error: 0xC0029151 at Execute Process Task, Execute Process Task: In Executing "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe" "C:\Users\Q300L\Desktop\GGTT.py" at "", The process exit code was "1" while the expected was "0".
Task failed: Execute Process Task
Warning: 0x80019002 at Package: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED.  The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
SSIS package "C:\Users\Q300L\source\repos\TestScript\Package.dtsx" finished: Failure.

Process details.

My Python script is a simple web scraping that takes the SPY companies from a wikipedia table.

import csv
import requests
import pandas as pd
from bs4 import BeautifulSoup

website_url = requests.get("https://en.wikipedia.org/wiki/List_of_S%26P_500_companies").text

soup = BeautifulSoup(website_url, 'html.parser')

My_table = soup.find('table', attrs={"id":"constituents"})

counter_ = 0

df = pd.DataFrame(columns=["symbol", "security", "SEC_fillings", "GICS_Sector", "Headquarters_Location", "Date_first_added", "CIK", "Founded"])

for tr in My_table.find_all('tr'):
    counter_ += 1
    tds = tr.find_all('td')
    if not tds:
        continue
    tmp_list = []
    for td in tds[:8]:
        tmp_list.append(td.text.strip())
    df.loc[counter_] = tmp_list

df.to_csv("C:/Users/Q300L/Desktop/Rich/Staging/SPY.csv", encoding='utf-8', index=False)

But the code gives me the error mentioned above. The code runs fine in both IDLE and Visual Studio Code. And succesfully creates a file with the scraped data.

I did try run a more simple task of creating a file with SSIS Execute Process Task, to get a minimum viable product up and running. The below code runs just fine, when executing my SSIS package:

import csv
with open('C:/Users/Q300L/Desktop/innovators.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(["SN", "Name", "Contribution"])
    writer.writerow([1, "Linus Torvalds", "Linux Kernel"])
    writer.writerow([2, "Tim Berners-Lee", "World Wide Web"])
    writer.writerow([3, "Guido van Rossum", "Python Programming"])

I also tried to make a simple python script with import csv and nothing else. Which runs fine, when I then add the next import requests it starts to complain, and throws the same error.

I'm hoping some may point me in the right direction. Thanks!


问:
Create Max and Min column values from a single column value pandas
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

```<code>Kg
0.5
0.5
1
1
1
2
2
5
5
5
</code>```

Expected Output

```<code>Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5
</code>```

How can this be done in pandas ?

答:
```<code>#get unique values and counts of each value in the Kg column
val,counts = np.unique(df.Kg,return_counts=True)

#shift forward by 1 and replace the first value with 0
val = np.roll(val,1)
val[0] = 0

#repeat the count of each value with the counts generated earlier
df['Kg_from'] = np.repeat(val,counts)

df

     Kg Kg_from
0   0.5 0.0
1   0.5 0.0
2   1.0 0.5
3   1.0 0.5
4   1.0 0.5
5   2.0 1.0
6   2.0 1.0
7   5.0 2.0
8   5.0 2.0
9   5.0 2.0
</code>```

Body:
I have a dataframe like the one below and I need to create two columns out of the base column.

Input

Kg
0.5
0.5
1
1
1
2
2
5
5
5

Expected Output

Kg_From  Kg_To
0      0.5
0      0.5
0.5    1
0.5    1
0.5    1
1      2
1      2
2      5
2      5
2      5

How can this be done in pandas ?


问:
Finding common elements in two arrays of different size
I have a problem to find common elements in two arrays and that's of different size.

Take , Array A1 of size n and Array A2 of size m, and m != n

So far, I've tried to iterate lists one by one and copy elements to another list. If the element already contains mark it, but I know it's not a good solution.

答: Throw your A2 array into a HashSet, then iterate through A1; if the current element is in the set, it's a common element. This takes O(m + n) time and O(min(m, n)) space. </p>


问:
Django problem with foreginKey in templates
I am started learning Django and I have question. I have code like this:

```<code>from django.db import models
from django.utils import timezone

class Worker(models.Model):
    firstname = models.CharField(max_length = 32, blank=False, null=False)
    lastname = models.CharField(max_length = 32, blank=False, null=False)

class Computer(models.Model):
    TYPE = {
        (0, 'PC'),
        (1, 'Laptop'),
    }
    workerId = models.ForeignKey(Worker, on_delete=models.SET_NULL, blank=True, null=True)
    prod = models.CharField(max_length = 32, blank=False, null=False)
    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)
</code>```

What I should do in views and templates if I want to do list with workers and theirs computers? One computer can be for one user or for no one but one worker can have a few computers.

My template for this look like:

```<code>{% block site %}
    {% for work in worker %}
        <p>{{ work.id }} {{ work.fullname }}
            {{ work.lastname }}</p><br>
            {% if comp.workerId == work.id%}
                {{ comp }}
            {% else %}
                <p>Empty</p>
            {% endif %}
    {% endfor %}
    {% for c in comp %}
        <p>{{ c }}</p>
    {% endfor %}
{% endblock %}
</code>```

But I always have "Empty". Thanks for help

答:
I've actually explained this before in 2 questions, here and here.

Basically, a ForiegnKey object is a key because it's unique for the class owning it, This means your computer has only one worker, BE SURE TO CALL IT WORKER, NOT WORKERID as this is OOP and when you access mycomputer.worker, you have a Worker object which has .id and .pk so it makes no sense to call it workerId.

Each worker now has a .computer_qs which you can change like this

```<code>workerId = models.ForeignKey(Worker,
                             on_delete=models.SET_NULL,
                             blank=True, null=True, related_name="computers")
</code>```

don't forget to call it worker. now it's .computers instead of .computer_qs.

In your templates iterate workerObj.computers.all to access single computer objects and have fun with it!

Body:
I am started learning Django and I have question. I have code like this:

from django.db import models
from django.utils import timezone

class Worker(models.Model):
    firstname = models.CharField(max_length = 32, blank=False, null=False)
    lastname = models.CharField(max_length = 32, blank=False, null=False)

class Computer(models.Model):
    TYPE = {
        (0, 'PC'),
        (1, 'Laptop'),
    }
    workerId = models.ForeignKey(Worker, on_delete=models.SET_NULL, blank=True, null=True)
    prod = models.CharField(max_length = 32, blank=False, null=False)
    type = models.PositiveSmallIntegerField(default=0, choices=TYPE)

What I should do in views and templates if I want to do list with workers and theirs computers? One computer can be for one user or for no one but one worker can have a few computers.

My template for this look like:

{% block site %}
    {% for work in worker %}

{{ work.id }} {{ work.fullname }}
            {{ work.lastname }}

            {% if comp.workerId == work.id%}
                {{ comp }}
            {% else %}

Empty

            {% endif %}
    {% endfor %}
    {% for c in comp %}

{{ c }}

    {% endfor %}
{% endblock %}

But I always have "Empty". Thanks for help

Body:
I've actually explained this before in 2 questions, here and here.

Basically, a ForiegnKey object is a key because it's unique for the class owning it, This means your computer has only one worker, BE SURE TO CALL IT WORKER, NOT WORKERID as this is OOP and when you access mycomputer.worker, you have a Worker object which has .id and .pk so it makes no sense to call it workerId.

Each worker now has a .computer_qs which you can change like this

workerId = models.ForeignKey(Worker,
                             on_delete=models.SET_NULL,
                             blank=True, null=True, related_name="computers")

don't forget to call it worker. now it's .computers instead of .computer_qs.

In your templates iterate workerObj.computers.all to access single computer objects and have fun with it!


问:
?: ?? Operators Instead Of IF|ELSE
```<code>public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}
</code>```

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

```<code>if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}
</code>```

[ 2 ]

```<code>if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}
</code>```

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

答:
If you are concerned with the verbosity of your code I would write this rather than trying to abuse expressions.</p>

```<code>if (Source == value) return;
Source = value;
RaisePropertyChanged("Source");
</code>```

Title: ?: ?? Operators Instead Of IF|ELSE

Body:
public string Source
{
    get
    {
        /*
        if ( Source == null ){
            return string . Empty;
        } else {
            return Source;
        }
        */
        return Source ?? string.Empty;
    }
    set
    {
        /*
        if ( Source == null ) {
            Source = string . Empty;
        } else {
            if ( Source == value ) {
                Source = Source;
            } else {
                Source = value;
            }
        }
        */
        Source == value ? Source : value ?? string.Empty;
        RaisePropertyChanged ( "Source" );
    }
}

Can I use ?: ?? operators EXACTLY as If/Else?

My Question :

How to write the following with ?: ?? operators

[ 1 ]

if ( Source == null ){
    // Return Nothing
} else {
    return Source;
}

[ 2 ]

if ( Source == value ){
    // Do Nothing
} else {
    Source = value;
    RaisePropertyChanged ( "Source" );
}

Briefly : How to do nothing, return nothing and do multiple instructions with ?: ?? operator?

Body:
If you are concerned with the verbosity of your code I would write this rather than trying to abuse expressions.

if (Source == value) return;
Source = value;
RaisePropertyChanged("Source");


问:
Undeletable or persistent docker-compose volumes or data storage
is there possible to somehow create persistent storage for containers, created with docker-compose and don't remove them even when running docker-compose down -v so they will be automaticly attached to their containers after again starting the docker-compose up -d ?

答:
What I usually do is to use an external volume, something like:

```<code>$ docker volume create nodemodules
</code>```

docker-compose.yml

```<code>version: '3.7'

services:
  frontend:
    image: node:11
    volumes:
      - nodemodules:/app/node_modules

volumes:
  nodemodules:
    external: true
</code>```

Refer the docs for more info: https://docs.docker.com/compose/compose-file/#external

Body:
What I usually do is to use an external volume, something like:

$ docker volume create nodemodules

docker-compose.yml

version: '3.7'

services:
  frontend:
    image: node:11
    volumes:
      - nodemodules:/app/node_modules

volumes:
  nodemodules:
    external: true

Refer the docs for more info: https://docs.docker.com/compose/compose-file/#external


问:
gcc unable to find "windows.h, winsock2.h and ws2tcpip.h" header files even after installing mingw package on Linux
I am trying to create a c/c++ program using winsock2.h, windows.h and ws2tcpip.h in Linux. But I get the following error messages:

cannot open source file "winsock2.h"C/C++(1696)

Likewise for windows.h

cannot open source file "windows.h"C/C++(1696)

I have already installed Mingw on my system using this command

```<code>mingw-w64-common mingw-w64-i686-dev mingw-w64-tools mingw-w64-x86-64-dev
</code>```

My Program

```<code>#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")

 int main() { return 0; }
</code>```

VSC ver - 1.45.1

OS - Debian

答:
The problems seem to be something related to "not finding header files". If with gcc to include the custom headers path (or directory), you do something as below.

NOTE: My intentions here are not using the mingw offered headers with gcc; this is just for demonstration purpose.

dpkg -L mingw-w64-common gives such output on my system.

```<code>/usr/share/mingw-w64/include/windows.h
/usr/share/mingw-w64/include/winsock2.h
/usr/share/mingw-w64/include/ws2tcpip.h
</code>```

gcc -v test.c gives such output on my system

```<code>#include "..." search starts here:
#include <...> search starts here:
 /usr/lib/gcc/x86_64-linux-gnu/9/include
 /usr/local/include
 /usr/lib/gcc/x86_64-linux-gnu/9/include-fixed
 /usr/include/x86_64-linux-gnu
 /usr/include
</code>```

So it is evident that the headers or not in the default search path. In this particular case, you need to compile with gcc -I/usr/share/mingw-w64/include. You give a similar option for your toolchain's compiler. But then you may need to deal with the linking errors based on what libraries your code is using.

Body:
I am trying to create a c/c++ program using winsock2.h, windows.h and ws2tcpip.h in Linux. But I get the following error messages:

cannot open source file "winsock2.h"C/C++(1696)

Likewise for windows.h

cannot open source file "windows.h"C/C++(1696)

I have already installed Mingw on my system using this command

mingw-w64-common mingw-w64-i686-dev mingw-w64-tools mingw-w64-x86-64-dev

My Program

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#pragma comment(lib, "Ws2_32.lib")

 int main() { return 0; }

VSC ver - 1.45.1

OS - Debian

Body:
The problems seem to be something related to "not finding header files". If with gcc to include the custom headers path (or directory), you do something as below.

NOTE: My intentions here are not using the mingw offered headers with gcc; this is just for demonstration purpose.

dpkg -L mingw-w64-common gives such output on my system.

/usr/share/mingw-w64/include/windows.h
/usr/share/mingw-w64/include/winsock2.h
/usr/share/mingw-w64/include/ws2tcpip.h

gcc -v test.c gives such output on my system

#include "..." search starts here:
#include <...> search starts here:
 /usr/lib/gcc/x86_64-linux-gnu/9/include
 /usr/local/include
 /usr/lib/gcc/x86_64-linux-gnu/9/include-fixed
 /usr/include/x86_64-linux-gnu
 /usr/include

So it is evident that the headers or not in the default search path. In this particular case, you need to compile with gcc -I/usr/share/mingw-w64/include. You give a similar option for your toolchain's compiler. But then you may need to deal with the linking errors based on what libraries your code is using.


问:
I want my accordion to close when I click anywhere else on the page
The accordion should automatically close when I click anywhere else on the page.

This I will only be using on mobile so it should work on mobile devices.

```<code>var acc = document.getElementsByClassName("accordion_mobile");
var i;

// Open the first accordion
// Add onclick listener to every accordion element
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        // For toggling purposes detect if the clicked section is already "active"
        var isActive = this.classList.contains("active");

        // Close all accordions
        var allAccordions = document.getElementsByClassName("accordion_mobile");
        for (j = 0; j < allAccordions.length; j++) {
            // Remove active class from section header
            allAccordions[j].classList.remove("active");

            // Remove the max-height class from the panel to close it
            var panel = allAccordions[j].nextElementSibling;
            var maxHeightValue = getStyle(panel, "maxHeight");

            if (maxHeightValue !== "0px") {
                panel.style.maxHeight = null;
            }
        }

        // Toggle the clicked section using a ternary operator
        isActive ? this.classList.remove("active") : this.classList.add("active");

        // Toggle the panel element
        var panel = this.nextElementSibling;
        var maxHeightValue = getStyle(panel, "maxHeight");

        if (maxHeightValue !== "0px") {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    };
}

// Cross-browser way to get the computed height of a certain element. Credit to @CMS on StackOverflow (http://stackoverflow.com/a/2531934/7926565)
function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hypen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
            return letter.toUpperCase();
        });
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
            return (function(value) {
                var oldLeft = el.style.left,
                    oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft + "px";
                el.style.left = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
            })(value);
        }
        return value;
    }
}
</code>```

CSS:

```<code>button.accordion_mobile {
    color: #ffffff;
    cursor: pointer;
    padding: 10px;
    width: 100%;
    border: none;
    text-align: center;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion_mobile:after {
    display: none
}

button.accordion_mobile.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}

.acc_mobile {
  position: absolute;
  bottom:0px;
}

.yoga_mobile {
  background-color: rgba(215,66,41,0.8)!important;
}

.accommodation_mobile {
  background-color: rgba(231,96,47,0.85)!important;
}

.food_mobile {
  background-color: rgba(243,154,49,0.85)!important;
}

.paintball_mobile {
  background-color: rgba(137,172,162,0.9)!important;
}

.cable_mobile {
  background-color: rgba(61,152,164,0.85)!important;
}

.scuba_mobile {
  background-color: rgba(19,98,122,0.85)!important;
}
</code>```

HTML:

```<code><div class="acc_mobile"><button class="accordion_mobile yoga_mobile">YOGA</button>
    <div class="panel yoga_mobile">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>

    <button class="accordion_mobile accommodation_mobile">ACCOMMODATION</button>
    <div class="panel accommodation_mobile">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>

    <button class="accordion_mobile food_mobile">FOOD</button>
    <div class="panel food_mobile">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>

    <button class="accordion_mobile paintball_mobile">PAINTBALL</button>
    <div class="panel paintball_mobile">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>

    <button class="accordion_mobile cable_mobile">CABLE</button>
    <div class="panel cable_mobile">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>

    <button class="accordion_mobile scuba_mobile">SCUBA</button>
    <div class="panel scuba_mobile">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    </div>
</div>
</code>```

答:
```<code>addEventListener("click", function(a) {
    if (a.srcElement.className.indexOf('accordion_mobile') == -1) {
        var allAccordions = document.getElementsByClassName("accordion_mobile");
        for (j = 0; j < allAccordions.length; j++) {
            // Remove active class from section header
            allAccordions[j].classList.remove("active");

            // Remove the max-height class from the panel to close it
            var panel = allAccordions[j].nextElementSibling;
            var maxHeightValue = getStyle(panel, "maxHeight");

            if (maxHeightValue !== "0px") {
                panel.style.maxHeight = null;
            }
        }
    }
});
</code>```

Fiddle: https://jsfiddle.net/fkdv5a67/

Body:
The accordion should automatically close when I click anywhere else on the page.

This I will only be using on mobile so it should work on mobile devices.

var acc = document.getElementsByClassName("accordion_mobile");
var i;

// Open the first accordion
// Add onclick listener to every accordion element
for (i = 0; i < acc.length; i++) {
    acc[i].onclick = function() {
        // For toggling purposes detect if the clicked section is already "active"
        var isActive = this.classList.contains("active");

        // Close all accordions
        var allAccordions = document.getElementsByClassName("accordion_mobile");
        for (j = 0; j < allAccordions.length; j++) {
            // Remove active class from section header
            allAccordions[j].classList.remove("active");

            // Remove the max-height class from the panel to close it
            var panel = allAccordions[j].nextElementSibling;
            var maxHeightValue = getStyle(panel, "maxHeight");

            if (maxHeightValue !== "0px") {
                panel.style.maxHeight = null;
            }
        }

        // Toggle the clicked section using a ternary operator
        isActive ? this.classList.remove("active") : this.classList.add("active");

        // Toggle the panel element
        var panel = this.nextElementSibling;
        var maxHeightValue = getStyle(panel, "maxHeight");

        if (maxHeightValue !== "0px") {
            panel.style.maxHeight = null;
        } else {
            panel.style.maxHeight = panel.scrollHeight + "px";
        }
    };
}

// Cross-browser way to get the computed height of a certain element. Credit to @CMS on StackOverflow (http://stackoverflow.com/a/2531934/7926565)
function getStyle(el, styleProp) {
    var value, defaultView = (el.ownerDocument || document).defaultView;
    if (defaultView && defaultView.getComputedStyle) {
        // sanitize property name to css notation
        // (hypen separated words eg. font-Size)
        styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
        return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
    } else if (el.currentStyle) { // IE
        // sanitize property name to camelCase
        styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
            return letter.toUpperCase();
        });
        value = el.currentStyle[styleProp];
        // convert other units to pixels on IE
        if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
            return (function(value) {
                var oldLeft = el.style.left,
                    oldRsLeft = el.runtimeStyle.left;
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft + "px";
                el.style.left = oldLeft;
                el.runtimeStyle.left = oldRsLeft;
                return value;
            })(value);
        }
        return value;
    }
}

CSS:

button.accordion_mobile {
    color: #ffffff;
    cursor: pointer;
    padding: 10px;
    width: 100%;
    border: none;
    text-align: center;
    outline: none;
    font-size: 15px;
    transition: 0.4s;
}

button.accordion_mobile:after {
    display: none
}

button.accordion_mobile.active:after {
    content: "\2212";
}

div.panel {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
}

.acc_mobile {
  position: absolute;
  bottom:0px;
}

.yoga_mobile {
  background-color: rgba(215,66,41,0.8)!important;
}

.accommodation_mobile {
  background-color: rgba(231,96,47,0.85)!important;
}

.food_mobile {
  background-color: rgba(243,154,49,0.85)!important;
}

.paintball_mobile {
  background-color: rgba(137,172,162,0.9)!important;
}

.cable_mobile {
  background-color: rgba(61,152,164,0.85)!important;
}

.scuba_mobile {
  background-color: rgba(19,98,122,0.85)!important;
}

HTML:

<button class="accordion_mobile yoga_mobile">YOGA</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button class="accordion_mobile accommodation_mobile">ACCOMMODATION</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button class="accordion_mobile food_mobile">FOOD</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button class="accordion_mobile paintball_mobile">PAINTBALL</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button class="accordion_mobile cable_mobile">CABLE</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

    <button class="accordion_mobile scuba_mobile">SCUBA</button>

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Body:
addEventListener("click", function(a) {
    if (a.srcElement.className.indexOf('accordion_mobile') == -1) {
        var allAccordions = document.getElementsByClassName("accordion_mobile");
        for (j = 0; j < allAccordions.length; j++) {
            // Remove active class from section header
            allAccordions[j].classList.remove("active");

            // Remove the max-height class from the panel to close it
            var panel = allAccordions[j].nextElementSibling;
            var maxHeightValue = getStyle(panel, "maxHeight");

            if (maxHeightValue !== "0px") {
                panel.style.maxHeight = null;
            }
        }
    }
});

Fiddle: https://jsfiddle.net/fkdv5a67/


问:
Error with sendto() function: Invalid Argument Error
I am working on writing a ping CLI program for linux and I have been getting errno 22: invalid argument in the sendto() function. I don't understand why, all the arguments seem to be correct.

Here is where I call the function:

```<code>    // send echo request
    bytesSent = sendto(socketFD,                                                        // socket file descriptor
                      (char*)&packet, PacketSize,                                       // packet and size
                      0,                                                                // flags
                      (sockaddr*)DestinationAddr, (socklen_t)sizeof(DestinationAddr));  // destination address and size
</code>```

'packet' looks like this:
(I call initializePacket() in the function where I call sendto())

```<code>struct PacketData {
    icmphdr header;
    char message[PacketSize - sizeof(header)];      // want total size to be 64 bytes
};

PacketData initializePacket(int &transmitted) {
    PacketData packet = {};

    packet.header.type = ICMP_ECHO;                 // set ICMP type to Echo
    packet.header.un.echo.id = getpid() & 0xFFFF;   // set id (ICMP field is 16 bits)
    packet.header.checksum = 0;                     // fixed checksum because data is unchanging
    packet.header.un.echo.sequence = transmitted++;

    // fill up message
    memset(&packet.message, '0', sizeof(packet.message));
    packet.message[PacketSize - sizeof(packet.header) - 1] = '\0';

    return packet;
}
</code>```

'DestinationAddr' is this:

```<code>    // variables needed to store IP Address
    addrinfo* result;
    sockaddr_in* DestinationAddr;
    char ipString[INET_ADDRSTRLEN];

    // get IP Address and store in result (passed by reference)
    if (getIPAddress(argv[1], result) != 0) {
        std::cout << "Invalid IP Address. Terminating ...\n";
        exit(EXIT_FAILURE);
    }
    else {
        DestinationAddr = (sockaddr_in*)result->ai_addr;                        // get struct from resulting linked list
        void* address;
        address = &DestinationAddr->sin_addr;                                   // store IP Address
        inet_ntop(result->ai_family, address, ipString, sizeof(ipString));      // convert binary IP to string
        std::cout << "IP: " << ipString << std::endl;
    }
</code>```

And the getIPAddress() function is:

```<code>int getIPAddress(char* hostName, addrinfo* &result) {
    addrinfo tempStruct = {0};

    tempStruct.ai_family = AF_INET;         // want IPv4
    tempStruct.ai_socktype = SOCK_DGRAM;    // set socket type to datagram
    tempStruct.ai_flags = AI_PASSIVE;       // fill in IP automatically

    // get and validate IP address
    return (getaddrinfo(hostName, &PortNo, &tempStruct, &result));
}
</code>```

PortNo is defined as: const char PortNo = '0';

答:
According to documentation icmp:

A user protocol may receive ICMP packets for all local sockets by opening a raw socket with the protocol IPPROTO_ICMP.

So, try creating your socket like that:

```<code>socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)
</code>```

And, if you encounter EPERM error, then run your program as root.

Body:
I am working on writing a ping CLI program for linux and I have been getting errno 22: invalid argument in the sendto() function. I don't understand why, all the arguments seem to be correct.

Here is where I call the function:

    // send echo request
    bytesSent = sendto(socketFD,                                                        // socket file descriptor
                      (char*)&packet, PacketSize,                                       // packet and size
                      0,                                                                // flags
                      (sockaddr*)DestinationAddr, (socklen_t)sizeof(DestinationAddr));  // destination address and size

'packet' looks like this:
(I call initializePacket() in the function where I call sendto())

struct PacketData {
    icmphdr header;
    char message[PacketSize - sizeof(header)];      // want total size to be 64 bytes
};

PacketData initializePacket(int &transmitted) {
    PacketData packet = {};

    packet.header.type = ICMP_ECHO;                 // set ICMP type to Echo
    packet.header.un.echo.id = getpid() & 0xFFFF;   // set id (ICMP field is 16 bits)
    packet.header.checksum = 0;                     // fixed checksum because data is unchanging
    packet.header.un.echo.sequence = transmitted++;

    // fill up message
    memset(&packet.message, '0', sizeof(packet.message));
    packet.message[PacketSize - sizeof(packet.header) - 1] = '\0';

    return packet;
}

'DestinationAddr' is this:

    // variables needed to store IP Address
    addrinfo* result;
    sockaddr_in* DestinationAddr;
    char ipString[INET_ADDRSTRLEN];

    // get IP Address and store in result (passed by reference)
    if (getIPAddress(argv[1], result) != 0) {
        std::cout << "Invalid IP Address. Terminating ...\n";
        exit(EXIT_FAILURE);
    }
    else {
        DestinationAddr = (sockaddr_in*)result->ai_addr;                        // get struct from resulting linked list
        void* address;
        address = &DestinationAddr->sin_addr;                                   // store IP Address
        inet_ntop(result->ai_family, address, ipString, sizeof(ipString));      // convert binary IP to string
        std::cout << "IP: " << ipString << std::endl;
    }

And the getIPAddress() function is:

int getIPAddress(char* hostName, addrinfo* &result) {
    addrinfo tempStruct = {0};

    tempStruct.ai_family = AF_INET;         // want IPv4
    tempStruct.ai_socktype = SOCK_DGRAM;    // set socket type to datagram
    tempStruct.ai_flags = AI_PASSIVE;       // fill in IP automatically

    // get and validate IP address
    return (getaddrinfo(hostName, &PortNo, &tempStruct, &result));
}

PortNo is defined as: const char PortNo = '0';

Body:
According to documentation icmp:

A user protocol may receive ICMP packets for all local sockets by opening a raw socket with the protocol IPPROTO_ICMP.

So, try creating your socket like that:

socket(AF_INET, SOCK_RAW, IPPROTO_ICMP)

And, if you encounter EPERM error, then run your program as root.


问:
Complex jquery selector that looks for a token in a string.split
I have an html table where one of the columns contains s with comma-delimited data.  I want to come up with a jQuery selector that returns all of the rows (
s are preferable, but the s will work for now) where one of the comma-delimited tokens  in a span tag matches a supplied string.

I started with something like the following:

```<code>$('td.col_8 span:contains("duck")')
</code>```

which will get me all spans in a particular column containing the word 'duck'.  However, it could also match fox, mallard-duck. Since 'duck' is not a unique token in that span, I wouldn't want that included in the match.

Is there a way to narrow my result set so I'm only including results where there's an exact match to a particular token in a column-delimited list?

(I'm using jQuery 1.2.3)

答:
I think this should do it

```<code>$('td.col_8 span').filter(function() {
    return $(this).text().match(/^duck$/);
});
</code>```

Now you just need to define the regex that you need, or implement a string split and array search to return a boolean value to indicate if the  should be included.

Body:
I have an html table where one of the columns contains s with comma-delimited data.  I want to come up with a jQuery selector that returns all of the rows (
s are preferable, but the s will work for now) where one of the comma-delimited tokens  in a span tag matches a supplied string.

I started with something like the following:

$('td.col_8 span:contains("duck")')

which will get me all spans in a particular column containing the word 'duck'.  However, it could also match fox, mallard-duck. Since 'duck' is not a unique token in that span, I wouldn't want that included in the match.

Is there a way to narrow my result set so I'm only including results where there's an exact match to a particular token in a column-delimited list?

(I'm using jQuery 1.2.3)

Body:
I think this should do it

$('td.col_8 span').filter(function() {
    return $(this).text().match(/^duck$/);
});

Now you just need to define the regex that you need, or implement a string split and array search to return a boolean value to indicate if the <span> should be included.


问:
Add value of the already existing key in dict in a form of container in Python
Is there any built-in function that would do the following?

```<code>dictionary = {‘a’:1, ‘b’:2, ‘c’:3}

dictionary.update(c=10)

# what happens
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:10}

# what I want to happen:
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:(3, 10)}
</code>```

By default if keys are the same, later key would override earlier one.
If the key is already present in dict, the value of the new key: value pair would be added to already existing value in a form of container, like tuple, or list or set.

I can write a helper function to do so but I believe it should be something built-in for this matter.

答:
You can do this

```<code>from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["b"].append(2)
d["c"].append(3)
d["c"].append(10)

print(d)
</code>```

Result

```<code>defaultdict(list, {'a': [1], 'b': [2], 'c': [3, 10]})
</code>```

Body:
Is there any built-in function that would do the following?

dictionary = {‘a’:1, ‘b’:2, ‘c’:3}

dictionary.update(c=10)

# what happens
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:10}

# what I want to happen:
dictionary  ---- {‘a’:1, ‘b’:2, ‘c’:(3, 10)}

By default if keys are the same, later key would override earlier one.
If the key is already present in dict, the value of the new key: value pair would be added to already existing value in a form of container, like tuple, or list or set.

I can write a helper function to do so but I believe it should be something built-in for this matter.

Body:
You can do this

from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["b"].append(2)
d["c"].append(3)
d["c"].append(10)

print(d)

Result

defaultdict(list, {'a': [1], 'b': [2], 'c': [3, 10]})


问:
Merge Separate Windows (and tabs within) into one in Sublime Text 3
On my mac, I work with a lot of tabs and windows in SublimeText 3. I often like to pull tabs out to create a new window but later, I want to be able to easily consolidate them.

Scenario: I have two SublimeText windows open, each with 5 tabs. Now, I'd like to merge all the tabs of window 2 into window 1 so I only have one remaining window with 10 tabs.

Chrome has a fabulous extension called Merge Windows that demonstrates this behavior perfectly.

How would I do this in SublimeText 3?

答:
[Not sure for other OS but for MAC it is easy and very useful]

In mac, open sublime,

```<code>click Window -> Click Merge all Windows
</code>```

Also make sure that this won't work if you just have one window open which is pretty obvious.

Body:
[Not sure for other OS but for MAC it is easy and very useful]

In mac, open sublime,

click Window -> Click Merge all Windows

Also make sure that this won't work if you just have one window open which is pretty obvious.


问:
What is the difference between types String and string?
Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?

```<code>var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!
</code>```

Current version of the compiler says:

```<code>Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object.
     Prefer using 'string' when possible.
</code>```

Is that a bug?

答:
For quick readers:

Don’t ever use the types Number, String, Boolean, Symbol, or Object. These types refer to non-primitive boxed objects that are almost never used appropriately in JavaScript code. (emphasis mine)

Source:
https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html

Body:
Does anyone know the difference between String and string in TypeScript? Am I correct in assuming that they ought to be the same?

var a: String = "test";
var b: string = "another test";
a = b;
b = a; // this gives a compiler error!

Current version of the compiler says:

Type 'String' is not assignable to type 'string'.
  'string' is a primitive, but 'String' is a wrapper object.
     Prefer using 'string' when possible.

Is that a bug?


问:
sap-cloud-sdk-pipeline_How to configure multiple productive branches in config.yml file?
I can trigger different branch for production deployment as I set it as productive branch in .pipeline/config.yml file as below:
general:
  collectTelemetryData: false
  productiveBranch: 'develop'

Question:
1. How I can set multiple branches as productive Branch in this file?
2. Is there a way for me to filter all feature branches from productive branch?

答:
To answer your question, I would like to understand more about your use case. How are the different "productive branches" different? How is the branching model? We designed the pipeline for a continuous deployment model where you either work with PRs to one branch (be it called master, trunk or develop), or directly commit on this branch.

There are two potential solutions for question 1

First, you can set different values for productive branch on different branches in the pipeline config file. Those branches are then treated equally, so each push on one of those branches triggers a deployment. Of course this has implications for diffs and PRs between those branches.

Second, you might consider extending the production deployment stage via an stage level extension. This provides more control over the workflow to you, you can fully customize the branch pattern you need, but it is more complex to do.

I don't understand your second question, but I think with what the pipeline has built in you can't do that. With an extension you're free to build whatever logic fits your purpose.

Please feel free to elaborate on your requirements. I can't promise anything, but we are always interested in understanding workflows we're not yet aware of to consider this in future design.

Kind regards


问:
Recycler view strange behaviour when height is match_parent
I am facing an strange behaviour now days. I am using view binding for refrencing ids. When RecyclerView height is wrap_content the item display perfectly but when I set recyclerview height match_parent the item width is automatically wrapped (wrap_content) in run time but in xml I have set item width is match_parent.

Please help me to solve this problem.

Please look at my xml and kt files -:

```<code><LinearLayou ------
 <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRvTrainerReview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>
</code>```

row_item

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/_1sdp"
    android:background="@color/colorWhite"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="@dimen/_10sdp">

    <TextView
        android:id="@+id/idTvDate"
        style="@style/MediumText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="14 feb"
        android:includeFontPadding="false"
        android:textColor="@color/colorBlack"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/idTvStartTime"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:gravity="center"
        android:includeFontPadding="false"
        android:text="19:30" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_right_arrow" />

</LinearLayout>

</code>```

adapter file -:

```<code>
class FeedbackDataAdapter(
    private var mcontext: Context,
    private var mItemList: MutableList<ResponseTrainerFeedback.Result.Training>,
    var mClickListener: OnClickListener?
) : RecyclerView.Adapter<TrainingDataViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrainingDataViewHolder {
       var layoutInflater =   mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as (LayoutInflater)
        val rowEventMemberBinding =
            RowEventDataBinding.inflate(layoutInflater, parent, false)
        return TrainingDataViewHolder(rowEventMemberBinding)
    }

    override fun getItemCount(): Int =  mItemList.size

    override fun onBindViewHolder(holder: TrainingDataViewHolder, position: Int) {
        holder.mBinding.idTvDate.text = mItemList[holder.adapterPosition].trainingName
        holder.mBinding.idTvStartTime.invisible()

        holder.itemView.setOnClickListener {
            if(mItemList.size > 0){
                mClickListener?.onItemClick(holder.adapterPosition)
            }
        }

    }

    fun refreshList(mFeedbackList: MutableList<ResponseTrainerFeedback.Result.Training>) {
        this.mItemList = mFeedbackList
        notifyDataSetChanged()
    }

}

class TrainingDataViewHolder(var mBinding: RowEventDataBinding) :
    RecyclerView.ViewHolder(mBinding.root) {

}
</code>```

答:
I've tried your code and It's working.

I've only refactored your adapter according to Android training and if you want to do the codelab: https://codelabs.developers.google.com/codelabs/kotlin-android-training-diffutil-databinding

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrainingDataViewHolder {
       return TrainingDataViewHolder.from(parent)
    }

    override fun getItemCount(): Int =  mItemList.size

    override fun onBindViewHolder(holder: TrainingDataViewHolder, position: Int) {
        holder.bind(mItemList[position])
        holder.itemView.setOnClickListener {
            if(mItemList.size > 0){
                mClickListener?.onItemClick(holder.adapterPosition)
            }
        }
    }

    fun refreshList(mFeedbackList: MutableList<ResponseTrainerFeedback.Result.Training>) {
        this.mItemList = mFeedbackList
        notifyDataSetChanged()
    }

}

class TrainingDataViewHolder(var mBinding: RowEventDataBinding) :
    RecyclerView.ViewHolder(mBinding.root) {

    fun bind(data: YOURDATA) {
        mBinding.idTv = data // it'll map automatically all the property, replace idTv by the name of your variable in your layout
        mBinding.idTvStartTime.invisible()
    }

    companion object {
        fun from(parent: ViewGroup): TrainingDataViewHolder {
            return TrainingDataViewHolder(RowEventDataBinding.inflate(LayoutInflater.from(parent.context), parent, false))
        }
    }

}
```

<p><strong>row_item</strong></p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>
        <variable
            name="idTv"
            type="package.name.to.data" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="1dp"
        android:background="@android:color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="10dp">

        <TextView
            android:id="@+id/idTvDate"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:text="@{idTv.idTvDate}"
            android:includeFontPadding="false"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            tools:text="14 feb"/>

        <TextView
            android:id="@+id/idTvStartTime"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:gravity="center"
            android:includeFontPadding="false"
            android:text="19:30" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/arrow_up_float" />

    </LinearLayout>
</layout>
</code>```

PS: I don't see <layout> in your row_item, are you sure you're doing binding correctly ?

Body:
I am facing an strange behaviour now days. I am using view binding for refrencing ids. When RecyclerView height is wrap_content the item display perfectly but when I set recyclerview height match_parent the item width is automatically wrapped (wrap_content) in run time but in xml I have set item width is match_parent.

Please help me to solve this problem.

Please look at my xml and kt files -:

<LinearLayou ------
 <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRvTrainerReview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>

row_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/_1sdp"
    android:background="@color/colorWhite"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="@dimen/_10sdp">

    <TextView
        android:id="@+id/idTvDate"
        style="@style/MediumText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="14 feb"
        android:includeFontPadding="false"
        android:textColor="@color/colorBlack"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/idTvStartTime"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="0.2"
        android:gravity="center"
        android:includeFontPadding="false"
        android:text="19:30" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_right_arrow" />

</LinearLayout>

adapter file -:

class FeedbackDataAdapter(
    private var mcontext: Context,
    private var mItemList: MutableList<ResponseTrainerFeedback.Result.Training>,
    var mClickListener: OnClickListener?
) : RecyclerView.Adapter<TrainingDataViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrainingDataViewHolder {
       var layoutInflater =   mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as (LayoutInflater)
        val rowEventMemberBinding =
            RowEventDataBinding.inflate(layoutInflater, parent, false)
        return TrainingDataViewHolder(rowEventMemberBinding)
    }

    override fun getItemCount(): Int =  mItemList.size

    override fun onBindViewHolder(holder: TrainingDataViewHolder, position: Int) {
        holder.mBinding.idTvDate.text = mItemList[holder.adapterPosition].trainingName
        holder.mBinding.idTvStartTime.invisible()

        holder.itemView.setOnClickListener {
            if(mItemList.size > 0){
                mClickListener?.onItemClick(holder.adapterPosition)
            }
        }

    }

    fun refreshList(mFeedbackList: MutableList<ResponseTrainerFeedback.Result.Training>) {
        this.mItemList = mFeedbackList
        notifyDataSetChanged()
    }

}

class TrainingDataViewHolder(var mBinding: RowEventDataBinding) :
    RecyclerView.ViewHolder(mBinding.root) {

}

Body:
I've tried your code and It's working.

I've only refactored your adapter according to Android training and if you want to do the codelab: https://codelabs.developers.google.com/codelabs/kotlin-android-training-diffutil-databinding

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TrainingDataViewHolder {
       return TrainingDataViewHolder.from(parent)
    }

    override fun getItemCount(): Int =  mItemList.size

    override fun onBindViewHolder(holder: TrainingDataViewHolder, position: Int) {
        holder.bind(mItemList[position])
        holder.itemView.setOnClickListener {
            if(mItemList.size > 0){
                mClickListener?.onItemClick(holder.adapterPosition)
            }
        }
    }

    fun refreshList(mFeedbackList: MutableList<ResponseTrainerFeedback.Result.Training>) {
        this.mItemList = mFeedbackList
        notifyDataSetChanged()
    }

}

class TrainingDataViewHolder(var mBinding: RowEventDataBinding) :
    RecyclerView.ViewHolder(mBinding.root) {

    fun bind(data: YOURDATA) {
        mBinding.idTv = data // it'll map automatically all the property, replace idTv by the name of your variable in your layout
        mBinding.idTvStartTime.invisible()
    }

    companion object {
        fun from(parent: ViewGroup): TrainingDataViewHolder {
            return TrainingDataViewHolder(RowEventDataBinding.inflate(LayoutInflater.from(parent.context), parent, false))
        }
    }

}

row_item

<?xml version="1.0" encoding="utf-8"?>
<layout>

    <data>
        <variable
            name="idTv"
            type="package.name.to.data" />
    </data>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="1dp"
        android:background="@android:color/white"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="10dp">

        <TextView
            android:id="@+id/idTvDate"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.8"
            android:text="@{idTv.idTvDate}"
            android:includeFontPadding="false"
            android:textColor="@android:color/black"
            android:textStyle="bold"
            tools:text="14 feb"/>

        <TextView
            android:id="@+id/idTvStartTime"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="0.2"
            android:gravity="center"
            android:includeFontPadding="false"
            android:text="19:30" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/arrow_up_float" />

    </LinearLayout>
</layout>

PS: I don't see <layout> in your row_item, are you sure you're doing binding correctly ?


问:
Woo-commerce Changing the default weight unit text from kg to kiloGrams and display kilograms in product page and in additional information
Hey I'm trying to change the weight unit text from kg to kiloGrams in additional information at product page but the code is working for Description string to change but not for working for kg text can't figure out why.

would be really great if anyone could suggest. Thanks.

```<code>add_filter( 'gettext', 'bbloomer_translate_woocommerce_strings', 999, 3 );

function bbloomer_translate_woocommerce_strings( $translated, $untranslated, $domain ) {

   if ( ! is_admin() && 'woocommerce' === $domain ) {

      switch ( $translated) {

         case 'g' :

            $translated = 'grams';
            break;

         case 'Description' :

            $translated = 'Product Specifications';
            break;

         // ETC

      }

   }

   return $translated;

}
</code>```

答:
// To update the units in woocommerce from g to grams or another

update_option( 'woocommerce_weight_unit', 'grams' );

Body:
Hey I'm trying to change the weight unit text from kg to kiloGrams in additional information at product page but the code is working for Description string to change but not for working for kg text can't figure out why.

would be really great if anyone could suggest. Thanks.

add_filter( 'gettext', 'bbloomer_translate_woocommerce_strings', 999, 3 );

function bbloomer_translate_woocommerce_strings( $translated, $untranslated, $domain ) {

   if ( ! is_admin() && 'woocommerce' === $domain ) {

      switch ( $translated) {

         case 'g' :

            $translated = 'grams';
            break;

         case 'Description' :

            $translated = 'Product Specifications';
            break;

         // ETC

      }

   }

   return $translated;

}


问:
bash script to find unique value in a file with index
I have a text file ,test.txt, like

```<code>shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg
</code>```

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

```<code>cbv
cfg
cvb
df
dfg
hgh
sdf
</code>```

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

```<code>cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3
</code>```

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

```<code>    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh
</code>```

Desired o/p same .
Thanks,
Ravi

答:
Try this command to print column with all original indexes:

```<code>awk '{k=tolower($2); arr[k]=arr[k] " " NR} END{for(v in arr) print v, arr[v]}' test.txt | sort -f -k 1,1
</code>```

OUTPUT

```<code>cbv  1 2
cfg  12
cvb  10
df  4 5 7 9
dfg  6 8
hgh  11
sdf  3
</code>```

Update: using awk only solution

```<code>awk '{k=tolower($2); arr[k]=arr[k] " " NR} END{n=asorti(arr, dest); for(i = 1; i <= n; i++) print dest[i], arr[dest[i]]}' test.txt
</code>```

Your file can have any number of columns but this command will only look at 2nd column.

Body:
I have a text file ,test.txt, like

shekhar cbv
ravi cbv
ravi sdf
asd df
ravi Df
ravi dfg
ravi df
ravi dfg
ravi df
afas cvb
sdf hgh
sasdg cfg

I want to sort based on 2nd field and want to write 2nd field only on "result.txt"
 Currently I am doing following:

sort -k 2,2 test.txt| uniq -i -f 1 | cut -d ' ' -f2 > result.txt

which is writing 2n field i.e.

cbv
cfg
cvb
df
dfg
hgh
sdf

Corresponding to every unique 2nd field value I want its,all, index in original file.
How this is possible ?

Desired Output:

cbv 1 2
cfg 12
cvb 10
df 4 5 7 9
dfg 6 8
hgh 11
sdf 3

One more thing if say there is 3rd field also. How to achieve the above only mean while sorting and finding uniqueness only 2nd field is used.

input With 3rd field

    shekhar cbv rg
    ravi cbv fdf
    ravi sdf dfh
    asd df dfhdfh
    ravi Df fgh
    ravi dfg dfh
    ravi df dfgh
    ravi dfg dfgh
    ravi df dfhg
    afas cvb fhfg
    sdf hgh cgfhfg
    sasdg cfg fgh

Desired o/p same .
Thanks,
Ravi

Body:
Try this command to print column with all original indexes:

awk '{k=tolower($2); arr[k]=arr[k] " " NR} END{for(v in arr) print v, arr[v]}' test.txt | sort -f -k 1,1

OUTPUT

cbv  1 2
cfg  12
cvb  10
df  4 5 7 9
dfg  6 8
hgh  11
sdf  3

Update: using awk only solution

awk '{k=tolower($2); arr[k]=arr[k] " " NR} END{n=asorti(arr, dest); for(i = 1; i <= n; i++) print dest[i], arr[dest[i]]}' test.txt

Your file can have any number of columns but this command will only look at 2nd column.


问:
Having trouble removing first and last character from urls in csv
I am getting the following error when using requests requests.exceptions.InvalidSchema: No connection adapters were found for'['https://www.example.com/contact/find..']' . So there are these two braces at the start and at the end of the links which I am reading from a csv file. These braces end up there because of this statement links_total.append('https://www.example.com'+cell_link['href']) . I am trying to slice the row before requests .Is not working. I used row = row[1:-1] which gives the following error requests.exceptions.InvalidURL: Failed to parse: []. I'd like to remove these braces.

```<code>try:
    with open('rt.csv', 'r') as read_obj:
      csv_reader = reader(read_obj)
      for row in csv_reader:
        row = row[1:-1]
        page2 = requests.get(row)
</code>```

This line is from a program I used to scrape these links to the csv file. links_total.append('https://www.example.com'+cell_link['href'])

答: I just tried with row = row[-1] and it worked.

Body:
I am getting the following error when using requests requests.exceptions.InvalidSchema: No connection adapters were found for'['https://www.example.com/contact/find..']' . So there are these two braces at the start and at the end of the links which I am reading from a csv file. These braces end up there because of this statement links_total.append('https://www.example.com'+cell_link['href']) . I am trying to slice the row before requests .Is not working. I used row = row[1:-1] which gives the following error requests.exceptions.InvalidURL: Failed to parse: []. I'd like to remove these braces.

try:
    with open('rt.csv', 'r') as read_obj:
      csv_reader = reader(read_obj)
      for row in csv_reader:
        row = row[1:-1]
        page2 = requests.get(row)

This line is from a program I used to scrape these links to the csv file. links_total.append('https://www.example.com'+cell_link['href'])


问:
Java 8 : how to extract a HashMap from a ArrayList of HashMap in Java 8 using streams?
I have the following sample result when I query a database :

```<code>dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]
</code>```

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

```<code>{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }
</code>```

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

```<code>
    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

</code>```

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

答:
As I don't know the type of Object you are using, so I am performing this on String. But it is valid for any type of object.

 HashMap result = (HashMap<String, HashMap<String, String>>) listOfHashMaps.stream()
               .collect(Collectors.toMap(e-> e.get("roll"),e->e));

```

As type casting will help you to achieve this.

Body:
I have the following sample result when I query a database :

dataList  = [{ name : name1, rollno: rollno1 }, { name : name2, rollno: rollno2 } ]

I want to convert this list of hashmaps into a single hashmap using Java 8 streams.
I tried using Collectors.toMap() but i am not sure how to refer to rollNo as key and the hashmap as the value inside the toMap method.

Exected output :

{ rollno1 : { name : name1, rollno: rollno1 } , rollno2 : { name : name2, rollno: rollno2 } }

I tried doing it using a for each loop on the list and then adding the rollno as key to a hashmap and the hashmap as value itself of that rollno.

    HashMap<String,HashMap<String,String>> newMap = new HashMap();

    for(HashMap<String,String> record : dataList){
        String key = record.get("rollno").toString();
        newMap.put(key,record);
    }

Is there a way to refactor this code using functional streams in Java 8?
Will using streams collect method give any performance advantage over the foreach for doing this?

Will appreciate any leads. Thanks

Body:
As I don't know the type of Object you are using, so I am performing this on String. But it is valid for any type of object.

 HashMap result = (HashMap<String, HashMap<String, String>>) listOfHashMaps.stream()
               .collect(Collectors.toMap(e-> e.get("roll"),e->e));

As type casting will help you to achieve this.


问:
Mock file with Jest
I can not create a json file with a mock with jest in node.js.

I tried this :

```<code>const mock = require('mock-fs');
mock({
    'test.json': [{ 'name':'John', 'age':30, 'car':null }]
});
</code>```

but that does not work, he does not like the arguments put in content for the file.

Do you have an idea of how? Thank's

答:
Modified the gist found above to be used in jest:

Add this to your jest.setup.js:

```<code>// mock file
class MockFile {
  constructor ({ name = 'mock.jpg', size = 1024, type = 'image/jpg', lastModified = new Date() }) {
    var blob = new Blob(['a'.repeat(size)], { type })
    blob.lastModifiedDate = lastModified

    return new File([blob], name)
  }
}

global.MockFile = MockFile
</code>```

Use it in your test like this:

```<code>const mockFile = new MockFile({
  name: 'testFile',
  type: 'image/jpg',
  size: 512
})
</code>```

Title: Mock file with Jest

Body:
I can not create a json file with a mock with jest in node.js.

I tried this :

const mock = require('mock-fs');
mock({
    'test.json': [{ 'name':'John', 'age':30, 'car':null }]
});

but that does not work, he does not like the arguments put in content for the file.

Do you have an idea of how? Thank's

Body:
Modified the gist found above to be used in jest:

Add this to your jest.setup.js:

// mock file
class MockFile {
  constructor ({ name = 'mock.jpg', size = 1024, type = 'image/jpg', lastModified = new Date() }) {
    var blob = new Blob(['a'.repeat(size)], { type })
    blob.lastModifiedDate = lastModified

    return new File([blob], name)
  }
}

global.MockFile = MockFile

Use it in your test like this:

const mockFile = new MockFile({
  name: 'testFile',
  type: 'image/jpg',
  size: 512
})


问:
oracle sql to convert timestamp to date
i have to convert different timezone string to date. in my table, i have column defined as varchar2. which contains data as below. i need to convert to one time zone(exampple to central time) and extract date from that. i tried different ways but getting invalid month error or not date. ANy suggestions from your end?</p>

```<code>1/16/2020 6:28:44 AM -08:00
11/8/2019 3:20:30 AM -05:00
10/25/2019 6:08:21 PM +05:30
</code>```

答:
I believe you first need to convert it to timestamp with timezone ad then cast it to date:

```<code>select CAST(to_timestamp_tz (dat_col, 'MM/DD/YYYY HH12:MI:SS AM TZH:TZM' ) AS DATE)
from test
</code>```

here is a demo

This will turn your data into specific timezone :

```<code>select
to_timestamp_tz(dat_col, 'MM/DD/YYYY HH12:MI:SS AM TZH:TZM')at time zone 'Europe/Moscow'
from test
</code>```

Then you can cast that :

```<code>select
CAST
(to_timestamp_tz(dat_col, 'MM/DD/YYYY HH12:MI:SS AM TZH:TZM')at time zone 'Europe/Moscow'
AS DATE)
from test
</code>```

Please provide your expected results for more accurate code...

Title: oracle sql to convert timestamp to date

Body:
i have to convert different timezone string to date. in my table, i have column defined as varchar2. which contains data as below. i need to convert to one time zone(exampple to central time) and extract date from that. i tried different ways but getting invalid month error or not date. ANy suggestions from your end?

1/16/2020 6:28:44 AM -08:00
11/8/2019 3:20:30 AM -05:00
10/25/2019 6:08:21 PM +05:30

Body:
I believe you first need to convert it to timestamp with timezone ad then cast it to date:

select CAST(to_timestamp_tz (dat_col, 'MM/DD/YYYY HH12:MI:SS AM TZH:TZM' ) AS DATE)
from test

here is a demo

This will turn your data into specific timezone :

select
to_timestamp_tz(dat_col, 'MM/DD/YYYY HH12:MI:SS AM TZH:TZM')at time zone 'Europe/Moscow'
from test

Then you can cast that :

select
CAST
(to_timestamp_tz(dat_col, 'MM/DD/YYYY HH12:MI:SS AM TZH:TZM')at time zone 'Europe/Moscow'
AS DATE)
from test

Please provide your expected results for more accurate code...


问:
Avoiding duplicate deletion in python regex
I am removing lines from a bunch of txt files using regex using Python; however, I came across a case where it sometimes does a duplicate deletion if the line contains a string fairly similar to the first one

```<code>s = 'market.fruit.apple'
</code>```

The txt file might contain the following lines

```<code>market.fruit.apple
market.fruit.apple.all
</code>```

But if I run

```<code>open_file = open('test.txt', 'r')
read_file = open_file.read()
r = re.compile(r"(?<!\S){0}.*(?:[\r\n]\s*)?".format(s))
read_file = r.sub('',read_file)
write_file = open('test.txt', 'w')
write_file.write(read_file)
</code>```

it removes both market.fruit.apple and market.fruit.apple.all when only the first one should be removed. How do I avoid it? I tried setting the count parameter to 1 but that didn't do anything. I was thinking of doing a string similarity between the strings and use a different regex if it matches the right condition but I figured this might be unneccesary overhead if I scale this up.

Edit: Corrected some typos in the example above, can be repro in regex101.com/r/q7qWVh/1

答:
There are a couple of problems with this RegEx. First, the dot in your string is interpreted as the "any single character" token, not the literal dot. It needs to be escaped with a backslash: \.. Next, the non-capturing group in the end to match whitespace is optional, and the .* before it will just continue matching characters until it finds a new line. I also don't understand the purpose of the first negative lookbehind.

As to how to fix it, here is my suggestion:

1- If you need to compare the line with a string literal and you are not using any of the RegEx features, you can just read the lines and filter them as such:

lines = open_file.readlines()
lines = [line for line in lines if line != s]
```

2- If you need it in Regex, you can simply replace the non-capturing groups with ^ and $, signifying start and end of line, respectively. The new RegEx will be ^market\.fruit\.apple$, and you can see it in action here: https://regex101.com/r/pi7Wjw/1/

Make sure to also check the re library documentation for more info about how to use the various special symbols.

Body:
I am removing lines from a bunch of txt files using regex using Python; however, I came across a case where it sometimes does a duplicate deletion if the line contains a string fairly similar to the first one

s = 'market.fruit.apple'

The txt file might contain the following lines

market.fruit.apple
market.fruit.apple.all

But if I run

open_file = open('test.txt', 'r')
read_file = open_file.read()
r = re.compile(r"(?<!\S){0}.*(?:[\r\n]\s*)?".format(s))
read_file = r.sub('',read_file)
write_file = open('test.txt', 'w')
write_file.write(read_file)

it removes both market.fruit.apple and market.fruit.apple.all when only the first one should be removed. How do I avoid it? I tried setting the count parameter to 1 but that didn't do anything. I was thinking of doing a string similarity between the strings and use a different regex if it matches the right condition but I figured this might be unneccesary overhead if I scale this up.

Edit: Corrected some typos in the example above, can be repro in regex101.com/r/q7qWVh/1

Body:
There are a couple of problems with this RegEx. First, the dot in your string is interpreted as the "any single character" token, not the literal dot. It needs to be escaped with a backslash: \.. Next, the non-capturing group in the end to match whitespace is optional, and the .* before it will just continue matching characters until it finds a new line. I also don't understand the purpose of the first negative lookbehind.

As to how to fix it, here is my suggestion:

1- If you need to compare the line with a string literal and you are not using any of the RegEx features, you can just read the lines and filter them as such:

lines = open_file.readlines()
lines = [line for line in lines if line != s]

2- If you need it in Regex, you can simply replace the non-capturing groups with ^ and $, signifying start and end of line, respectively. The new RegEx will be ^market\.fruit\.apple$, and you can see it in action here: https://regex101.com/r/pi7Wjw/1/

Make sure to also check the re library documentation for more info about how to use the various special symbols.


问:
How to set the size for each ion-popover
I have more than one ion-popover.I want to set the size for everyone.I researched this problem and I tried everything and I couldn't. However, I succeded to change the size globally, in variables.scss, but not individually. Does anyone know how to set every ion-popover? P.s I am using ionic 5 with angular

Here is only what I could have done, changing globally.
This I added in variables.scss

```<code>    ion-popover {
  .popover-wrapper {
   .popover-content {
     width: fit-content;
   }
  }
}
</code>```

答:
ion-popover has a property called cssClass. You can assign unique class to each one and then target it from anywhere as mentioned here.

```<code> async presentPopover(ev: any) {
    const popover = await this.popoverController.create({
      component: PopoverComponent,
      cssClass: 'my-custom-class',
      event: ev,
      translucent: true
    });
    return await popover.present();
  }
</code>```

Now you can do something like following (Notice &.my-custom-class):

```<code>ion-popover {
&.my-custom-class {
  .popover-wrapper {
   .popover-content {
     width: fit-content;
   }
  }
}
}
</code>```

Body:
I have more than one ion-popover.I want to set the size for everyone.I researched this problem and I tried everything and I couldn't. However, I succeded to change the size globally, in variables.scss, but not individually. Does anyone know how to set every ion-popover? P.s I am using ionic 5 with angular

Here is only what I could have done, changing globally.
This I added in variables.scss

    ion-popover {
  .popover-wrapper {
   .popover-content {
     width: fit-content;
   }
  }
}

Body:
ion-popover has a property called cssClass. You can assign unique class to each one and then target it from anywhere as mentioned here.

 async presentPopover(ev: any) {
    const popover = await this.popoverController.create({
      component: PopoverComponent,
      cssClass: 'my-custom-class',
      event: ev,
      translucent: true
    });
    return await popover.present();
  }

Now you can do something like following (Notice &.my-custom-class):

ion-popover {
&.my-custom-class {
  .popover-wrapper {
   .popover-content {
     width: fit-content;
   }
  }
}
}