问:
Put a binary char array in a file C++
I'm writing a program where one server send binary messages to a client.
I receive the binary data sent by the server, but then I can't get it into a file correctly.
The objective is then to decrypt the file with openSSL.

Here is my code:

```<code>int     client::_writeFile()
{
    char    buf[bytes_received * bytes_received];
    recv(this->_socket, buf, bytes_received, 0);
    std::string const file("files/recv");
    std::ofstream f(file.c_str(), std::ios::binary);

    for (int i = 0; i < bytes_received + 1; i++)
    {
        f.write(&buf[i],sizeof(buf[i]));
    }
    f.close();

    system("openssl enc -d -aes-256-cbc -in files/recv -out files/decrypted.txt -pass pass:.key");

    return (SUCCESS);
}
</code>```

Thank you in advance for your help!

答:
you need something along these lines

```<code>char    buf[1000];
std::string const file("files/recv");
std::ofstream f(file.c_str(), std::ios::binary);
while(true){
   int count = recv(this->_socket, buf, sizeof(buf), 0);
   if (count ==0)
      break;
    f.write(buf,count);
}
f.close();
</code>```

this assumes that the remote end closes the connection once its finished sending the data

Title: Put a binary char array in a file C++

Body:
I'm writing a program where one server send binary messages to a client.
I receive the binary data sent by the server, but then I can't get it into a file correctly.
The objective is then to decrypt the file with openSSL.

Here is my code:

int     client::_writeFile()
{
    char    buf[bytes_received * bytes_received];
    recv(this->_socket, buf, bytes_received, 0);
    std::string const file("files/recv");
    std::ofstream f(file.c_str(), std::ios::binary);

    for (int i = 0; i < bytes_received + 1; i++)
    {
        f.write(&buf[i],sizeof(buf[i]));
    }
    f.close();

    system("openssl enc -d -aes-256-cbc -in files/recv -out files/decrypted.txt -pass pass:.key");

    return (SUCCESS);
}

Thank you in advance for your help!

Body:
you need something along these lines

char    buf[1000];
std::string const file("files/recv");
std::ofstream f(file.c_str(), std::ios::binary);
while(true){
   int count = recv(this->_socket, buf, sizeof(buf), 0);
   if (count ==0)
      break;
    f.write(buf,count);
}
f.close();

this assumes that the remote end closes the connection once its finished sending the data


来源: stackexchange

问:
Password check before page loads
I am trying to make a webpage that asks the user for a password prompt before the page loads. Once the correct password is typed, the page will proceed to load. If the password typed is incorrect, it will keep asking the user for the password until they get it right. The webpage currently does not ask for a password and goes right to the page.

HTML:

```<code><html>
<head>
<title>Password Page</title>
<script type="text/javascript" src="password.js"></script>
</head>
<body onload="passwordCheck()">
<h1>How'd you know the password?</h1>
</body>
</html>
</code>```

JavaScript:

```<code>// Password: ilikepie
function passwordCheck(){
var password = prompt("Please enter the password.");

if (password.value=="ilikepie"){
window.alert("Password correct!");
else{
while(password.value !="ilikepie"){
window.alert(password);}
</code>```

答:
This will ask you the password only one time if its correct otherwise it will keep asking. this is recursive function.</p>
```<code>window.onload=passwordCheck;
function passwordCheck()
{
    var password = prompt("Please enter the password.");
    if (password !== "bello")
    {
        passwordCheck();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Password check before page loads

Body:
I am trying to make a webpage that asks the user for a password prompt before the page loads. Once the correct password is typed, the page will proceed to load. If the password typed is incorrect, it will keep asking the user for the password until they get it right. The webpage currently does not ask for a password and goes right to the page.

HTML:

<title>Password Page</title>

How'd you know the password?

JavaScript:

// Password: ilikepie
function passwordCheck(){
var password = prompt("Please enter the password.");

if (password.value=="ilikepie"){
window.alert("Password correct!");
else{
while(password.value !="ilikepie"){
window.alert(password);}

Body:
This will ask you the password only one time if its correct otherwise it will keep asking. this is recursive function.

window.onload=passwordCheck;
function passwordCheck()
{
    var password = prompt("Please enter the password.");
    if (password !== "bello")
    {
        passwordCheck();
    }
}

ContentLicense: CC BY-SA 4.0


问:
How to create a function with a typed callback which ensures all callback parameters are passed to it
Given a function that accepts a callback with typed arguments, how can I make sure it doesn't allow functions without arguments.

I have added a sample code snippet that represents my problem

function x(cb: (a: number) => any) {
  cb(12)
}
x((a: number) => 1) // OK
x(() => 1) // OK
x((a: string) => 1) // Error: Argument of type '(x: string) => number' is not assignable to parameter of type '(a: number) => any'.
```

The second line should generate an error as this doesn't pass a complete list of parameters required by the callback

I want to enforce that every usage of function x should have all parameters in the callback as specified in the original function signature

Playground link

答:
The general behavior of TypeScript is that it's okay to have a function which requires less arguments than what's provided.  For example, when you have an onClick function (e: MouseEvent) => void it's fine to provide a function which does not use e.

So we have to get tricky here in order to disallow () => 1 as this function is assignable to (a: number) => any.

Solution

```<code>function x<T extends (a: number) => any>(cb: T & ([] extends Parameters<T> ? never : T)) {
  cb(12)
}
x((a: number) => 1) // OK
x(() => 1) // Error: Argument of type '() => number' is not assignable to parameter of type 'never'.
x((a: string) => 1) // Error: Argument of type '(x: string) => number' is not assignable to parameter of type '(a: number) => any'.
</code>```

Explanation

I am using a generic type parameter T to represent the callback argument of our function x.  We say that cb must be T, but we also impose an additional rule.  We need to check the arguments of the callback which are Parameters<T>.  If an empty array [] is assignable to these arguments ([] extends Parameters<T>), we say that cb must be T & never.

T & never is an impossible condition which causes us to get the red-underlined error on your second example.  Here T is inferred as () => number so cb must be never.  Therefore we get an error "Argument of type '() => number' is not assignable to parameter of type 'never'."

Your example function x doesn't return anything, but it could return cb(12) and get the correct return type based on the return type of the callback cb.

```<code>function x<T extends (a: number) => any>(cb: T & ([] extends Parameters<T> ? never : T)): ReturnType<T> {
  return cb(12)
}
</code>```

TypeScript Playground Link

Body:
Given a function that accepts a callback with typed arguments, how can I make sure it doesn't allow functions without arguments.

I have added a sample code snippet that represents my problem

function x(cb: (a: number) => any) {
  cb(12)
}
x((a: number) => 1) // OK
x(() => 1) // OK
x((a: string) => 1) // Error: Argument of type '(x: string) => number' is not assignable to parameter of type '(a: number) => any'.

The second line should generate an error as this doesn't pass a complete list of parameters required by the callback

I want to enforce that every usage of function x should have all parameters in the callback as specified in the original function signature

Playground link

Body:
The general behavior of TypeScript is that it's okay to have a function which requires less arguments than what's provided.  For example, when you have an onClick function (e: MouseEvent) => void it's fine to provide a function which does not use e.

So we have to get tricky here in order to disallow () => 1 as this function is assignable to (a: number) => any.

Solution

function x<T extends (a: number) => any>(cb: T & ([] extends Parameters<T> ? never : T)) {
  cb(12)
}
x((a: number) => 1) // OK
x(() => 1) // Error: Argument of type '() => number' is not assignable to parameter of type 'never'.
x((a: string) => 1) // Error: Argument of type '(x: string) => number' is not assignable to parameter of type '(a: number) => any'.

Explanation

I am using a generic type parameter T to represent the callback argument of our function x.  We say that cb must be T, but we also impose an additional rule.  We need to check the arguments of the callback which are Parameters<T>.  If an empty array [] is assignable to these arguments ([] extends Parameters<T>), we say that cb must be T & never.

T & never is an impossible condition which causes us to get the red-underlined error on your second example.  Here T is inferred as () => number so cb must be never.  Therefore we get an error "Argument of type '() => number' is not assignable to parameter of type 'never'."

