问:
python script removes file extension
I have some video files

```<code>A Single Man (2009).avi
Accident (2009).mkv
Adventureland (2009).mp4
</code>```

I use a python script that rename in this way

```<code>A Single Man (2009) [Drama]
Accident (2009) [Thriller]
Adventureland (2009) [Comedy]
</code>```

What is the problem ? Script removes file extension. I don't understand why

Part 1 : the function makes an API request to TMDb to search for a movie with the specified name and year, using the supplied API key. If the request was successful, it extracts the movie data from the response.

```<code>import os
import re
import requests

# Replace "YOUR_API_KEY" with your TMDb API key
api_key = 'My Api KEY'

# Let's create a function to get the movie ID from TMDb
def get_movie_id(name, year):
  # We encode the name of the movie to insert it in the URL
  name_encoded = requests.utils.quote(name)

  # We build the URL of the API request
  url = f'https://api.themoviedb.org/3/search/movie?api_key={api_key}&query={name_encoded}&year={year}'

  # We send the API request
  response = requests.get(url)

  # We verify that the request was successful
  if response.status_code == 200:
    # We extract the movie data from the response
    data = response.json()
</code>```

Part 2: after getting the search results from the API request response, the code checks that there are search results. If there are, it takes the first movie of the search results and extracts the movie ID from it. Then, it returns the movie ID. If there are no search results or if the API request was unsuccessful, the function returns None.

```<code>    # We verify that there are search results
    if data['total_results'] > 0:
      # Let's take the first movie of the search results
      movie = data['results'][0]

      # We extract the movie ID from the data
      movie_id = movie['id']

      return movie_id
    else:
      return None
  else:
    return None
</code>```

Part 3: this code defines a function called get_movie_genre that takes one argument movie_id, which represents the ID of a movie. The function then makes an API request to TMDb to get the movie data with the specified ID, using the supplied API key. If the request is successful, it extracts the film genre from the obtained data and returns it. If the request was unsuccessful, the function returns None.

```<code># Let's create a function to get the movie genre from TMDb
def get_movie_genre(movie_id):
  # We build the URL of the API request
  url = f'https://api.themoviedb.org/3/movie/{movie_id}?api_key={api_key}'

  # We send the API request
  response = requests.get(url)

  # We verify that the request was successful
  if response.status_code == 200:
    # We extract the movie data from the response
    data = response.json()

    # We extract the film genre from the data
    genre = data['genres'][0]['name']

    return genre
  else:
    return None
</code>```

Part 4: this code is a loop that iterates through all the files in the current directory. For each file, the code checks that it is a video file (ending in .avi or .mp4). If the file is a video, the code extracts the movie name and year from the filename using a regular expression. Then, the code looks up the movie on TMDb using the get_movie_id function we saw earlier.

If the movie is found, the code gets the genre of the movie using the get_movie_genre function we saw earlier. If the genre is found, the code constructs a new filename using the movie name, year, and genre. If the new name doesn't already exist, the code prints the old file name and the new computed name. Finally, the code renames the file to the new name.

```<code># We loop over the files in the directory
for file in os.listdir():
  # We verify that the file is a video file
  if file.endswith('.avi') or file.endswith('.mp4'):
    # We extract the movie name and year from the file name
    match = re.search(r'(.*) \(((?:19|20)\d\d)\)', file)

    name = match.group(1)
    year = match.group(2)

    # We search for the movie on TMDb
    movie_id = get_movie_id(name, year)

    # We verify that the movie has been found
    if movie_id:
      # We get the genre of the film
      genre = get_movie_genre(movie_id)

      # Let's verify that the genus has been found
      if genre:
        # Let's construct the new file name
        new_name = f'{name} ({year}) [{genre}]'

        # We check if a file with the new name already exists
        if not os.path.exists(new_name):
          # Stampa il nome del file e il nuovo nome calcolato
          print(f'{file} -> {new_name}')

    # Let's rename the file
    os.rename(file, new_name)
</code>```

Title: python script removes file extension

Body:
I have some video files

A Single Man (2009).avi
Accident (2009).mkv
Adventureland (2009).mp4

I use a python script that rename in this way

A Single Man (2009) [Drama]
Accident (2009) [Thriller]
Adventureland (2009) [Comedy]

What is the problem ? Script removes file extension. I don't understand why

Part 1 : the function makes an API request to TMDb to search for a movie with the specified name and year, using the supplied API key. If the request was successful, it extracts the movie data from the response.

import os
import re
import requests

# Replace "YOUR_API_KEY" with your TMDb API key
api_key = 'My Api KEY'

# Let's create a function to get the movie ID from TMDb
def get_movie_id(name, year):
  # We encode the name of the movie to insert it in the URL
  name_encoded = requests.utils.quote(name)

  # We build the URL of the API request
  url = f'https://api.themoviedb.org/3/search/movie?api_key={api_key}&query={name_encoded}&year={year}'

  # We send the API request
  response = requests.get(url)

  # We verify that the request was successful
  if response.status_code == 200:
    # We extract the movie data from the response
    data = response.json()

Part 2: after getting the search results from the API request response, the code checks that there are search results. If there are, it takes the first movie of the search results and extracts the movie ID from it. Then, it returns the movie ID. If there are no search results or if the API request was unsuccessful, the function returns None.

    # We verify that there are search results
    if data['total_results'] > 0:
      # Let's take the first movie of the search results
      movie = data['results'][0]

      # We extract the movie ID from the data
      movie_id = movie['id']

      return movie_id
    else:
      return None
  else:
    return None

Part 3: this code defines a function called get_movie_genre that takes one argument movie_id, which represents the ID of a movie. The function then makes an API request to TMDb to get the movie data with the specified ID, using the supplied API key. If the request is successful, it extracts the film genre from the obtained data and returns it. If the request was unsuccessful, the function returns None.

# Let's create a function to get the movie genre from TMDb
def get_movie_genre(movie_id):
  # We build the URL of the API request
  url = f'https://api.themoviedb.org/3/movie/{movie_id}?api_key={api_key}'

  # We send the API request
  response = requests.get(url)

  # We verify that the request was successful
  if response.status_code == 200:
    # We extract the movie data from the response
    data = response.json()

    # We extract the film genre from the data
    genre = data['genres'][0]['name']

    return genre
  else:
    return None

Part 4: this code is a loop that iterates through all the files in the current directory. For each file, the code checks that it is a video file (ending in .avi or .mp4). If the file is a video, the code extracts the movie name and year from the filename using a regular expression. Then, the code looks up the movie on TMDb using the get_movie_id function we saw earlier.

If the movie is found, the code gets the genre of the movie using the get_movie_genre function we saw earlier. If the genre is found, the code constructs a new filename using the movie name, year, and genre. If the new name doesn't already exist, the code prints the old file name and the new computed name. Finally, the code renames the file to the new name.

# We loop over the files in the directory
for file in os.listdir():
  # We verify that the file is a video file
  if file.endswith('.avi') or file.endswith('.mp4'):
    # We extract the movie name and year from the file name
    match = re.search(r'(.*) \(((?:19|20)\d\d)\)', file)

    name = match.group(1)
    year = match.group(2)

    # We search for the movie on TMDb
    movie_id = get_movie_id(name, year)

    # We verify that the movie has been found
    if movie_id:
      # We get the genre of the film
      genre = get_movie_genre(movie_id)

      # Let's verify that the genus has been found
      if genre:
        # Let's construct the new file name
        new_name = f'{name} ({year}) [{genre}]'

        # We check if a file with the new name already exists
        if not os.path.exists(new_name):
          # Stampa il nome del file e il nuovo nome calcolato
          print(f'{file} -> {new_name}')

    # Let's rename the file
    os.rename(file, new_name)


来源: stackexchange

问:
Third container stuck on starting and HNS hangs on Windows Server 2022
Previously I had a Windows Server 2019 and I could start hundreds of containers without any issue.
Now I'm trying to renew my environment with a Windows Server 2022 Datacenter.

I have 3 copies of docker-compose.ymls. Each has a exposed port as follows:

```<code>version: '3.8'
services:
  web:
    image: "mcr.microsoft.com/windows/nanoserver:ltsc2022"
    ports:
      - "4604:80"
    command: "ping 4.2.2.4 -t"
</code>```

The exposed ports are different on each yml so there is no conflict.

First container starts, Second container start but when staring the THIRD container, the Host Network Service (HNS) comes up in TaskManager, taking 20-30% of CPU and container stuck on starting and nothing happens after this.

I tried several scenarios to reach the simplest way to reproduce this error. The key point is exposing ports on containers. Without exposing ports I can start multiple containers.

What is the difference between networking defaults in Windows Server 2019 and 2022?

Should I start some windows services on 2022?

ContentLicense: CC BY-SA 4.0

Body:
Previously I had a Windows Server 2019 and I could start hundreds of containers without any issue.
Now I'm trying to renew my environment with a Windows Server 2022 Datacenter.

I have 3 copies of docker-compose.ymls. Each has a exposed port as follows:

version: '3.8'
services:
  web:
    image: "mcr.microsoft.com/windows/nanoserver:ltsc2022"
    ports:
      - "4604:80"
    command: "ping 4.2.2.4 -t"

The exposed ports are different on each yml so there is no conflict.

