问:
Java - check for a particular folder recursively
How should I effectively check for the availability of particular folder(myfolder) recursively and if available, then create a tmp directory parallel to it
Example:

```<code>#ls -l
--parent folder
  --projects
    -- sub folders (further depth is possible)
      -- myfolder
      -- tmp
</code>```

I'm from python background and yet to get used to java. Below is what I could come up with.

```<code>import java.io.File;

class Main
{
    public static void main(String[] args)
    {
        String currentDir = System.getProperty("user.dir");
        String projectDir = currentDir + "/projects"; // under this I have to search the for the `myfolder` recursively.
        File file = new File(projectDir);

        if (file.isDirectory()) {
            new File("tmp").mkdirs();
          }
        else {
            System.out.println("Directory doesn't exist!!");
        }
    }
</code>```

note: I use java 8

答:
Below is a method that recursively searches through all the sub-directories that might be contained within the provided local directory path for a specific directory (folder) name. When the first instance of that directory name is found the search halts and the full path to that directory is returned.

From that point, the returned path string should be parsed to get the parent path. Something like that could be done something like this:

```<code>String foundFolderParentPath = foundDirectory.substring(0,
                                  foundDirectory.lastIndexOf(File.separator));
</code>```

Now you would want to check and see if the tmp directory already exists there. Maybe you don't need to create it or, you may want to carry out some other action based on that fact:

```<code>if (new File(foundFolderParentPath + File.separator + "tmp").exists()) {
    // tmp already exists...Do whatever...
}
else {
    // Otherwise Create the tmp directory...
    new File(foundFolderParentPath + File.separator + "tmp").mkdir();
}
</code>```

Here is the recursive findDirectory() method:

```<code>/**
 * This method recursively searches through all sub-directories beginning
 * from the supplied searchStartPath until the supplied folder to find is
 * found.<br>
 *
 * @param searchStartPath (String) The full path to start the search from.<br>
 *
 * @param folderToSearchFor (String) The directory (folder) or sub-directory
 * (sub-folder) name to search for. Just a single name should be supplied, not multiple directory names..<br>
 *
 * @return (String) If the search is successful then the full path to that
 * found folder is returned. If the search was unsuccessful then Null String
 * (""), an empty string is returned.
 */
public static String findDirectory(String searchStartPath, String folderToSearchFor) {
    String foundPath = "";
    File[] folders = new File(searchStartPath).listFiles(File::isDirectory);
    if (folders.length == 0) {
        return "";
    }
    String tmp;
    for (int i = 0; i < folders.length; i++) {
        String currentPath = folders[i].getAbsolutePath();
        if (currentPath.equals(folderToSearchFor) ||
                    currentPath.substring(currentPath.lastIndexOf(File.separator) + 1)
                                      .equals(folderToSearchFor)) {
             foundPath = currentPath;
             break;
        }
        tmp = "";
        // The recursive call...
        tmp = findDirectory(folders[i].getAbsolutePath(), folderToSearchFor);
        if (!tmp.isEmpty()) {
            // Directory is found...
            foundPath = tmp;
            break; // Get out of loop. It's No longer needed.
        }
    }
    return foundPath;
}
</code>```

How you might use this method:

```<code>String currentDir = System.getProperty("user.dir");
String projectDir = currentDir + "/Projects"; // under this I have to search the for the `myfolder` recursively.
String searchForDirectory =  "mySpecialFolder";
String foundDirectory = findDirectory(currentDir, searchForDirectory);

if (foundDirectory.isEmpty()) {
    System.out.println("The folder to find (" + searchForDirectory
                     + ") could not be found!");
}
else {
    System.out.println("The ' " + searchForDirectory +
                       "' Folder is found at: --> " + foundDirectory);
    /* Create the 'tmp' folder within the same parent folder where
       mySpecialFolder resides in.                      */
    String foundFolderParentPath = foundDirectory.substring(0,
                            foundDirectory.lastIndexOf(File.separator));

    // Is there a 'tmp' folder already there?
    if (new File(foundFolderParentPath + File.separator + "tmp").exists()) {
        // Yes there is..
        System.out.println("\nThere is no need to create the 'tmp' folder! It already"
                    + "exists within the\nparent path of: --> " + foundFolderParentPath);
    }
    else {
        // No here isn't so create it...
        new File(foundFolderParentPath + File.separator + "tmp").mkdir();
        System.out.println("The 'tmp' folder was created within the parent path indicated below:");
        System.out.println(foundFolderParentPath);
        System.out.println();
    }

    // Display a File-Chooser to prove it just for the heck of it.
    javax.swing.JFileChooser fc = new javax.swing.JFileChooser(foundFolderParentPath);
    fc.showDialog(null, "Just A Test");
}
</code>```

Body:
How should I effectively check for the availability of particular folder(myfolder) recursively and if available, then create a tmp directory parallel to it
Example:

#ls -l
--parent folder
  --projects
    -- sub folders (further depth is possible)
      -- myfolder
      -- tmp

I'm from python background and yet to get used to java. Below is what I could come up with.

import java.io.File;

class Main
{
    public static void main(String[] args)
    {
        String currentDir = System.getProperty("user.dir");
        String projectDir = currentDir + "/projects"; // under this I have to search the for the `myfolder` recursively.
        File file = new File(projectDir);

        if (file.isDirectory()) {
            new File("tmp").mkdirs();
          }
        else {
            System.out.println("Directory doesn't exist!!");
        }
    }

note: I use java 8

Body:
Below is a method that recursively searches through all the sub-directories that might be contained within the provided local directory path for a specific directory (folder) name. When the first instance of that directory name is found the search halts and the full path to that directory is returned.

From that point, the returned path string should be parsed to get the parent path. Something like that could be done something like this:

String foundFolderParentPath = foundDirectory.substring(0,
                                  foundDirectory.lastIndexOf(File.separator));

Now you would want to check and see if the tmp directory already exists there. Maybe you don't need to create it or, you may want to carry out some other action based on that fact:

if (new File(foundFolderParentPath + File.separator + "tmp").exists()) {
    // tmp already exists...Do whatever...
}
else {
    // Otherwise Create the tmp directory...
    new File(foundFolderParentPath + File.separator + "tmp").mkdir();
}

Here is the recursive findDirectory() method:

/**
 * This method recursively searches through all sub-directories beginning
 * from the supplied searchStartPath until the supplied folder to find is
 * found.<br>
 *
 * @param searchStartPath (String) The full path to start the search from.<br>
 *
 * @param folderToSearchFor (String) The directory (folder) or sub-directory
 * (sub-folder) name to search for. Just a single name should be supplied, not multiple directory names..<br>
 *
 * @return (String) If the search is successful then the full path to that
 * found folder is returned. If the search was unsuccessful then Null String
 * (""), an empty string is returned.
 */
public static String findDirectory(String searchStartPath, String folderToSearchFor) {
    String foundPath = "";
    File[] folders = new File(searchStartPath).listFiles(File::isDirectory);
    if (folders.length == 0) {
        return "";
    }
    String tmp;
    for (int i = 0; i < folders.length; i++) {
        String currentPath = folders[i].getAbsolutePath();
        if (currentPath.equals(folderToSearchFor) ||
                    currentPath.substring(currentPath.lastIndexOf(File.separator) + 1)
                                      .equals(folderToSearchFor)) {
             foundPath = currentPath;
             break;
        }
        tmp = "";
        // The recursive call...
        tmp = findDirectory(folders[i].getAbsolutePath(), folderToSearchFor);
        if (!tmp.isEmpty()) {
            // Directory is found...
            foundPath = tmp;
            break; // Get out of loop. It's No longer needed.
        }
    }
    return foundPath;
}

How you might use this method:

String currentDir = System.getProperty("user.dir");
String projectDir = currentDir + "/Projects"; // under this I have to search the for the `myfolder` recursively.
String searchForDirectory =  "mySpecialFolder";
String foundDirectory = findDirectory(currentDir, searchForDirectory);

if (foundDirectory.isEmpty()) {
    System.out.println("The folder to find (" + searchForDirectory
                     + ") could not be found!");
}
else {
    System.out.println("The ' " + searchForDirectory +
                       "' Folder is found at: --> " + foundDirectory);
    /* Create the 'tmp' folder within the same parent folder where
       mySpecialFolder resides in.                      */
    String foundFolderParentPath = foundDirectory.substring(0,
                            foundDirectory.lastIndexOf(File.separator));

    // Is there a 'tmp' folder already there?
    if (new File(foundFolderParentPath + File.separator + "tmp").exists()) {
        // Yes there is..
        System.out.println("\nThere is no need to create the 'tmp' folder! It already"
                    + "exists within the\nparent path of: --> " + foundFolderParentPath);
    }
    else {
        // No here isn't so create it...
        new File(foundFolderParentPath + File.separator + "tmp").mkdir();
        System.out.println("The 'tmp' folder was created within the parent path indicated below:");
        System.out.println(foundFolderParentPath);
        System.out.println();
    }

    // Display a File-Chooser to prove it just for the heck of it.
    javax.swing.JFileChooser fc = new javax.swing.JFileChooser(foundFolderParentPath);
    fc.showDialog(null, "Just A Test");
}


来源: stackexchange

问:
How do you make a recipe for kivy-ios?
I have made an app that uses NumPy, SciPy and Pandas which I want to put onto my iOS device. I compile and build using Kivy-iOS but there are errors with the Pandas and SciPy packages and they can't simply be installed via pip install or python toolchain.py pip install.

I have been looking around all day at forums etc and it seems these two need to be built into a recipe. There is already a NumPy recipe that I have included in my attempts to compile, but this doesn't include the other packages.

I haven't ever made a recipe before and can't really find any info on how to do it.

Has anyone done a Pandas or Scipy recipe before, or even some other recipe that I could follow?

EDIT:
I am still unable to find any solutions on this, it seems there is little to no info available on the subject. With my build using kivy-iOS, when I run it in XCode I get the error no module named mmap which I have seen is supposed to be in the python build. So I am unsure what is happening.

If anyone could please help me out, that would be great as I'm very stuck right now.

EDIT:
Bump

答:
I had the same problem. I prepared something like this, for Mqtt:

```<code>from kivy_ios.toolchain import PythonRecipe
class PahoMqtt(PythonRecipe):
   version = "1"
   url = "https://github.com/eclipse/paho.mqtt.python/archive/refs/heads/master.zip"
   depends = ["python"]

   recipe = PahoMqtt()
</code>```

I put it in ..kivy_ios/recipes/paho_mqtt directory. I'm not sure but after 'toolchain build paho_mqtt', compilation process appears to be fine. It works!

ContentLicense: CC BY-SA 4.0

Title: How do you make a recipe for kivy-ios?

Body:
I had the same problem. I prepared something like this, for Mqtt:

from kivy_ios.toolchain import PythonRecipe
class PahoMqtt(PythonRecipe):
   version = "1"
   url = "https://github.com/eclipse/paho.mqtt.python/archive/refs/heads/master.zip"
   depends = ["python"]