Your example function x doesn't return anything, but it could return cb(12) and get the correct return type based on the return type of the callback cb.

function x<T extends (a: number) => any>(cb: T & ([] extends Parameters<T> ? never : T)): ReturnType<T> {
  return cb(12)
}

TypeScript Playground Link


问:
SyntaxError: Unexpected end of JSON input in react/express
Scratching my head like crazy, my "POST" route works just fine and the same exact code for my "PUT" route is returning a "SyntaxError: Unexpected end of JSON input" in the browser. It WILL update, but its not going thru the .then() parts of my fetch request, and going right to the catch block.

Fetch on my react app:

```<code>   const updateCourse = async(e) => {
        e.preventDefault();
         const encodedCreds = btoa(
             `${props.creds.emailAddress}:${props.creds.password}`
           );

    await fetch('http://localhost:5000/api/courses/' + params.id, {
         method: 'PUT',
         headers : {
             'Content-Type': 'application/json',
             Authorization: `Basic ${encodedCreds}`,
         },
         body: JSON.stringify(course)
     }).then(res =>  res.json())
     .then((data) => {
         if(data.message) {
           setErrorMessage(data.message.errors)
         }else{
             nav('/course/' + data)
         }
        })

     .catch((err) => {
         console.log('error message', err)
     });

</code>```

API response in express:

```<code>    router.put("/api/courses/:id", authUser, async (req, res) => {
  try {
    const findCourse = await courses.findOne({
      where: {
        id: req.params.id,
      },
    });

    if (findCourse) {
      //----IF ITS A VALID COURSE--//
      const updateCourse = await findCourse.update(req.body);
      res.status(204);
      res.json(updateCourse.id)

    } else {
      res.json({
        message: "Could not find course",
      });
    }
  } catch (err) {
    res.json({
      message: err
    });

  }
});
</code>```

find the full code here : https://github.com/ccarver80/React-REST-FS-API

答:
Fixed it! I didn't realize my API was sending back a 204 status which is "No content" so my client wasn't seeing any JSON to process technically.

A simple "IF/ELSE" statement in my client fixed this issue,

```<code> .then((res) => {
         if(res.status === 204) {
             nav('/course/' + params.id)
         }else {
            return res.json()
         }
     })
</code>```

Body:
Scratching my head like crazy, my "POST" route works just fine and the same exact code for my "PUT" route is returning a "SyntaxError: Unexpected end of JSON input" in the browser. It WILL update, but its not going thru the .then() parts of my fetch request, and going right to the catch block.

Fetch on my react app:

   const updateCourse = async(e) => {
        e.preventDefault();
         const encodedCreds = btoa(
             `${props.creds.emailAddress}:${props.creds.password}`
           );

    await fetch('http://localhost:5000/api/courses/' + params.id, {
         method: 'PUT',
         headers : {
             'Content-Type': 'application/json',
             Authorization: `Basic ${encodedCreds}`,
         },
         body: JSON.stringify(course)
     }).then(res =>  res.json())
     .then((data) => {
         if(data.message) {
           setErrorMessage(data.message.errors)
         }else{
             nav('/course/' + data)
         }
        })

     .catch((err) => {
         console.log('error message', err)
     });

API response in express:

    router.put("/api/courses/:id", authUser, async (req, res) => {
  try {
    const findCourse = await courses.findOne({
      where: {
        id: req.params.id,
      },
    });

    if (findCourse) {
      //----IF ITS A VALID COURSE--//
      const updateCourse = await findCourse.update(req.body);
      res.status(204);
      res.json(updateCourse.id)

    } else {
      res.json({
        message: "Could not find course",
      });
    }
  } catch (err) {
    res.json({
      message: err
    });

  }
});

find the full code here : https://github.com/ccarver80/React-REST-FS-API

Body:
Fixed it! I didn't realize my API was sending back a 204 status which is "No content" so my client wasn't seeing any JSON to process technically.

A simple "IF/ELSE" statement in my client fixed this issue,

 .then((res) => {
         if(res.status === 204) {
             nav('/course/' + params.id)
         }else {
            return res.json()
         }
     })


问:
In Junit 5 how can I call a test class method from an extension?
In Junit 5 I'm trying to get a test class method to run from an extension.  I'm using the Junit 5 extension interface, TestWatcher, and overriding the testFailed() method.

The purpose of this extension is to take a screen shot on failure in the test class's Selenium WebDriver browser and attach it to that test's Allure report.  The test class method has the instantiated browser and annotation for attaching to Allure.  And my takeScreenshot method relies on the browser and a testName string from the test class to run correctly.

```<code>package utils;

public class ScreenshotOnFailureExtension implements TestWatcher{
    @Override
    public void testFailed(ExtensionContext context, Throwable cause) {
        try {
            Object clazz = context.getRequiredTestInstance();
            Method takeScreenshot = clazz.getClass().getMethod("takeScreenshot");
            takeScreenshot.setAccessible(true);
            Object test = clazz.getClass().getConstructor().newInstance();
            takeScreenshot.invoke(test);
        } catch (Exception e) {
            e.printStackTrace();
        }
}
</code>```

And the code in my test class is something like this:

```<code>package tests;

@ExtendWith(ScreenshotOnFailureExtension.class)
public class MyTest implements Config {
    public WebDriver driver;
    public String testName;

//bunch of Junit5 annotations with functions to initialize above variables omitted...

    //take a screen shot
    public void takeScreenshot() {
        System.out.println("Taking screenshot.");
        byte[] srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
        saveScreenshot(srcFile, testName+ ".png");
    }

    //this attaches screenshot to an allure test result
    @Attachment(value = "{testName}", type = "image/png")
    public byte[] saveScreenshot(byte[] screenShot, String testName) {
        System.out.println("Attaching screenshot to Allure report");
        return screenShot;
    }
}
</code>```

The above test class is able to take a screen shot correctly when calling from @AfterEach in the test method.  But I only want to take it on a failure.

When I run the test it calls takeScreenshot, but then gives an exception while executing it:

Taking screenshot.java.lang.reflect.InvocationTargetException

at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)   at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)   at
utils.ScreenshotOnFailureExtension.testFailed(ScreenshotOnFailureExtension.java:49)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$nodeFinished$14(TestMethodTestDescriptor.java:299)
at
org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor.lambda$invokeTestWatchers$3(MethodBasedTestDescriptor.java:134)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)   at
org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor.invokeTestWatchers(MethodBasedTestDescriptor.java:132)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.nodeFinished(TestMethodTestDescriptor.java:290)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.nodeFinished(TestMethodTestDescriptor.java:65)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.reportCompletion(NodeTestTask.java:176)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:89)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)   at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)   at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at
org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.NullPointerException     at
tests.Base.takeScreenshot(Base.java:240)  ... 49 more

You can see my logging statement being output before the NullPointerException caused by the next line of code in that method (referencing the driver from the test instance).  Is there a correct way to trigger the existing test instance's takeScreenshot() method in context?

OR

If there is a simpler way to take a screen shot on failure directly in the test's @AfterEach method, PLEASE let me know. Seems like a pretty basic use case. :)

答:
The solution ended up looking like this. You could add other actions here for a Selenium test because this executes just before test tear-down.

If you are using Junit5 for Selenium testing you can use the AfterTestExecutionCallback so that the RequiredTestInstance contains both the reference to the browser AND the final result of the test!

```<code>package utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class ActionsOnFailureExtension implements AfterTestExecutionCallback {

    @Override
    public void afterTestExecution(ExtensionContext context) throws Exception {
        // if an ExecutionException is part of the context then the test failed
        Boolean testFailed = context.getExecutionException().isPresent();
        if (testFailed) {
            // take a screenshot via Java reflection
            try {
                Object clazz = context.getRequiredTestInstance();
                Method takeScreenshot = clazz.getClass().getMethod("takeScreenshot");
                // 'takeScreenshot' is a method in my test class
                // that uses the Selenium driver to take the screenshot
                // and then attaches it to the Allure report
                takeScreenshot.setAccessible(true);
                takeScreenshot.invoke(clazz);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
</code>```