First container starts, Second container start but when staring the THIRD container, the Host Network Service (HNS) comes up in TaskManager, taking 20-30% of CPU and container stuck on starting and nothing happens after this.

I tried several scenarios to reach the simplest way to reproduce this error. The key point is exposing ports on containers. Without exposing ports I can start multiple containers.

What is the difference between networking defaults in Windows Server 2019 and 2022?

Should I start some windows services on 2022?


问:
How can I add methods to floats and integers?
I am trying to make a game that has collision in python (not pygame) I need to add the width of a turtle to the xcor of another. But the xcor of the other turtle is classified as a method. This prevents me of doing what i need to do.

I tried the following:

```<code>if enemy.xcor == player.xcor or enemy.xcor == **player.xcor + player.width or enemy.xcor == player.xcor**
</code>```

All I got was:

```<code>
 if missile.xcor == sleigh.xcor or missile.xcor == sleighX + width_ or missile.xcor == sleighX - width_:
                                                      ~~~~~~~~^~~~~~~~
TypeError: unsupported operand type(s) for +: 'method' and 'method'

</code>```

Is there any way I can get around this?

Body:
I am trying to make a game that has collision in python (not pygame) I need to add the width of a turtle to the xcor of another. But the xcor of the other turtle is classified as a method. This prevents me of doing what i need to do.

I tried the following:

if enemy.xcor == player.xcor or enemy.xcor == **player.xcor + player.width or enemy.xcor == player.xcor**

All I got was:

 if missile.xcor == sleigh.xcor or missile.xcor == sleighX + width_ or missile.xcor == sleighX - width_:
                                                      ~~~~~~~~^~~~~~~~
TypeError: unsupported operand type(s) for +: 'method' and 'method'

Is there any way I can get around this?


问:
how to rename variables of language in code blocks in markdown with javascript or python
can anyone recommend a way to write a function that I can pass in code blocks that are defined as follows in javascript:

```<code>const someMarkdown = "non code stuff blah blah \n
\```
const oldVar = 5;
oldVar *= 10;
const stringWithVarName = 'oldVar';
\```
other non code stuff"
</code>```

and call something like renameVariable(someMarkdown, oldVar, 'newVar') that will return the following:

```<code>"non code stuff blah blah \n
\```
const newVar = 5;
newVar *= 10;
const stringWithVarName = 'oldVar';
\```
other non code stuff"
</code>```

Body:
can anyone recommend a way to write a function that I can pass in code blocks that are defined as follows in javascript:

const someMarkdown = "non code stuff blah blah \n
\```
const oldVar = 5;
oldVar *= 10;
const stringWithVarName = 'oldVar';
\```
other non code stuff"

and call something like renameVariable(someMarkdown, oldVar, 'newVar') that will return the following:

"non code stuff blah blah \n
\```
const newVar = 5;
newVar *= 10;
const stringWithVarName = 'oldVar';
\```
other non code stuff"


问:
WPF MEF Plugin As Page?
I am building an application and this is my first experience with extensibility, plugins or addons, so I'm really new to this.

Using a tutorial from here I've built what I believe is a suitable interface and importer (both below), but I am unsure on how exactly to build the plugins themselves, as building them as pages in separate solutions will build them into a separate application, not provide the separate compiled page files.

Can someone either provide me with a basic example of a WPF application with external addon Pages or provide me with a link to a suitable source? I have had absolutely no luck finding anything like this.

Interface:

```<code>internal interface PORTaddon
{
    public string Name { get; }
    public Page PageReference { get; }
    void Setup();
}
</code>```

Importer:

```<code>if (!Directory.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Addons")))
        {
            Directory.CreateDirectory(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Addons"));
        }

        //Get Addons path & contents
        string addonPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Addons");
        DirectoryCatalog catalog = new DirectoryCatalog(addonPath);
        CompositionContainer container = new CompositionContainer(catalog);

        //Addons importer
        IEnumerable<PORTaddon> addons = container.GetExportedValues<PORTaddon>();
</code>```

Title: WPF MEF Plugin As Page?

Body:
I am building an application and this is my first experience with extensibility, plugins or addons, so I'm really new to this.

Using a tutorial from here I've built what I believe is a suitable interface and importer (both below), but I am unsure on how exactly to build the plugins themselves, as building them as pages in separate solutions will build them into a separate application, not provide the separate compiled page files.

Can someone either provide me with a basic example of a WPF application with external addon Pages or provide me with a link to a suitable source? I have had absolutely no luck finding anything like this.

Interface:

internal interface PORTaddon
{
    public string Name { get; }
    public Page PageReference { get; }
    void Setup();
}

Importer:

if (!Directory.Exists(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Addons")))
        {
            Directory.CreateDirectory(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Addons"));
        }

        //Get Addons path & contents
        string addonPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Addons");
        DirectoryCatalog catalog = new DirectoryCatalog(addonPath);
        CompositionContainer container = new CompositionContainer(catalog);

        //Addons importer
        IEnumerable<PORTaddon> addons = container.GetExportedValues<PORTaddon>();


问:
How to approximate the convex hull of a curved letter to a quadrilateral?
I have an input image such as:

Which will turn out after being preprocessed as:

Now, this image is a little bit inclined and what I want to do is to fix it with cv2.warpPerspective().

So, in order to do that, I generate a quadrilateral approximating (with cv2.approxPolyDP()) the convex hull. This is the actual code that I use:

hull = cv2.convexHull(contour)

# Reduce to quadrilateral
epsilon = 0.1 * cv2.arcLength(hull, True)
approximated = cv2.approxPolyDP(hull, epsilon, True)
```
<p>The convex hull of that preprocessed image looks like this:
<img src="https://i.stack.imgur.com/DV7kv.png" alt="enter image description here" /></p>
<p>But, when I approximate it, I get the following results:
<img src="https://i.stack.imgur.com/5TbRi.png" alt="enter image description here" /></p>
<p>What I want to achieve is something like this:
<img src="https://i.stack.imgur.com/3utea.png" alt="enter image description here" /></p>
<p>Here's an example on how it works with a letter without curves:
<img src="https://i.stack.imgur.com/lnV9W.png" alt="enter image description here" /></p>
<p>Which will get transformed into:</p>
<p><img src="https://i.stack.imgur.com/64Tzo.png" alt="enter image description here" /></p>
<p>In short, the issue lays when approximating the convex hull to a quadrilateral.
How can I achieve such quadrilateral on a letter with curves?</p>
<p>Here's the full code that I have written to do that:</p>
<pre class="lang-py prettyprint-override"><code>def _perspective_fix_convex_hull(self):
    # RETR_TREE retrieves all of the contours and reconstructs a full hierarchy of nested contours
    # used for maximum accuracy (my deduction)
    contours, _ = cv2.findContours(self.preprocessed_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # Draw all contours to a new image
    self.image_contours = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)
    cv2.drawContours(self.image_contours, contours, -1, (0, 255, 0), 2)

    self.convex_hulls_contours = []
    self.approximated_contours = []
    for contour in contours:
        # Get contour area

        area = cv2.contourArea(contour)
        if area < 200:
            # Too small for a letter
            continue

        image = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)

        hull = cv2.convexHull(contour)
        cv2.drawContours(image, [hull], -1, (0, 255, 0), 2)

        self.convex_hulls_contours.append(image)

        # Reduce to quadrilateral
        epsilon = 0.1 * cv2.arcLength(hull, True)
        approximated = cv2.approxPolyDP(hull, epsilon, True)

        # Draw approximated contour
        image = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)
        cv2.drawContours(image, [approximated], -1, (255, 0, 0), 1)

        self.approximated_contours.append(image)

        if len(approximated) == 4:
            image = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)
            cv2.drawContours(image, [approximated], -1, (0, 0, 255), 2)

            self.final_contour = image

            letter_hull = [a[0] for a in approximated] # Remove extra dimension [[x, y]] -> [x, y]
            break

    # Create placeholder for rectangle points
    rectangle = np.zeros((4, 2), dtype="float32")

    # Top-left point has smallest sum
    # Bottom-right point has largest sum
    # sum = x + y
    s = np.sum(letter_hull, axis=1)
    rectangle[0] = letter_hull[np.argmin(s)]
    rectangle[2] = letter_hull[np.argmax(s)]

    # Top-right point has smallest difference
    # Bottom-left point has largest difference
    # difference = x - y
    d = np.diff(letter_hull, axis=1)
    rectangle[1] = letter_hull[np.argmin(d)]
    rectangle[3] = letter_hull[np.argmax(d)]

    # Compute width and height of new image based on points
    (top_left, top_right, bottom_right, bottom_left) = rectangle

    # Width may be either top-right to top-left or bottom-right to bottom-left
    # TL;DR: Pythagorean theorem
    width_top = np.sqrt(((top_right[0] - top_left[0]) ** 2) + ((top_right[1] - top_left[1]) ** 2))
    width_bottom = np.sqrt(((bottom_right[0] - bottom_left[0]) ** 2) + ((bottom_right[1] - bottom_left[1]) ** 2))
    width = max(int(width_top), int(width_bottom))

    # Height may be either top-right to bottom-right or top-left to bottom-left
    # TL;DR: Pythagorean theorem
    height_right = np.sqrt(((top_right[0] - bottom_right[0]) ** 2) + ((top_right[1] - bottom_right[1]) ** 2))
    height_left = np.sqrt(((top_left[0] - bottom_left[0]) ** 2) + ((top_left[1] - bottom_left[1]) ** 2))
    height = max(int(height_right), int(height_left))

    # Create destination points
    destination = np.array([
        [0, 0],
        [width - 1, 0],
        [width - 1, height - 1],
        [0, height - 1]
    ], dtype="float32")

    # Compute perspective transform matrix
    matrix = cv2.getPerspectiveTransform(rectangle, destination)
    warped = cv2.warpPerspective(self.preprocessed_image, matrix, (width, height))

    # Add padding
    self.warped_image = cv2.copyMakeBorder(warped, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=(0, 0, 0))