   recipe = PahoMqtt()

I put it in ..kivy_ios/recipes/paho_mqtt directory. I'm not sure but after 'toolchain build paho_mqtt', compilation process appears to be fine. It works!


Title: How to change index of a given list's element?

Body:
I have a list of 51 elements.
keypoints = ['0.49395501613616943', '0.3686272203922272', '0.9999948740005493'...]. The original index of my list goes in order from 0,1,2...50. But i have to set new indices to the elements of the list and order them accordingly in a new list. How can i do that?

My new indices:

NEW_INDEX = [39, 40, 41, 21, 22, 23,
27, 28, 29, 33, 34, 35, 24, 25, 26,
30, 31, 32, 36, 37, 38, 42, 43, 44, 45, 46, 47,
48, 49, 50, 3, 4, 5, 9, 10, 11, 15, 16, 17,
6, 7, 8, 12, 13, 14, 18, 19, 20, 0, 1, 2]

Body:
Assuming this question is about python syntax.

In pure python, you can use a list comprehension and indices:

keypoints = ['0.49395501613616943', '0.3686272203922272', '0.9999948740005493', '0.9473770229920709', '0.7699773520016487', '0.540962426318277']
new_index = [2, 1, 5, 4, 0, 3]

ordered_keypoints = [keypoints[i] for i in new_index]

print(ordered_keypoints)
# ['0.9999948740005493', '0.3686272203922272', '0.540962426318277', '0.7699773520016487', '0.49395501613616943', '0.9473770229920709']

Using numpy, there is an even more convenient notation:

import numpy as np

keypoints = np.array(['0.49395501613616943', '0.3686272203922272', '0.9999948740005493', '0.9473770229920709', '0.7699773520016487', '0.540962426318277'])
new_index = np.array([2, 1, 5, 4, 0, 3])

ordered_keypoints = keypoints[new_index]

print(ordered_keypoints)
# ['0.9999948740005493' '0.3686272203922272' '0.540962426318277'
#  '0.7699773520016487' '0.49395501613616943' '0.9473770229920709']


问:
Can't start httpd - Failure while executing; `/bin/launchctl bootstrap gui/501 /Users/*/Library/LaunchAgents/homebrew.mxcl.httpd.plist` exited with 5
Just tried accessing my localhost today, but it doesn't work. I worked yesterday, but I believe it's because my Mac crashed. I've tried started httpd again with brew services start httpd. This results in:

Bootstrap failed: 5: Input/output error
Try re-running the command as root for richer errors.
Error: Failure while executing; /bin/launchctl bootstrap gui/501 /Users/UserName/Library/LaunchAgents/homebrew.mxcl.httpd.plist exited with 5.

Have tried reinstalling httpd, but it still gives the same error.
Any ideas what the cause can be?

答:
I had the same problem after I upgraded to macOS Monterey. But I solved my issue via these commands.

Unload homebrew.mxcl.httpd.plist

```<code>launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.httpd.plist
</code>```

And then load it again:

```<code>launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.httpd.plist
</code>```

After that I used this command to start httpd again.

```<code>brew services start httpd
</code>```

Body:
I had the same problem after I upgraded to macOS Monterey. But I solved my issue via these commands.

Unload homebrew.mxcl.httpd.plist

launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.httpd.plist

And then load it again:

launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.httpd.plist

After that I used this command to start httpd again.

brew services start httpd


问:
React Testing Library: When to use userEvent.click and when to use fireEvent
I'm presently learning React-Testing-Library.

I'd like to test mouse interaction with an element. Presently it's a bit unclear to me the difference between userEvent.click(element) and fireEvent.click(element). Are both recommended for use, and in the example below are they being correctly implemented?

```<code>const mockFunction = jest.fn(() => console.info('button clicked'));
const { getByTestId } = render(<MyAwesomeButton onClick={mockFunction} />);
const myAwesomeButton = getByTestId('my-awesome-button');

// Solution A
fireEvent(myAwesomeButton)
expect(mockFunction.toHaveBeenCalledTimes(1);

// Solution B
userEvent.click(myAwesomeButton);
expect(mockFunction).toHaveBeenCalledTimes(1);
</code>```

Thanks in advance for any clarity.

答:
According to Docs, you should use user-event to test interaction with your components.

fireEvent dispatches exactly the events you tell it to and just those - even if those exact events never had been dispatched in a real interaction in a browser.

User-event on the other hand dispatches the events like they would happen if a user interacted with the document. That might lead to the same events you previously dispatched per fireEvent directly, but it also might catch bugs that make it impossible for a user to trigger said events.

Body:
I'm presently learning React-Testing-Library.

I'd like to test mouse interaction with an element. Presently it's a bit unclear to me the difference between userEvent.click(element) and fireEvent.click(element). Are both recommended for use, and in the example below are they being correctly implemented?

const mockFunction = jest.fn(() => console.info('button clicked'));
const { getByTestId } = render(<MyAwesomeButton onClick={mockFunction} />);
const myAwesomeButton = getByTestId('my-awesome-button');

// Solution A
fireEvent(myAwesomeButton)
expect(mockFunction.toHaveBeenCalledTimes(1);

// Solution B
userEvent.click(myAwesomeButton);
expect(mockFunction).toHaveBeenCalledTimes(1);

Thanks in advance for any clarity.


问:
How do I get rid of okhttp3 "A connection to ... was was leaked" warning when returning a minio stream as spring ResponseEntity?
I am reading a file with minio and have a REST controller that returns the inputstream given by minio as an InputStreamResource. Here is my code:

```<code>@GetMapping("/download")
fun download(): ResponseEntity<InputStreamResource> {

  // read file from minio
  // getObjectResponse is an InputStream
  ...
  val getObjectResponse = minioClient.getObject(getObjectArgs)

  return ResponseEntity.ok().body(InputStreamResource(getObjectResponse))
}
</code>```

According to this question wrapping an InputStream into a InputStreamResource is correct, and spring is supposed to close the underlying InputStream after the reponse is delivered. Yet I still get the infamous

```<code>okhttp3.OkHttpClient: A connection to ... was leaked. Did you forget to close a response body?
</code>```

What are my options here? I would rather not need to copy and buffer the minio content into memory as these files tend to be very large.

答: By using Yuri Schimkes suggestion to improve logging and some debugging I found out that spring is closing the inputstream only when a HTTP 200 is returned and the inpustream is actually read and delivered. In my case sometimes caching happened (spring magic with etags) and spring returned a HTTP 304 without consuming and closing the inputstream.

Body:
I am reading a file with minio and have a REST controller that returns the inputstream given by minio as an InputStreamResource. Here is my code:

@GetMapping("/download")
fun download(): ResponseEntity<InputStreamResource> {

  // read file from minio
  // getObjectResponse is an InputStream
  ...
  val getObjectResponse = minioClient.getObject(getObjectArgs)

  return ResponseEntity.ok().body(InputStreamResource(getObjectResponse))
}

According to this question wrapping an InputStream into a InputStreamResource is correct, and spring is supposed to close the underlying InputStream after the reponse is delivered. Yet I still get the infamous

okhttp3.OkHttpClient: A connection to ... was leaked. Did you forget to close a response body?

What are my options here? I would rather not need to copy and buffer the minio content into memory as these files tend to be very large.


问:
Set (Group) grade array with nested section array and section contains subject array
Here I have an array of objects. I want each grade as a separate array and inside the array, I want the grade based section and subjects.

The schema is with a set of grades, in each grade contains a section array; and in each section contains the subject array.

Input (Sample from DB):

```<code>[
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 924,
    section_name: 'B'
  },
  RowDataPacket {
    grade_id: 5,
    grade_name: '5',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 210,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 3,
    grade_name: '3',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 208,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 3,
    grade_name: '3',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 727,
    section_name: 'B'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 2,
    subject_name: 'English',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 4,
    subject_name: 'Science',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 5,
    subject_name: 'EVS',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 6,
    subject_name: 'Social',
    section_id: 209,
    section_name: 'A'
  }
]
</code>```

Code:

let result = Object.values(results.reduce((a, { grade_id, grade_name, ...props }) => {
    if (!a[grade_id])
        a[grade_id] = Object.assign({}, { grade_id, grade_name: grade_name, sectionDetails: [{ section_id: props.section_id, section_name: props.section_name }] });
    else
        a[grade_id].sectionDetails.push({ section_id: props.section_id, section_name: props.section_name });
    return a;
}, {}));

console.log(result);
```
<p>The output which I get:</p>
```{
    "status_code": 200,
    "status": "success",
    "data": [
        {
            "grade_id": 3,
            "grade_name": "3",
            "sectionDetails": [
                {
                    "section_id": 208,
                    "section_name": "A"
                },
                {
                    "section_id": 727,
                    "section_name": "B"
                }
            ],
        },
        {
            "grade_id": 4,
            "grade_name": "4",
            "sectionDetails": [
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 924,
                    "section_name": "B"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                }
            ],
        },
        {
            "grade_id": 5,
            "grade_name": "5",
            "sectionDetails": [
                {
                    "section_id": 210,
                    "section_name": "A"
                }
            ],
        }
    ],
}
```
<p>Expected schema:</p>
```[
    {
        "grade_id": "3",
        "grade_name": "3",
        "section_details": [
            {
                "section_id": "747",
                "section_name": "A",
                "subject_details": [
                    {
                        "subject_id": 3,
                        "subject_name": "Maths"
                    },
                    {
                        "subject_id": 4,
                        "subject_name": "Science"
                    }
                ],
            }
        ],
    },
    {
        "grade_id": "5",
        "grade_name": "5",
        "section_details": [
            {
                "section_id": "747",
                "section_name": "A",
                "subject_details": [
                    {
                        "subject_id": 3,
                        "subject_name": "Maths"
                    },
                    {
                        "subject_id": 4,
                        "subject_name": "Science"
                    }
                ],
            },
            {
                "section_id": "747",
                "section_name": "A",
                "subject_details": [
                    {
                        "subject_id": 3,
                        "subject_name": "Maths"
                    }
                ]
            }
        ],
    },
]
```

答:
Concept:

Group by grade_id and section_id for subjects.

Group by grade_id from result (1).

let groupedByGradeSection = Object.values(results.reduce((a:{ [key: string]: any }, { grade_id, grade_name, ...props }) => {
    let key = `Grade_${grade_id}_Section_${props.section_id}`;

    if (!a[key])
        a[key] = Object.assign({}, { grade_id, grade_name: grade_name, section_id: props.section_id, section_name: props.section_name, subject_details: [{  subject_id: props.subject_id, subject_name: props.subject_name  }] });
    else
        a[key].subject_details.push({  subject_id: props.subject_id, subject_name: props.subject_name  });
    return a;
}, {}));

let result = Object.values(groupedByGradeSection.reduce((a:{ [key: string]: any }, { grade_id, grade_name, ...props }) => {
    if (!a[grade_id])
        a[grade_id] = Object.assign({}, { grade_id, grade_name: grade_name, section_details: [{  section_id: props.section_id, section_name: props.section_name, subject_details: props.subject_details  }] });
    else
        a[grade_id].section_details.push({  section_id: props.section_id, section_name: props.section_name, subject_details: props.subject_details  });
    return a;
}, {}));

console.log(result);
```

Sample Demo on Typescript Playground

Body:
Here I have an array of objects. I want each grade as a separate array and inside the array, I want the grade based section and subjects.

The schema is with a set of grades, in each grade contains a section array; and in each section contains the subject array.

Input (Sample from DB):

[
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 924,
    section_name: 'B'
  },
  RowDataPacket {
    grade_id: 5,
    grade_name: '5',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 210,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 3,
    grade_name: '3',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 208,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 3,
    grade_name: '3',
    subject_id: 3,
    subject_name: 'Maths',
    section_id: 727,
    section_name: 'B'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 2,
    subject_name: 'English',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 4,
    subject_name: 'Science',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 5,
    subject_name: 'EVS',
    section_id: 209,
    section_name: 'A'
  },
  RowDataPacket {
    grade_id: 4,
    grade_name: '4',
    subject_id: 6,
    subject_name: 'Social',
    section_id: 209,
    section_name: 'A'
  }
]