Body:
In Junit 5 I'm trying to get a test class method to run from an extension.  I'm using the Junit 5 extension interface, TestWatcher, and overriding the testFailed() method.

The purpose of this extension is to take a screen shot on failure in the test class's Selenium WebDriver browser and attach it to that test's Allure report.  The test class method has the instantiated browser and annotation for attaching to Allure.  And my takeScreenshot method relies on the browser and a testName string from the test class to run correctly.

package utils;

public class ScreenshotOnFailureExtension implements TestWatcher{
    @Override
    public void testFailed(ExtensionContext context, Throwable cause) {
        try {
            Object clazz = context.getRequiredTestInstance();
            Method takeScreenshot = clazz.getClass().getMethod("takeScreenshot");
            takeScreenshot.setAccessible(true);
            Object test = clazz.getClass().getConstructor().newInstance();
            takeScreenshot.invoke(test);
        } catch (Exception e) {
            e.printStackTrace();
        }
}

And the code in my test class is something like this:

package tests;

@ExtendWith(ScreenshotOnFailureExtension.class)
public class MyTest implements Config {
    public WebDriver driver;
    public String testName;

//bunch of Junit5 annotations with functions to initialize above variables omitted...

    //take a screen shot
    public void takeScreenshot() {
        System.out.println("Taking screenshot.");
        byte[] srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
        saveScreenshot(srcFile, testName+ ".png");
    }

    //this attaches screenshot to an allure test result
    @Attachment(value = "{testName}", type = "image/png")
    public byte[] saveScreenshot(byte[] screenShot, String testName) {
        System.out.println("Attaching screenshot to Allure report");
        return screenShot;
    }
}

The above test class is able to take a screen shot correctly when calling from @AfterEach in the test method.  But I only want to take it on a failure.

When I run the test it calls takeScreenshot, but then gives an exception while executing it:

Taking screenshot.java.lang.reflect.InvocationTargetException

at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)   at
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)   at
utils.ScreenshotOnFailureExtension.testFailed(ScreenshotOnFailureExtension.java:49)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$nodeFinished$14(TestMethodTestDescriptor.java:299)
at
org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor.lambda$invokeTestWatchers$3(MethodBasedTestDescriptor.java:134)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)   at
org.junit.jupiter.engine.descriptor.MethodBasedTestDescriptor.invokeTestWatchers(MethodBasedTestDescriptor.java:132)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.nodeFinished(TestMethodTestDescriptor.java:290)
at
org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.nodeFinished(TestMethodTestDescriptor.java:65)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.reportCompletion(NodeTestTask.java:176)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:89)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)   at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)   at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at
org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at
org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at
org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at
org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at
org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at
org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at
org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at
org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: java.lang.NullPointerException     at
tests.Base.takeScreenshot(Base.java:240)  ... 49 more

You can see my logging statement being output before the NullPointerException caused by the next line of code in that method (referencing the driver from the test instance).  Is there a correct way to trigger the existing test instance's takeScreenshot() method in context?

OR

If there is a simpler way to take a screen shot on failure directly in the test's @AfterEach method, PLEASE let me know. Seems like a pretty basic use case. :)

Body:
The solution ended up looking like this. You could add other actions here for a Selenium test because this executes just before test tear-down.

If you are using Junit5 for Selenium testing you can use the AfterTestExecutionCallback so that the RequiredTestInstance contains both the reference to the browser AND the final result of the test!

package utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.jupiter.api.extension.AfterTestExecutionCallback;
import org.junit.jupiter.api.extension.ExtensionContext;

public class ActionsOnFailureExtension implements AfterTestExecutionCallback {