</code>```

Body:
I have an input image such as:

Which will turn out after being preprocessed as:

Now, this image is a little bit inclined and what I want to do is to fix it with cv2.warpPerspective().

So, in order to do that, I generate a quadrilateral approximating (with cv2.approxPolyDP()) the convex hull. This is the actual code that I use:

hull = cv2.convexHull(contour)

# Reduce to quadrilateral
epsilon = 0.1 * cv2.arcLength(hull, True)
approximated = cv2.approxPolyDP(hull, epsilon, True)

The convex hull of that preprocessed image looks like this:

But, when I approximate it, I get the following results:

What I want to achieve is something like this:

Here's an example on how it works with a letter without curves:

Which will get transformed into:

In short, the issue lays when approximating the convex hull to a quadrilateral.
How can I achieve such quadrilateral on a letter with curves?

Here's the full code that I have written to do that:

def _perspective_fix_convex_hull(self):
    # RETR_TREE retrieves all of the contours and reconstructs a full hierarchy of nested contours
    # used for maximum accuracy (my deduction)
    contours, _ = cv2.findContours(self.preprocessed_image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # Draw all contours to a new image
    self.image_contours = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)
    cv2.drawContours(self.image_contours, contours, -1, (0, 255, 0), 2)

    self.convex_hulls_contours = []
    self.approximated_contours = []
    for contour in contours:
        # Get contour area

        area = cv2.contourArea(contour)
        if area < 200:
            # Too small for a letter
            continue

        image = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)

        hull = cv2.convexHull(contour)
        cv2.drawContours(image, [hull], -1, (0, 255, 0), 2)

        self.convex_hulls_contours.append(image)

        # Reduce to quadrilateral
        epsilon = 0.1 * cv2.arcLength(hull, True)
        approximated = cv2.approxPolyDP(hull, epsilon, True)

        # Draw approximated contour
        image = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)
        cv2.drawContours(image, [approximated], -1, (255, 0, 0), 1)

        self.approximated_contours.append(image)

        if len(approximated) == 4:
            image = cv2.cvtColor(self.preprocessed_image, cv2.COLOR_GRAY2BGR)
            cv2.drawContours(image, [approximated], -1, (0, 0, 255), 2)

            self.final_contour = image

            letter_hull = [a[0] for a in approximated] # Remove extra dimension [[x, y]] -> [x, y]
            break

    # Create placeholder for rectangle points
    rectangle = np.zeros((4, 2), dtype="float32")

    # Top-left point has smallest sum
    # Bottom-right point has largest sum
    # sum = x + y
    s = np.sum(letter_hull, axis=1)
    rectangle[0] = letter_hull[np.argmin(s)]
    rectangle[2] = letter_hull[np.argmax(s)]

    # Top-right point has smallest difference
    # Bottom-left point has largest difference
    # difference = x - y
    d = np.diff(letter_hull, axis=1)
    rectangle[1] = letter_hull[np.argmin(d)]
    rectangle[3] = letter_hull[np.argmax(d)]

    # Compute width and height of new image based on points
    (top_left, top_right, bottom_right, bottom_left) = rectangle

    # Width may be either top-right to top-left or bottom-right to bottom-left
    # TL;DR: Pythagorean theorem
    width_top = np.sqrt(((top_right[0] - top_left[0]) ** 2) + ((top_right[1] - top_left[1]) ** 2))
    width_bottom = np.sqrt(((bottom_right[0] - bottom_left[0]) ** 2) + ((bottom_right[1] - bottom_left[1]) ** 2))
    width = max(int(width_top), int(width_bottom))

    # Height may be either top-right to bottom-right or top-left to bottom-left
    # TL;DR: Pythagorean theorem
    height_right = np.sqrt(((top_right[0] - bottom_right[0]) ** 2) + ((top_right[1] - bottom_right[1]) ** 2))
    height_left = np.sqrt(((top_left[0] - bottom_left[0]) ** 2) + ((top_left[1] - bottom_left[1]) ** 2))
    height = max(int(height_right), int(height_left))

    # Create destination points
    destination = np.array([
        [0, 0],
        [width - 1, 0],
        [width - 1, height - 1],
        [0, height - 1]
    ], dtype="float32")

    # Compute perspective transform matrix
    matrix = cv2.getPerspectiveTransform(rectangle, destination)
    warped = cv2.warpPerspective(self.preprocessed_image, matrix, (width, height))

    # Add padding
    self.warped_image = cv2.copyMakeBorder(warped, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=(0, 0, 0))


问:
Responsive picture on day Christmas day
how can i make this responsive

```<code> <!--
 var picture='';
 mytime=new Date();
 mymonth=mytime.getMonth()+1;
 mydate=mytime.getDate();
 if (mymonth==12 && mydate==25){picture="<img src=http://numanme.co.uk/numanme-site/images/christmas/merry-christmas.jpg>";
 }
 //-->
 document.write(picture);
 </script>
</code>```

Tried every thing i can think of

Title: Responsive picture on day Christmas day

Body:
how can i make this responsive

 document.write(picture);
 </script>

Tried every thing i can think of


问:
GraphQL: Multi-staged query and reuse response from previous stages
I have some GQL queries that depend on their execution on other queries. I am looking for the idiomatic way to do it using GQL syntax.
I have for example two queries, "address" and "contact", each of which requires a token value. This value is retrieved from another query, "info". See below:

```<code>query($request: TokenRequest!)  {
    info(request: $request) {
      token
    }
}

query($query: InfoQuery!, $token: String)  {
    address(query: $query) {
      response
    }
    contact  {
      email
    }
}
</code>```

Instead of having two separate calls, is there a way to make all of these calls in one place instead of two? This will also require reusing the value gotten from "info" in order for the ither queries to work.

Body:
I have some GQL queries that depend on their execution on other queries. I am looking for the idiomatic way to do it using GQL syntax.
I have for example two queries, "address" and "contact", each of which requires a token value. This value is retrieved from another query, "info". See below:

query($request: TokenRequest!)  {
    info(request: $request) {
      token
    }
}

query($query: InfoQuery!, $token: String)  {
    address(query: $query) {
      response
    }
    contact  {
      email
    }
}

Instead of having two separate calls, is there a way to make all of these calls in one place instead of two? This will also require reusing the value gotten from "info" in order for the ither queries to work.


问:
Flutter Main ListView Won't Respond to Mouse Scrolling
this: model.sideList.elementAt(model.getIndex).screen is a ListView with a scrollbar as a parent widget.
Thanks.

I tried removing the Scrollbar widget, wrapping my shown SizedBox of the screen with a SingleChildScrollView, removing scrollControllers.
`

```<code>return Scaffold(
  body: Row(
    mainAxisAlignment: MainAxisAlignment.start,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
      SideMenu(context1: context),
      SizedBox(
        width: size.width > 1000 ? size.width * 0.825 : size.width * 0.775,
        child: model.sideList.elementAt(model.getIndex).screen,
      ),
    ],
  ),
);
</code>```

`

Body:
this: model.sideList.elementAt(model.getIndex).screen is a ListView with a scrollbar as a parent widget.
Thanks.

I tried removing the Scrollbar widget, wrapping my shown SizedBox of the screen with a SingleChildScrollView, removing scrollControllers.
`

return Scaffold(
  body: Row(
    mainAxisAlignment: MainAxisAlignment.start,
    crossAxisAlignment: CrossAxisAlignment.center,
    children: [
      SideMenu(context1: context),
      SizedBox(
        width: size.width > 1000 ? size.width * 0.825 : size.width * 0.775,
        child: model.sideList.elementAt(model.getIndex).screen,
      ),
    ],
  ),
);

`


问:
React Router enter from route
I have a static website hosted on GitHub pages and I'm using React Router v6 in my website to handle routing to dynamically generated web pages. The issue I'm running into is that if I visit a route (i.e. root/child) without first visiting root I get a 404. This sort of makes sense since my website on GitHub pages starts at root and there is technically no webpage at root/child hosted by GitHub Pages. How can I get around this and have links to root/child work?

I am building my webpage using Vite and I'm statically generating the website, then pushing the content to GitHub Pages.

I'm using createBrowserRouter with a setup that looks like this:

const router = createBrowserRouter([
  {
    path: "/root/",
    element: <Root />,
    errorElement: <ErrorPage fromArtifact={false} />,
    loader: () => artifacts,
  },
  {
    path: "/root/:id",
    element: <ArtifactPage />,
    errorElement: <ErrorPage fromArtifact />,
    loader: ({ params }) =>
      artifacts.find((artifact: ArtifactData) => artifact.id === params.id),
  },
]);
```

Thanks!

Title: React Router enter from route