Code:

let result = Object.values(results.reduce((a, { grade_id, grade_name, ...props }) => {
    if (!a[grade_id])
        a[grade_id] = Object.assign({}, { grade_id, grade_name: grade_name, sectionDetails: [{ section_id: props.section_id, section_name: props.section_name }] });
    else
        a[grade_id].sectionDetails.push({ section_id: props.section_id, section_name: props.section_name });
    return a;
}, {}));

console.log(result);

The output which I get:

{
    "status_code": 200,
    "status": "success",
    "data": [
        {
            "grade_id": 3,
            "grade_name": "3",
            "sectionDetails": [
                {
                    "section_id": 208,
                    "section_name": "A"
                },
                {
                    "section_id": 727,
                    "section_name": "B"
                }
            ],
        },
        {
            "grade_id": 4,
            "grade_name": "4",
            "sectionDetails": [
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 924,
                    "section_name": "B"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                },
                {
                    "section_id": 209,
                    "section_name": "A"
                }
            ],
        },
        {
            "grade_id": 5,
            "grade_name": "5",
            "sectionDetails": [
                {
                    "section_id": 210,
                    "section_name": "A"
                }
            ],
        }
    ],
}

Expected schema:

[
    {
        "grade_id": "3",
        "grade_name": "3",
        "section_details": [
            {
                "section_id": "747",
                "section_name": "A",
                "subject_details": [
                    {
                        "subject_id": 3,
                        "subject_name": "Maths"
                    },
                    {
                        "subject_id": 4,
                        "subject_name": "Science"
                    }
                ],
            }
        ],
    },
    {
        "grade_id": "5",
        "grade_name": "5",
        "section_details": [
            {
                "section_id": "747",
                "section_name": "A",
                "subject_details": [
                    {
                        "subject_id": 3,
                        "subject_name": "Maths"
                    },
                    {
                        "subject_id": 4,
                        "subject_name": "Science"
                    }
                ],
            },
            {
                "section_id": "747",
                "section_name": "A",
                "subject_details": [
                    {
                        "subject_id": 3,
                        "subject_name": "Maths"
                    }
                ]
            }
        ],
    },
]

Body:
Concept:

Group by grade_id and section_id for subjects.

Group by grade_id from result (1).

let groupedByGradeSection = Object.values(results.reduce((a:{ [key: string]: any }, { grade_id, grade_name, ...props }) => {
    let key = `Grade_${grade_id}_Section_${props.section_id}`;

    if (!a[key])
        a[key] = Object.assign({}, { grade_id, grade_name: grade_name, section_id: props.section_id, section_name: props.section_name, subject_details: [{  subject_id: props.subject_id, subject_name: props.subject_name  }] });
    else
        a[key].subject_details.push({  subject_id: props.subject_id, subject_name: props.subject_name  });
    return a;
}, {}));

let result = Object.values(groupedByGradeSection.reduce((a:{ [key: string]: any }, { grade_id, grade_name, ...props }) => {
    if (!a[grade_id])
        a[grade_id] = Object.assign({}, { grade_id, grade_name: grade_name, section_details: [{  section_id: props.section_id, section_name: props.section_name, subject_details: props.subject_details  }] });
    else
        a[grade_id].section_details.push({  section_id: props.section_id, section_name: props.section_name, subject_details: props.subject_details  });
    return a;
}, {}));

console.log(result);

<a href="https://www.typescriptlang.org/play?ssl=96&ssc=21&pln=76&pc=1#code/DYUwLgBATiDOCuwywgXggbQFAQgbx1wgHMoBDAExAH0BLCgLggBYAaQ3UymgOzIFsQTAOTNh7IhAQAjAFYgAxmDqMIAZglEZ8pdT6CRAWTJgAFrHEcpisLQD2PFUwBMABgCcm3LBv3H+oQhhAEFhQgBfTQJJLionFi8ScjiAkTFE7Rt4jStM3VSg4zMLDN8HePdnNlyy-wFA4QAhMNxIwmiiWJp6JgBWRK69epFey0k85R71DPg5LILhIvMxrVr45wBGV1KlPyGDINCIqKtBqZyY5N5hoLUV71mdSdULrUf5m8WTZZ3bcqm3AAOX57BZHVonS7cbIDK77Bp3GZzXTnJFPeFGb4lGq7f6qADsznxIPKC2ax3apzhU2qUJSn3SuXeKNUzjRHwOwgAojxiMBaLBTPdrLjHACPCS6pzwRA2rgOpxqapaZ04QtGeNmc8mCqHsjlAsAMoKWggHgKEDCnyi9YSnF-KUNGVy-BU6E02HQ9VWrXxfpM-UYoJcgBqhqta3FnntoM+zshqvdys99M5GregamADZ2flPoa7CayMAIzao5KgyEWrKsABdADcWCwoEgpDs8AADiAKI0AJ4AcSuhtqaAgAHl9QA6ABuxfgcAAFDAEEhYJOYBR4BaFwuyAw8JgANYgXtMWBgKC0Xm1phkHi92WsfBJJNPwYBJ+Tr8dqB2DsocIAEo0AAPldSQWwgY8H3QAADQdoQAEjwM4KHCahhxtZCfz-NdrQdFRwlgxtJCsWgADMIAXABCMgMGg2tAKsSQ6IY0cJyeScyFgWBaGIHgFzwSJn1Qt81Rud96iffC9imHD-0nGS8WktYCnkvDVKkqRfSoMAyFoYBYCYDAD20zNVHUxTfXoaTfTU38FImeFWlrWVAJIogQEMkBmKIViT1rKzA10-TDMnDt4EFQS9XROSHLw6yKFswN7NwoL0QCVp3KsGAwHgKAeAgMhG2EoTAOyrAAHpKoUBxYDsUBJ2AOxiAXNtO27PsEKoTCHQqyDl0QSB0A4mwZznRd2q7HsByHWp127LcQB3PcD3ok8zwvK9iBvIr70fESlTEr0tK-cL4rc0DwKICiqNojBUMY3zcDox72KnbjeP4wTSpfOIbL+64DkkwQVJtEKDKMzBTKUsULPixTIySkUCNSxzNNBsz0QhwymEspycZQWVXKAjzcC8nxnqKh6lUC2HqEJ8LItMaKUdk+G0vpgH6bRjSbQ-LGskJvGEYJ8BQqJ0mcvAfLCuKrBSqAirap4erGua1rBqQdygA" rel="nofollow noreferrer">Sample Demo on Typescript Playground


问:
How to make the (fixed) content hide and show after rest content is scrolled

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
  <head>
    <body>

        <div>
            <h1>hello</h1>
            <img src="image.jpeg" alt="">
        </div>
        <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit.
             endis iusto eligendi rem solutaaborummaxime?
        </p>
    </body>
  </head>
</html></code>```

Hello, I want the fixed bottom content to be visible after all the upper contents are scrolled using html and css only if possible or by using js.

答:
```<code><!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title></title>
   </head>
   <body>
    <style>

    * {
        box-sizing: content-box;
    }

    /*grid background https: //stackoverflow.com/questions/3540194/how-to-make-a-grid-like-graph-paper-grid-with-just-css */

    body {
        background-size: 50px 50px;
        background-image: linear-gradient(to right, red 1px, transparent 1px), linear-gradient(to bottom, blue 1px, transparent 1px);
        margin: 0px;
        padding: 0px;
    }

    div.content {
        background: #aaaa;
        /* mystical numbers maybe to do with margin collapse
             https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
             */
        margin-top: -15px
    }

    p {
        background-color: aqua;
        position: fixed;
        bottom: 0;
    }

    div.sentinel {
        height: 0px;
        background-color: #f00;
    }

    .hide {
        opacity: 0;
    }

    .filler {
        height: 100px;
        background: #dddd;
        margin: 5px;
    }

    </style>
      <div class="filler"></div>
      <div class="content">
         <h1>hello</h1>
         <img src="https://via.placeholder.com/150" alt="" height="150px" width="150px">
      </div>
      <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit.
         endis iusto eligendi rem solutaaborummaxime?
      </p>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="sentinel"></div>
      <script>
         /* https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API */
         /* https://developers.google.com/web/updates/2016/04/intersectionobserver*/
         /* https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units */
         /* https://prettier.io/playground/ */
         /* https://www.freeformatter.com/css-beautifier.html */
         /* https://www.freeformatter.com/html-formatter.html */
         /* https://goonlinetools.com/html-formatter/ */
         var intersectionObserver = new IntersectionObserver(
           (entries) => {
             entries.forEach((entry) => {
               console.log(entry);
               console.log(entry.time);
               console.log(entry.target);
               console.log(entry.isIntersecting);
               console.log(entry.intersectionRatio);
               console.log(entry.intersectionRect);
               console.log(entry.boundingClientRect);
               console.log(entry.rootBounds);
             });
             if (entries[0].isIntersecting) {
               p.classList.add("hide");
             } else {
               p.classList.remove("hide");
             }
           },
           {
             root: null,
             threshold: 0,
             /* rootMargin expand bottom to make sure sentinel hits */
             rootMargin: "0px 0px 1px 0px",
           }
         );
         var mySentinel = document.querySelector("div.sentinel");
         var p = document.querySelector("p");
         intersectionObserver.observe(mySentinel);

      </script>
   </body>