    @Override
    public void afterTestExecution(ExtensionContext context) throws Exception {
        // if an ExecutionException is part of the context then the test failed
        Boolean testFailed = context.getExecutionException().isPresent();
        if (testFailed) {
            // take a screenshot via Java reflection
            try {
                Object clazz = context.getRequiredTestInstance();
                Method takeScreenshot = clazz.getClass().getMethod("takeScreenshot");
                // 'takeScreenshot' is a method in my test class
                // that uses the Selenium driver to take the screenshot
                // and then attaches it to the Allure report
                takeScreenshot.setAccessible(true);
                takeScreenshot.invoke(clazz);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


问:
Pandas merge two dataframes with one to many relationship
I am trying to merge two pandas DataFrames with one of many relationship.

```<code>import pandas as pd

df1 = pd.DataFrame({'name': ['AA', 'BB', 'CC'],
                    'col1': [1, 2, 3],
                    'col2': [1, 2, 3] })

df2 = pd.DataFrame({'name': ['AA', 'AA', 'BB'],
                    'col1': [1, 2, 3],
                    'col2': [1, 2, 3] })

df_merged = pd.merge(
                     df1,
                     df2,
                     left_on = 'name',
                     right_on = 'name',
                     how = "inner"
                    )
</code>```

Two questions.

How do I join the two DataFrames using pd.merge without inserting new rows in df1? Shape of df1 needs not change. name is unique in df1.

For rows with one-to-many relationship, I'd like join the first row from df2.

When I merge the two DataFrames, it creates new columns - col1.x, col2.x, col1.y, col2.y? I'd like only copy of those columns.

答:
Use left join and drop duplicates</p>
```<code>df1.merge(df2, how='left', on='name').drop_duplicates(subset='name',keep='first')
</code>```

Body:
I am trying to merge two pandas DataFrames with one of many relationship.

import pandas as pd

df1 = pd.DataFrame({'name': ['AA', 'BB', 'CC'],
                    'col1': [1, 2, 3],
                    'col2': [1, 2, 3] })

df2 = pd.DataFrame({'name': ['AA', 'AA', 'BB'],
                    'col1': [1, 2, 3],
                    'col2': [1, 2, 3] })

df_merged = pd.merge(
                     df1,
                     df2,
                     left_on = 'name',
                     right_on = 'name',
                     how = "inner"
                    )

Two questions.

How do I join the two DataFrames using pd.merge without inserting new rows in df1? Shape of df1 needs not change. name is unique in df1.

For rows with one-to-many relationship, I'd like join the first row from df2.

When I merge the two DataFrames, it creates new columns - col1.x, col2.x, col1.y, col2.y? I'd like only copy of those columns.

Body:
Use left join and drop duplicates

df1.merge(df2, how='left', on='name').drop_duplicates(subset='name',keep='first')


问:
Swift UI + Cannot assign value of type 'JsonResponse' to type 'JsonResponse.Type'
Below is the code : Getting error : Cannot assign value of type 'JsonResponse' to type 'JsonResponse.Type'
Not sure why it is showing this error.
Any help please</p>
```<code>struct JsonResponse: Codable {
    var message: String
    var statusCode: String
    var results: Results
}

    class ReadData: ObservableObject  {
        @Published var response = [Results]()
        @Published var message: String = ""
        @Published var jsonData = JsonResponse.self

        init(){
            self.loadData()
        }

        func loadData()  {
            guard let url = Bundle.main.url(forResource: "list", withExtension: "json")
                else {
                    print("Json file not found")
                    return
                }

            let data = try? Data(contentsOf: url)

            if let data = data {
                            if let decodedResponse = try? JSONDecoder().decode(JsonResponse.self, from: data) as JsonResponse {
                                DispatchQueue.main.async {
                                    self.message = decodedResponse.message
                                    self.jsonData = decodedResponse // Cannot assign value of type 'JsonResponse' to type 'JsonResponse.Type'
                                }
                                return
                            }
                        }
        }

    }
</code>```

答:
Should be</p>
```<code>@Published var jsonData:JsonResponse?
</code>```

Body:
Below is the code : Getting error : Cannot assign value of type 'JsonResponse' to type 'JsonResponse.Type'
Not sure why it is showing this error.
Any help please

struct JsonResponse: Codable {
    var message: String
    var statusCode: String
    var results: Results
}

    class ReadData: ObservableObject  {
        @Published var response = [Results]()
        @Published var message: String = ""
        @Published var jsonData = JsonResponse.self

        init(){
            self.loadData()
        }

        func loadData()  {
            guard let url = Bundle.main.url(forResource: "list", withExtension: "json")
                else {
                    print("Json file not found")
                    return
                }

            let data = try? Data(contentsOf: url)

            if let data = data {
                            if let decodedResponse = try? JSONDecoder().decode(JsonResponse.self, from: data) as JsonResponse {
                                DispatchQueue.main.async {
                                    self.message = decodedResponse.message
                                    self.jsonData = decodedResponse // Cannot assign value of type 'JsonResponse' to type 'JsonResponse.Type'
                                }
                                return
                            }
                        }
        }

    }

Body:
Should be

@Published var jsonData:JsonResponse?


问:
partition of an IEnumerable sequence
Say I'm interating over a seq, using for..in..do and an exception is thrown midway. How do I get a 'pointer' to the place in the sequence I last read from.

For example, I want to print what's remaining in the sequence after the exception is raised.

```<code>open System.Collections.Generic

let s = seq { 1;2;3;5;6 }
exception MyEx of IEnumerator<int>

try
    let mutable count = 0
    for item in s do
        printfn "%d" item
        if count = 1 then
            printfn "raising exception"
            raise (MyEx (s.GetEnumerator()))
        count <- count + 1
with
| MyEx ex ->
    while ex.MoveNext() do
        printfn "%d" ex.Current
</code>```

I could rewrite it using the enumerator explicitly and MoveNext() and pass the enumerator to the exception constructor but I want to know if there is a way to do it using the for .. in .. do

答:
As mentioned in the comments, it is likely that there is a simpler solution to the problem you are actually trying to solve (most likely, you can avoid exceptions altogether).

However, if (most likely too) creative solution to the problem would be to use a custom computation expression. The following is a very incomplete implemntation that has a special for operation which automatically checks for exceptions in the body and wraps them in ForLoopException with also captures the rest of the sequence:

```<code>exception ForLoopException of exn * seq<obj>

type AutoSeqBuilder() =
  member x.For(s:seq<'a>, f) =
    use en = s.GetEnumerator()
    let rec loop() =
      if en.MoveNext() then
        try f en.Current
        with e ->
          let rest = seq {
            yield box en.Current
            while en.MoveNext() do yield box en.Current }
          raise(ForLoopException(e, rest))
        loop ()
    loop()
  member x.Zero() = ()
  member x.Combine(a, b) = a; b()
  member x.Delay(f) = f
  member x.Run(f) = f()
  member x.TryWith(f, g) =
    try f() with e -> g e

let serr = AutoSeqBuilder()
</code>```

Now you can use the serr computation builder to do something like this:

```<code>serr {
  try
    for i in 0 .. 10 do
      if i > 5 then failwith "Too much"
      printfn "Processing %d" i
  with ForLoopException(e, rest) ->
    for v in rest do
      printfn "Failed or skipped %O" v }
</code>```

Title: partition of an IEnumerable sequence

Body:
Say I'm interating over a seq, using for..in..do and an exception is thrown midway. How do I get a 'pointer' to the place in the sequence I last read from.

For example, I want to print what's remaining in the sequence after the exception is raised.

open System.Collections.Generic

let s = seq { 1;2;3;5;6 }
exception MyEx of IEnumerator<int>

try
    let mutable count = 0
    for item in s do
        printfn "%d" item
        if count = 1 then
            printfn "raising exception"
            raise (MyEx (s.GetEnumerator()))
        count <- count + 1
with
| MyEx ex ->
    while ex.MoveNext() do
        printfn "%d" ex.Current

I could rewrite it using the enumerator explicitly and MoveNext() and pass the enumerator to the exception constructor but I want to know if there is a way to do it using the for .. in .. do

Body:
As mentioned in the comments, it is likely that there is a simpler solution to the problem you are actually trying to solve (most likely, you can avoid exceptions altogether).

However, if (most likely too) creative solution to the problem would be to use a custom computation expression. The following is a very incomplete implemntation that has a special for operation which automatically checks for exceptions in the body and wraps them in ForLoopException with also captures the rest of the sequence:

exception ForLoopException of exn * seq<obj>

type AutoSeqBuilder() =
  member x.For(s:seq<'a>, f) =
    use en = s.GetEnumerator()
    let rec loop() =
      if en.MoveNext() then
        try f en.Current
        with e ->
          let rest = seq {
            yield box en.Current
            while en.MoveNext() do yield box en.Current }
          raise(ForLoopException(e, rest))
        loop ()
    loop()
  member x.Zero() = ()
  member x.Combine(a, b) = a; b()
  member x.Delay(f) = f
  member x.Run(f) = f()
  member x.TryWith(f, g) =
    try f() with e -> g e

let serr = AutoSeqBuilder()

Now you can use the serr computation builder to do something like this:

serr {
  try
    for i in 0 .. 10 do
      if i > 5 then failwith "Too much"
      printfn "Processing %d" i
  with ForLoopException(e, rest) ->
    for v in rest do
      printfn "Failed or skipped %O" v }


问:
org.hibernate.ObjectNotFoundException: No row with the given identifier exists, but it DOES
I've got a hibernate problem that I can't fix.

The setup: Java EE, web app, Hibernate 3.2, Tomcat 6, Struts 2.

Basically, I persist an object with my server logic (a struts action), then try and pull that data out for the next page and display it.

I check the database after I save the object, and sure enough, I can see the row there with all the data.

But when I try and retrieve it I get this:

```<code>org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [msc.model.Picture#73]
</code>```

To make things even muddier, when I restart Tomcat and try and access the same object, I don't get the error - Hibernate finds the row just fine.

Hibernate will also be able to see the row if I do some other operations - maybe add a row here and there to the database, not even on the same table.

From all this I suspect a Hibernate bug, but I'm a Hibernate newbie so I am probably wrong. Please help! I've googled and googled to no avail.

Here is my Hibernate config:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/msc</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">-------</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">80</property>
        <property name="current_session_context_class">thread</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <mapping resource="msc/model/Picture.hbm.xml"/>
        <mapping resource="msc/model/Comment.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
</code>```

Here are my two mapping files:

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="msc.model.Picture" table="PICTURE">
    <id column="PICTURE_ID" name="id">
      <generator class="native"/>
    </id>
    <property name="story"/>
    <property name="email"/>
    <property name="category"/>
    <property name="state"/>
    <property name="ratings"/>
    <property name="views"/>
    <property name="timestamp"/>
    <property name="title"/>
    <property lazy="true" name="image" type="blob">
      <column name="IMAGE"/>
    </property>
    <property lazy="true" name="refinedImage" type="blob">
      <column name="REFINEDIMAGE"/>
    </property>
    <property lazy="true" name="thumbnail" type="blob">
      <column name="THUMBNAIL"/>
    </property>
    <bag cascade="save-update" lazy="true" name="comments" table="COMMENT">
      <key column="PICTURE"/>
      <one-to-many class="msc.model.Comment"/>
    </bag>
  </class>
</hibernate-mapping>
</code>```

and

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="msc.model.User" table="USER">
    <id column="USER_ID" name="id">
      <generator class="native"/>
    </id>
    <property name="username"/>
    <property name="email"/>
    <bag cascade="save-update" lazy="true" name="pictures" table="PICTURE">
      <key column="USER"/>
      <one-to-many class="msc.model.Picture"/>
    </bag>
    <bag cascade="save-update" lazy="true" name="comments" table="COMMENT">
      <key column="USER"/>
      <one-to-many class="msc.model.Comment"/>
    </bag>
  </class>
</hibernate-mapping>
</code>```

Please let me know if you need more info, I'm happy to oblige.

(note: this is not a duplicate of this question, the scenario is not the same "No row with the given identifier exists" although it DOES exist)

EDIT: as requested, posting Java code:

Code to save object

```<code>Session hib_ses = HibernateUtil.getSessionFactory().getCurrentSession();

hib_ses.beginTransaction();

hib_ses.save(user);

hib_ses.getTransaction().commit();
</code>```

Code to display data (an image in this case)

```<code>public class ImageAction extends ActionSupport implements ServletResponseAware, SessionAware {

    private HttpServletResponse response;
    Map session;
    private Long id;
    private int thumbnail;
    private InputStream inputStream;

    @Override
    public String execute() throws Exception {
        response.setContentType("image/jpeg");
        Session hib_session = HibernateUtil.getSessionFactory().getCurrentSession();
        hib_session.beginTransaction();

        //what is the ID now?
        Picture pic = (Picture) hib_session.load(Picture.class, getId());

        if (thumbnail == 1) {
            inputStream = (ByteArrayInputStream) pic.getThumbnail().getBinaryStream();
        } else {
            inputStream = (ByteArrayInputStream) pic.getRefinedImage().getBinaryStream();
        }

        hib_session.close();
        return SUCCESS;
    }
</code>```

答:
My issue was that the child in the relation had a FK which didn't map to the PK of the parent so I had to change the JoinColumn to include referencedColumnName

```<code>@Entity
@Table(name = "child")
class Child {
    @ManyToOne
    @JoinColumn(name = "child_id", referencedColumnName = "non_pk_parent_id")
    var iabCategory: IabCategory
}
</code>```

Note that this caused another issue because of a bug in Hibernate. Here's a stackoverflow post on it:
Jpa Repository got error cannot not serializable when get data from database

and the link to the Hibernate bug: https://hibernate.atlassian.net/browse/HHH-7668

This bug forced me to mark the parent Serializable

```<code>@Entity
@Table(name = "parent")
class Parent : Serializable {

}
</code>```

The bug would cause a ClassCastException to be thrown if the parent didn't implement Serializable

Body:
I've got a hibernate problem that I can't fix.

The setup: Java EE, web app, Hibernate 3.2, Tomcat 6, Struts 2.

Basically, I persist an object with my server logic (a struts action), then try and pull that data out for the next page and display it.

I check the database after I save the object, and sure enough, I can see the row there with all the data.

But when I try and retrieve it I get this:

org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [msc.model.Picture#73]

To make things even muddier, when I restart Tomcat and try and access the same object, I don't get the error - Hibernate finds the row just fine.

Hibernate will also be able to see the row if I do some other operations - maybe add a row here and there to the database, not even on the same table.

From all this I suspect a Hibernate bug, but I'm a Hibernate newbie so I am probably wrong. Please help! I've googled and googled to no avail.

Here is my Hibernate config:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/msc</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">-------</property>

        <property name="connection.pool_size">80</property>
        <property name="current_session_context_class">thread</property>

        <property name="show_sql">true</property>
        <mapping resource="msc/model/Picture.hbm.xml"/>
        <mapping resource="msc/model/Comment.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

Here are my two mapping files:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="msc.model.Picture" table="PICTURE">
    <id column="PICTURE_ID" name="id">
      <generator class="native"/>
    </id>
    <property name="story"/>
    <property name="email"/>
    <property name="category"/>
    <property name="state"/>
    <property name="ratings"/>
    <property name="views"/>
    <property name="timestamp"/>
    <property name="title"/>
    <property lazy="true" name="image" type="blob">
      <column name="IMAGE"/>
    </property>
    <property lazy="true" name="refinedImage" type="blob">
      <column name="REFINEDIMAGE"/>
    </property>
    <property lazy="true" name="thumbnail" type="blob">
      <column name="THUMBNAIL"/>
    </property>
    <bag cascade="save-update" lazy="true" name="comments" table="COMMENT">
      <key column="PICTURE"/>
      <one-to-many class="msc.model.Comment"/>
    </bag>
  </class>
</hibernate-mapping>

and

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="msc.model.User" table="USER">
    <id column="USER_ID" name="id">
      <generator class="native"/>
    </id>
    <property name="username"/>
    <property name="email"/>
    <bag cascade="save-update" lazy="true" name="pictures" table="PICTURE">
      <key column="USER"/>
      <one-to-many class="msc.model.Picture"/>
    </bag>
    <bag cascade="save-update" lazy="true" name="comments" table="COMMENT">
      <key column="USER"/>
      <one-to-many class="msc.model.Comment"/>
    </bag>
  </class>
</hibernate-mapping>

Please let me know if you need more info, I'm happy to oblige.

(note: this is not a duplicate of this question, the scenario is not the same "No row with the given identifier exists" although it DOES exist)

EDIT: as requested, posting Java code:

Code to save object

Session hib_ses = HibernateUtil.getSessionFactory().getCurrentSession();

hib_ses.beginTransaction();

hib_ses.save(user);

hib_ses.getTransaction().commit();

Code to display data (an image in this case)

public class ImageAction extends ActionSupport implements ServletResponseAware, SessionAware {

    private HttpServletResponse response;
    Map session;
    private Long id;
    private int thumbnail;
    private InputStream inputStream;

    @Override
    public String execute() throws Exception {
        response.setContentType("image/jpeg");
        Session hib_session = HibernateUtil.getSessionFactory().getCurrentSession();
        hib_session.beginTransaction();

        //what is the ID now?
        Picture pic = (Picture) hib_session.load(Picture.class, getId());

        if (thumbnail == 1) {
            inputStream = (ByteArrayInputStream) pic.getThumbnail().getBinaryStream();
        } else {
            inputStream = (ByteArrayInputStream) pic.getRefinedImage().getBinaryStream();
        }

        hib_session.close();
        return SUCCESS;
    }

Body:
My issue was that the child in the relation had a FK which didn't map to the PK of the parent so I had to change the JoinColumn to include referencedColumnName

@Entity
@Table(name = "child")
class Child {
    @ManyToOne
    @JoinColumn(name = "child_id", referencedColumnName = "non_pk_parent_id")
    var iabCategory: IabCategory
}

Note that this caused another issue because of a bug in Hibernate. Here's a stackoverflow post on it:
Jpa Repository got error cannot not serializable when get data from database

and the link to the Hibernate bug: https://hibernate.atlassian.net/browse/HHH-7668

This bug forced me to mark the parent Serializable

@Entity
@Table(name = "parent")
class Parent : Serializable {

}

The bug would cause a ClassCastException to be thrown if the parent didn't implement Serializable


问:
Faster : Zeroing cython array
I'm using this to cleanup array in Cython

```<code>cdef void fill(DTYPE[:] ary):
    cdef int i, size = len(ary)
    for i in range(size): ary[i] = 0
</code>```

is there a faster way ?

they seems to have it,cdef'd

source

```<code>cdef inline void zero(array self):
    """ set all elements of array to zero. """
    memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize)
</code>```

generated code :

```<code>    cdef array.array rows
    array.zero(rows)

__pyx_f_7cpython_5array_zero(__pyx_v_rows);
</code>```

but if :

```<code>    cdef float[::1] rows
</code>```

@DavidW example generates a cleaner version i.e. for-loop

summarized it here and added some more tricks

答:
```<code>cdef void fill(double[:] ary):
    ary[:] = 0
</code>```

compiles. It's certainly the clearest way and is converted to a straightforward looking C loop. It also means that you don't have to worry about turning off boundschecking and negative indexing.

It'll be helped a little if you declare ary as contiguous (double[::1] ary), although of course that restricts the types of arrays it can do. If you aren't prepared to only accept contiguous arrays, then you should not use memset since it'll be zeroing stuff outside your array.

Title: Faster : Zeroing cython array

Body:
I'm using this to cleanup array in Cython

cdef void fill(DTYPE[:] ary):
    cdef int i, size = len(ary)
    for i in range(size): ary[i] = 0

is there a faster way ?

they seems to have it,cdef'd

source

cdef inline void zero(array self):
    """ set all elements of array to zero. """
    memset(self.data.as_chars, 0, Py_SIZE(self) * self.ob_descr.itemsize)

generated code :

    cdef array.array rows
    array.zero(rows)

__pyx_f_7cpython_5array_zero(__pyx_v_rows);

but if :

    cdef float[::1] rows

@DavidW example generates a cleaner version i.e. for-loop

summarized it here and added some more tricks

Body:
cdef void fill(double[:] ary):
    ary[:] = 0

compiles. It's certainly the clearest way and is converted to a straightforward looking C loop. It also means that you don't have to worry about turning off boundschecking and negative indexing.

It'll be helped a little if you declare ary as contiguous (double[::1] ary), although of course that restricts the types of arrays it can do. If you aren't prepared to only accept contiguous arrays, then you should not use memset since it'll be zeroing stuff outside your array.


问:
HRESULT: 0x800A03EC on Worksheet.range
I am getting HRESULT: 0x800A03EC on Worksheet.range method. Number of rows are more than 70K. Office 2007.

Code:

```<code>Microsoft.Office.Interop.Excel.Range neededRange
    = currentWS.Range[cell.Cells[1, 1], cell.Cells[nRowCount, nColumnCount]];
</code>```

Here my rowcount is more than 65530 . Breaks on this function. I have observed that it breaks only when row count goes more than 65530.

答:
EDIT: THIS IS WAY BETTER!!!
You don't need that old function, sorry.  Just do as follows:

```<code>Microsoft.Office.Interop.Excel.Range neededRange = currentWS.Range["A1", ((Microsoft.Office.Interop.Excel.Range)currentWS.Cells[nRowCount, nColumnCount])];
</code>```

That should work like a charm.  And for future reference, put the relevant code that you are using inside of your question.  Don't make people ask for it in comments. I imagine that's why you got downvoted.

Title: HRESULT: 0x800A03EC on Worksheet.range

Body:
I am getting HRESULT: 0x800A03EC on Worksheet.range method. Number of rows are more than 70K. Office 2007.

Code:

Microsoft.Office.Interop.Excel.Range neededRange
    = currentWS.Range[cell.Cells[1, 1], cell.Cells[nRowCount, nColumnCount]];

Here my rowcount is more than 65530 . Breaks on this function. I have observed that it breaks only when row count goes more than 65530.

Body:
EDIT: THIS IS WAY BETTER!!!
You don't need that old function, sorry.  Just do as follows:

Microsoft.Office.Interop.Excel.Range neededRange = currentWS.Range["A1", ((Microsoft.Office.Interop.Excel.Range)currentWS.Cells[nRowCount, nColumnCount])];

That should work like a charm.  And for future reference, put the relevant code that you are using inside of your question.  Don't make people ask for it in comments. I imagine that's why you got downvoted.


问:
Typescript: Compile Utility Types into module's declaration file
This might just be wishful thinking:

I have a module foo that uses the Parameters<> from a different mod bar, and passes it out of the current mod (foo).  So now if some new mod baz requires foo, it has to Also install the @types for the mod that foo is using: bar in order to figure out the Parameters<> Type.  This feels like a common situation, and I was hoping there was a way to handle it that didn't involve forcing baz to need all the declarations from bar, like a way that the extracted types compiled into foo's declaration maybe.  Greatly appreciate any guidance!

module bar index.ts:

```<code>export function doSomething(param: any) { }
</code>```

module foo index.ts:

```<code>import { doSomething } from "bar"
export function DoAnotherThing(param: Parameters<typeof doSomething>[0]) {
    doSomething(param)
}
</code>```

module baz index.ts

```<code>import { doAnotherThing } from "foo"

// if @types/bar isn't also installed:
// Type 'unknown' has no matching index signature for type 'number'
doAnotherThing(123)
</code>```

答:
Let the dependency tree just do its work. You don't need any special magic here.

You should just need to add @types/bar in the devDependencies of the foo module. Now npm install foo should install foo, bar and @types/bar, and everything should work just fine.

Body:
This might just be wishful thinking:

I have a module foo that uses the Parameters<> from a different mod bar, and passes it out of the current mod (foo).  So now if some new mod baz requires foo, it has to Also install the @types for the mod that foo is using: bar in order to figure out the Parameters<> Type.  This feels like a common situation, and I was hoping there was a way to handle it that didn't involve forcing baz to need all the declarations from bar, like a way that the extracted types compiled into foo's declaration maybe.  Greatly appreciate any guidance!

module bar index.ts:

export function doSomething(param: any) { }

module foo index.ts:

import { doSomething } from "bar"
export function DoAnotherThing(param: Parameters<typeof doSomething>[0]) {
    doSomething(param)
}

module baz index.ts

import { doAnotherThing } from "foo"

// if @types/bar isn't also installed:
// Type 'unknown' has no matching index signature for type 'number'
doAnotherThing(123)


问:
Docker-compose FastAPI --reload
I have FastAPI app running in docker docker container. It works well except only one thing

The app doesn't reload if any changes. The changes applied only if i restart the container. But i wonder why it doesn't reload app if i put in command --reload flag?

I understand that docker itself do not reload if some changes in code. But app must be if flag --reload in command .

If I misunderstand, please advise how to achieve what i want. Thanks

main.py

```<code>from typing import Optional

import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)
</code>```

docker-compose.yml

```<code>version: "3"

services:

  web:
    build: .
    restart: always
    command: bash -c "uvicorn main:app --host 0.0.0.0 --port 8000 --reload"
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

  db:
    image: postgres
    ports:
      - "50009:5432"
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=test_db
</code>```

答:
this works for me

version: "3.9"

services:
  people:
    container_name: people
    build: .
    working_dir: /code/app
    command: uvicorn main:app --host 0.0.0.0 --reload
    environment:
      DEBUG: 1
    volumes:
      - ./app:/code/app
    ports:
      - 8008:8000
    restart: on-failure
```
<p>this is my directory structure</p>
```.
├── Dockerfile
├── Makefile
├── app
│   └── main.py
├── docker-compose.yml
└── requirements.txt
```
<p>make sure <code>working_dir</code> and <code>volumes</code> section's <code>- ./app:/code/app</code> match</p>
<p>example run:</p>
<pre class="lang-sh prettyprint-override"><code>docker-compose up --build

...
Attaching to people
people    | INFO:     Will watch for changes in these directories: ['/code/app']
</code>```

Title: Docker-compose FastAPI --reload

Body:
I have FastAPI app running in docker docker container. It works well except only one thing

The app doesn't reload if any changes. The changes applied only if i restart the container. But i wonder why it doesn't reload app if i put in command --reload flag?

I understand that docker itself do not reload if some changes in code. But app must be if flag --reload in command .

If I misunderstand, please advise how to achieve what i want. Thanks

main.py

from typing import Optional

import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000, reload=True)

docker-compose.yml

version: "3"

services:

  web:
    build: .
    restart: always
    command: bash -c "uvicorn main:app --host 0.0.0.0 --port 8000 --reload"
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db

  db:
    image: postgres
    ports:
      - "50009:5432"
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=test_db

Body:
this works for me

version: "3.9"

services:
  people:
    container_name: people
    build: .
    working_dir: /code/app
    command: uvicorn main:app --host 0.0.0.0 --reload
    environment:
      DEBUG: 1
    volumes:
      - ./app:/code/app
    ports:
      - 8008:8000
    restart: on-failure

this is my directory structure

.
├── Dockerfile
├── Makefile
├── app
│   └── main.py
├── docker-compose.yml
└── requirements.txt

make sure working_dir and volumes section's - ./app:/code/app match

example run:

docker-compose up --build

...
Attaching to people
people    | INFO:     Will watch for changes in these directories: ['/code/app']


问:
How to populate fields based on Post Codes
So this is a googlesheet i made it, its basically like match making spreadsheet, the tab to look at is Host Create Listing and Guest Request to Stay, so i just need able to match the Guest and the host those who are having the common post code in them.

I have tried using the FILTER function however its not working. What should be the right function here to use to get those matched in the MATCH MAKING SHEET?

MATCHMAKING_SHEET

答:
use:

```<code>=ARRAYFORMULA({FILTER(
 'Guest Request to Stay'!A2:A20&" "&'Guest Request to Stay'!B2:B20,
 'Guest Request to Stay'!H2:H20<>""), VLOOKUP(FILTER(
 'Guest Request to Stay'!H2:H20, 'Guest Request to Stay'!H2:H20<>""),
 {'Host Create Listing'!I2:I9, 'Host Create Listing'!C2:C9&" "&
  'Host Create Listing'!D2:D9, 'Host Create Listing'!I2:I9}, {2, 3}, 0)})
</code>```

Body:
use:

=ARRAYFORMULA({FILTER(
 'Guest Request to Stay'!A2:A20&" "&'Guest Request to Stay'!B2:B20,
 'Guest Request to Stay'!H2:H20<>""), VLOOKUP(FILTER(
 'Guest Request to Stay'!H2:H20, 'Guest Request to Stay'!H2:H20<>""),
 {'Host Create Listing'!I2:I9, 'Host Create Listing'!C2:C9&" "&
  'Host Create Listing'!D2:D9, 'Host Create Listing'!I2:I9}, {2, 3}, 0)})


问:
Iterate over two strings checking to see if it matches with its pair
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

```<code>    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }
</code>```

'''

答:
Avoid char

The char type is legacy, essentially broken. As a 16-bit value, char is physically incapable of representing most characters. The char type in your particular case would work. But using char is a bad habit generally, as such code may break when encountering any of about 75,000 characters defined in Unicode.

Code point

Use code point integer numbers instead. A code point is the number assigned to each of the over 140,000 characters defined by the Unicode Consortium.

Here we get an IntStream, a series of int values, one for each character in the input string. Then we collect these integer numbers into an array of int values.

```<code>int[] codePoints1 = seq1.codePoints().toArray() ;
int[] codePoints2 = seq2.codePoints().toArray() ;
</code>```

You said the input strings may be of unequal length. So our two arrays may be jagged, of different lengths. Figure out the size of the shorter array.

```<code>int smallerSize = Math.min( codePoints1.length , codePoints2.length ) ;
</code>```

Keep track of the index number of mismatched rows.

```<code>List<Integer> mismatchIndices = new ArrayList <>();
</code>```

Loop the arrays based on that smaller size.

```<code>for( int i = 0 ; i < smallerSize ; i ++ )
{
    if ( isBasePairValid( codePoint first , codePoint second ) )
    {
        …
    } else
    {
        mismatchIndices.add( i ) ;
    }
}
</code>```

Write an isBasePairValid method

Write the isBasePairValid method, taking two arguments, the code points of the two nucleobase letters.

static int A = "A".codePointAt( 0 ) ;  // Annoying zero-based index counting. So first character is number zero.
static int C = "C".codePointAt( 0 ) ;
static int G = "G".codePointAt( 0 ) ;
static int T = "T".codePointAt( 0 ) ;

if( first == A ) return ( second == T )
else if( first == T ) return ( second == A )
else if( first == C ) return ( second == G )
else if( first == G ) return ( second == C )
else { throw new IllegalStateException( … ) ; }
```
<p>Count the mismatches.</p>
```int countMismatches = mismatchIndices.size() ;
```

Body:
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }

'''

Body:
Avoid char

The char type is legacy, essentially broken. As a 16-bit value, char is physically incapable of representing most characters. The char type in your particular case would work. But using char is a bad habit generally, as such code may break when encountering any of about 75,000 characters defined in Unicode.

Code point

Use code point integer numbers instead. A code point is the number assigned to each of the over 140,000 characters defined by the Unicode Consortium.

Here we get an IntStream, a series of int values, one for each character in the input string. Then we collect these integer numbers into an array of int values.

int[] codePoints1 = seq1.codePoints().toArray() ;
int[] codePoints2 = seq2.codePoints().toArray() ;

You said the input strings may be of unequal length. So our two arrays may be jagged, of different lengths. Figure out the size of the shorter array.

int smallerSize = Math.min( codePoints1.length , codePoints2.length ) ;

Keep track of the index number of mismatched rows.

List<Integer> mismatchIndices = new ArrayList <>();

Loop the arrays based on that smaller size.

for( int i = 0 ; i < smallerSize ; i ++ )
{
    if ( isBasePairValid( codePoint first , codePoint second ) )
    {
        …
    } else
    {
        mismatchIndices.add( i ) ;
    }
}

Write an isBasePairValid method

Write the isBasePairValid method, taking two arguments, the code points of the two nucleobase letters.

static int A = "A".codePointAt( 0 ) ;  // Annoying zero-based index counting. So first character is number zero.
static int C = "C".codePointAt( 0 ) ;
static int G = "G".codePointAt( 0 ) ;
static int T = "T".codePointAt( 0 ) ;

if( first == A ) return ( second == T )
else if( first == T ) return ( second == A )
else if( first == C ) return ( second == G )
else if( first == G ) return ( second == C )
else { throw new IllegalStateException( … ) ; }

Count the mismatches.

int countMismatches = mismatchIndices.size() ;


问:
Replace the order of parametrs of the function
```<code>    # STEP 2 - FORMATNAME
    # Format Name -  takes in first and last name and  returns it as Last, First Name

    def format_name(first, last):
        # print("Student: TODO")
        str(last,first)
        return

def main():
    print(format_name('Bill','Nye'))

if __name__ == "__main__":
    main()

TypeError: decoding str is not supported
</code>```

Please help me to solve this problem. I have to replace the order of parametrs of the function.

答:
How about this:

def format_name(first, last):
    return last, first

last, first = format_name('John', 'Snow')
print(f"{last.strip()} {first.strip()}")  # Snow John
```

function returns two objects, which you can parse into two different variables. Then you can apply strip function on them.

Body:
    # STEP 2 - FORMATNAME
    # Format Name -  takes in first and last name and  returns it as Last, First Name

    def format_name(first, last):
        # print("Student: TODO")
        str(last,first)
        return

def main():
    print(format_name('Bill','Nye'))

if __name__ == "__main__":
    main()

TypeError: decoding str is not supported

Please help me to solve this problem. I have to replace the order of parametrs of the function.

Body:
How about this:

def format_name(first, last):
    return last, first

last, first = format_name('John', 'Snow')
print(f"{last.strip()} {first.strip()}")  # Snow John

function returns two objects, which you can parse into two different variables. Then you can apply strip function on them.


问:
WooCommerce how to perform a redirection for not logged in users
I need a redirection for all not logged-in users on my WordPress site.

All of them should every time be redirected to the login site. So that nobody without a login can access the site. Important is, I made this redirection because I have an API that also needs to have access to the site if I would do this with .htaccess the API hadn't have any access to the information.

I used the following PHP code:

```<code>add_action('template_redirect','woo_check_loggedin');
function woo_check_loggedin(){

      if(!is_user_logged_in() && !is_page(lost-password) ){
          wp_redirect("https://example.com/wp-login.php");
          exit;
      }

   }
</code>```

But this only works, when I go to "example.com". When I enter directly the URL "example.com/shop" you can still visit the site. How can I avoid this?

答:
You could use the request property of the wp global variable and wp_login_url function.

add_action('template_redirect', 'woo_check_loggedin');

function woo_check_loggedin()
{
    global $wp;

    if (
        !is_user_logged_in()
        &&
        'my-account/lost-password' != $wp->request
       )
      {
        wp_safe_redirect(wp_login_url(get_permalink()));
        exit;
      }
}
```

This answer has been tested on woo 6.1 and works!

Related answers for redirection on Wooommerce:

https://stackoverflow.com/a/70137563/15040627

https://stackoverflow.com/a/70395951/15040627

Body:
I need a redirection for all not logged-in users on my WordPress site.

All of them should every time be redirected to the login site. So that nobody without a login can access the site. Important is, I made this redirection because I have an API that also needs to have access to the site if I would do this with .htaccess the API hadn't have any access to the information.

I used the following PHP code:

add_action('template_redirect','woo_check_loggedin');
function woo_check_loggedin(){

      if(!is_user_logged_in() && !is_page(lost-password) ){
          wp_redirect("https://example.com/wp-login.php");
          exit;
      }

   }

But this only works, when I go to "example.com". When I enter directly the URL "example.com/shop" you can still visit the site. How can I avoid this?

Body:
You could use the request property of the wp global variable and wp_login_url function.

add_action('template_redirect', 'woo_check_loggedin');

function woo_check_loggedin()
{
    global $wp;

    if (
        !is_user_logged_in()
        &&
        'my-account/lost-password' != $wp->request
       )
      {
        wp_safe_redirect(wp_login_url(get_permalink()));
        exit;
      }
}

This answer has been tested on woo 6.1 and works!

Related answers for redirection on Wooommerce:

https://stackoverflow.com/a/70137563/15040627

https://stackoverflow.com/a/70395951/15040627


问:
Precision@K as a custom metric in Keras
I include Precision@K as a custom metric in Keras. According to the documentation

```<code>import keras.backend as K

def mean_pred(y_true, y_pred):
    return K.mean(y_pred)

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy', mean_pred])
</code>```

I just need to calculate a function using Keras backend and pass it at the compilation step.

With Numpy only precision@k could be calculated as the following example:

```<code>def precisionatk(y_true,y_pred,k)
    precision_average = []
    idx =  (-y_pred).argsort(axis=-1)[:,:k]
    for i in range(idx.shape[0]):
        precision_sample = 0
        for j in idx[i,:]:
            if y_true[i,j] == 1:
                precision_sample += 1
        precision_sample = precision_sample / k
        precision_average.append(precision_sample)
    return np.mean(precision_average)

y_true = np.array([[0,0,1,0],[1,0,1,0]])
y_pred = np.array([[0.1,0.4,0.8,0.2],[0.3,0.2,0.5,0.1]])

print(precisionatk(y_true,y_pred,2))

0.75
</code>```

So, how to I translate this to Keras backend?

EDIT: I'm working with a multilabel problem and the y_true is always an array with ones or zeros, and y_prediction each class probability.

答:
You can use Keras-native implementation of Precision@k: tf.keras.metrics.TopKCategoricalAccuracy

https://www.tensorflow.org/api_docs/python/tf/keras/metrics/TopKCategoricalAccuracy

Title: Precision@K as a custom metric in Keras

Body:
I include Precision@K as a custom metric in Keras. According to the documentation

import keras.backend as K

def mean_pred(y_true, y_pred):
    return K.mean(y_pred)

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy', mean_pred])

I just need to calculate a function using Keras backend and pass it at the compilation step.

With Numpy only precision@k could be calculated as the following example:

def precisionatk(y_true,y_pred,k)
    precision_average = []
    idx =  (-y_pred).argsort(axis=-1)[:,:k]
    for i in range(idx.shape[0]):
        precision_sample = 0
        for j in idx[i,:]:
            if y_true[i,j] == 1:
                precision_sample += 1
        precision_sample = precision_sample / k
        precision_average.append(precision_sample)
    return np.mean(precision_average)

y_true = np.array([[0,0,1,0],[1,0,1,0]])
y_pred = np.array([[0.1,0.4,0.8,0.2],[0.3,0.2,0.5,0.1]])

print(precisionatk(y_true,y_pred,2))

0.75

So, how to I translate this to Keras backend?

EDIT: I'm working with a multilabel problem and the y_true is always an array with ones or zeros, and y_prediction each class probability.


问:
subprocess.check_output Showing [WinError 2] The system cannot find the file specified
I've had this error for the past 2 or 3 days and I have no clue what I've done wrong or how to fix it

I'm starting to think it's not even the code problem its just my PC
because this was working the other day but no it's not

all it is trying to do is get my HWID then verify my HWID is in the Pastebin

I am on windows 11
and using python and subprocess

here is the error

```<code>File "C:\Users\myname\Desktop\python-stuff\dark\Dark.py", line 33, in <module>
    hardwareid = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')[1].strip()
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified
</code>```

and here is the code

```<code>hardwareid = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')[1].strip()
site = requests.get('https://pastebin.com/raw/hMX2AiWf')

try:
    if hardwareid in site.text:
        pass
    else:
        os.system("cls & title cls & title Dark - HWID Error")
        print()
        print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}ERROR{Fore.RED}] HWID Not In Database.')
        print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}HWID{Fore.RED}]: ' + hardwareid)
        print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}Administrator{Fore.RED}] Send HWID To Administrator To Be Whitelisted.')
        time.sleep(15)
        os._exit(1)
except:
    print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}ERROR{Fore.RED}] FAILED to connect to database')
    time.sleep(5)
    os._exit(1)
</code>```

I have tried adding "shell=True" to the code but then I get this error

```<code>'wmic' is not recognized as an internal or external command,
operable program or batch file.
Traceback (most recent call last):
  File "C:\Users\myname\Desktop\python-stuff\HWID\HWID.py", line 18, in <module>
    hardwareid = subprocess.check_output('wmic csproduct get uuid', shell=True).decode().split('\n')[1].strip()
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 524, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command 'wmic csproduct get uuid' returned non-zero exit status 1.
</code>```

I really really need help
I will pay if this gets fixed
Please, someone, help me

答:
wmic has been deprecated according to the docs and may have been removed in some windows update (don't have 11 myself so can't confirm).

The WMI command-line (WMIC) utility is deprecated as of Windows 10, version 21H1 ...

With the intended interface now being powershell's CIM cmdlets. For the UUID, Get-CimInstance can be used with the Win32_ComputerSystemProduct class, from python this can be done by passing the command to powershell.exe like so:

>>> subprocess.check_output(
    [
        "powershell.exe",
        "Get-CimInstance -Class Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID",
    ]
)

b'00000000-0000-0000-0000-D8CB8AC79XXX\r\n'
```
<p>You can also pass the text argument to <code>check_output</code> to get a string directly instead of decoding it yourself</p>
<pre class="lang-py prettyprint-override"><code>>>> subprocess.check_output(
    [
        "powershell.exe",
        "Get-CimInstance -Class Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID",
    ],
    text=True,
)

'00000000-0000-0000-0000-D8CB8AC79XXX\n'
</code>```

Body:
I've had this error for the past 2 or 3 days and I have no clue what I've done wrong or how to fix it

I'm starting to think it's not even the code problem its just my PC
because this was working the other day but no it's not

all it is trying to do is get my HWID then verify my HWID is in the Pastebin

I am on windows 11
and using python and subprocess

here is the error

File "C:\Users\myname\Desktop\python-stuff\dark\Dark.py", line 33, in <module>
    hardwareid = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')[1].strip()
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 966, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 1435, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

and here is the code

hardwareid = subprocess.check_output('wmic csproduct get uuid').decode().split('\n')[1].strip()
site = requests.get('https://pastebin.com/raw/hMX2AiWf')

try:
    if hardwareid in site.text:
        pass
    else:
        os.system("cls & title cls & title Dark - HWID Error")
        print()
        print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}ERROR{Fore.RED}] HWID Not In Database.')
        print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}HWID{Fore.RED}]: ' + hardwareid)
        print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}Administrator{Fore.RED}] Send HWID To Administrator To Be Whitelisted.')
        time.sleep(15)
        os._exit(1)
except:
    print(f' {Fore.RED}[{Fore.LIGHTCYAN_EX}ERROR{Fore.RED}] FAILED to connect to database')
    time.sleep(5)
    os._exit(1)

I have tried adding "shell=True" to the code but then I get this error

'wmic' is not recognized as an internal or external command,
operable program or batch file.
Traceback (most recent call last):
  File "C:\Users\myname\Desktop\python-stuff\HWID\HWID.py", line 18, in <module>
    hardwareid = subprocess.check_output('wmic csproduct get uuid', shell=True).decode().split('\n')[1].strip()
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 420, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "C:\Users\myname\AppData\Local\Programs\Python\Python310\lib\subprocess.py", line 524, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command 'wmic csproduct get uuid' returned non-zero exit status 1.

I really really need help
I will pay if this gets fixed
Please, someone, help me

Body:
wmic has been deprecated according to the docs and may have been removed in some windows update (don't have 11 myself so can't confirm).

The WMI command-line (WMIC) utility is deprecated as of Windows 10, version 21H1 ...

With the intended interface now being powershell's CIM cmdlets. For the UUID, Get-CimInstance can be used with the Win32_ComputerSystemProduct class, from python this can be done by passing the command to powershell.exe like so:

>>> subprocess.check_output(
    [
        "powershell.exe",
        "Get-CimInstance -Class Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID",
    ]
)

b'00000000-0000-0000-0000-D8CB8AC79XXX\r\n'

You can also pass the text argument to check_output to get a string directly instead of decoding it yourself

>>> subprocess.check_output(
    [
        "powershell.exe",
        "Get-CimInstance -Class Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID",
    ],
    text=True,
)

'00000000-0000-0000-0000-D8CB8AC79XXX\n'