Body:
I have a static website hosted on GitHub pages and I'm using React Router v6 in my website to handle routing to dynamically generated web pages. The issue I'm running into is that if I visit a route (i.e. root/child) without first visiting root I get a 404. This sort of makes sense since my website on GitHub pages starts at root and there is technically no webpage at root/child hosted by GitHub Pages. How can I get around this and have links to root/child work?

I am building my webpage using Vite and I'm statically generating the website, then pushing the content to GitHub Pages.

I'm using createBrowserRouter with a setup that looks like this:

const router = createBrowserRouter([
  {
    path: "/root/",
    element: <Root />,
    errorElement: <ErrorPage fromArtifact={false} />,
    loader: () => artifacts,
  },
  {
    path: "/root/:id",
    element: <ArtifactPage />,
    errorElement: <ErrorPage fromArtifact />,
    loader: ({ params }) =>
      artifacts.find((artifact: ArtifactData) => artifact.id === params.id),
  },
]);

Thanks!


问:
Converting CNG RSA BLOB to openssl BLOB?
I want to make application windows exchange pair key and use it in openssl php , how I can change BCRYPT_RSAKEY_BLOB to openSSL ?

I used but RSA SEQUENCE still deffrent   :

```<code>PBYTE pbASN;
// Length of the ASN.1 encoded key
DWORD cbASN;
// Generate the key
CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbPrivateKeyBlob, CRYPT_ENCODE_ALLOC_FLAG, NULL, &pbASN, &cbASN) {
    std::cout << "CryptEncodeObjectEx" << GetLastError() << std::endl;
}
</code>```

Body:
I want to make application windows exchange pair key and use it in openssl php , how I can change BCRYPT_RSAKEY_BLOB to openSSL ?

I used but RSA SEQUENCE still deffrent   :

PBYTE pbASN;
// Length of the ASN.1 encoded key
DWORD cbASN;
// Generate the key
CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_RSA_PRIVATE_KEY, pbPrivateKeyBlob, CRYPT_ENCODE_ALLOC_FLAG, NULL, &pbASN, &cbASN) {
    std::cout << "CryptEncodeObjectEx" << GetLastError() << std::endl;
}


问:
Nginx redirects everything except specific file
I have an nginx server I need to configure to redirect traffic for all requests except those requesting a specific file.

So if a request comes in for example.com/whatever I want it sent to www.example.com/whatever unless it's for example.com/this/specific/file.

I have found this question that seems to be exactly the same but it doesn't have a working answer.

I have done some googling and found this example for the redirect but it redirects everything. I need to be able to set an exception to this rule.

```<code>server {
    listen 80;
    listen 443 ssl;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}
</code>```

How would I got about doing this?

Update:

I have been trying to use the location headers as instructed in the comment by @Richard Smith and it is working on the redirects but the two files (/.well-known/matrix/server and /.well-known/matrix/client) are both returning 404. My Nginx config (/etc/nginx/sites-enabled/matrix) is below:

```<code>server {
       listen 80;
       server_name example.com;
       return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # If you don't wanna serve a site, comment this out
    root /var/www/html;

    location /.well-known/matrix/server {
      return 200 '{"m.server": "example.com:443"}';
      add_header Content-Type application/json;
    }
    location /.well-known/matrix/client {
      return 200 '{"m.homeserver": {"base_url": "https://example.com"},"m.identity_server": {"base_url": "https://vector.im"}}';
      add_header Content-Type application/json;
      add_header "Access-Control-Allow-Origin" *;
    }
    location / {
      return 301 https://www.example.com$request_uri;
    }
}

server {
    listen 8448 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location / {
        proxy_pass http://localhost:8008;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}
</code>```

At the moment if I place a file at /var/www/html/.well-known/matrix/client (or server) I get the option to download the file. If I don't place a file there it returns 404. I just want to return the JSON output from the nginx.conf file.

The goal here is to set up a matrix home server.

Body:
I have an nginx server I need to configure to redirect traffic for all requests except those requesting a specific file.

So if a request comes in for example.com/whatever I want it sent to www.example.com/whatever unless it's for example.com/this/specific/file.

I have found this question that seems to be exactly the same but it doesn't have a working answer.

I have done some googling and found this example for the redirect but it redirects everything. I need to be able to set an exception to this rule.

server {
    listen 80;
    listen 443 ssl;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

How would I got about doing this?

Update:

I have been trying to use the location headers as instructed in the comment by @Richard Smith and it is working on the redirects but the two files (/.well-known/matrix/server and /.well-known/matrix/client) are both returning 404. My Nginx config (/etc/nginx/sites-enabled/matrix) is below:

server {
       listen 80;
       server_name example.com;
       return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    # If you don't wanna serve a site, comment this out
    root /var/www/html;

    location /.well-known/matrix/server {
      return 200 '{"m.server": "example.com:443"}';
      add_header Content-Type application/json;
    }
    location /.well-known/matrix/client {
      return 200 '{"m.homeserver": {"base_url": "https://example.com"},"m.identity_server": {"base_url": "https://vector.im"}}';
      add_header Content-Type application/json;
      add_header "Access-Control-Allow-Origin" *;
    }
    location / {
      return 301 https://www.example.com$request_uri;
    }
}

server {
    listen 8448 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    location / {
        proxy_pass http://localhost:8008;
        proxy_set_header X-Forwarded-For $remote_addr;
    }
}

At the moment if I place a file at /var/www/html/.well-known/matrix/client (or server) I get the option to download the file. If I don't place a file there it returns 404. I just want to return the JSON output from the nginx.conf file.

The goal here is to set up a matrix home server.


问:
Pyspark RandomForestClassifier Py4JError: An error occurred while calling o85.fit
I am fitting RandomForestClassifier to the dataset (DecisionTreeClassifier is working fine on that dataset).

"An error occurred while calling {0}{1}{2}".
336                 format(target_id, ".", name))

The complete traceback is given below:

```<code>/usr/local/lib/python3.8/dist-packages/pyspark/ml/wrapper.py in _fit(self, dataset)
    381
    382     def _fit(self, dataset: DataFrame) -> JM:
--> 383         java_model = self._fit_java(dataset)
    384         model = self._create_model(java_model)
    385         return self._copyValues(model)

/usr/local/lib/python3.8/dist-packages/pyspark/ml/wrapper.py in _fit_java(self, dataset)
    378
    379         self._transfer_params_to_java()
--> 380         return self._java_obj.fit(dataset._jdf)
    381
    382     def _fit(self, dataset: DataFrame) -> JM:

/usr/local/lib/python3.8/dist-packages/py4j/java_gateway.py in __call__(self, *args)
   1319
   1320         answer = self.gateway_client.send_command(command)
-> 1321         return_value = get_return_value(
   1322             answer, self.gateway_client, self.target_id, self.name)
   1323

/usr/local/lib/python3.8/dist-packages/pyspark/sql/utils.py in deco(*a, **kw)
    188     def deco(*a: Any, **kw: Any) -> Any:
    189         try:
--> 190             return f(*a, **kw)
    191         except Py4JJavaError as e:
    192             converted = convert_exception(e.java_exception)

/usr/local/lib/python3.8/dist-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    332                     format(target_id, ".", name, value))
    333         else:
--> 334             raise Py4JError(
    335                 "An error occurred while calling {0}{1}{2}".
    336                 format(target_id, ".", name))

Py4JError: An error occurred while calling o85.fit
</code>```

I am creating a random forest model in pyspark on the expedia dataset and am facing this issue.

The code leading to this error is given here:

```<code>va = VectorAssembler(inputCols = x_train.columns, outputCol='features')

va_df = va.transform(x_train)
va_df = va_df.select(['features', 'hotel_cluster'])

rf = RandomForestClassifier(featuresCol="features", labelCol="hotel_cluster", numTrees=10)
dt = rf.fit(va_df) # error here
</code>```

Any help in identifying the issue will be highly appreciated!

Body:
I am fitting RandomForestClassifier to the dataset (DecisionTreeClassifier is working fine on that dataset).

"An error occurred while calling {0}{1}{2}".
336                 format(target_id, ".", name))

The complete traceback is given below:

/usr/local/lib/python3.8/dist-packages/pyspark/ml/wrapper.py in _fit(self, dataset)
    381
    382     def _fit(self, dataset: DataFrame) -> JM:
--> 383         java_model = self._fit_java(dataset)
    384         model = self._create_model(java_model)
    385         return self._copyValues(model)

/usr/local/lib/python3.8/dist-packages/pyspark/ml/wrapper.py in _fit_java(self, dataset)
    378
    379         self._transfer_params_to_java()
--> 380         return self._java_obj.fit(dataset._jdf)
    381
    382     def _fit(self, dataset: DataFrame) -> JM:

/usr/local/lib/python3.8/dist-packages/py4j/java_gateway.py in __call__(self, *args)
   1319
   1320         answer = self.gateway_client.send_command(command)
-> 1321         return_value = get_return_value(
   1322             answer, self.gateway_client, self.target_id, self.name)
   1323

/usr/local/lib/python3.8/dist-packages/pyspark/sql/utils.py in deco(*a, **kw)
    188     def deco(*a: Any, **kw: Any) -> Any:
    189         try:
--> 190             return f(*a, **kw)
    191         except Py4JJavaError as e:
    192             converted = convert_exception(e.java_exception)