</html>
</code>```

Use sentinel at bottom of body. Note: sentinel can be zero height. Increase rootMargin bottom to make sure sentinel invokes intersectionobserver callback when it transitions to anywhere in the viewport (threshold:0 and root:null).

Body:
hello

Lorem ipsum dolor, sit amet consectetur adipisicing elit.
             endis iusto eligendi rem solutaaborummaxime?

Hello, I want the fixed bottom content to be visible after all the upper contents are scrolled using html and css only if possible or by using js.

Body:
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <title></title>
   </head>
   <body>
    <style>

    * {
        box-sizing: content-box;
    }

    /*grid background https: //stackoverflow.com/questions/3540194/how-to-make-a-grid-like-graph-paper-grid-with-just-css */

    body {
        background-size: 50px 50px;
        background-image: linear-gradient(to right, red 1px, transparent 1px), linear-gradient(to bottom, blue 1px, transparent 1px);
        margin: 0px;
        padding: 0px;
    }

    div.content {
        background: #aaaa;
        /* mystical numbers maybe to do with margin collapse
             https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
             */
        margin-top: -15px
    }

    p {
        background-color: aqua;
        position: fixed;
        bottom: 0;
    }

    div.sentinel {
        height: 0px;
        background-color: #f00;
    }

    .hide {
        opacity: 0;
    }

    .filler {
        height: 100px;
        background: #dddd;
        margin: 5px;
    }

    </style>
      <div class="filler"></div>
      <div class="content">
         <h1>hello</h1>
         <img src="https://via.placeholder.com/150" alt="" height="150px" width="150px">
      </div>
      <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit.
         endis iusto eligendi rem solutaaborummaxime?
      </p>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="filler"></div>
      <div class="sentinel"></div>
      <script>
         /* https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API */
         /* https://developers.google.com/web/updates/2016/04/intersectionobserver*/
         /* https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units */
         /* https://prettier.io/playground/ */
         /* https://www.freeformatter.com/css-beautifier.html */
         /* https://www.freeformatter.com/html-formatter.html */
         /* https://goonlinetools.com/html-formatter/ */
         var intersectionObserver = new IntersectionObserver(
           (entries) => {
             entries.forEach((entry) => {
               console.log(entry);
               console.log(entry.time);
               console.log(entry.target);
               console.log(entry.isIntersecting);
               console.log(entry.intersectionRatio);
               console.log(entry.intersectionRect);
               console.log(entry.boundingClientRect);
               console.log(entry.rootBounds);
             });
             if (entries[0].isIntersecting) {
               p.classList.add("hide");
             } else {
               p.classList.remove("hide");
             }
           },
           {
             root: null,
             threshold: 0,
             /* rootMargin expand bottom to make sure sentinel hits */
             rootMargin: "0px 0px 1px 0px",
           }
         );
         var mySentinel = document.querySelector("div.sentinel");
         var p = document.querySelector("p");
         intersectionObserver.observe(mySentinel);

      </script>
   </body>
</html>

Use sentinel at bottom of body. Note: sentinel can be zero height. Increase rootMargin bottom to make sure sentinel invokes intersectionobserver callback when it transitions to anywhere in the viewport (threshold:0 and root:null).


问:
How to get renamed enum name from enum value?
So I have

```<code>#[derive(Deserialize, Clone, Debug, Copy)]
pub enum ComparisonOperators {
    #[serde(rename = "=")]
    EQ,
    #[serde(rename = "!=")]
    NEQ,
    #[serde(rename = ">")]
    GT,
    #[serde(rename = ">=")]
    GE,
    #[serde(rename = "<")]
    LT,
    #[serde(rename = "<=")]
    LE,
}
</code>```

I want to get from let i = ComparisonOperators::GE to ">=". Can I do this by not adding a mapper?

答:
You can add the Serialize tag, and then use the serde_json to serialize to a String as per your attributes renaming:

use serde::{Deserialize, Serialize};
use serde_json; // 1.0.78

#[derive(Deserialize, Serialize, Clone, Debug, Copy)]
pub enum ComparisonOperators {
    #[serde(rename = "=")]
    EQ,
    #[serde(rename = "!=")]
    NEQ,
    #[serde(rename = ">")]
    GT,
    #[serde(rename = ">=")]
    GE,
    #[serde(rename = "<")]
    LT,
    #[serde(rename = "<=")]
    LE,
}

fn main() {
    let tag = serde_json::to_string(&ComparisonOperators::EQ).unwrap();
    println!("{tag}");
}
```
<p>Playground</p>
<p>You can even implement display for your enum based on that:</p>
<pre class="lang-rust prettyprint-override"><code>impl fmt::Display for ComparisonOperators {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", serde_json::to_string(self).unwrap())
    }
}
</code>```

Playground

Remember that Display gives you a ToString implementation for free.

Body:
So I have

#[derive(Deserialize, Clone, Debug, Copy)]
pub enum ComparisonOperators {
    #[serde(rename = "=")]
    EQ,
    #[serde(rename = "!=")]
    NEQ,
    #[serde(rename = ">")]
    GT,
    #[serde(rename = ">=")]
    GE,
    #[serde(rename = "<")]
    LT,
    #[serde(rename = "<=")]
    LE,
}

I want to get from let i = ComparisonOperators::GE to ">=". Can I do this by not adding a mapper?

Body:
You can add the Serialize tag, and then use the serde_json to serialize to a String as per your attributes renaming:

use serde::{Deserialize, Serialize};
use serde_json; // 1.0.78

#[derive(Deserialize, Serialize, Clone, Debug, Copy)]
pub enum ComparisonOperators {
    #[serde(rename = "=")]
    EQ,
    #[serde(rename = "!=")]
    NEQ,
    #[serde(rename = ">")]
    GT,
    #[serde(rename = ">=")]
    GE,
    #[serde(rename = "<")]
    LT,
    #[serde(rename = "<=")]
    LE,
}

fn main() {
    let tag = serde_json::to_string(&ComparisonOperators::EQ).unwrap();
    println!("{tag}");
}

Playground

You can even implement display for your enum based on that:

impl fmt::Display for ComparisonOperators {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", serde_json::to_string(self).unwrap())
    }
}

Playground

Remember that Display gives you a ToString implementation for free.


问:
React Native, accessing a single element from an array nested in state
how can I access a single element from an array nested in a state like this

```<code>state = {
    modal: false,
    post: [
      {
        key: "1",
        title: "A Good Boi",
        des: "He's a good boi and every one know it.",
        image: require("../assets/dog.jpg"),
      },
      {
        key: "2",
        title: "John Cena",
        des: "As you can see, You can't see me!",
        image: require("../assets/cena.jpg"),
      },
    ]
  };
.....
    <MyList.Provider
          value={{

          }}
        >
          <FlatList
            data={this.state.post}
            renderItem={({ item }) => (
              <>
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => this.deleteItem(item)}
                  style={styles.Delete}
                >
                  <MaterialCommunityIcons name="delete" color="red" size={30} />
                </TouchableOpacity>
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => this.props.navigation.navigate("Edit", item)}
                  style={styles.Edit}
                >
                  <MaterialCommunityIcons
                    name="playlist-edit"
                    color="green"
                    size={35}
                  />
                </TouchableOpacity>
                <Card
                  title={item.title}
                  subTitle={item.des}
                  image={item.image}
                  onPress={() =>
                    this.props.navigation.navigate("Details", item)
                  }
                />
              </>
            )}
          />
        </MyList.Provider>
</code>```

how can I do this like this.state.post({title}) or some way else??
I need to use this values with context so I can share and change some particular data with between 2 screens.  I know  to pass data I need to use context or navigation.navigate("route name",item). But if I use navigation I won't able to edit it but how can I pass data in context value from array set, if I do this.state.post it will return whole list and if i do this.state.post[0].title it will return only title of that post. So how can i do this? Please help

答:
Use .map() function
Ex-

var cat_data = categories_list.map(function (item) {

```<code>var cat_data = categories_list.map(function (item) {
    return {
      name: item.Name,
      thumb_url: item.PictureModel.ImageUrl,
      cat_id: item.Id.toString(),
    };
  });
  this.setState({
    data: cat_data,
  });
</code>```

Body:
how can I access a single element from an array nested in a state like this

state = {
    modal: false,
    post: [
      {
        key: "1",
        title: "A Good Boi",
        des: "He's a good boi and every one know it.",
        image: require("../assets/dog.jpg"),
      },
      {
        key: "2",
        title: "John Cena",
        des: "As you can see, You can't see me!",
        image: require("../assets/cena.jpg"),
      },
    ]
  };
.....
    <MyList.Provider
          value={{

          }}
        >
          <FlatList
            data={this.state.post}
            renderItem={({ item }) => (
              <>
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => this.deleteItem(item)}
                  style={styles.Delete}
                >
                  <MaterialCommunityIcons name="delete" color="red" size={30} />
                </TouchableOpacity>
                <TouchableOpacity
                  activeOpacity={0.7}
                  onPress={() => this.props.navigation.navigate("Edit", item)}
                  style={styles.Edit}
                >
                  <MaterialCommunityIcons
                    name="playlist-edit"
                    color="green"
                    size={35}
                  />
                </TouchableOpacity>
                <Card
                  title={item.title}
                  subTitle={item.des}
                  image={item.image}
                  onPress={() =>
                    this.props.navigation.navigate("Details", item)
                  }
                />
              </>
            )}
          />
        </MyList.Provider>

how can I do this like this.state.post({title}) or some way else??
I need to use this values with context so I can share and change some particular data with between 2 screens.  I know  to pass data I need to use context or navigation.navigate("route name",item). But if I use navigation I won't able to edit it but how can I pass data in context value from array set, if I do this.state.post it will return whole list and if i do this.state.post[0].title it will return only title of that post. So how can i do this? Please help

Body:
Use .map() function
Ex-

var cat_data = categories_list.map(function (item) {

var cat_data = categories_list.map(function (item) {
    return {
      name: item.Name,
      thumb_url: item.PictureModel.ImageUrl,
      cat_id: item.Id.toString(),
    };
  });
  this.setState({
    data: cat_data,
  });


问:
Prepare map of list with values from object where key is value from list inside this object
I have class like:

```<code>public class User {
   private Long id;
   private String firstname;
   private String lastname;
   private Address address;
   private boolean active;
   private List<Country> countries;
}

public class Country {
  private String name;
  private String capital;
}
</code>```

And I need to sort users by country's name. I made something like this:

```<code>        final Map<String, List<UserHelper>> usersByCountry = new HashMap<>();

        users.stream()
                .filter(User::isActive)
                .forEach(user -> user.getCountry().stream()
                        .map(Country::getName)
                        .forEach(name -> {
                            if (usersByCountry.containsKey(name)) {
                                usersByCountry.get(name).add(new UserHelper(user.getId(), user.getFirstname()));
                            } else {
                                usersByCountry.put(name, new ArrayList<>(List.of(new UserHelper(user.getId(), user.getFirstname()))));
                            }
                        }));

    @Value
    private class UserHelper {
        Long id;
        String firstname;
    }
</code>```

But I want to avoid adding elements to map in foreach. I prefer something like Collectors.toMap() or groupingBy but I don't have any idea how can I do this in this place.

答:
If I understood your question correctly, you want to group the users by their countries. As a user can have many countries, you have to expect a user to possibly end up in multiple groups.

One way would be to introduce an auxiliary class, UserCountry:

```<code>public record UserCountry(User user, Country country) {}
</code>```

(this could be a class if you do not have Java 16+).

Then you could flatMap all users together with their countries, and group by each country:

```<code>final Map<Country, List<User>> result =
    users.stream()
        .flatMap(user -> user.countries.stream().map(country -> new UserCountry(user, country)))
        .collect(
            Collectors.groupingBy(
                UserCountry::country,
                Collectors.mapping(UserCountry::user, Collectors.toList())));
</code>```

Body:
I have class like:

public class User {
   private Long id;
   private String firstname;
   private String lastname;
   private Address address;
   private boolean active;
   private List<Country> countries;
}

public class Country {
  private String name;
  private String capital;
}

And I need to sort users by country's name. I made something like this:

        final Map<String, List<UserHelper>> usersByCountry = new HashMap<>();

        users.stream()
                .filter(User::isActive)
                .forEach(user -> user.getCountry().stream()
                        .map(Country::getName)
                        .forEach(name -> {
                            if (usersByCountry.containsKey(name)) {
                                usersByCountry.get(name).add(new UserHelper(user.getId(), user.getFirstname()));
                            } else {
                                usersByCountry.put(name, new ArrayList<>(List.of(new UserHelper(user.getId(), user.getFirstname()))));
                            }
                        }));

    @Value
    private class UserHelper {
        Long id;
        String firstname;
    }

But I want to avoid adding elements to map in foreach. I prefer something like Collectors.toMap() or groupingBy but I don't have any idea how can I do this in this place.

Body:
If I understood your question correctly, you want to group the users by their countries. As a user can have many countries, you have to expect a user to possibly end up in multiple groups.

One way would be to introduce an auxiliary class, UserCountry:

public record UserCountry(User user, Country country) {}

(this could be a class if you do not have Java 16+).

Then you could flatMap all users together with their countries, and group by each country:

final Map<Country, List<User>> result =
    users.stream()
        .flatMap(user -> user.countries.stream().map(country -> new UserCountry(user, country)))
        .collect(
            Collectors.groupingBy(
                UserCountry::country,
                Collectors.mapping(UserCountry::user, Collectors.toList())));


问:
Hibernate Creating Or Updating Entity triggers update on related (Child) Entity
Whenever I update UserEntity hibernate triggers an update on the related UserRoles table. I found similar issues here but could not find a working solution.

```<code>@Entity
@Table(name = "users")
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserEntity implements Serializable {

  @Id
  @GeneratedValue(strategy = AUTO)
  private UUID uuid;

  @Column(name = "first_name")
  private String firstName;

  @Column(name = "last_name")
  private String lastName;

  private String email;

  @JsonIgnore private String password;

  @JsonIgnore
  @OneToMany(mappedBy = "user", fetch = LAZY, cascade = REMOVE)
  @Builder.Default
  private List<UserRoleEntity> roles = new ArrayList<>();
</code>```
```<code>@Entity
@Table(name = "user_roles")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EntityListeners(AuditingEntityListener.class)
@TypeDef(name = "enum_postgres_sql", typeClass = PostgresEnumType.class)
public class UserRoleEntity {

  @Id
  @GeneratedValue(strategy = AUTO)
  private UUID uuid;

  @Column(name = "role")
  @Enumerated(STRING)
  @Type(type = "enum_postgres_sql")
  private Role role;

  @ManyToOne
  @JoinColumn(name = "user_uuid", updatable = false)
  private UserEntity user;

  @Type(
      type = "com.vladmihalcea.hibernate.type.array.ListArrayType",
      parameters = {@Parameter(name = ListArrayType.SQL_ARRAY_TYPE, value = "permission")})
  @Column(name = "permissions", columnDefinition = "permission[]")
  @Builder.Default
  private List<Permission> permissions = new ArrayList<>();

  @CreatedBy @OneToOne private UserEntity createdBy;

  @LastModifiedBy @OneToOne private UserEntity lastModifiedBy;
}

</code>```

Create user:

```<code>UserEntity user =
        UserEntity.builder()
            .firstName(dto.getFirstName())
            .lastName(dto.getLastName())
            .email(dto.getEmail())
            .createdAt(LocalDateTime.now())
            .build();
repository.save(user);
</code>```

Update user:

```<code> repository
        .findById(uuid)
        .ifPresentOrElse(
            e -> {
              e.setFirstName(dto.getFirstName());
              e.setLastName(dto.getLastName());
              if (!StringUtils.equals(dto.getEmail(), e.getEmail())) {
                e.setEmail(dto.getEmail());
              }
              e.setUpdatedAt(LocalDateTime.now());
              repository.save(e);
            },
            () -> {
              LOGGER.error("UserEntity with uuid: {} not found", uuid);
              throw new UserEntityNotFoundException(uuid);
            });
</code>```

Repo

```<code>import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<UserEntity, UUID> {}
</code>```

Does anyone have an idea how to prevent this?

The reason I want to prevent this is that I'm using triggers in Postgresql to write logs of user actions and unnecessary updates mess things up... :(

Here are some logs:

```<code>2021-07-07 01:17:04,748 INFO  o.s.d.r.c.DeferredRepositoryInitializationListener:53 - Spring Data repositories initialized!
2021-07-07 01:17:04,768 INFO  c.s.j.l.u.w.UserLogControllerGetCreatedUserIntegrationTest:61 - Started UserLogControllerGetCreatedUserIntegrationTest in 36.711 seconds (JVM running for 39.424)
2021-07-07 01:17:04,936 DEBUG c.s.j.t.m.DatabaseMixin:31 - TestContainers database properties: test@jdbc:postgresql://localhost:56611/test?loggerLevel=OFF
2021-07-07 01:17:05,112 DEBUG o.h.SQL:128 -
    insert
    into
        users
        (changed_by_uuid, company_uuid, created_at, email, first_name, last_name, password, status, type, updated_at, uuid)
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2021-07-07 01:17:05,115 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [1] as [OTHER] - [null]
2021-07-07 01:17:05,115 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [2] as [OTHER] - [null]
2021-07-07 01:17:05,116 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [3] as [TIMESTAMP] - [2021-07-07T01:17:05.104298]
2021-07-07 01:17:05,117 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [VARCHAR] - [new@test.com]
2021-07-07 01:17:05,117 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [VARCHAR] - [John]
2021-07-07 01:17:05,118 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [6] as [VARCHAR] - [Doe]
2021-07-07 01:17:05,118 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [7] as [VARCHAR] - [$2a$10$woVXWhuoHEqoIZMlul6/4.cc.33AyTCUc8nDWDiqImuj0vqlY.PK.]
2021-07-07 01:17:05,118 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [10] as [TIMESTAMP] - [2021-07-07T01:17:05.104346]
2021-07-07 01:17:05,119 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [11] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,140 DEBUG o.h.SQL:128 -
    insert
    into
        user_roles
        (changed_by_uuid, permissions, role, user_uuid, uuid)
    values
        (?, ?, ?, ?, ?)
2021-07-07 01:17:05,140 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [1] as [OTHER] - [null]
2021-07-07 01:17:05,141 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [2] as [ARRAY] - [[Ljava.lang.Object;@24be7cee]
2021-07-07 01:17:05,152 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,153 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [OTHER] - [2fa664b9-f9cd-4092-a38b-c46d47c0ab95]
2021-07-07 01:17:05,156 DEBUG o.h.SQL:128 -
    update
        user_roles
    set
        changed_by_uuid=?,
        permissions=?,
        role=?,
        user_uuid=?
    where
        uuid=?
2021-07-07 01:17:05,156 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [1] as [OTHER] - [null]
2021-07-07 01:17:05,157 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [2] as [ARRAY] - [[CREATE]]
2021-07-07 01:17:05,157 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,157 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [OTHER] - [2fa664b9-f9cd-4092-a38b-c46d47c0ab95]
2021-07-07 01:17:05,165 DEBUG o.h.SQL:128 -
    insert
    into
        user_roles
        (changed_by_uuid, permissions, role, user_uuid, uuid)
    values
        (?, ?, ?, ?, ?)
2021-07-07 01:17:05,165 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [1] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,165 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [2] as [ARRAY] - [[Ljava.lang.Object;@4bc4b33b]
2021-07-07 01:17:05,166 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,166 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [OTHER] - [afe1ed15-005f-4c2e-8d55-bd3db570dc2e]
2021-07-07 01:17:05,168 DEBUG o.h.SQL:128 -
    update
        user_roles
    set
        changed_by_uuid=?,
        permissions=?,
        role=?,
        user_uuid=?
    where
        uuid=?
</code>```

答:
The permissions were mapped badly

This is the way it should look

permissions column is mutable and Hibernate flushes again because it can't determine dirtiness

The solution was:

```<code>  @Type(
      type = "com.vladmihalcea.hibernate.type.array.EnumArrayType",
      parameters = {@Parameter(name = EnumArrayType.SQL_ARRAY_TYPE, value = "permission")})
  @Column(name = "permissions", columnDefinition = "permission[]")
  private Permission[] permissions;
</code>```

Body:
Whenever I update UserEntity hibernate triggers an update on the related UserRoles table. I found similar issues here but could not find a working solution.

@Entity
@Table(name = "users")
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserEntity implements Serializable {

  @Id
  @GeneratedValue(strategy = AUTO)
  private UUID uuid;

  @Column(name = "first_name")
  private String firstName;

  @Column(name = "last_name")
  private String lastName;

  private String email;

  @JsonIgnore private String password;

  @JsonIgnore
  @OneToMany(mappedBy = "user", fetch = LAZY, cascade = REMOVE)
  @Builder.Default
  private List<UserRoleEntity> roles = new ArrayList<>();

@Entity
@Table(name = "user_roles")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@EntityListeners(AuditingEntityListener.class)
@TypeDef(name = "enum_postgres_sql", typeClass = PostgresEnumType.class)
public class UserRoleEntity {

  @Id
  @GeneratedValue(strategy = AUTO)
  private UUID uuid;

  @Column(name = "role")
  @Enumerated(STRING)
  @Type(type = "enum_postgres_sql")
  private Role role;

  @ManyToOne
  @JoinColumn(name = "user_uuid", updatable = false)
  private UserEntity user;

  @Type(
      type = "com.vladmihalcea.hibernate.type.array.ListArrayType",
      parameters = {@Parameter(name = ListArrayType.SQL_ARRAY_TYPE, value = "permission")})
  @Column(name = "permissions", columnDefinition = "permission[]")
  @Builder.Default
  private List<Permission> permissions = new ArrayList<>();

  @CreatedBy @OneToOne private UserEntity createdBy;

  @LastModifiedBy @OneToOne private UserEntity lastModifiedBy;
}

Create user:

UserEntity user =
        UserEntity.builder()
            .firstName(dto.getFirstName())
            .lastName(dto.getLastName())
            .email(dto.getEmail())
            .createdAt(LocalDateTime.now())
            .build();
repository.save(user);

Update user:

 repository
        .findById(uuid)
        .ifPresentOrElse(
            e -> {
              e.setFirstName(dto.getFirstName());
              e.setLastName(dto.getLastName());
              if (!StringUtils.equals(dto.getEmail(), e.getEmail())) {
                e.setEmail(dto.getEmail());
              }
              e.setUpdatedAt(LocalDateTime.now());
              repository.save(e);
            },
            () -> {
              LOGGER.error("UserEntity with uuid: {} not found", uuid);
              throw new UserEntityNotFoundException(uuid);
            });

Repo

import org.springframework.data.repository.CrudRepository;

public interface UserRepository extends CrudRepository<UserEntity, UUID> {}

Does anyone have an idea how to prevent this?

The reason I want to prevent this is that I'm using triggers in Postgresql to write logs of user actions and unnecessary updates mess things up... :(

Here are some logs:

2021-07-07 01:17:04,748 INFO  o.s.d.r.c.DeferredRepositoryInitializationListener:53 - Spring Data repositories initialized!
2021-07-07 01:17:04,768 INFO  c.s.j.l.u.w.UserLogControllerGetCreatedUserIntegrationTest:61 - Started UserLogControllerGetCreatedUserIntegrationTest in 36.711 seconds (JVM running for 39.424)
2021-07-07 01:17:04,936 DEBUG c.s.j.t.m.DatabaseMixin:31 - TestContainers database properties: test@jdbc:postgresql://localhost:56611/test?loggerLevel=OFF
2021-07-07 01:17:05,112 DEBUG o.h.SQL:128 -
    insert
    into
        users
        (changed_by_uuid, company_uuid, created_at, email, first_name, last_name, password, status, type, updated_at, uuid)
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2021-07-07 01:17:05,115 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [1] as [OTHER] - [null]
2021-07-07 01:17:05,115 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [2] as [OTHER] - [null]
2021-07-07 01:17:05,116 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [3] as [TIMESTAMP] - [2021-07-07T01:17:05.104298]
2021-07-07 01:17:05,117 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [VARCHAR] - [new@test.com]
2021-07-07 01:17:05,117 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [VARCHAR] - [John]
2021-07-07 01:17:05,118 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [6] as [VARCHAR] - [Doe]
2021-07-07 01:17:05,118 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [7] as [VARCHAR] - [$2a$10$woVXWhuoHEqoIZMlul6/4.cc.33AyTCUc8nDWDiqImuj0vqlY.PK.]
2021-07-07 01:17:05,118 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [10] as [TIMESTAMP] - [2021-07-07T01:17:05.104346]
2021-07-07 01:17:05,119 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [11] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,140 DEBUG o.h.SQL:128 -
    insert
    into
        user_roles
        (changed_by_uuid, permissions, role, user_uuid, uuid)
    values
        (?, ?, ?, ?, ?)
2021-07-07 01:17:05,140 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [1] as [OTHER] - [null]
2021-07-07 01:17:05,141 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [2] as [ARRAY] - [[Ljava.lang.Object;@24be7cee]
2021-07-07 01:17:05,152 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,153 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [OTHER] - [2fa664b9-f9cd-4092-a38b-c46d47c0ab95]
2021-07-07 01:17:05,156 DEBUG o.h.SQL:128 -
    update
        user_roles
    set
        changed_by_uuid=?,
        permissions=?,
        role=?,
        user_uuid=?
    where
        uuid=?
2021-07-07 01:17:05,156 TRACE o.h.t.d.s.BasicBinder:52 - binding parameter [1] as [OTHER] - [null]
2021-07-07 01:17:05,157 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [2] as [ARRAY] - [[CREATE]]
2021-07-07 01:17:05,157 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,157 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [OTHER] - [2fa664b9-f9cd-4092-a38b-c46d47c0ab95]
2021-07-07 01:17:05,165 DEBUG o.h.SQL:128 -
    insert
    into
        user_roles
        (changed_by_uuid, permissions, role, user_uuid, uuid)
    values
        (?, ?, ?, ?, ?)
2021-07-07 01:17:05,165 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [1] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,165 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [2] as [ARRAY] - [[Ljava.lang.Object;@4bc4b33b]
2021-07-07 01:17:05,166 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [4] as [OTHER] - [4df92c40-fde1-4a09-bfe9-53f2deb2f41d]
2021-07-07 01:17:05,166 TRACE o.h.t.d.s.BasicBinder:64 - binding parameter [5] as [OTHER] - [afe1ed15-005f-4c2e-8d55-bd3db570dc2e]
2021-07-07 01:17:05,168 DEBUG o.h.SQL:128 -
    update
        user_roles
    set
        changed_by_uuid=?,
        permissions=?,
        role=?,
        user_uuid=?
    where
        uuid=?

Body:
The permissions were mapped badly

This is the way it should look

permissions column is mutable and Hibernate flushes again because it can't determine dirtiness

The solution was:

  @Type(
      type = "com.vladmihalcea.hibernate.type.array.EnumArrayType",
      parameters = {@Parameter(name = EnumArrayType.SQL_ARRAY_TYPE, value = "permission")})
  @Column(name = "permissions", columnDefinition = "permission[]")
  private Permission[] permissions;


问:
NameError: name 'name' is not defined
In this code, how can I use the (name) variable inside of any other function Knowing that the variable is a local variable? I would really love some pointers if you have any, thank you.

def get_Name():
    name = input("What's Your Name? ")
    return f"{name} Is A Male. "

def get_Age():
    age = input("What's Your Age? ")
    return f"{name} Is {age} Years Old"

get_Name()
get_Age()
```

答:
You can use a class

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def get_name():
    return f"{self.name} Is A Male. "

  def get_age():
    return f"{self.name} Is {self.age} Years Old"

person = Person(
  name=input("What's Your Name? "),
  age=input("What's Your Age? "),
)
person.get_name()
person.get_age()
```

Title: NameError: name 'name' is not defined


问:
Heroku engines.node (package.json) unspecified
I'm having a problem with pushing my codes to Heroku.

package.json

```<code>{
  "name": "my-app",
  "version": "0.1.0",
  "engine": {
    "node": "12.16.2",
    "npm": "6.13.4"
  },
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bcrypt": "^4.0.1",
    "body-parser": "^1.18.3",
    "cookie-parser": "^1.4.3",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.4.20",
    "nodemon": "^2.0.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "node server/index.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "backend": "nodemon server/index.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

output

```<code>remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Resolving node version 12.x...
remote:        Downloading and installing node 12.16.1...
remote:        Using default npm version: 6.13.4
<!-- more stuff -->
remote: -----> Build
remote:        Running build
remote:
remote:        > my-app@0.1.0 build /tmp/build_016788c07037e47ee5638bf5c1b1f631
remote:        > react-scripts build
remote:
remote:        Could not find a required file.
remote:          Name: index.html
remote:          Searched in: /tmp/build_016788c07037e47ee5638bf5c1b1f631/public
remote: npm ERR! code ELIFECYCLE
remote: npm ERR! errno 1
remote: npm ERR! my-app@0.1.0 build: `react-scripts build`
remote: npm ERR! Exit status 1
remote: npm ERR!
remote: npm ERR! Failed at the my-app@0.1.0 build script.
remote: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
remote:
remote: npm ERR! A complete log of this run can be found in:
remote: npm ERR!     /tmp/npmcache.yXjxR/_logs/2020-04-11T07_16_57_245Z-debug.log
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        Some possible problems:
remote:
remote:        - Node version not specified in package.json
remote:          https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version
remote:
remote:        Love,
remote:        Heroku
remote:
remote:  !     Push rejected, failed to compile Node.js app.
remote:
remote:  !     Push failed
</code>```

As you can see even though I specified my node and npm version in package.json Heroku is not recognising it and my push is rejected. I tried to make a ticket on the Heroku website but since this is a free application they did not allow me to ask on their helpline.

edit

I upgraded the npm and node version to the default by Heroku but I get the error Could not find a required file.Name: index.html

答:
my package.json didnt have
"engines" specified

adding
"engines": { "node": "12.16.1", "npm": "6.14.4" },
in my package.json fixed it

Body:
I'm having a problem with pushing my codes to Heroku.

package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "engine": {
    "node": "12.16.2",
    "npm": "6.13.4"
  },
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bcrypt": "^4.0.1",
    "body-parser": "^1.18.3",
    "cookie-parser": "^1.4.3",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^5.4.20",
    "nodemon": "^2.0.2",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1"
  },
  "scripts": {
    "start": "node server/index.js",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "backend": "nodemon server/index.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

output

remote:        engines.node (package.json):  unspecified
remote:        engines.npm (package.json):   unspecified (use default)
remote:
remote:        Resolving node version 12.x...
remote:        Downloading and installing node 12.16.1...
remote:        Using default npm version: 6.13.4

remote: -----> Build
remote:        Running build
remote:
remote:        > my-app@0.1.0 build /tmp/build_016788c07037e47ee5638bf5c1b1f631
remote:        > react-scripts build
remote:
remote:        Could not find a required file.
remote:          Name: index.html
remote:          Searched in: /tmp/build_016788c07037e47ee5638bf5c1b1f631/public
remote: npm ERR! code ELIFECYCLE
remote: npm ERR! errno 1
remote: npm ERR! my-app@0.1.0 build: `react-scripts build`
remote: npm ERR! Exit status 1
remote: npm ERR!
remote: npm ERR! Failed at the my-app@0.1.0 build script.
remote: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
remote:
remote: npm ERR! A complete log of this run can be found in:
remote: npm ERR!     /tmp/npmcache.yXjxR/_logs/2020-04-11T07_16_57_245Z-debug.log
remote:
remote: -----> Build failed
remote:
remote:        We're sorry this build is failing! You can troubleshoot common issues here:
remote:        https://devcenter.heroku.com/articles/troubleshooting-node-deploys
remote:
remote:        Some possible problems:
remote:
remote:        - Node version not specified in package.json
remote:          https://devcenter.heroku.com/articles/nodejs-support#specifying-a-node-js-version
remote:
remote:        Love,
remote:        Heroku
remote:
remote:  !     Push rejected, failed to compile Node.js app.
remote:
remote:  !     Push failed

As you can see even though I specified my node and npm version in package.json Heroku is not recognising it and my push is rejected. I tried to make a ticket on the Heroku website but since this is a free application they did not allow me to ask on their helpline.

edit

I upgraded the npm and node version to the default by Heroku but I get the error Could not find a required file.Name: index.html


问:
How to turn on display with mouse move but not with VK_SPACE
This code disables 1 display out of 2. The task is to turn it on not from VK_SPACE, but from mouse movement.

I tried to do it through WM_MOUSEMOVE, but so far nothing has worked. I don't really understand how this problem can be implemented.

If there is an opportunity to implement this topic, I will be very grateful.

```<code>#include <iostream>
#include <windows.h>
#include <vector>
#include <lowlevelmonitorconfigurationapi.h>
#include <windowsx.h>

#pragma comment(lib, "Dxva2.lib")

#define KEY_DOWN(key) ((::GetAsyncKeyState(key) & 0x80000) ? 1 : 0)
#define KEY_UP(key)   ((::GetAsyncKeyState(key) & 0x80000) ? 0 : 1)

const BYTE PowerMode = 0xD6;  // VCP Code defined in VESA Monitor Control Command Set (MCCS) standard
const DWORD PowerOn = 0x01;
const DWORD PowerOff = 0x04;

// Monitor description struct
struct MonitorDesc
{
    HANDLE hdl;
    DWORD power;
};

// Monitor enumeration callback
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
    std::vector<MonitorDesc>* pMonitors = reinterpret_cast<std::vector<MonitorDesc>*>(dwData);

    DWORD nMonitorCount;
    if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &nMonitorCount))
    {
        PHYSICAL_MONITOR* pMons = new PHYSICAL_MONITOR[nMonitorCount];

        if (GetPhysicalMonitorsFromHMONITOR(hMonitor, nMonitorCount, pMons))
        {
            for (DWORD i = 0; i < nMonitorCount; i++)
            {
                MonitorDesc desc;
                desc.hdl = pMons[i].hPhysicalMonitor;

                pMonitors->push_back(desc);
            }
        }
        delete[] pMons;
    }
    return TRUE;
}

// Switch monitor power
void MonitorSwitch(MonitorDesc& monitor, DWORD mode)
{
    if (monitor.power == mode)
        return;

    SetVCPFeature(monitor.hdl, PowerMode, mode);
    monitor.power = mode;
}

int main()
{
    // Скрытие консоли

    HWND hWnd;
    AllocConsole();
    hWnd = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(hWnd, 0);

    std::vector<MonitorDesc> monitors;
    EnumDisplayMonitors(NULL, NULL, &MonitorEnumProc, reinterpret_cast<LPARAM>(&monitors));

    // Init
    for (auto& monitor : monitors)
    {
        monitor.power = PowerOn;
    }

    // Here select the first one monitor as example
    MonitorDesc targetMonitor = monitors[0];

    while (1)
    {
        if (::GetAsyncKeyState('L') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL) && KEY_DOWN(VK_MENU))
                // turn off
                if (targetMonitor.power == PowerOn)
                    MonitorSwitch(targetMonitor, PowerOff);

        }
        if (::GetAsyncKeyState(VK_SPACE) == -32767)
        {
            if (KEY_DOWN(VK_SPACE))
                // turn on
                MonitorSwitch(targetMonitor, PowerOn);
        }
        if (::GetAsyncKeyState('E') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL))
                return 0;
        }
    }
}
</code>```

答:
I use GetCursorPos to get the real-time mouse position and perform an energy-saving operation when the mouse is over the edge of a monitor.Here is my code，I commented the code in detail.</p>
```<code>#include <iostream>
#include <windows.h>
#include <vector>
#include <lowlevelmonitorconfigurationapi.h>
#include <windowsx.h>

#pragma comment(lib, "Dxva2.lib")

#define KEY_DOWN(key) ((::GetAsyncKeyState(key) & 0x80000) ? 1 : 0)
#define KEY_UP(key)   ((::GetAsyncKeyState(key) & 0x80000) ? 0 : 1)

const BYTE PowerMode = 0xD6;  // VCP Code defined in VESA Monitor Control Command Set (MCCS) standard
const DWORD PowerOn = 0x01;
const DWORD PowerOff = 0x04;

// Monitor description struct
struct MonitorDesc
{
    HANDLE hdl;
    DWORD power;
};

// Monitor enumeration callback
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
    std::vector<MonitorDesc>* pMonitors = reinterpret_cast<std::vector<MonitorDesc>*>(dwData);

    DWORD nMonitorCount;
    if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &nMonitorCount))
    {
        PHYSICAL_MONITOR* pMons = new PHYSICAL_MONITOR[nMonitorCount];

        if (GetPhysicalMonitorsFromHMONITOR(hMonitor, nMonitorCount, pMons))
        {
            for (DWORD i = 0; i < nMonitorCount; i++)
            {
                MonitorDesc desc;
                desc.hdl = pMons[i].hPhysicalMonitor;

                pMonitors->push_back(desc);
            }
        }
        delete[] pMons;
    }
    return TRUE;
}

// Switch monitor power
void MonitorSwitch(MonitorDesc& monitor, DWORD mode)
{
    if (monitor.power == mode)
        return;

    SetVCPFeature(monitor.hdl, PowerMode, mode);
    monitor.power = mode;
}

int main()
{

    // Скрытие консоли

    HWND hWnd;
    AllocConsole();
    hWnd = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(hWnd, 1);

    std::vector<MonitorDesc> monitors;
    EnumDisplayMonitors(NULL, NULL, &MonitorEnumProc, reinterpret_cast<LPARAM>(&monitors));

    // Init
    for (auto& monitor : monitors)
    {
        monitor.power = PowerOn;
    }

    // Here select the first one monitor as example
    MonitorDesc targetMonitor = monitors[0];
    int currentMonitorID = 0; //need start this exe in monitors[0]

    //Mouse position
    LONG zx = -1;
    LONG zy = -1;
    POINT ptB = { 0, 0 };

    while (1)
    {
        /*---------------------------------------------------------------*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*-     monitors[0]          -             monitors[1]          -*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*---------------------------------------------------------------*/
        /*                       {1919,1079}                             */

        LPPOINT xy = &ptB;   //Location variables
        GetCursorPos(xy);    //Gets the current mouse position

        //If the mouse moves, (i.e. the current coordinates change to print out the coordinates) print out the coordinates.
        if ((zx != xy->x) || (zy != xy->y))
        {
            //Here you need to test the edge of your monitor[0]
            //After Test, delete this and Hide the console by ShowWindow(hWnd, 0)
            printf("x=%d,y=%d\n", xy->x, xy->y);
        }

        //The coordinate in the lower right corner of my monitor is {1919,1079}
        if (xy->x > 1919 && currentMonitorID == 0)
        {
            currentMonitorID = 1;
            MonitorSwitch(monitors[1], PowerOn);
            MonitorSwitch(monitors[0], PowerOff);
        }
        else if ( xy->x <= 1919 && currentMonitorID == 1)
        {
            currentMonitorID = 0;
            MonitorSwitch(monitors[0], PowerOn);
            MonitorSwitch(monitors[1], PowerOff);
        }

        /*if (::GetAsyncKeyState('L') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL) && KEY_DOWN(VK_MENU))
                // turn off
                if (targetMonitor.power == PowerOn)
                    MonitorSwitch(targetMonitor, PowerOff);

        }
        if (::GetAsyncKeyState(VK_SPACE) == -32767)
        {
            if (KEY_DOWN(VK_SPACE))
                // turn on
                MonitorSwitch(targetMonitor, PowerOn);
        }*/
        if (::GetAsyncKeyState('E') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL))
                return 0;
        }

    }
}
</code>```

Body:
This code disables 1 display out of 2. The task is to turn it on not from VK_SPACE, but from mouse movement.

I tried to do it through WM_MOUSEMOVE, but so far nothing has worked. I don't really understand how this problem can be implemented.

If there is an opportunity to implement this topic, I will be very grateful.

#include <iostream>
#include <windows.h>
#include <vector>
#include <lowlevelmonitorconfigurationapi.h>
#include <windowsx.h>

#pragma comment(lib, "Dxva2.lib")

#define KEY_DOWN(key) ((::GetAsyncKeyState(key) & 0x80000) ? 1 : 0)
#define KEY_UP(key)   ((::GetAsyncKeyState(key) & 0x80000) ? 0 : 1)

const BYTE PowerMode = 0xD6;  // VCP Code defined in VESA Monitor Control Command Set (MCCS) standard
const DWORD PowerOn = 0x01;
const DWORD PowerOff = 0x04;

// Monitor description struct
struct MonitorDesc
{
    HANDLE hdl;
    DWORD power;
};

// Monitor enumeration callback
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
    std::vector<MonitorDesc>* pMonitors = reinterpret_cast<std::vector<MonitorDesc>*>(dwData);

    DWORD nMonitorCount;
    if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &nMonitorCount))
    {
        PHYSICAL_MONITOR* pMons = new PHYSICAL_MONITOR[nMonitorCount];

        if (GetPhysicalMonitorsFromHMONITOR(hMonitor, nMonitorCount, pMons))
        {
            for (DWORD i = 0; i < nMonitorCount; i++)
            {
                MonitorDesc desc;
                desc.hdl = pMons[i].hPhysicalMonitor;

                pMonitors->push_back(desc);
            }
        }
        delete[] pMons;
    }
    return TRUE;
}

// Switch monitor power
void MonitorSwitch(MonitorDesc& monitor, DWORD mode)
{
    if (monitor.power == mode)
        return;

    SetVCPFeature(monitor.hdl, PowerMode, mode);
    monitor.power = mode;
}

int main()
{
    // Скрытие консоли

    HWND hWnd;
    AllocConsole();
    hWnd = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(hWnd, 0);

    std::vector<MonitorDesc> monitors;
    EnumDisplayMonitors(NULL, NULL, &MonitorEnumProc, reinterpret_cast<LPARAM>(&monitors));

    // Init
    for (auto& monitor : monitors)
    {
        monitor.power = PowerOn;
    }

    // Here select the first one monitor as example
    MonitorDesc targetMonitor = monitors[0];

    while (1)
    {
        if (::GetAsyncKeyState('L') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL) && KEY_DOWN(VK_MENU))
                // turn off
                if (targetMonitor.power == PowerOn)
                    MonitorSwitch(targetMonitor, PowerOff);

        }
        if (::GetAsyncKeyState(VK_SPACE) == -32767)
        {
            if (KEY_DOWN(VK_SPACE))
                // turn on
                MonitorSwitch(targetMonitor, PowerOn);
        }
        if (::GetAsyncKeyState('E') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL))
                return 0;
        }
    }
}