/usr/local/lib/python3.8/dist-packages/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    332                     format(target_id, ".", name, value))
    333         else:
--> 334             raise Py4JError(
    335                 "An error occurred while calling {0}{1}{2}".
    336                 format(target_id, ".", name))

Py4JError: An error occurred while calling o85.fit

I am creating a random forest model in pyspark on the expedia dataset and am facing this issue.

The code leading to this error is given here:

va = VectorAssembler(inputCols = x_train.columns, outputCol='features')

va_df = va.transform(x_train)
va_df = va_df.select(['features', 'hotel_cluster'])

rf = RandomForestClassifier(featuresCol="features", labelCol="hotel_cluster", numTrees=10)
dt = rf.fit(va_df) # error here

Any help in identifying the issue will be highly appreciated!


问:
Push to NavigationStack and Pop to root
I got a Static List/VStack where you can create a post and select the Category, Headline, Description exc. I got a hard time wrapping my head around the new NavigationStack and how to return to the root view (CreatePostView) from CategoryPickerView.

Passing the navigationPath as a parameter doesn't work and doesn't feel like the most logic approach. I could easily add a @Environment(.dismiss) but that also seems like the wrong approach, and wouldn't work when I want to add more views to the stack like SubCategoryPickerView.

It's a simple question so I have tried to minimise the code as much as possible.

CreatePostView

```<code>@ObservedObject var viewModel = CreatePostViewModel()
@State private var navigationPath = NavigationPath()

var body: some View {

NavigationStack(path: $navigationPath) {
    ScrollView {
       VStack {
           NavigationLink(destination: CategoryPickerView(category: $viewModel.category)
               Text("Pick Category")
           }
       }
    }
 }
</code>```

CategoryPickerView

```<code>@Binding var category: Category
@State var categories: [Category] = Category.categories

var body: some View {

List(categories) { category in
    ForEach(categories) { category in
        NavigationLink(value: SubCategory(category)) {
            Text(category.query)
        }
    }
}
.navigationDestination()
.toolbar {
   // ToolbarItem
   Button {
       How to pop to rootview?
   }
}
</code>```

Title: Push to NavigationStack and Pop to root

Body:
I got a Static List/VStack where you can create a post and select the Category, Headline, Description exc. I got a hard time wrapping my head around the new NavigationStack and how to return to the root view (CreatePostView) from CategoryPickerView.

Passing the navigationPath as a parameter doesn't work and doesn't feel like the most logic approach. I could easily add a @Environment(.dismiss) but that also seems like the wrong approach, and wouldn't work when I want to add more views to the stack like SubCategoryPickerView.

It's a simple question so I have tried to minimise the code as much as possible.

CreatePostView

@ObservedObject var viewModel = CreatePostViewModel()
@State private var navigationPath = NavigationPath()