Body:
I use GetCursorPos to get the real-time mouse position and perform an energy-saving operation when the mouse is over the edge of a monitor.Here is my code，I commented the code in detail.

#include <iostream>
#include <windows.h>
#include <vector>
#include <lowlevelmonitorconfigurationapi.h>
#include <windowsx.h>

#pragma comment(lib, "Dxva2.lib")

#define KEY_DOWN(key) ((::GetAsyncKeyState(key) & 0x80000) ? 1 : 0)
#define KEY_UP(key)   ((::GetAsyncKeyState(key) & 0x80000) ? 0 : 1)

const BYTE PowerMode = 0xD6;  // VCP Code defined in VESA Monitor Control Command Set (MCCS) standard
const DWORD PowerOn = 0x01;
const DWORD PowerOff = 0x04;

// Monitor description struct
struct MonitorDesc
{
    HANDLE hdl;
    DWORD power;
};

// Monitor enumeration callback
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData)
{
    std::vector<MonitorDesc>* pMonitors = reinterpret_cast<std::vector<MonitorDesc>*>(dwData);

    DWORD nMonitorCount;
    if (GetNumberOfPhysicalMonitorsFromHMONITOR(hMonitor, &nMonitorCount))
    {
        PHYSICAL_MONITOR* pMons = new PHYSICAL_MONITOR[nMonitorCount];

        if (GetPhysicalMonitorsFromHMONITOR(hMonitor, nMonitorCount, pMons))
        {
            for (DWORD i = 0; i < nMonitorCount; i++)
            {
                MonitorDesc desc;
                desc.hdl = pMons[i].hPhysicalMonitor;

                pMonitors->push_back(desc);
            }
        }
        delete[] pMons;
    }
    return TRUE;
}

// Switch monitor power
void MonitorSwitch(MonitorDesc& monitor, DWORD mode)
{
    if (monitor.power == mode)
        return;

    SetVCPFeature(monitor.hdl, PowerMode, mode);
    monitor.power = mode;
}

int main()
{

    // Скрытие консоли

    HWND hWnd;
    AllocConsole();
    hWnd = FindWindowA("ConsoleWindowClass", NULL);
    ShowWindow(hWnd, 1);

    std::vector<MonitorDesc> monitors;
    EnumDisplayMonitors(NULL, NULL, &MonitorEnumProc, reinterpret_cast<LPARAM>(&monitors));

    // Init
    for (auto& monitor : monitors)
    {
        monitor.power = PowerOn;
    }

    // Here select the first one monitor as example
    MonitorDesc targetMonitor = monitors[0];
    int currentMonitorID = 0; //need start this exe in monitors[0]

    //Mouse position
    LONG zx = -1;
    LONG zy = -1;
    POINT ptB = { 0, 0 };

    while (1)
    {
        /*---------------------------------------------------------------*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*-     monitors[0]          -             monitors[1]          -*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*-                          -                                  -*/
        /*---------------------------------------------------------------*/
        /*                       {1919,1079}                             */

        LPPOINT xy = &ptB;   //Location variables
        GetCursorPos(xy);    //Gets the current mouse position

        //If the mouse moves, (i.e. the current coordinates change to print out the coordinates) print out the coordinates.
        if ((zx != xy->x) || (zy != xy->y))
        {
            //Here you need to test the edge of your monitor[0]
            //After Test, delete this and Hide the console by ShowWindow(hWnd, 0)
            printf("x=%d,y=%d\n", xy->x, xy->y);
        }

        //The coordinate in the lower right corner of my monitor is {1919,1079}
        if (xy->x > 1919 && currentMonitorID == 0)
        {
            currentMonitorID = 1;
            MonitorSwitch(monitors[1], PowerOn);
            MonitorSwitch(monitors[0], PowerOff);
        }
        else if ( xy->x <= 1919 && currentMonitorID == 1)
        {
            currentMonitorID = 0;
            MonitorSwitch(monitors[0], PowerOn);
            MonitorSwitch(monitors[1], PowerOff);
        }

        /*if (::GetAsyncKeyState('L') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL) && KEY_DOWN(VK_MENU))
                // turn off
                if (targetMonitor.power == PowerOn)
                    MonitorSwitch(targetMonitor, PowerOff);

        }
        if (::GetAsyncKeyState(VK_SPACE) == -32767)
        {
            if (KEY_DOWN(VK_SPACE))
                // turn on
                MonitorSwitch(targetMonitor, PowerOn);
        }*/
        if (::GetAsyncKeyState('E') == -32767)
        {
            if (KEY_DOWN(VK_CONTROL))
                return 0;
        }

    }
}