var body: some View {

NavigationStack(path: $navigationPath) {
    ScrollView {
       VStack {
           NavigationLink(destination: CategoryPickerView(category: $viewModel.category)
               Text("Pick Category")
           }
       }
    }
 }

CategoryPickerView

@Binding var category: Category
@State var categories: [Category] = Category.categories

var body: some View {

List(categories) { category in
    ForEach(categories) { category in
        NavigationLink(value: SubCategory(category)) {
            Text(category.query)
        }
    }
}
.navigationDestination()
.toolbar {
   // ToolbarItem
   Button {
       How to pop to rootview?
   }
}


问:
Creating offcanvas in bootstrap 4 and react
I have a div which I want to always show for long screen devices. For small screen devices, I want to show a button with hamburger menu and slide in the div from left edge of the device screen when the hamburge button is clicked. This is possible out of the box with offcanvas property in bootstrap 5. But, our project uses "bootstrap": "^4.6.0" which does not support offcanvas property.

Our current project uses "react-bootstrap": "^1.4.3" which does not support offcanvas component. However, version react-bootstrap 2.7 does support offcanvas.

Quick googling lead me to many workarounds which achieves the same with jQuery or some JS: example-1, example-2, example-3

Apart from this, I tried this react-offcanvas-menu-component, but it was giving conflicts in npm packages.

Is it possible to achieve the same with bootstrap-4?
If not, can I achieve the same result without needing to custom write JS and complex CSS? Or is there some library / npm package which allows to achieve the same?

How should I implement offcanvas menu in react in our project (avoiding any major JS framework like jQuery that follows different paradigm from React's components based paradigm)? Or I am without any solution?


问:
Neither BindingResult nor plain target object for bean name 'user' available as request attribute error
I am new on spring. I am just trying to create my own CRUD OneToMany project. I have user and course table in my database. Course table has user_id foreign key references user(id).

When user successfully logged into the page, homePage.jsp comes and user courses are listed. When we click "Add Course" button in homePage.jsp, course-form.jsp file comes and we should add course.

The problem is, when I try to add course, I lost my user modelAttribute because in this time another attribute is on process with spring mvc.

When addedCourse form action performed these error occurs,

```<code> Cannot invoke "com.veg.entity.User.addCourse(com.veg.entity.Course)" because "user" is null

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
</code>```

My Controller,

```<code>@PostMapping("/showFormForAdd")
    public String showFormForAdd(@ModelAttribute("user") User theUser, Model theModel) {

        Course theCourse = new Course();

        theCourse.setUser(theUser);

        theModel.addAttribute("course", theCourse);

        theModel.addAttribute("user", theUser);

        return "course-form";
    }

    @PostMapping("addedCourse")
    public String addedCourse(@ModelAttribute("course") Course theCourse, Model theModel) {

        User user = theCourse.getUser();

        userService.save(user, theCourse);

        theModel.addAttribute("user", user);

        return "homePage";
    }
</code>```

homePage.jsp

```<code>

            <p>Welcome ${user.username}</p>

            <span>

                <form:form action="showFormForAdd" modelAttribute="user" method="POST">

                    <form:hidden path="username"/>
                    <form:hidden path="password"/>

                    <input type="submit" value="Add Course" class="add-course"/>

                </form:form>

            </span>

            <table>
                <tbody>
                    <tr>
                        <th>Course id</th>
                        <th>Course title</th>
                    </tr>

                    <c:forEach var="temp" items="${user.courses}">

                        <tr>

                            <td> ${temp.id} </td>
                            <td> ${temp.title} </td>

                        </tr>

                    </c:forEach>
                </tbody>
            </table>
</code>```

course-form.jsp

```<code><p>Welcome ${user.username}</p>

    <span>
        <form:form action="loggedUser" modelAttribute="user" method="POST">

            <form:hidden path="username"/>
            <form:hidden path="password"/>

            <input type="submit" value="Back to Course List" class="add-course"/>

        </form:form>
    </span>

        <!-- In the below I lost my user modelAttribute because I should use course attribute -->

    <form:form action="addedCourse" modelAttribute="course" method="POST">
        <table>
            <tbody>
                <tr>
                    <td> Title </td>
                    <td> <form:input path="title"/> </td>
                </tr>

                <tr>
                    <td colspan="2">
                    <input type="submit" value="Add Course" class="add-course"/>
                    </td>
                </tr>

            </tbody>
        </table>

    </form:form>
</code>```

I have @Transactional in my service, @Repository in my DAO and there is no problem with sessionFactory.

Body:
I am new on spring. I am just trying to create my own CRUD OneToMany project. I have user and course table in my database. Course table has user_id foreign key references user(id).

When user successfully logged into the page, homePage.jsp comes and user courses are listed. When we click "Add Course" button in homePage.jsp, course-form.jsp file comes and we should add course.

The problem is, when I try to add course, I lost my user modelAttribute because in this time another attribute is on process with spring mvc.

When addedCourse form action performed these error occurs,

 Cannot invoke "com.veg.entity.User.addCourse(com.veg.entity.Course)" because "user" is null

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

My Controller,

@PostMapping("/showFormForAdd")
    public String showFormForAdd(@ModelAttribute("user") User theUser, Model theModel) {

        Course theCourse = new Course();

        theCourse.setUser(theUser);

        theModel.addAttribute("course", theCourse);

        theModel.addAttribute("user", theUser);

        return "course-form";
    }

    @PostMapping("addedCourse")
    public String addedCourse(@ModelAttribute("course") Course theCourse, Model theModel) {

        User user = theCourse.getUser();

        userService.save(user, theCourse);

        theModel.addAttribute("user", user);

        return "homePage";
    }

homePage.jsp

Welcome ${user.username}

                <form:form action="showFormForAdd" modelAttribute="user" method="POST">

                    <form:hidden path="username"/>
                    <form:hidden path="password"/>

                    <input type="submit" value="Add Course" class="add-course"/>

                </form:form>

                        Course id
                        Course title

                    <c:forEach var="temp" items="${user.courses}">

                             ${temp.id}
                             ${temp.title}

                    </c:forEach>

course-form.jsp

Welcome ${user.username}

        <form:form action="loggedUser" modelAttribute="user" method="POST">

            <form:hidden path="username"/>
            <form:hidden path="password"/>

            <input type="submit" value="Back to Course List" class="add-course"/>

        </form:form>

    <form:form action="addedCourse" modelAttribute="course" method="POST">

                     Title
                     <form:input path="title"/>

                    <input type="submit" value="Add Course" class="add-course"/>

    </form:form>

I have @Transactional in my service, @Repository in my DAO and there is no problem with sessionFactory.


问:
Rounding an Array
I've tried using np.round to clean up the discrepancy between the arrays with no success, can someone please help me. it should be np.array_equal(H,k) is True

```<code>data_1_P = np.array([
    [0.3, 0.2, 0.1, 0.2, 0.2],
    [0.3, 0.1, 0.2, 0.2, 0.2],
    [0.2, 0.2, 0.2, 0.2, 0.2]])
data_1_Q = np.array([
    [0.3, 0.2, 0.1, 0.2, 0.2],
    [0.3, 0.2, 0.1, 0.2, 0.2],
    [0.3, 0.2, 0.1, 0.2, 0.2]])

def _hellinger_distance_py(P, Q):
    P, Q = P.tolist(), Q.tolist()
    H = []
    for p_i, q_i in zip(P, Q):
        h = 0
        for p_ij, q_ij in zip(p_i, q_i):
            d = math.sqrt(p_ij) - math.sqrt(q_ij)
            h += d**2
        H.append(math.sqrt(h))
    H = [1/math.sqrt(2) * h for h in H]
    return np.array(H)

def hellinger_distance(P, Q):
    z = np.sqrt(np.sum(abs(np.power((np.sqrt(P) - np.sqrt(Q)),2)),axis =1 ))* np.sqrt(1/ 2)
    return z

k = _hellinger_distance_py(data_1_P,data_1_Q)

array([0.        , 0.13098583, 0.11674618])

H = hellinger_distance(data_1_P,data_1_Q)

array([0.        , 0.13098583, 0.11674618])

diffs = H - k
print(diffs)
print(np.abs(diffs).sum())

[0.00000000e+00 0.00000000e+00 2.77555756e-17]
2.7755575615628914e-17

np.array_equal(H,k)
False

if np.abs(diffs).sum() > 0:
    print("Hellinger-Distanz:  there is discrepancy  (Different {})".format(diffs))
    code_fail()
</code>```

Title: Rounding an Array

Body:
I've tried using np.round to clean up the discrepancy between the arrays with no success, can someone please help me. it should be np.array_equal(H,k) is True

data_1_P = np.array([
    [0.3, 0.2, 0.1, 0.2, 0.2],
    [0.3, 0.1, 0.2, 0.2, 0.2],
    [0.2, 0.2, 0.2, 0.2, 0.2]])
data_1_Q = np.array([
    [0.3, 0.2, 0.1, 0.2, 0.2],
    [0.3, 0.2, 0.1, 0.2, 0.2],
    [0.3, 0.2, 0.1, 0.2, 0.2]])

def _hellinger_distance_py(P, Q):
    P, Q = P.tolist(), Q.tolist()
    H = []
    for p_i, q_i in zip(P, Q):
        h = 0
        for p_ij, q_ij in zip(p_i, q_i):
            d = math.sqrt(p_ij) - math.sqrt(q_ij)
            h += d**2
        H.append(math.sqrt(h))
    H = [1/math.sqrt(2) * h for h in H]
    return np.array(H)

def hellinger_distance(P, Q):
    z = np.sqrt(np.sum(abs(np.power((np.sqrt(P) - np.sqrt(Q)),2)),axis =1 ))* np.sqrt(1/ 2)
    return z

k = _hellinger_distance_py(data_1_P,data_1_Q)

array([0.        , 0.13098583, 0.11674618])

H = hellinger_distance(data_1_P,data_1_Q)

array([0.        , 0.13098583, 0.11674618])

diffs = H - k
print(diffs)
print(np.abs(diffs).sum())

[0.00000000e+00 0.00000000e+00 2.77555756e-17]
2.7755575615628914e-17

np.array_equal(H,k)
False

if np.abs(diffs).sum() > 0:
    print("Hellinger-Distanz:  there is discrepancy  (Different {})".format(diffs))
    code_fail()


问:
How to get the MainWindow winId from a subclass?
When i have the subclass below running in two different 'MainWindow' guis, how i could get the winId from the 'MainWindow' which this widget belongs to?

I tried:

class Test: public QFrame
{
    Q_OBJECT

public:

    Test(QWidget* parent = 0) : QFrame(parent)
    {
        QWidget* widget = this;
        while (widget->parentWidget() != NULL)
        {
            widget = widget->parentWidget();
            //qDebug() << "name: " << widget->objectName();
        }

        HWND id = (HWND)widget->winId();
    }
}
```

Theres another way than walking over parentWidget()?

Body:
When i have the subclass below running in two different 'MainWindow' guis, how i could get the winId from the 'MainWindow' which this widget belongs to?

I tried:

class Test: public QFrame
{
    Q_OBJECT

public:

    Test(QWidget* parent = 0) : QFrame(parent)
    {
        QWidget* widget = this;
        while (widget->parentWidget() != NULL)
        {
            widget = widget->parentWidget();
            //qDebug() << "name: " << widget->objectName();
        }

        HWND id = (HWND)widget->winId();
    }
}

Theres another way than walking over parentWidget()?


问:
Value Error - Recommender System with ALS Model
I have a database that I got online for the movies. The database has an ID (Just an interaction with the movie, ID does not mean anything), User, and MovieID. Each seperate row represent a given user watching a given movie, so I am trying to write a movie reccomendation system for each user. So you give me a user and I output the list of movies that they might like.

Here is the database (Almost 90,000 rows and a lot of different movies)

```<code>    ID  User    MovieID
0   17556   2591    88879
1   17557   3101    88879
2   17598   3101    88879
3   17598   3101    88879
4   17604   9459937 88879
... ... ... ...
88085   73266   9468430 9948
88086   73310   9467397 112749
88087   73371   9468018 109281
88088   73371   9468018 109281
88089   73381   9468360 109508
</code>```

So I used internet and found the following code:

```<code>import implicit
from scipy.sparse import coo_matrix

# Drop any duplicate rows from the DataFrame
df = df.drop_duplicates(subset=["User", "MovieID"])

# Sort the DataFrame by the User column
df = df.sort_values("User")

# Create a pivot table with the User as the index, the MovieID as the columns, and the ID as the values
bookings = df.pivot_table(index="User", columns="MovieID", values="ID", aggfunc=len, fill_value=0)

# Convert the pivot table to a sparse matrix in the COOrdinate format
M = coo_matrix(bookings)

# Convert the sparse matrix to the CSR format
M = M.tocsr()

# Create an ALS model
model = implicit.als.AlternatingLeastSquares(factors=10)

# Fit the model to the data
model.fit(M)

def recommend_movies(user):
    # Make sure the user is in the index of the pivot table
    if user not in bookings.index:
        return []

    # Get the user index in the matrix
    user_index = list(bookings.index).index(user)

    # Get the recommendations for the user
    recommendations = model.recommend(user_index, M, N=10)

    # Get the movie IDs of the recommended movies
    recommended_movies = [bookings.columns[index] for index, _ in recommendations]

    return recommended_movies

# Example usage:
recommendations = recommend_movies(3101)

# Print the recommendations
print(recommendations)
</code>```

But this error kep coming up on this line:

recommendations = recommend_movies(3101)

```<code>47             user_count = 1 if np.isscalar(userid) else len(userid)
     48             if user_items.shape[0] != user_count:
---> 49                 raise ValueError("user_items must contain 1 row for every user in userids")
     50
     51         user = self._user_factor(userid, user_items, recalculate_user)

ValueError: user_items must contain 1 row for every user in userids
</code>```

I tried using ChatGPT but it was not able to give me the solution and I also looked online and was not able to find anything. There are some duplicate User values and MovieID values in the dataset as can be seen, because users watch multiple movies and also sometimes rewatch the same movies

Body:
I have a database that I got online for the movies. The database has an ID (Just an interaction with the movie, ID does not mean anything), User, and MovieID. Each seperate row represent a given user watching a given movie, so I am trying to write a movie reccomendation system for each user. So you give me a user and I output the list of movies that they might like.

Here is the database (Almost 90,000 rows and a lot of different movies)

    ID  User    MovieID
0   17556   2591    88879
1   17557   3101    88879
2   17598   3101    88879
3   17598   3101    88879
4   17604   9459937 88879
... ... ... ...
88085   73266   9468430 9948
88086   73310   9467397 112749
88087   73371   9468018 109281
88088   73371   9468018 109281
88089   73381   9468360 109508

So I used internet and found the following code:

import implicit
from scipy.sparse import coo_matrix

# Drop any duplicate rows from the DataFrame
df = df.drop_duplicates(subset=["User", "MovieID"])

# Sort the DataFrame by the User column
df = df.sort_values("User")

# Create a pivot table with the User as the index, the MovieID as the columns, and the ID as the values
bookings = df.pivot_table(index="User", columns="MovieID", values="ID", aggfunc=len, fill_value=0)

# Convert the pivot table to a sparse matrix in the COOrdinate format
M = coo_matrix(bookings)

# Convert the sparse matrix to the CSR format
M = M.tocsr()

# Create an ALS model
model = implicit.als.AlternatingLeastSquares(factors=10)

# Fit the model to the data
model.fit(M)

def recommend_movies(user):
    # Make sure the user is in the index of the pivot table
    if user not in bookings.index:
        return []

    # Get the user index in the matrix
    user_index = list(bookings.index).index(user)

    # Get the recommendations for the user
    recommendations = model.recommend(user_index, M, N=10)

    # Get the movie IDs of the recommended movies
    recommended_movies = [bookings.columns[index] for index, _ in recommendations]

    return recommended_movies

# Example usage:
recommendations = recommend_movies(3101)

# Print the recommendations
print(recommendations)

But this error kep coming up on this line:

recommendations = recommend_movies(3101)

47             user_count = 1 if np.isscalar(userid) else len(userid)
     48             if user_items.shape[0] != user_count:
---> 49                 raise ValueError("user_items must contain 1 row for every user in userids")
     50
     51         user = self._user_factor(userid, user_items, recalculate_user)

ValueError: user_items must contain 1 row for every user in userids

I tried using ChatGPT but it was not able to give me the solution and I also looked online and was not able to find anything. There are some duplicate User values and MovieID values in the dataset as can be seen, because users watch multiple movies and also sometimes rewatch the same movies


问:
replicate numpy style array initialisation in c++
I'm trying to replicate basic NumPy functionalities in C++ (for practice).

I'm stuck replicating the following initialization:
here's how it looks in python/NumPy:

```<code>x = np.array([[1], [2]])
</code>```

which evaluates to:

```<code>array([[1],
       [2]])
</code>```

In my C++ code, I decided to use std::vector. I currently have two functions to initialize arrays (I want to use overloading so that I can always use the same function name when initializing an array).

function1 declaration for 1D arrays:

```<code>std::vector<std::vector<int>> init(std::vector<int> vec);
</code>```

I can use this like so:

```<code>std::vector<std::vector<int>> vec1d = init({0, 1, 2});
</code>```

function2 declaration for 2D arrays:

```<code>std::vector<std::vector<int>> init(std::vector<std::vector<int>> vec);
</code>```

I can use this like so:

```<code>std::vector<std::vector<int>> vec2d = init({{0, 1, 2}, {4, 5, 6}});
</code>```

However, I'm unable to implement the NumPy-like initialization shown at the top of my question.
If I try to run the following line:

```<code>std::vector<std::vector<int>> vec2d = init({{0}, {1}});
</code>```

I get the following error:

```<code>error: call to 'init' is ambiguous
</code>```

I thought that the 2D version of the function would be called.

What do I have to change (or what other overloaded functions do I have to add) in order for this type of initialization to work?

Body:
I'm trying to replicate basic NumPy functionalities in C++ (for practice).

I'm stuck replicating the following initialization:
here's how it looks in python/NumPy:

x = np.array([[1], [2]])

which evaluates to:

array([[1],
       [2]])

In my C++ code, I decided to use std::vector. I currently have two functions to initialize arrays (I want to use overloading so that I can always use the same function name when initializing an array).

function1 declaration for 1D arrays:

std::vector<std::vector<int>> init(std::vector<int> vec);

I can use this like so:

std::vector<std::vector<int>> vec1d = init({0, 1, 2});

function2 declaration for 2D arrays:

std::vector<std::vector<int>> init(std::vector<std::vector<int>> vec);

I can use this like so:

std::vector<std::vector<int>> vec2d = init({{0, 1, 2}, {4, 5, 6}});

However, I'm unable to implement the NumPy-like initialization shown at the top of my question.
If I try to run the following line:

std::vector<std::vector<int>> vec2d = init({{0}, {1}});

I get the following error:

error: call to 'init' is ambiguous

I thought that the 2D version of the function would be called.

What do I have to change (or what other overloaded functions do I have to add) in order for this type of initialization to work?


问:
React components not showing up on the screen
I am getting started on Reactjs today to build a login page.

Here is my code:

Login.js

```<code>import styled from "styled-components";

const Login = (props) => {
    return (<div>Login</div>)
}

export default Login;
</code>```

App.js

```<code>import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import './App.css';
import Login from './Login.js';

function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route exact path='/'>
            <Login />
          </Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;

</code>```

But when I typed 'yarn start' and refresh the page, nothing shows up.

I'd appreciate it if you could tell me where I got wrong.

Body:
I am getting started on Reactjs today to build a login page.

Here is my code:

Login.js

import styled from "styled-components";

const Login = (props) => {
    return (
Login
)
}

export default Login;

App.js

import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import './App.css';
import Login from './Login.js';

function App() {
  return (

      <Router>
        <Routes>
          <Route exact path='/'>
            <Login />
          </Route>
        </Routes>
      </Router>

  );
}

export default App;

But when I typed 'yarn start' and refresh the page, nothing shows up.

I'd appreciate it if you could tell me where I got wrong.


问:
Is there any way to convert HTML content to readable text in iTextSharp?
I am using iTextSharp for creating PDF documents in a .Net Core application. Sometimes I receive a HTML content as below:

```<code><p>This is a <strong>bold text</strong> and also\n this is a new line.</p>
</code>```

The result after converting to readable Text, should be:

This is a bold text and also

 this is a new line.

Body:
I am using iTextSharp for creating PDF documents in a .Net Core application. Sometimes I receive a HTML content as below:

This is a bold text and also\n this is a new line.

The result after converting to readable Text, should be:

This is a bold text and also

 this is a new line.


问:
Select latest values in timeseries table
I have a timeseries table in Postgres that collects events of various types, with their values and a timestamp. In stylized form it looks like this:

evt_type
evt_val_01
evt_val_02
evt_time

1
0.5
10
1

2
0.7
12
1

3
0.8
13
1

2
0.1
21
2

2
0.3
98
3

3
0.4
76
3

2
0.2
3
4

I'd like now to create a SELECT query that returns the latest (by timestamp in evt_time) values per event type (evt_typ), i.e., the query should return:

evt_type
evt_val
evt_val_02
evt_time

1
0.5
10
1

2
0.2
3
4

3
0.4
76
3

In QuestDB for instance, this is easy to be achieved by the LATEST ON parameter. However, I am struggling to find an efficient Postgres approach that makes full use of index on evt_time and evt_type. The trivial approach using

```<code>select evt_type, max(evt_time) from events group by evt_type
</code>```

In a sub-query, is way too slow, as the real-life table has double-digit million rows and about a thousand event types, plus about a dozen value columns. I tried to use various forms of last_value(), and LATERAL joins, but did not manage to get it right thus far.

Any suggestions how to structure the SELECT query would be greatly appreciated. PS, I'm on Postgres 15.1

Body:
I have a timeseries table in Postgres that collects events of various types, with their values and a timestamp. In stylized form it looks like this:

evt_type
evt_val_01
evt_val_02
evt_time

1
0.5
10
1

2
0.7
12
1

3
0.8
13
1

2
0.1
21
2

2
0.3
98
3

3
0.4
76
3

2
0.2
3
4

I'd like now to create a SELECT query that returns the latest (by timestamp in evt_time) values per event type (evt_typ), i.e., the query should return:

evt_type
evt_val
evt_val_02
evt_time

1
0.5
10
1

2
0.2
3
4

3
0.4
76
3

In QuestDB for instance, this is easy to be achieved by the LATEST ON parameter. However, I am struggling to find an efficient Postgres approach that makes full use of index on evt_time and evt_type. The trivial approach using

select evt_type, max(evt_time) from events group by evt_type

In a sub-query, is way too slow, as the real-life table has double-digit million rows and about a thousand event types, plus about a dozen value columns. I tried to use various forms of last_value(), and LATERAL joins, but did not manage to get it right thus far.

Any suggestions how to structure the SELECT query would be greatly appreciated. PS, I'm on Postgres 15.1


问:
How to send Hcaptcha token with Python?
I need to automatically register accounts in one service and there I need to solve a captcha. I use this code to send captcha token:

```<code>send_token = driver.find_element(By.NAME, "h-captcha-response")
send_token.send_keys(form_token)
</code>```

This code only works on simple demo sites. This method does not work in my service, here is the website:
https://auth.alchemy.com/signup?redirectUrl=https%3A%2F%2Fdashboard.alchemy.com%2Fsignup%3Fa%3Dgoerli_faucet%26redirectUrl%3Dhttps%253A%252F%252Fgoerlifaucet.com%252F%253FauthRefresh%253DTrue

I'm just starting to learn Python and JS I don't know at all.
I would like to know the principle of searching for this "place", where to send the token and how to do it, thanks in advance)
I have examples of sending a token using JS in other services. Maybe this will help somehow)
1:

```<code>driver.execute_script("verifyCallback(arguments[0])", (form_token))
</code>```

2:

```<code>driver.execute_script("form_token = arguments[0]", (form_token))
driver.execute_script('hcaptcha.getResponse = function() {return form_token}')
</code>```

It seems to me that I found the "place" where the token appears after solving the captcha manually, but unfortunately I don't know what to do with it)

Title: How to send Hcaptcha token with Python?

Body:
I need to automatically register accounts in one service and there I need to solve a captcha. I use this code to send captcha token:

send_token = driver.find_element(By.NAME, "h-captcha-response")
send_token.send_keys(form_token)

This code only works on simple demo sites. This method does not work in my service, here is the website:
https://auth.alchemy.com/signup?redirectUrl=https%3A%2F%2Fdashboard.alchemy.com%2Fsignup%3Fa%3Dgoerli_faucet%26redirectUrl%3Dhttps%253A%252F%252Fgoerlifaucet.com%252F%253FauthRefresh%253DTrue

I'm just starting to learn Python and JS I don't know at all.
I would like to know the principle of searching for this "place", where to send the token and how to do it, thanks in advance)
I have examples of sending a token using JS in other services. Maybe this will help somehow)
1:

driver.execute_script("verifyCallback(arguments[0])", (form_token))

2:

driver.execute_script("form_token = arguments[0]", (form_token))
driver.execute_script('hcaptcha.getResponse = function() {return form_token}')

It seems to me that I found the "place" where the token appears after solving the captcha manually, but unfortunately I don't know what to do with it)


问:
django inline_formset get pk from foreign key item before save to make a form validation
django noob here, well i´ve be dealing with this for over a day and i cant figure out, so decide to post, any help, thanks!

have this project and i want to validate this formset, this formset have a select with product list, and quantiy, i need to validate if when saving new data, that the product selected have o not stock enough and raise a form validation error, but i cant figure out how to get the pk from the related model, already read several articles but cant make it work

this models.py

```<code>
class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    description = models.CharField(max_length=50)
    stock = models.IntegerField(default='0')

    def __str__(self):
        return self.description + '(' + str(self.stock)+')'

    def save(self, *args, **kwargs):
        self.description = self.description.title()
        super(Product, self).save(*args, **kwargs)

class Invoice(models.Model):

    invoice_id = models.AutoField(primary_key=True)
    client_id = models.ForeignKey(Client, on_delete=models.CASCADE)
    date = models.DateTimeField()
    status = models.BooleanField(default=True)

    def __str__(self):
        return str(self.invoice_id)

class InvoiceItem(models.Model):
    invoice_id = models.ForeignKey(Invoice, on_delete=models.CASCADE)
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
    qty = models.IntegerField(default='0')
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['invoice_id', 'product_id'], name='unique invoiceitem')
        ]

</code>```

these are my forms.py

```<code>class InvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice
        exclude = ['status']
        labels = {
            'client_id': ('Cliente'),
            'date': ('Fecha'),
        }
        widgets = {
            'date':forms.DateInput(
                attrs={'type': 'date'},
            ),
        }

class InvoiceItemForm(forms.ModelForm):
    class Meta:
        model = InvoiceItem
        fields = ['product_id', 'qty', 'price', 'price']
        labels = {
            'product_id': ('Producto'),
            'qty': ('Cantidad'),
            'price': ('Precio'),
        }
        widgets = {
            'price': forms.NumberInput(attrs={'step': '0.01'}),

        }
</code>```

my view.py

```<code>def create(request):
    forminvoice = InvoiceForm(request.POST or None)
    formset = inlineformset_factory(
    Invoice, InvoiceItem, form=InvoiceItemForm, min_num=1, extra=0, can_delete=True)
    if request.method == "POST":
        if forminvoice.is_valid():
            forminvoice = forminvoice.save(commit=False)
            forminvoice.date = datetime.datetime.now()
            forminvoice.save()
            formset = formset(request.POST, instance=forminvoice)
            if formset.is_valid():
                 formset.save()
                return redirect('/create_order')
    context = {
        "forminvoice": forminvoice,
        "formset": formset,
    }
    return render(request, "partials/create.html", context)
</code>```

alredy tried official inline and yt, and want to find a way to do it

also tried the clean() in forms.py or through the views

```<code>def clean(self): cdata = super().clean()           Product.objects.get(product_id=cdata.get("product_id_id")).stock product_id = cdata.get("product_id_id") stock = Product.objects.get(product_id=product_id).stock if qty > stock:    raise forms.ValidationError("No")
</code>```

forms.py

```<code>product = Product.objects.get(product_id=form.product_id_id)
</code>```

Body:
django noob here, well i´ve be dealing with this for over a day and i cant figure out, so decide to post, any help, thanks!

have this project and i want to validate this formset, this formset have a select with product list, and quantiy, i need to validate if when saving new data, that the product selected have o not stock enough and raise a form validation error, but i cant figure out how to get the pk from the related model, already read several articles but cant make it work

this models.py

class Product(models.Model):
    product_id = models.AutoField(primary_key=True)
    description = models.CharField(max_length=50)
    stock = models.IntegerField(default='0')

    def __str__(self):
        return self.description + '(' + str(self.stock)+')'

    def save(self, *args, **kwargs):
        self.description = self.description.title()
        super(Product, self).save(*args, **kwargs)

class Invoice(models.Model):

    invoice_id = models.AutoField(primary_key=True)
    client_id = models.ForeignKey(Client, on_delete=models.CASCADE)
    date = models.DateTimeField()
    status = models.BooleanField(default=True)

    def __str__(self):
        return str(self.invoice_id)

class InvoiceItem(models.Model):
    invoice_id = models.ForeignKey(Invoice, on_delete=models.CASCADE)
    product_id = models.ForeignKey(Product, on_delete=models.CASCADE)
    qty = models.IntegerField(default='0')
    price = models.DecimalField(max_digits=10, decimal_places=2, default=0)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['invoice_id', 'product_id'], name='unique invoiceitem')
        ]

these are my forms.py

class InvoiceForm(forms.ModelForm):
    class Meta:
        model = Invoice
        exclude = ['status']
        labels = {
            'client_id': ('Cliente'),
            'date': ('Fecha'),
        }
        widgets = {
            'date':forms.DateInput(
                attrs={'type': 'date'},
            ),
        }

class InvoiceItemForm(forms.ModelForm):
    class Meta:
        model = InvoiceItem
        fields = ['product_id', 'qty', 'price', 'price']
        labels = {
            'product_id': ('Producto'),
            'qty': ('Cantidad'),
            'price': ('Precio'),
        }
        widgets = {
            'price': forms.NumberInput(attrs={'step': '0.01'}),

        }

my view.py

def create(request):
    forminvoice = InvoiceForm(request.POST or None)
    formset = inlineformset_factory(
    Invoice, InvoiceItem, form=InvoiceItemForm, min_num=1, extra=0, can_delete=True)
    if request.method == "POST":
        if forminvoice.is_valid():
            forminvoice = forminvoice.save(commit=False)
            forminvoice.date = datetime.datetime.now()
            forminvoice.save()
            formset = formset(request.POST, instance=forminvoice)
            if formset.is_valid():
                 formset.save()
                return redirect('/create_order')
    context = {
        "forminvoice": forminvoice,
        "formset": formset,
    }
    return render(request, "partials/create.html", context)

alredy tried official inline and yt, and want to find a way to do it

also tried the clean() in forms.py or through the views

def clean(self): cdata = super().clean()           Product.objects.get(product_id=cdata.get("product_id_id")).stock product_id = cdata.get("product_id_id") stock = Product.objects.get(product_id=product_id).stock if qty > stock:    raise forms.ValidationError("No")

forms.py

product = Product.objects.get(product_id=form.product_id_id)


问:
Dataframe manipulation for relative dates
I need to determine which ID's were the first time the PIECE_NUMBER had been ordered in >3 years (ex. A PIECE_NUMBER had an ID (row) dated Jan 2nd 2011, and did not appear again until Jan 3rd 2014. This would be a first time demand in >3 years).

Here is a sample of my dataframe:

```<code>pd.DataFrame({'ID': {5039: 5040, 76015: 76016, 14833: 14834},
 'Date': {5039: Timestamp('2012-05-10 00:00:00'),
  76015: Timestamp('2017-08-27 00:00:00'),
  14833: Timestamp('2013-02-03 00:00:00')},
 'PIECE_NUMBER': {5039: 'PN_9347', 76015: 'PN_9047', 14833: 'PN_5612'},
 'CODE': {5039: 'E', 76015: 'D', 14833: 'E'}})
</code>```

Here is the code I have:

# Calculate the number of years since the last time the piece was ordered

```<code>df["Years Since Last Order"] = df.sort_values(by=["PIECE_NUMBER", "Date"]).groupby("PIECE_NUMBER")["Date"].diff().dt.days / 365
</code>```

# Select only the ID where the number of years since the last time the piece was ordered is greater than 3

```<code>df = df[df["Years Since Last Order"] > 3]
</code>```

Is this the correct implementation? Is there any way to improve it?

Body:
I need to determine which ID's were the first time the PIECE_NUMBER had been ordered in >3 years (ex. A PIECE_NUMBER had an ID (row) dated Jan 2nd 2011, and did not appear again until Jan 3rd 2014. This would be a first time demand in >3 years).

Here is a sample of my dataframe:

pd.DataFrame({'ID': {5039: 5040, 76015: 76016, 14833: 14834},
 'Date': {5039: Timestamp('2012-05-10 00:00:00'),
  76015: Timestamp('2017-08-27 00:00:00'),
  14833: Timestamp('2013-02-03 00:00:00')},
 'PIECE_NUMBER': {5039: 'PN_9347', 76015: 'PN_9047', 14833: 'PN_5612'},
 'CODE': {5039: 'E', 76015: 'D', 14833: 'E'}})

Here is the code I have:

# Calculate the number of years since the last time the piece was ordered

df["Years Since Last Order"] = df.sort_values(by=["PIECE_NUMBER", "Date"]).groupby("PIECE_NUMBER")["Date"].diff().dt.days / 365

# Select only the ID where the number of years since the last time the piece was ordered is greater than 3

df = df[df["Years Since Last Order"] > 3]

Is this the correct implementation? Is there any way to improve it?