问:
jQuerymobile - Blocks & Splitscreen for iPad
We are working with the framework of jQuery Mobile for the graphical interface of our iPad app, based on HTML5. Because we're creating an app for the iPad, we essentially need the typical split-screen like it is on ipad: A  narrow sidebar on the left side and the main content on the right side:

Now my question: I'm searching for the code to create this splitted screen and I do not find anything for this in the jquerymobile documentation– Did I miss it or didn't I understand it? If the code for the splitscreen doesn't exist on this website, where can I find something related?

Because I didn't find anything related to what I need, I tried another way to get this splitscreen. So I was working with blocks in the css stylesheets:

for explanation: In jQuerymobile documentation, I found a category with the name "content formatting>layout grid (column)" ( http://jquerymobile.com/demos/1.0b1/#/demos/1.0b1/docs/content/content-grids.html)
So I thought about creating two blocks for making the splitted screen. BUT I don't need a splitted screen with 50/50, but much more 20/80 or 30/70. I tried to change it into my stylesheet:

```<code>.ui-grid-x { overflow: hidden; }
.ui-block-x, .ui-block-y { margin: 0; padding: 0; border: 0; float: left; min-height:1px;}

/* grid a: 20/80 */
.ui-grid-x .ui-block-x  { width: 20%; }
.ui-grid-x .ui-block-y { width: 80%; }
.ui-grid-x .ui-block-x { clear: left; }
</code>```

the original was:

```<code>.ui-grid-a, .ui-grid-b, .ui-grid-c, .ui-grid-d { overflow: hidden; }
.ui-block-a, .ui-block-b, .ui-block-c, .ui-block-d, .ui-block-e { margin: 0; padding: 0; border: 0; float: left; min-height:1px;}

.ui-grid-a .ui-block-a, .ui-grid-a .ui-block-b { width: 50%; }
.ui-grid-a .ui-block-a { clear: left; }
</code>```

Does anybody know what I did wrong? How to change the size of the blocks? Is it the right way to do it like this?
Thanks alot in advance.

答:
Use JQuery Mobile's Grid Layout and just override "width" on "ui-block-a" and "ui-block-b" to split screen as per your need.

for sample demo page checkout this blog
http://mdshannan1.blogspot.com/2011/08/jquery-mobile-split-screen-20-80-hack.html

ContentLicense: CC BY-SA 3.0

Body:
We are working with the framework of jQuery Mobile for the graphical interface of our iPad app, based on HTML5. Because we're creating an app for the iPad, we essentially need the typical split-screen like it is on ipad: A  narrow sidebar on the left side and the main content on the right side:

Now my question: I'm searching for the code to create this splitted screen and I do not find anything for this in the jquerymobile documentation– Did I miss it or didn't I understand it? If the code for the splitscreen doesn't exist on this website, where can I find something related?

Because I didn't find anything related to what I need, I tried another way to get this splitscreen. So I was working with blocks in the css stylesheets:

for explanation: In jQuerymobile documentation, I found a category with the name "content formatting>layout grid (column)" ( http://jquerymobile.com/demos/1.0b1/#/demos/1.0b1/docs/content/content-grids.html)
So I thought about creating two blocks for making the splitted screen. BUT I don't need a splitted screen with 50/50, but much more 20/80 or 30/70. I tried to change it into my stylesheet:

.ui-grid-x { overflow: hidden; }
.ui-block-x, .ui-block-y { margin: 0; padding: 0; border: 0; float: left; min-height:1px;}

/* grid a: 20/80 */
.ui-grid-x .ui-block-x  { width: 20%; }
.ui-grid-x .ui-block-y { width: 80%; }
.ui-grid-x .ui-block-x { clear: left; }

the original was:

.ui-grid-a, .ui-grid-b, .ui-grid-c, .ui-grid-d { overflow: hidden; }
.ui-block-a, .ui-block-b, .ui-block-c, .ui-block-d, .ui-block-e { margin: 0; padding: 0; border: 0; float: left; min-height:1px;}

.ui-grid-a .ui-block-a, .ui-grid-a .ui-block-b { width: 50%; }
.ui-grid-a .ui-block-a { clear: left; }

Does anybody know what I did wrong? How to change the size of the blocks? Is it the right way to do it like this?
Thanks alot in advance.


问:
OpenCv error can't open camera through video capture
I was using my cam through opencv and suddenly after restarting I ran my code it shows below error:

```<code>[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (802) open VIDEOIO ERROR: V4L: can't open camera by index 0
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    retval, buffer_img = cv2.imencode('.jpg', frame)
cv2.error: OpenCV(4.1.2) /io/opencv/modules/imgcodecs/src/loadsave.cpp:877: error: (-215:Assertion failed) !image.empty() in function 'imencode'
</code>```

```<code>cap = cv2.VideoCapture(0)  # here it throws an error

import json
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    retval, buffer_img = cv2.imencode('.jpg', frame)

    resdata = base64.b64encode(buffer_img)

    resdata = "data:image/png;base64,"+ str(resdata.decode("utf-8"))
    PARAMS = {'image': resdata}

    # Our operations on the frame come here
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
</code>```

I also tried with cap = cv2.VideoCapture(1) but then it shows can't find camera

How can I fix this issue?

答:
I found a solution in https://github.com/opencv/opencv/issues/19527 where the video capture is inside the function instead of outside. That worked for me (ubuntu)</p>
```<code>def frame_generation():

camera = cv2.VideoCapture(0) #resolved, correct position

while(True):
</code>```

Body:
I was using my cam through opencv and suddenly after restarting I ran my code it shows below error:

[ WARN:0] global /io/opencv/modules/videoio/src/cap_v4l.cpp (802) open VIDEOIO ERROR: V4L: can't open camera by index 0
Traceback (most recent call last):
  File "test.py", line 20, in <module>
    retval, buffer_img = cv2.imencode('.jpg', frame)
cv2.error: OpenCV(4.1.2) /io/opencv/modules/imgcodecs/src/loadsave.cpp:877: error: (-215:Assertion failed) !image.empty() in function 'imencode'

cap = cv2.VideoCapture(0)  # here it throws an error

import json
while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    retval, buffer_img = cv2.imencode('.jpg', frame)

    resdata = base64.b64encode(buffer_img)

    resdata = "data:image/png;base64,"+ str(resdata.decode("utf-8"))
    PARAMS = {'image': resdata}

    # Our operations on the frame come here
    #gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

I also tried with cap = cv2.VideoCapture(1) but then it shows can't find camera

How can I fix this issue?

Body:
I found a solution in https://github.com/opencv/opencv/issues/19527 where the video capture is inside the function instead of outside. That worked for me (ubuntu)

def frame_generation():

camera = cv2.VideoCapture(0) #resolved, correct position

while(True):