问:
How do I ensure my MVC app redirects to an error page when a certain exception occurs?
I have seen a nice example whereby the MVC controller class inherits from another controller class which handles an exception and returns a view with the error inside like so:

```<code>public class ApplicationController : Controller
{
    public ActionResult NotFound()
    {
        return View("NotFound");
    }

    public ActionResult InsufficientPriveleges()
    {
        return View("InsufficientPriveleges");
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception is NotFoundException)
        {
            filterContext.Result = NotFound();
            filterContext.ExceptionHandled = true;
            return;
        }
        if (filterContext.Exception is InsufficientPrivelegesException)
        {
            filterContext.Result = InsufficientPriveleges();
            filterContext.ExceptionHandled = true;
            return;
        }

        base.OnException(filterContext);
    }
}
</code>```

However, I've noticed that say for example my controller is loading in a partial view for something the user should not have access to, the error will then be shown inside the partial view on the page.

I'd like the whole page to show the error, in effect the exception should redirect to a completely new page.  How can I achieve this using the current class shown above?

答:
You gotta handle ajax call differently. I would simply use error() of jquery $.ajax to handle that kind of ajax call error.</p>

```<code>$.ajax({
    ...
    success: function(g) {
          //process normal
    },
    error: function(request, status, error) {
          //process exception here
    }
})
</code>```

Body:
I have seen a nice example whereby the MVC controller class inherits from another controller class which handles an exception and returns a view with the error inside like so:

public class ApplicationController : Controller
{
    public ActionResult NotFound()
    {
        return View("NotFound");
    }

    public ActionResult InsufficientPriveleges()
    {
        return View("InsufficientPriveleges");
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        if (filterContext.Exception is NotFoundException)
        {
            filterContext.Result = NotFound();
            filterContext.ExceptionHandled = true;
            return;
        }
        if (filterContext.Exception is InsufficientPrivelegesException)
        {
            filterContext.Result = InsufficientPriveleges();
            filterContext.ExceptionHandled = true;
            return;
        }

        base.OnException(filterContext);
    }
}

However, I've noticed that say for example my controller is loading in a partial view for something the user should not have access to, the error will then be shown inside the partial view on the page.

I'd like the whole page to show the error, in effect the exception should redirect to a completely new page.  How can I achieve this using the current class shown above?

Body:
You gotta handle ajax call differently. I would simply use error() of jquery $.ajax to handle that kind of ajax call error.

$.ajax({
    ...
    success: function(g) {
          //process normal
    },
    error: function(request, status, error) {
          //process exception here
    }
})


来源: stackexchange

问:
Typescript merge two interfaces

UPDATE

i found this solution

```<code>type Merge<T, U> = {
  [K in keyof T | keyof U]: K extends keyof U? U[K]: K extends keyof T? T[K]: never;
};
</code>```

is there something like this in typescript?(spread operator)

```<code>type Merge<T, U> = ...[K in keyof T]: T[K], ...[K in keyof U]: U[K]
</code>```

my task is to Merge two types into a new type. Keys of the second type overrides keys of the first type.
for example:

```<code>interface User {
  id: string;
  name: string;
  age: number;
  role: "admin" | "moderator" | "user";
  occupation: string;
}
interface User2 {
  id: string;
  name: string;
  age: boolean;
}

type mergedType = Merge<User, User2>
</code>```

after merge, interface type will be something like this->

```<code>{
  id: string;
  name: string;
  age: boolean;
  role: "admin" | "moderator" | "user";
  occupation: string;
}
</code>```

答:
If the types were never in conflict, it would be just be User & User2, but in your example User has age: number and User2 has age: boolean, so they conflict.

You can handle that the way you've said you want to (using the second one's definition) with a mapped type using a conditional type to pick the property type from B if it's there or from A if it isn't, intersected with the second type you're merging:

type MergeTypes = {
    [key in keyof A]: key extends keyof B ? B[key] : A[key];
} & B;
```
<p>(Edit: Or the rather simpler <code>type MergeTypes<A, B> = Omit<A, keyof B> & B;</code> as pointed out by M. Erim Tuzcuoglu and this answer to another question. Doh!)</p>
<p>Usage:</p>
<pre class="lang-typescript prettyprint-override"><code>type MergedType = MergeTypes<User, User2>;
</code>```

Playground link

Here's how that works:

key in keyof A says that the mapped type will have a key for each key of the type A

key extends keyof B checks to see if the key is also a key of type B

If it is, we use B[key] as the property type; if it isn't, we use A[key]

The result of the above only has the properties that A has (but with B's type for them if they both have it), it won't have ones that only exist on B. So we add & B at the end to add them.

ContentLicense: CC BY-SA 4.0

Title: Typescript merge two interfaces

Body:
UPDATE

i found this solution

type Merge<T, U> = {
  [K in keyof T | keyof U]: K extends keyof U? U[K]: K extends keyof T? T[K]: never;
};

is there something like this in typescript?(spread operator)

type Merge<T, U> = ...[K in keyof T]: T[K], ...[K in keyof U]: U[K]

my task is to Merge two types into a new type. Keys of the second type overrides keys of the first type.
for example:

interface User {
  id: string;
  name: string;
  age: number;
  role: "admin" | "moderator" | "user";
  occupation: string;
}
interface User2 {
  id: string;
  name: string;
  age: boolean;
}

type mergedType = Merge<User, User2>

after merge, interface type will be something like this->

{
  id: string;
  name: string;
  age: boolean;
  role: "admin" | "moderator" | "user";
  occupation: string;
}

Body:
If the types were never in conflict, it would be just be User & User2, but in your example User has age: number and User2 has age: boolean, so they conflict.

You can handle that the way you've said you want to (using the second one's definition) with a mapped type using a conditional type to pick the property type from B if it's there or from A if it isn't, intersected with the second type you're merging:

type MergeTypes<A, B> = {
    [key in keyof A]: key extends keyof B ? B[key] : A[key];
} & B;

(Edit: Or the rather simpler type MergeTypes<A, B> = Omit<A, keyof B> & B; as pointed out by M. Erim Tuzcuoglu and this answer to another question. Doh!)

Usage:

type MergedType = MergeTypes<User, User2>;

Playground link

Here's how that works:

key in keyof A says that the mapped type will have a key for each key of the type A

key extends keyof B checks to see if the key is also a key of type B

If it is, we use B[key] as the property type; if it isn't, we use A[key]

The result of the above only has the properties that A has (but with B's type for them if they both have it), it won't have ones that only exist on B. So we add & B at the end to add them.


问:
How to fix Android Cannot get a dirty matrix error?
An unknown error was output while using the soft keyboard

```<code>A/OpenGLRenderer: Cannot get a dirty matrix!
A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 42843 (Thread-12), pid 15445
</code>```

Why does such an error occur?? How do you solve it?

答:
do not call View#getLocationOnScreen or View#getMatrix on you worker thread,

View#getLocationOnScreen or View#getMatrix will reset variable 'mPrimitiveFields.mMatrixOrPivotDirty' to false and check it, if true then crash;

Many APIs that run on the main thread like View#setScaleX/setScaleY/setAlpha will set variable 'mPrimitiveFields.mMatrixOrPivotDirty' to true

so if 'View#getLocationOnScreen or View#getMatrix' run on worker thread, it is possible to concurrently modify the variable 'mPrimitiveFields.mMatrixOrPivotDirty' and cause a crash

f you want a more detailed analysis, visit this:
https://www.jianshu.com/p/d6d3bb641198

http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/jni/android_view_RenderNode.cpp
http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/hwui/RenderProperties.h

View#getLocationOnScreen or View#getMatrix ->
android_view_RenderNode.cpp#android_view_RenderNode_getTransformMatrix ->

```<code>    static void android_view_RenderNode_getTransformMatrix(jlong renderNodePtr, jlong outMatrixPtr) {
        RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
        SkMatrix* outMatrix = reinterpret_cast<SkMatrix*>(outMatrixPtr);

        // call updateMatrix to reset 'mPrimitiveFields.mMatrixOrPivotDirty' to false
        renderNode->mutateStagingProperties().updateMatrix();
        // check 'mPrimitiveFields.mMatrixOrPivotDirty', if true then crash
        const SkMatrix* transformMatrix = renderNode->stagingProperties().getTransformMatrix();

        if (transformMatrix) {
            *outMatrix = *transformMatrix;
        } else {
            outMatrix->setIdentity();
        }
    }

    const SkMatrix* getTransformMatrix() const {
        LOG_ALWAYS_FATAL_IF(mPrimitiveFields.mMatrixOrPivotDirty, "Cannot get a dirty matrix!");
        return mComputedFields.mTransformMatrix;
    }
</code>```

Body:
An unknown error was output while using the soft keyboard

A/OpenGLRenderer: Cannot get a dirty matrix!
A/libc: Fatal signal 6 (SIGABRT), code -1 (SI_QUEUE) in tid 42843 (Thread-12), pid 15445

Why does such an error occur?? How do you solve it?

Body:
do not call View#getLocationOnScreen or View#getMatrix on you worker thread,

View#getLocationOnScreen or View#getMatrix will reset variable 'mPrimitiveFields.mMatrixOrPivotDirty' to false and check it, if true then crash;

Many APIs that run on the main thread like View#setScaleX/setScaleY/setAlpha will set variable 'mPrimitiveFields.mMatrixOrPivotDirty' to true

so if 'View#getLocationOnScreen or View#getMatrix' run on worker thread, it is possible to concurrently modify the variable 'mPrimitiveFields.mMatrixOrPivotDirty' and cause a crash

f you want a more detailed analysis, visit this:
https://www.jianshu.com/p/d6d3bb641198

http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/jni/android_view_RenderNode.cpp
http://androidxref.com/9.0.0_r3/xref/frameworks/base/libs/hwui/RenderProperties.h

View#getLocationOnScreen or View#getMatrix ->
android_view_RenderNode.cpp#android_view_RenderNode_getTransformMatrix ->

    static void android_view_RenderNode_getTransformMatrix(jlong renderNodePtr, jlong outMatrixPtr) {
        RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
        SkMatrix* outMatrix = reinterpret_cast<SkMatrix*>(outMatrixPtr);

        // call updateMatrix to reset 'mPrimitiveFields.mMatrixOrPivotDirty' to false
        renderNode->mutateStagingProperties().updateMatrix();
        // check 'mPrimitiveFields.mMatrixOrPivotDirty', if true then crash
        const SkMatrix* transformMatrix = renderNode->stagingProperties().getTransformMatrix();

        if (transformMatrix) {
            *outMatrix = *transformMatrix;
        } else {
            outMatrix->setIdentity();
        }
    }

    const SkMatrix* getTransformMatrix() const {
        LOG_ALWAYS_FATAL_IF(mPrimitiveFields.mMatrixOrPivotDirty, "Cannot get a dirty matrix!");
        return mComputedFields.mTransformMatrix;
    }


问:
condition variable ? with colon
Here is a snippet of a pseudocode from a friend.

```<code>int a=50, b=20, c=10;

if (b=(b>a ? a:c))
   c = a - b;
</code>```

What does the code b>a ? a:c mean exactly?

答:
It's called a conditional or ternary Operator.

It's similar to an if-else statement (short hand if Else).
For example, here b>a ? a : c if b > a then it returns a else it returns c.

For more info just google it.

Title: condition variable ? with colon

Body:
Here is a snippet of a pseudocode from a friend.

int a=50, b=20, c=10;

if (b=(b>a ? a:c))
   c = a - b;

What does the code b>a ? a:c mean exactly?


问:
Automatic download file from restFul Api with Net5
I have a restFul api with Net5, in this api I have a controller where an array of bytes is obtained that corresponds to a file (pdf, png, jpg...) that must later be sent to the client and automatically downloaded in the browser, but when doing my tests from Swagger the only thing I get is:

As I see it is not working correctly since I do not see the byte array anywhere and I only see the names of the classes in swagger.

```<code>    [HttpGet("{IdFichero}")]
    public async Task<IActionResult> ObtenerFichero(int IdFichero)
    {
        DbResponseImageHub response = await _unitOfWork.MensajeRepository.ObtenerImagenMensajeRepository(IdFichero);

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(response.fichero);
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "Document " + response.extension;

        switch (response.extension)
        {
            case "png":
                HttpContext.Response.ContentType = "image/png";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                break;
            case "jpg":
                HttpContext.Response.ContentType = "image/png";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                break;
            case "jpeg":
                HttpContext.Response.ContentType = "image/jpeg";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                break;
            case "bmp":
                HttpContext.Response.ContentType = "image/bmp";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/bmp");
                break;
            case "pdf":
                HttpContext.Response.ContentType = "application/pdf";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                break;
            case "docx":
                HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.documen");
                break;
            case "doc":
                HttpContext.Response.ContentType = "application/msword";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");
                break;
            case "xlsx":
                HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                break;
            case "xls":
                HttpContext.Response.ContentType = "application/vnd.ms-excel";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
                break;
            default:
                break;
        }

        return Ok(result);
    }
</code>```

If I use the FileResult, it shows me the error "The non-callable FileResult member cannot be used as a method."

```<code>return FileResult(result);
</code>```

If you could tell me what I'm doing wrong, I'd be very grateful.

答:
You have to return File object from your controller. Below is a code example which is very close to what you are trying to do (The file object must contain the bytes array for your file)

```<code>    [HttpGet("{IdFichero}")]
    public async Task<IActionResult> ObtenerFichero(int IdFichero)
    {
        string localFilePath = "C:\\1639842533574.jpeg";
        string extension = "jpeg";
        var myBytes = System.IO.File.ReadAllBytes(localFilePath);

        switch (extension)
        {
            case "jpg":
                return File(myBytes, "image/jpg");
            case "jpeg":
                return File(myBytes, "image/jpeg");
            default:
                return File(myBytes, "image/gif");
        }
    }
</code>```

Body:
I have a restFul api with Net5, in this api I have a controller where an array of bytes is obtained that corresponds to a file (pdf, png, jpg...) that must later be sent to the client and automatically downloaded in the browser, but when doing my tests from Swagger the only thing I get is:

As I see it is not working correctly since I do not see the byte array anywhere and I only see the names of the classes in swagger.

    [HttpGet("{IdFichero}")]
    public async Task<IActionResult> ObtenerFichero(int IdFichero)
    {
        DbResponseImageHub response = await _unitOfWork.MensajeRepository.ObtenerImagenMensajeRepository(IdFichero);

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
        result.Content = new ByteArrayContent(response.fichero);
        result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        result.Content.Headers.ContentDisposition.FileName = "Document " + response.extension;

        switch (response.extension)
        {
            case "png":
                HttpContext.Response.ContentType = "image/png";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                break;
            case "jpg":
                HttpContext.Response.ContentType = "image/png";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
                break;
            case "jpeg":
                HttpContext.Response.ContentType = "image/jpeg";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
                break;
            case "bmp":
                HttpContext.Response.ContentType = "image/bmp";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/bmp");
                break;
            case "pdf":
                HttpContext.Response.ContentType = "application/pdf";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                break;
            case "docx":
                HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.documen");
                break;
            case "doc":
                HttpContext.Response.ContentType = "application/msword";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");
                break;
            case "xlsx":
                HttpContext.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                break;
            case "xls":
                HttpContext.Response.ContentType = "application/vnd.ms-excel";
                result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
                break;
            default:
                break;
        }

        return Ok(result);
    }

If I use the FileResult, it shows me the error "The non-callable FileResult member cannot be used as a method."

return FileResult(result);

If you could tell me what I'm doing wrong, I'd be very grateful.

Body:
You have to return File object from your controller. Below is a code example which is very close to what you are trying to do (The file object must contain the bytes array for your file)

    [HttpGet("{IdFichero}")]
    public async Task<IActionResult> ObtenerFichero(int IdFichero)
    {
        string localFilePath = "C:\\1639842533574.jpeg";
        string extension = "jpeg";
        var myBytes = System.IO.File.ReadAllBytes(localFilePath);

        switch (extension)
        {
            case "jpg":
                return File(myBytes, "image/jpg");
            case "jpeg":
                return File(myBytes, "image/jpeg");
            default:
                return File(myBytes, "image/gif");
        }
    }


问:
How to position Upload button at the center of the block
Current condition of site

I want to make sure that the choose file button should be positioned at the upload image position. I am new to HTML and CSS.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Health Buddy</title>
    <link rel= "stylesheet" href="My_css.css">
</head>
<body>
    <div class="TOP">HEALTH BUDDY</div>
    <div class="class">Upload Image</div>
    <form action="/action_page.php">
        <input type="file" id="myFile" name="filename">
        <input type="submit">
    </form>
</body>
</html>
</code>```

答:
You can put the "choose file button" inside the "upload image" div. You can then position them to achieve what you want. Try this

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Health Buddy</title>
    <link rel= "stylesheet" href="My_css.css">

HEALTH BUDDY

    <form action="/action_page.php">

            Upload Image
            <input type="file" id="myFile" name="filename">

        <input type="submit">
    </form>

```

Body:
Current condition of site

I want to make sure that the choose file button should be positioned at the upload image position. I am new to HTML and CSS.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Health Buddy</title>
    <link rel= "stylesheet" href="My_css.css">

HEALTH BUDDY

Upload Image

    <form action="/action_page.php">
        <input type="file" id="myFile" name="filename">
        <input type="submit">
    </form>

Body:
You can put the "choose file button" inside the "upload image" div. You can then position them to achieve what you want. Try this

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Health Buddy</title>
    <link rel= "stylesheet" href="My_css.css">
    <style type="text/css">
        .class {
            width: 200px;
            height: 200px;
            border: 1px solid red;
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #myFile {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            opacity: 0;
            z-index: 1;
        }
    </style>
</head>
<body>
    <div class="TOP">HEALTH BUDDY</div>
    <form action="/action_page.php">
        <div class="class">
            Upload Image
            <input type="file" id="myFile" name="filename">
        </div>
        <input type="submit">
    </form>
</body>
</html>


问:
How to find sum of 2 date/time string in swift 5
I have multiple date/time string inside a loop

```<code>for item in self.sleepingActivityData ?? [] {
                    let value = Util.getFormattedDateString(inputDateString: self.findDateDiff(time1Str: item.startsAt ?? "", time2Str: item.endsAt ?? ""), inputDateFormat: "h m", outputDateFormat: "HH:mm")
                    print(value as Any) // "00:45"

                }
</code>```

value of 'value' is "00:45", "00:30", "00:45". I want to add this 3 timeString, So the sum should be "02:00"
how can I achieve this in swift?

This is my getFormattedDateString() func:

```<code>static func getFormattedDateString(inputDateString: String, inputDateFormat: String, outputDateFormat: String) -> String?{
        let dateFormatterInput = DateFormatter()
        dateFormatterInput.dateFormat = inputDateFormat//"yyyy-MM-dd HH:mm:ss"

        let dateFormatterOutput = DateFormatter()
        dateFormatterOutput.dateFormat = outputDateFormat//"EEEE, MMM dd hh:mm a"

        if let date = dateFormatterInput.date(from: inputDateString) {
            return (dateFormatterOutput.string(from: date))
        } else {
            return nil
        }
    }
</code>```

& thats how I found the difference between 2 time in findDateFiid() func:

```<code>   func findDateDiff(time1Str: String, time2Str: String) -> String {
        let timeformatter = DateFormatter()
        timeformatter.dateFormat = "HH:mm:ss"

        guard let time1 = timeformatter.date(from: time1Str),
            let time2 = timeformatter.date(from: time2Str) else { return "" }
        //You can directly use from here if you have two dates
        let interval = time2.timeIntervalSince(time1)
        let hour = interval / 3600;
        let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
        return "\(Int(hour)) \(Int(minute))"
    }
</code>```

答:
There is no string-date-math API.

Basically you need two methods to convert HH:mm to minutes and vice versa

```<code>func hhmmToMinutes(_ hhmm : String) -> Int {
    let components = hhmm.components(separatedBy: ":")
    guard components.count == 2,
          let hr = Int(components[0]),
          let mn = Int(components[1]) else { return 0 }
    return hr * 60 + mn
}

func minutesToHourMinute(_ minutes : Int) -> String {
    let hr = minutes / 60
    let mn = minutes % 60
    return String(format: "%02ld:%02ld", hr, mn)
}
</code>```

Then you use can higher level API to do the time math

```<code>let array = ["00:45", "00:30", "00:45"]
let minutes = array.map{hhmmToMinutes($0)}.reduce(0, +)
let timeString = minutesToHourMinute(minutes)
print(timeString) // 02:00
</code>```

Body:
I have multiple date/time string inside a loop

for item in self.sleepingActivityData ?? [] {
                    let value = Util.getFormattedDateString(inputDateString: self.findDateDiff(time1Str: item.startsAt ?? "", time2Str: item.endsAt ?? ""), inputDateFormat: "h m", outputDateFormat: "HH:mm")
                    print(value as Any) // "00:45"

                }

value of 'value' is "00:45", "00:30", "00:45". I want to add this 3 timeString, So the sum should be "02:00"
how can I achieve this in swift?

This is my getFormattedDateString() func:

static func getFormattedDateString(inputDateString: String, inputDateFormat: String, outputDateFormat: String) -> String?{
        let dateFormatterInput = DateFormatter()
        dateFormatterInput.dateFormat = inputDateFormat//"yyyy-MM-dd HH:mm:ss"

        let dateFormatterOutput = DateFormatter()
        dateFormatterOutput.dateFormat = outputDateFormat//"EEEE, MMM dd hh:mm a"

        if let date = dateFormatterInput.date(from: inputDateString) {
            return (dateFormatterOutput.string(from: date))
        } else {
            return nil
        }
    }

& thats how I found the difference between 2 time in findDateFiid() func:

   func findDateDiff(time1Str: String, time2Str: String) -> String {
        let timeformatter = DateFormatter()
        timeformatter.dateFormat = "HH:mm:ss"

        guard let time1 = timeformatter.date(from: time1Str),
            let time2 = timeformatter.date(from: time2Str) else { return "" }
        //You can directly use from here if you have two dates
        let interval = time2.timeIntervalSince(time1)
        let hour = interval / 3600;
        let minute = interval.truncatingRemainder(dividingBy: 3600) / 60
        return "\(Int(hour)) \(Int(minute))"
    }

Body:
There is no string-date-math API.

Basically you need two methods to convert HH:mm to minutes and vice versa

func hhmmToMinutes(_ hhmm : String) -> Int {
    let components = hhmm.components(separatedBy: ":")
    guard components.count == 2,
          let hr = Int(components[0]),
          let mn = Int(components[1]) else { return 0 }
    return hr * 60 + mn
}

func minutesToHourMinute(_ minutes : Int) -> String {
    let hr = minutes / 60
    let mn = minutes % 60
    return String(format: "%02ld:%02ld", hr, mn)
}

Then you use can higher level API to do the time math

let array = ["00:45", "00:30", "00:45"]
let minutes = array.map{hhmmToMinutes($0)}.reduce(0, +)
let timeString = minutesToHourMinute(minutes)
print(timeString) // 02:00


问:
How to get validation errors in an array?
I am developing an REST API using Codeigniter.
I need to have all error messages from Form validation in array format so that
I can easily respond in either JSON or XML.

Right now Codeigniter is delivering error messages with
 as delimiters (see below)
but that is not good for a REST based API.

```<code><p>There was an error with this item</p>
</code>```

How can I get errors in an array?

Thankful for all input!

答:
You can transform it easily:</p>

```<code>/**
 * @param $errors string
 * @return array
 */
function transformErrorsToArray ($errors) {
    $errors = explode('</p>', $errors);
    foreach ($errors as $index => $error) {
        $error = str_replace('<p>', '', $error);
        $error = trim($error);
        // ... more cleaning up if necessary
        $errors[$index] = $error
    }
    return $errors;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am developing an REST API using Codeigniter.
I need to have all error messages from Form validation in array format so that
I can easily respond in either JSON or XML.

Right now Codeigniter is delivering error messages with
 as delimiters (see below)
but that is not good for a REST based API.

There was an error with this item

How can I get errors in an array?

Thankful for all input!

Body:
You can transform it easily:

/**
 * @param $errors string
 * @return array
 */
function transformErrorsToArray ($errors) {
    $errors = explode('</p>', $errors);
    foreach ($errors as $index => $error) {
        $error = str_replace('<p>', '', $error);
        $error = trim($error);
        // ... more cleaning up if necessary
        $errors[$index] = $error
    }
    return $errors;
}


问:
Is there quick way to find static variables in Java in Netbeans to decrease initial memory?
SITUATION:

Hello; for years in all my projects,

I have been using static variables, to make codes talk with each other.

CONDITION:

I am specifically using Netbeans. But you can share other IDE solutions so people can see.

QUESTION:

Is there any way to find them all?

So, I can turn them into functions, to decrease some initial memory.

答:
I couldnot find an IDE solution to help coders. So, I came up with my own answer.

I recursively find all java files

read them as lines

selectively log them to a text file

Here is an example:

```<code>package com.tugalsan.tryout5;

import com.tugalsan.api.file.server.*;
import com.tugalsan.api.file.txt.server.*;
import java.nio.file.*;
import java.util.stream.*;

public class Run {

    public static void main(String... args) {
        var parentDirectory = Path.of("C:\\me\\codes\\GWT");
        var results = parentDirectory.resolve("results.log");
        TS_FileUtils.deleteFileIfExists(results);
        var append = true;
        var fileNameMatcher = "*.java";
        var sorted = false;
        var recursive = true;
        TS_DirectoryUtils.subFiles(parentDirectory, fileNameMatcher, sorted, recursive).forEach(javaFile -> {
            var lines = TS_FileTXTUtils.toArrayList(javaFile);
            IntStream.range(0, lines.size())
                    .filter(idx -> lines.get(idx).contains("static"))
                    .filter(idx -> !lines.get(idx).contains("import"))
                    .filter(idx -> !lines.get(idx).contains("class"))
                    .filter(idx -> !lines.get(idx).contains("interface"))
                    .filter(idx -> !lines.get(idx).contains("("))
                    .forEach(idx -> {
                        var line = lines.get(idx);
                        var logLine = String.join("", javaFile.toString(), ", ", String.valueOf(idx), ", ", line, "\n");
                        TS_FileTXTUtils.toFile(logLine, results, append);
                    });
        });
    }
}
</code>```

full code at github

Body:
I couldnot find an IDE solution to help coders. So, I came up with my own answer.

I recursively find all java files

read them as lines

selectively log them to a text file

Here is an example:

package com.tugalsan.tryout5;

import com.tugalsan.api.file.server.*;
import com.tugalsan.api.file.txt.server.*;
import java.nio.file.*;
import java.util.stream.*;

public class Run {

    public static void main(String... args) {
        var parentDirectory = Path.of("C:\\me\\codes\\GWT");
        var results = parentDirectory.resolve("results.log");
        TS_FileUtils.deleteFileIfExists(results);
        var append = true;
        var fileNameMatcher = "*.java";
        var sorted = false;
        var recursive = true;
        TS_DirectoryUtils.subFiles(parentDirectory, fileNameMatcher, sorted, recursive).forEach(javaFile -> {
            var lines = TS_FileTXTUtils.toArrayList(javaFile);
            IntStream.range(0, lines.size())
                    .filter(idx -> lines.get(idx).contains("static"))
                    .filter(idx -> !lines.get(idx).contains("import"))
                    .filter(idx -> !lines.get(idx).contains("class"))
                    .filter(idx -> !lines.get(idx).contains("interface"))
                    .filter(idx -> !lines.get(idx).contains("("))
                    .forEach(idx -> {
                        var line = lines.get(idx);
                        var logLine = String.join("", javaFile.toString(), ", ", String.valueOf(idx), ", ", line, "\n");
                        TS_FileTXTUtils.toFile(logLine, results, append);
                    });
        });
    }
}

full code at github


问:
Java Swing HiDPI Scaling
I have created a program using Java 8 that utilises a Swing GUI in the Eclipse IDE. To scale images and icons to appropriate sizes, it gets and uses the screen resolution. Upon compiling the program within Eclipse, the program displays perfectly fine, and everything seems to operate as it should. However, when I export the project as a "Runnable Jar", and run the program, the image scaling and the program look and feel are all off.

Upon further investigation, it appears that the runnable jar was returning a screen resolution that is exactly 2.5x less then that in eclipse (which is the actual resolution - 3840x2160 vs 1536x864). There is circumstantial evidence across the internet that Java 8 Look and Feels (or something of the sort) don't support HiDPI screen scaling. There are scattered solutions that claim to fix the problem, like updating to Java versions past 8, or by adding arguments to the jar compilation (whatever that means). This is already confusing to a Java novice, and it is only made more confusing by the program being displayed perfectly when run/compiled within the Eclipse IDE.

My question is whether anyone knows how to get a program compiled in Java using Swing to scale correctly on an HiDPI screen, and what the process is that I need to follow to compile a working program?

EDIT 1: Something interesting to note is that in my Windows settings, the "Scale and Layout", "Change the size of text, apps, and other items" is set to exactly 250%, meaning that this setting is obviously the cause of the scaling issues I am encountering. Does someone know how to bypass this setting from within the program, or why it works when I run it through Eclipse?

答:
Java 8 does not support High DPI. On Windows, it runs in DPI unaware mode and relies on Windows to stretch the window bitmap to the scale set for the monitor in the settings. It means the UI of the application looks blurry when displayed on a High DPI monitor.

Later versions of Java, Java 11 and above, support per-monitor High DPI settings. The UI of your application is correctly scaled up according to the settings, the text remains crisp. For the icons and images to remain crisp, you should use MultiResolutionImage or its basic implementation BaseMultiResolutionImage to provide higher resolution alternatives.

You should not base your images based on the screen resolution but rather on the scale set for a monitor. For example, a Full HD monitor 1920×1080 with 150% scale has the effective resolution 1280×720, it is the effective resolution that Java reports to you.

Title: Java Swing HiDPI Scaling


问:
React | Update State | using spread and array.push to update array
I have jsfiddle Link https://jsfiddle.net/ilikeflex/r2uws1ez/30/

I am trying to set new state by accessing the previous state. I have three different cases where i am trying to update the state but i am not sure why does Case2 and Case 3 does not work. Can you please help me ??

```<code>const useState = React.useState;

function Example() {

  const [todos, setTodos] = useState([
    {id:1,text:'Learn React'},
    {id:2,text:'Learn TypeScript'},
    {id:3,text:'Learn Java'}
    ]);

  const case1 = () => {
   const newItem = {id:3,text:'Learn C++'};

   setTodos((prevState) => {
    return prevState.concat(newItem);
   });

  }

  const case2 = () => {
   const newItem = {id:3,text:'Learn .Net'};

   setTodos((prevState) => {
    prevState.push(newItem);  // I am adding to previous state and returning it
    return prevState;
   });

  }

 const case3 = () => {
   const newItem = {id:3,text:'Learn C#'};

   setTodos((prevState) => {
    let result = { ...prevState, newItem }; // using spread operator
    return result;
   });

  }

  return (
    <div>

      <button onClick={case1}>Case 1</button>
      <button onClick={case2}>Case 2</button>
      <button onClick={case3}>Case 3</button>

      <ul>
            {todos.map((item) => (
            <li key={item.id}>{item.text}</li>
          ))}
      </ul>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'))
</code>```

答:
In all the cases, a new array need be to created and returned.

Case 1.

```<code>return prevState.concat(newItem); [ concat create a new array ]
</code>```

Case 2

```<code>const newState = [...prevState];  [ Spread Operator creates a new array ]
    newState.push(newItem);
    return newState;
</code>```

Case 3

```<code> let result = [...prevState, newItem ] ; [ Spread Operator creates a new array and newItem is added simultaneously ]
    return result;
</code>```

Body:
I have jsfiddle Link https://jsfiddle.net/ilikeflex/r2uws1ez/30/

I am trying to set new state by accessing the previous state. I have three different cases where i am trying to update the state but i am not sure why does Case2 and Case 3 does not work. Can you please help me ??

const useState = React.useState;

function Example() {

  const [todos, setTodos] = useState([
    {id:1,text:'Learn React'},
    {id:2,text:'Learn TypeScript'},
    {id:3,text:'Learn Java'}
    ]);

  const case1 = () => {
   const newItem = {id:3,text:'Learn C++'};

   setTodos((prevState) => {
    return prevState.concat(newItem);
   });

  }

  const case2 = () => {
   const newItem = {id:3,text:'Learn .Net'};

   setTodos((prevState) => {
    prevState.push(newItem);  // I am adding to previous state and returning it
    return prevState;
   });

  }

 const case3 = () => {
   const newItem = {id:3,text:'Learn C#'};

   setTodos((prevState) => {
    let result = { ...prevState, newItem }; // using spread operator
    return result;
   });

  }

  return (

      <button onClick={case1}>Case 1</button>
      <button onClick={case2}>Case 2</button>
      <button onClick={case3}>Case 3</button>

            {todos.map((item) => (

{item.text}

          ))}

  );
}

ReactDOM.render(<Example />, document.getElementById('root'))

Body:
In all the cases, a new array need be to created and returned.

Case 1.

return prevState.concat(newItem); [ concat create a new array ]

Case 2

const newState = [...prevState];  [ Spread Operator creates a new array ]
    newState.push(newItem);
    return newState;

Case 3

 let result = [...prevState, newItem ] ; [ Spread Operator creates a new array and newItem is added simultaneously ]
    return result;


问:
Cannot edit css of a class with variable
I am trying to get a line through  the li that i added when i click the li(like a grocery list).

```<code>$('document').ready(() => {
            let id = 1;

            $('.knop').click(() => {
                let boodschap = $('.tekst').val();
                let newli = `<li id="boodschap${id}"> ${boodschap}</li>`;
                $(".result").append(`${newli}`);
                id++;
            });

            $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
                console.log(event.target.id);
            });
        });
</code>```

I know the problem is in this part:

```<code> $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
</code>```

I dont get a error in my console. so im stuck.
but when i hard code the part where i put my ${target} it works.
you cant use a variable in the css function?
is there a way around this?

答:
I see you have target.val in your top example but the specified code just hs target.

Which one do you have in your code?

Also should it be target.val()?

can you console log your target and target.val() to make sure its equal to what you are hard coding?

```<code>
                let target = event.target.id;
console.log("my target", target)
console.log("target val", target.val())
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });```
```

Body:
I am trying to get a line through  the li that i added when i click the li(like a grocery list).

$('document').ready(() => {
            let id = 1;

            $('.knop').click(() => {
                let boodschap = $('.tekst').val();
                let newli = `<li id="boodschap${id}"> ${boodschap}</li>`;
                $(".result").append(`${newli}`);
                id++;
            });

            $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });
                console.log(event.target.id);
            });
        });

I know the problem is in this part:

 $('ul').click(() => {
                let target = event.target.id;
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });

I dont get a error in my console. so im stuck.
but when i hard code the part where i put my ${target} it works.
you cant use a variable in the css function?
is there a way around this?

Body:
I see you have target.val in your top example but the specified code just hs target.

Which one do you have in your code?

Also should it be target.val()?

can you console log your target and target.val() to make sure its equal to what you are hard coding?

                let target = event.target.id;
console.log("my target", target)
console.log("target val", target.val())
                $(`${target}`).css({
                    "text-decoration": "line-through"
                });```


问:
Matching encoded password field spring boot
I´m currently learning Spring-Boot framework and trying to create a custom field matching Validator following the guide at the page baledung.

My code is actually the same like on the page above, the only thing that's different is that I've encoded the password using BCryptPasswordEncoder.

Here is my user class.

```<code>    @FieldsValueMatch.List({
        @FieldsValueMatch(
                field = "password",
                fieldMatch = "verifyPassword",
                message = "Passwords do not match!"
        )
})
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "User")
public class User implements UserDetails {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    @NotEmpty(message = "{firstname.notempty}")
    private String firstname;

    @Column(nullable = false)
    @NotEmpty(message = "{lastname.notempty}")
    private String lastname;

    @Column(nullable = false,unique = true)
    @NotEmpty(message = "{email.notempty}")
    @Email(message = "{email.notwellformed}")
    private String email;

    @Column(nullable = false)
    @NotEmpty(message = "{password.notempty}")
    @ValidPassword
    private String password;

    @NotEmpty(message = "{verifyPassword.notempty}")
    @Transient
    private String verifyPassword;
</code>```

Controller:

```<code>    @PostMapping("/sign-up")
String signUp(@Valid User user, BindingResult bindingResult) {
    if (userService.userExists(user.getEmail())){
        bindingResult.rejectValue("email", "email.alreadyexists");
    }
    if(bindingResult.hasErrors()){
        return "sign-up";
    }
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    userService.signUpUser(user);
    return "redirect:/sign-in";
}
</code>```

signUpUser Method:

```<code>    public void signUpUser(User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    userRepository.save(user);
    final ConfirmationToken confirmationToken = new ConfirmationToken(user);
    confirmationTokenService.saveConfirmationToken(confirmationToken);
    sendConfirmationMail(user.getEmail(), confirmationToken.getConfirmationToken());
}
</code>```

And I recieve the following error:

```<code>    javax.validation.ConstraintViolationException: Validation failed for classes [com.project.project.entity.User] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='Passwords do not match!', propertyPath=verifyPassword, rootBeanClass=class com.project.project.entity.User, messageTemplate='Passwords do not match!'}
    ConstraintViolationImpl{interpolatedMessage='Password must be no more than 30 characters in length.', propertyPath=password, rootBeanClass=class com.project.project.entity.User, messageTemplate='Password must be no more than 30 characters in length.'}
]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:140) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:188) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:78) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:760) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:746) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
</code>```

I think that encoded password is being compared with the verifyPassword which isn't encoded. That's why I'm receieving this error or? How can I fix it?
If I also encode the verifyPassword, I still get the error.

Thanks in Advance.

答:
The length of 30 characters normally represents that a user of the system should type a password no more than 30 characters long. The typed password however when encoded by the system will be of a different length.

The error occurs because the User that you use to map your database entity has a validation constraint of password not exceeding 30 characters. The process to encode your password can modify the original length of the password. Therefore the error occurs.

You should create another class UserDto which would be accessible from the controller and will represent the information that is exchanged between the controller class and the actual user of the system which types the password. This new UserDto can then have this constraint of 30 characters and the database representation with User class can be without such constraint, since in database the password will be stored with a different length.

So you will use UserDto class to validate the input of the user, to the system, and you will use User class to map your database records inside a java object following the structure of the relative table.

Body:
I´m currently learning Spring-Boot framework and trying to create a custom field matching Validator following the guide at the page baledung.

My code is actually the same like on the page above, the only thing that's different is that I've encoded the password using BCryptPasswordEncoder.

Here is my user class.

    @FieldsValueMatch.List({
        @FieldsValueMatch(
                field = "password",
                fieldMatch = "verifyPassword",
                message = "Passwords do not match!"
        )
})
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity(name = "User")
public class User implements UserDetails {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    @NotEmpty(message = "{firstname.notempty}")
    private String firstname;

    @Column(nullable = false)
    @NotEmpty(message = "{lastname.notempty}")
    private String lastname;

    @Column(nullable = false,unique = true)
    @NotEmpty(message = "{email.notempty}")
    @Email(message = "{email.notwellformed}")
    private String email;

    @Column(nullable = false)
    @NotEmpty(message = "{password.notempty}")
    @ValidPassword
    private String password;

    @NotEmpty(message = "{verifyPassword.notempty}")
    @Transient
    private String verifyPassword;

Controller:

    @PostMapping("/sign-up")
String signUp(@Valid User user, BindingResult bindingResult) {
    if (userService.userExists(user.getEmail())){
        bindingResult.rejectValue("email", "email.alreadyexists");
    }
    if(bindingResult.hasErrors()){
        return "sign-up";
    }
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    userService.signUpUser(user);
    return "redirect:/sign-in";
}

signUpUser Method:

    public void signUpUser(User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    userRepository.save(user);
    final ConfirmationToken confirmationToken = new ConfirmationToken(user);
    confirmationTokenService.saveConfirmationToken(confirmationToken);
    sendConfirmationMail(user.getEmail(), confirmationToken.getConfirmationToken());
}

And I recieve the following error:

    javax.validation.ConstraintViolationException: Validation failed for classes [com.project.project.entity.User] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
    ConstraintViolationImpl{interpolatedMessage='Passwords do not match!', propertyPath=verifyPassword, rootBeanClass=class com.project.project.entity.User, messageTemplate='Passwords do not match!'}
    ConstraintViolationImpl{interpolatedMessage='Password must be no more than 30 characters in length.', propertyPath=password, rootBeanClass=class com.project.project.entity.User, messageTemplate='Password must be no more than 30 characters in length.'}
]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:140) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.preInsert(EntityIdentityInsertAction.java:188) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:78) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:185) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:128) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:55) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:760) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:746) ~[hibernate-core-5.6.4.Final.jar:5.6.4.Final]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]

I think that encoded password is being compared with the verifyPassword which isn't encoded. That's why I'm receieving this error or? How can I fix it?
If I also encode the verifyPassword, I still get the error.

Thanks in Advance.


问:
Interpolate seconds to milliseconds in dataset?
I have a sorted dataset by timestamps in seconds. However I need to somehow convert it to millisecond accuracy.

Example

```<code>    dataset = [
        # UNIX timestamps with reading data
        (0,  0.48499),
        (2,  0.48475),
        (3,  0.48475),
        (3,  0.48473),
        (3,  0.48433),
        (3,  0.48403),
        (3,  0.48403),
        (3,  0.48403),
        (3,  0.48403),
        (3,  0.48403),
        (5,  0.48396),
        (12, 0.48353),
    ]
</code>```

Expected output (roughly)

```<code>    interpolated = [
        # Timestamps with millisecond accuracy
        (0.0,  0.48499),
        (2.0,  0.48475),
        (3.0,  0.48475),
        (3.14,  0.48473),
        (3.28,  0.48433),
        (3.42,  0.48403),
        (3.57,  0.48403),
        (3.71,  0.48403),
        (3.85,  0.48403),
        (3.99,  0.48403),
        (5.0,  0.48396),
        (12.0, 0.48353),
    ]
</code>```

I don't have much experience with Pandas and I've gone through interpolate and drop_duplicates but couldn't figure out how to go about this.

I would think this is a common problem so any help appreciated. Ideally I want to spread evenly the numbers.

Body:
I have a sorted dataset by timestamps in seconds. However I need to somehow convert it to millisecond accuracy.

Example

    dataset = [
        # UNIX timestamps with reading data
        (0,  0.48499),
        (2,  0.48475),
        (3,  0.48475),
        (3,  0.48473),
        (3,  0.48433),
        (3,  0.48403),
        (3,  0.48403),
        (3,  0.48403),
        (3,  0.48403),
        (3,  0.48403),
        (5,  0.48396),
        (12, 0.48353),
    ]

Expected output (roughly)

    interpolated = [
        # Timestamps with millisecond accuracy
        (0.0,  0.48499),
        (2.0,  0.48475),
        (3.0,  0.48475),
        (3.14,  0.48473),
        (3.28,  0.48433),
        (3.42,  0.48403),
        (3.57,  0.48403),
        (3.71,  0.48403),
        (3.85,  0.48403),
        (3.99,  0.48403),
        (5.0,  0.48396),
        (12.0, 0.48353),
    ]

I don't have much experience with Pandas and I've gone through interpolate and drop_duplicates but couldn't figure out how to go about this.

I would think this is a common problem so any help appreciated. Ideally I want to spread evenly the numbers.

Body:
You can use groupby and apply methods. I didn't come up with a specific method like interpolate in this case, but there might be a more pythonic way.

Code:

import numpy as np
import pandas as pd

# Create a sample dataframe
dataset = [(0, 0.48499), (2, 0.48475), (3, 0.48475), (3, 0.48473), (3, 0.48433), (3, 0.48403), (3, 0.48403), (3, 0.48403), (3, 0.48403), (3, 0.48403), (5, 0.48396), (12, 0.48353)]
df = pd.DataFrame(dataset, columns=['t', 'value'])

# Convert UNIX timestamps into the desired format
df.t = df.groupby('t', group_keys=False).apply(lambda df: df.t + np.linspace(0, 1, len(df)))

Output:

t
value

0
0.48499

2
0.48475

3
0.48475

3.14286
0.48473

3.28571
0.48433

3.42857
0.48403

3.57143
0.48403

3.71429
0.48403

3.85714
0.48403

4
0.48403

5
0.48396

12
0.48353

(Input:)

t
value

0
0.48499

2
0.48475

3
0.48475

3
0.48473

3
0.48433

3
0.48403

3
0.48403

3
0.48403

3
0.48403

3
0.48403

5
0.48396

12
0.48353


问:
help with event click
I'm developing a html with this structure

```<code>div id="menuContainer">
    <div class = "menu ui-accordion-header ui-state-default ui-corner-all">
        <label class="formatText">Cliente</label><span class="ui-icon ui-icon-triangle-1-e menuIcon" style="float: right"></span>
            <div class = "subMenu ui-accordion-header ui-state-default ui-corner-all">
                <ul class="options">
                    <li>
                        <label class="formatText">Ver Cliente</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                <ul class="options">
                                    <li>
                                        <label class="formatText">Por Nombre</label><span class="ui-icon ui-icon-triangle-1-e" style="float: right"></span>
                                            <div class = "subMenuRight ui-accordion-header ui-state-default ui-corner-all">
                                                <ul class="options">
                                                    <li><label class="formatText">sub sub menu</label></li>
                                                    <li><label class="formatText">prueba</label></li>
                                                </ul>
                                            </div>
                                    </li>
                                    <li>
                                        <label class="formatText">Por Campana</label>
                                    </li>
                                </ul>
                            </div>
                    </li>
                    <li>
                        <label class="formatText">Reportes para Cliente</label>
                    </li>
                </ul>
            </div>
    </div>
</div>
</code>```

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

```<code>$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});
</code>```

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??

答:
As can be seen from the html code, there are two li's each for subMenu and subMenuRight. Maybe you should use the :first selector in each case:

```<code>$(".subMenu li:first").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li:first").click(function () {
    alert('click in the second child');
});
</code>```

Title: help with event click

Body:
I'm developing a html with this structure

div id="menuContainer">

        Cliente

                        Ver Cliente

                                        Por Nombre

sub sub menu

prueba

                                        Por Campana

                        Reportes para Cliente

notice that the principal div have class called menu, in the inside there are a some divs that with a classes called subMenu and subMenuRight, my problem it's that i want associate a event click to the father and other behavior to the divs children i tried like this

$(".menu").click(function () {
    alert('click in the father');
});
$(".subMenu li").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li").click(function () {
    alert('click in the second child');
});

The problem with this code it's that div father contains the divs children all the event handler are triggered. So my question is How can I modify the selector or validate the in the event handler for to only fire the exactly element that is clicked??

Body:
As can be seen from the html code, there are two li's each for subMenu and subMenuRight. Maybe you should use the :first selector in each case:

$(".subMenu li:first").click(function () {
    alert('click in the first child');
});
$(".subMenuRight li:first").click(function () {
    alert('click in the second child');
});


问:
How to render key and value with key having a custom name
I have a list of key value pair.

I am fetching them from an api using this function

```<code> void getPastSurvey() async {

    var response = await http.get(
        Uri.parse(
            "https://google.com/get_contact_data"),
        headers: {"Authorization": "Bearer $token"});
    int status = response.statusCode;
    var body = json.decode(response.body);

      try {
        List screenDataLong = body["screen_data_long"]["data"];
        for (var i in screenDataLong) {
          questions[i["key"]] = i["value"];
      } catch (e) {
        // debugPrint("caught error");
        // debugPrint("$e");
      }

    }
  }
</code>```

this is the json

```<code>"screen_data_long": {
        "conversation_id": "2laXjNPwlKI61qPQC6Xb16-us",
        "date": "2022-02-12T06:17:08.58",
        "contact": "contact 3",
        "data": [
            {
                "key": "user_id",
                "value": "afc7e6ff-878a-418b-9a2f-6f7fe2240085"
            },
            {
                "key": "user_email",
                "value": "tester@gmail.com"
            },
            {
                "key": "contact_id",
                "value": "contact 3"
            },
            {
                "key": "conversation_id",
                "value": "2laXjNPwlKI61qPQC6Xb16-us"
            },
            {
                "key": "participant_id",
                "value": "nphcda005555222"
            },
            {
                "key": "completed_at",
                "value": "2022-02-12T06:17:08.5796315+02:00"
            },
            {
                "key": "override_contact_data",
                "value": "Yes"
            },
            {
                "key": "seek_advice",
                "value": "Yes"
            },
            {
                "key": "reacto_items",
                "value": "[Fever]"
            },
            {
                "key": "reacto_begin",
                "value": "2022-02-12"
            },
            {
                "key": "reacto_status",
                "value": "Recovered/resolved"
            },
            {
                "key": "reacto_resolved_date",
                "value": "2022-02-12"
            },
            {
                "key": "reacto_impact_level",
                "value": "Uncomfortable (nuisance or irritation) but able to carry on with everyday activities"
            },
            {
                "key": "patient_pregnancy",
                "value": "Yes"
            }
</code>```

I have small widget function to render the data

```<code>List<Widget> generateData() {
    List<Widget> list = <Widget>[];
    questions.forEach((key, value) {
      list.add(Text(key, style: TextStyle(fontSize: 20.0)));
      list.add(Text(value, style: TextStyle(fontSize: 16.0)));
      list.add(Container(margin: EdgeInsets.all(15.0)));
    });

    return list;
  }
</code>```

And then I render it to the ui under a scroll view like

```<code> SingleChildScrollView(
                    child: Padding(
                        padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: generateOldSurvey())))
</code>```

I want to assign the keys custom values that are readable to the user and not DB names with underscores. Like the key user_email I display it as User email with the correct value under it.
How can I achieve this correctly inside the SingleChildScrollView ?

答:
You need to manually handle String in your keys.
Eg: if you want all the keys in the format user_email as User Email
you can split the string and add it

```<code>List<Widget> generateData() {
    List<Widget> list = <Widget>[];
    questions.forEach((key, value) {
      var keyList = key.split('_');  // ["user","email"]
      var keyValue = "${keyList[0]} ${keyList[1]}"; // "user name"
      list.add(Text(keyValue, style: TextStyle(fontSize: 20.0)));
      list.add(Text(value, style: TextStyle(fontSize: 16.0)));
      list.add(Container(margin: EdgeInsets.all(15.0)));
    });

    return list;
  }
</code>```

You can then title case the keyValue Using this

Body:
I have a list of key value pair.

I am fetching them from an api using this function

 void getPastSurvey() async {

    var response = await http.get(
        Uri.parse(
            "https://google.com/get_contact_data"),
        headers: {"Authorization": "Bearer $token"});
    int status = response.statusCode;
    var body = json.decode(response.body);

      try {
        List screenDataLong = body["screen_data_long"]["data"];
        for (var i in screenDataLong) {
          questions[i["key"]] = i["value"];
      } catch (e) {
        // debugPrint("caught error");
        // debugPrint("$e");
      }

    }
  }

this is the json

"screen_data_long": {
        "conversation_id": "2laXjNPwlKI61qPQC6Xb16-us",
        "date": "2022-02-12T06:17:08.58",
        "contact": "contact 3",
        "data": [
            {
                "key": "user_id",
                "value": "afc7e6ff-878a-418b-9a2f-6f7fe2240085"
            },
            {
                "key": "user_email",
                "value": "tester@gmail.com"
            },
            {
                "key": "contact_id",
                "value": "contact 3"
            },
            {
                "key": "conversation_id",
                "value": "2laXjNPwlKI61qPQC6Xb16-us"
            },
            {
                "key": "participant_id",
                "value": "nphcda005555222"
            },
            {
                "key": "completed_at",
                "value": "2022-02-12T06:17:08.5796315+02:00"
            },
            {
                "key": "override_contact_data",
                "value": "Yes"
            },
            {
                "key": "seek_advice",
                "value": "Yes"
            },
            {
                "key": "reacto_items",
                "value": "[Fever]"
            },
            {
                "key": "reacto_begin",
                "value": "2022-02-12"
            },
            {
                "key": "reacto_status",
                "value": "Recovered/resolved"
            },
            {
                "key": "reacto_resolved_date",
                "value": "2022-02-12"
            },
            {
                "key": "reacto_impact_level",
                "value": "Uncomfortable (nuisance or irritation) but able to carry on with everyday activities"
            },
            {
                "key": "patient_pregnancy",
                "value": "Yes"
            }

I have small widget function to render the data

List<Widget> generateData() {
    List<Widget> list = <Widget>[];
    questions.forEach((key, value) {
      list.add(Text(key, style: TextStyle(fontSize: 20.0)));
      list.add(Text(value, style: TextStyle(fontSize: 16.0)));
      list.add(Container(margin: EdgeInsets.all(15.0)));
    });

    return list;
  }

And then I render it to the ui under a scroll view like

 SingleChildScrollView(
                    child: Padding(
                        padding: EdgeInsets.only(top: 15.0, bottom: 15.0),
                        child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: generateOldSurvey())))

I want to assign the keys custom values that are readable to the user and not DB names with underscores. Like the key user_email I display it as User email with the correct value under it.
How can I achieve this correctly inside the SingleChildScrollView ?

Body:
You need to manually handle String in your keys.
Eg: if you want all the keys in the format user_email as User Email
you can split the string and add it

List<Widget> generateData() {
    List<Widget> list = <Widget>[];
    questions.forEach((key, value) {
      var keyList = key.split('_');  // ["user","email"]
      var keyValue = "${keyList[0]} ${keyList[1]}"; // "user name"
      list.add(Text(keyValue, style: TextStyle(fontSize: 20.0)));
      list.add(Text(value, style: TextStyle(fontSize: 16.0)));
      list.add(Container(margin: EdgeInsets.all(15.0)));
    });

    return list;
  }

You can then title case the keyValue Using this


问:
Calculate difference between min and max for each Pandas group
I want to calculate difference between max and min value for each group in pandas dataframe.
For example, I wrote a code that calculates standard deviation for each group.

```<code>import pandas as pd
import statistics

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

print(df)

df = df.groupby('Month')[['values_1', 'values_2']].std().round(2)
df = df.reset_index(drop = False)
print(df)
</code>```

Result looks like this:

```<code>    Month  values_1  values_2
0   Feb      2.94      1.63
1   Jan      2.87      1.26
2   Mar      4.27      0.50
</code>```

Now I want to modify the code so that I get the same type/looks of the result, but with max-min values instead of standard deviation.

答:
there is numpy's peak to peak for that also</p>
```<code>df.groupby('Month').agg(np.ptp)

       values_1  values_2
Month
Feb           6         4
Jan           6         3
Mar          10         1
</code>```

Body:
I want to calculate difference between max and min value for each group in pandas dataframe.
For example, I wrote a code that calculates standard deviation for each group.

import pandas as pd
import statistics

months = ["Jan", "Jan", "Jan", "Jan","Feb","Feb","Feb", "Feb", "Mar", "Mar", "Mar", "Mar"]
values_1 = [1,2,7,1,3,8,9,4,7,4,11,1]
values_2 = [8,6,6,5,6,6,8,4,9,9,10,9]
df = pd.DataFrame({"Month": months,
                   "values_1": values_1,
                   "values_2": values_2})

print(df)

df = df.groupby('Month')[['values_1', 'values_2']].std().round(2)
df = df.reset_index(drop = False)
print(df)

Result looks like this:

    Month  values_1  values_2
0   Feb      2.94      1.63
1   Jan      2.87      1.26
2   Mar      4.27      0.50

Now I want to modify the code so that I get the same type/looks of the result, but with max-min values instead of standard deviation.

Body:
there is numpy's peak to peak for that also

df.groupby('Month').agg(np.ptp)

       values_1  values_2
Month
Feb           6         4
Jan           6         3
Mar          10         1


问:
I need to install a picture, but it gives an error
I am trying to create a game based on Eric Matiz's book "learning python" and created the Ship module, there is an error in this module that I cannot solve

Here is the code itself:

```<code>import pygame

class Ship():

    def __init__(self, screen):
        """Init ship and sets its starting position"""
        self.screen = screen

        # load image ship and gets rectangle.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # every new ship is starting in bottom edge screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

    def bliteme(self):
        """Draws the ship at the current position."""
        self.screen.blit(self.image, self.rect)
</code>```

I tried to do it through the "os" module, but nothing worked
Error:

```<code>self.image = pygame.image.loading('images/ship.bmp')
FileNotFoundError error: There is no such file or directory.
</code>```

The file is located in the "images" directory with the name "ship.bmp", the path is specified correctly, but still gives an error

I tried to find an answer on the internet, but mostly such errors remain without a working answer

答:
It is not enough to put the files in the same directory or sub directory. You also need to set the working directory.
The image file path has to be relative to the current working directory. The working directory is possibly different to the directory of the python script.

Put the following at the beginning of your code to set the working directory to the same as the script's directory:

import os
os.chdir(os.path.dirname(os.path.abspath(__file__)))
```

Body:
I am trying to create a game based on Eric Matiz's book "learning python" and created the Ship module, there is an error in this module that I cannot solve

Here is the code itself:

import pygame

class Ship():

    def __init__(self, screen):
        """Init ship and sets its starting position"""
        self.screen = screen

        # load image ship and gets rectangle.
        self.image = pygame.image.load('images/ship.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # every new ship is starting in bottom edge screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

    def bliteme(self):
        """Draws the ship at the current position."""
        self.screen.blit(self.image, self.rect)

I tried to do it through the "os" module, but nothing worked
Error:

self.image = pygame.image.loading('images/ship.bmp')
FileNotFoundError error: There is no such file or directory.

The file is located in the "images" directory with the name "ship.bmp", the path is specified correctly, but still gives an error

I tried to find an answer on the internet, but mostly such errors remain without a working answer


答:
if you use .bind() instead you can set the preventBubble variable to false to prevent clicks bubbling up to parent elements (http://api.jquery.com/bind/)

```<code>$(".menu").bind('click', function () {
    alert('click in the father');
}, false);
$(".subMenu li").bind('click', function () {
    alert('click in the first child');
}, false);
$(".subMenuRight li").bind('click', function () {
    alert('click in the second child');
}, false);
</code>```

Title: help with event click

Body:
if you use .bind() instead you can set the preventBubble variable to false to prevent clicks bubbling up to parent elements (http://api.jquery.com/bind/)

$(".menu").bind('click', function () {
    alert('click in the father');
}, false);
$(".subMenu li").bind('click', function () {
    alert('click in the first child');
}, false);
$(".subMenuRight li").bind('click', function () {
    alert('click in the second child');
}, false);


问:
How do I split one-column data separated by spaces into multiple columns?
I need to split the column "leg1" into three columns (v1,v2,v3). The problem is that the amount of blank spaces is different by rows.

```<code>> head(data[,2:3])
    name                           leg1
513    1      0.00000  0.00000  0.00000
514    2   -0.00000  -0.00000  -0.00000
515    3      0.00000  0.00000  0.00000
516    4   -0.03467  -0.03848  -0.02331
517    5   -0.00000  -0.00000  -0.00000
518    6   -0.00000  -0.00000  -0.00000
</code>```

I tried to use gsub or substr, but I couldn`t do it.

Could anyone help me, please?

Thanks in advance!!

Body:
I need to split the column "leg1" into three columns (v1,v2,v3). The problem is that the amount of blank spaces is different by rows.

> head(data[,2:3])
    name                           leg1
513    1      0.00000  0.00000  0.00000
514    2   -0.00000  -0.00000  -0.00000
515    3      0.00000  0.00000  0.00000
516    4   -0.03467  -0.03848  -0.02331
517    5   -0.00000  -0.00000  -0.00000
518    6   -0.00000  -0.00000  -0.00000

I tried to use gsub or substr, but I couldn`t do it.

Could anyone help me, please?

Thanks in advance!!

Body:
You can use str_split_fixed from the stringr package, after first replacing multiple spaces with 1:

data <- data.frame(name = c(1,2,3,4,5))

data$leg1 <- c(
  "0.00000  0.00000  0.00000",
  "-0.00000  -0.00000  -0.00000",
  "0.00000  0.00000  0.00000",
  "-0.03467  -0.03848  -0.02331",
  "-0.00000  -0.00000  -0.00000")

data$leg1 <- gsub("\\s+", " ", str_trim(data$leg1))

str_split_fixed(data$leg1, " ", 3) %>%
  data.frame() %>%
  rename(v1 = X1, v2 = X2, v3 = X3) %>%
  cbind(data, .)

##   name                         leg1       v1       v2        v3
## 1    1    0.00000  0.00000  0.00000  0.00000  0.00000   0.00000
## 2    2 -0.00000  -0.00000  -0.00000 -0.00000 -0.00000  -0.00000
## 3    3    0.00000  0.00000  0.00000  0.00000  0.00000   0.00000
## 4    4 -0.03467  -0.03848  -0.02331 -0.03467 -0.03848  -0.02331
## 5    5 -0.00000  -0.00000  -0.00000 -0.00000 -0.00000  -0.00000


问:
Java ReentrantLock. Unlock method does not reset the header, how to remove the executed thread wrapped in a node?
I am learning Java ReentrantLock source code these days.
On the unlock method, it actually do two things:
(1) Check if acquire number == release number, if yes, set ExclusiveOwnerThread as null;
(2) if (1) is OK, unpark successor;

```<code>    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
</code>```

My question is, all these opearation did not change the header or dequeue any node in the waiting queue.

Without resetting header or dequeue operation, the waiting queue will grow infinitely as new thread acquire the lock.

Can anyone point out where did I ignore or something wrong with my understanding?

答:
header of the queue operation in acquireQueued method

```<code>    final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                //reset header， the second node of queue will be new header
                setHead(node);
                //help GC， the old header node will be GC
                p.next = null;
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}
</code>```

Body:
I am learning Java ReentrantLock source code these days.
On the unlock method, it actually do two things:
(1) Check if acquire number == release number, if yes, set ExclusiveOwnerThread as null;
(2) if (1) is OK, unpark successor;

    public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

My question is, all these opearation did not change the header or dequeue any node in the waiting queue.

Without resetting header or dequeue operation, the waiting queue will grow infinitely as new thread acquire the lock.

Can anyone point out where did I ignore or something wrong with my understanding?

Body:
header of the queue operation in acquireQueued method

    final boolean acquireQueued(final Node node, int arg) {
    boolean failed = true;
    try {
        boolean interrupted = false;
        for (;;) {
            final Node p = node.predecessor();
            if (p == head && tryAcquire(arg)) {
                //reset header， the second node of queue will be new header
                setHead(node);
                //help GC， the old header node will be GC
                p.next = null;
                failed = false;
                return interrupted;
            }
            if (shouldParkAfterFailedAcquire(p, node) &&
                parkAndCheckInterrupt())
                interrupted = true;
        }
    } finally {
        if (failed)
            cancelAcquire(node);
    }
}


问:
'IFormCollection' does not contain a definition for 'GetValues' in ASP.NET Core MVC
I am using below code in ASP.Net MVC

```<code>Entity.CurrentPassword = ConvertToSecureString(Request.Form.GetValues("CurrentPassword")[0]);
</code>```

Here Request is the HttpRequest ControllerBase.Request { get; } and Form is IFormCollection HttpRequest.Form { get;set; }

But while converting this to ASP.NET Core MVC, I'm getting below error:

'IFormCollection' does not contain a definition for 'GetValues' and no accessible extension method 'GetValues' accepting a first argument of type 'IFormCollection' could be found

Do we need to add any additional package for this in .Net core or is there any replacement for the similar functionality.

答:
In ASP.NET CORE, you can access the value from the indexer like this:</p>
```<code>Entity.CurrentPassword = ConvertToSecureString(Request.Form["CurrentPassword"][0]);
</code>```

Body:
I am using below code in ASP.Net MVC

Entity.CurrentPassword = ConvertToSecureString(Request.Form.GetValues("CurrentPassword")[0]);

Here Request is the HttpRequest ControllerBase.Request { get; } and Form is IFormCollection HttpRequest.Form { get;set; }

But while converting this to ASP.NET Core MVC, I'm getting below error:

'IFormCollection' does not contain a definition for 'GetValues' and no accessible extension method 'GetValues' accepting a first argument of type 'IFormCollection' could be found

Do we need to add any additional package for this in .Net core or is there any replacement for the similar functionality.

Body:
In ASP.NET CORE, you can access the value from the indexer like this:

Entity.CurrentPassword = ConvertToSecureString(Request.Form["CurrentPassword"][0]);


问:
JdbcSQLIntegrityConstraintViolationException when inserting new entry after schema generated from class and initial data loaded from file
I have a spring boot project with an h2 database.

I have an entity class from which the schema is to be generated:

```<code>@NoArgsConstructor
@Entity
@Table(name = "NAMES")
public class Name {

    @Id
    @GeneratedValue
    public Long id;

    @Column(nullable = false)
    public String name;

    public Name(String name) {
        this.name = name;
    }

}
</code>```

And I have a data.sql file:

```<code>insert into names (id, name) values (1, 'Alex');
insert into names (id, name) values (2, 'Bob');
</code>```

my application.properties is:

```<code>spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true
</code>```

The application starts up just fine, I can confirm with localhost:8080/h2-console that the data is loaded into the database.
But I cannot save new data into the table with

```<code>//public interface NameRepository extends CrudRepository<Name,Long> {}

@RestController
@Service
public class MyController {

  @Autowired
  private final NameRepository nameRepository;

  @PostMapping("/triggerError")
  public ResponseEntity<Void> trigger() {

    Name newName = new Name("Chris");
    nameRepository.save(newName);
    return ResponseEntity.ok().build();
  }
}
</code>```

The error message is:

```<code>could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.NAMES(ID) ( /* key:1 */ CAST(1 AS BIGINT), 'Alex')\"; SQL statement:
insert into names (name, id) values (?, ?) [23505-210]];
</code>```

I assume that this means that spring wants to insert the new name at id=1, not realizing that ids 1 and 2 are already in use. I guess the right parameters to @GeneratedValue could fix it but I do not understand what they mean and which one to choose.

Trial and error:

@GeneratedValue(strategy = GenerationType.AUTO) is the default, see above.

@GeneratedValue(strategy = GenerationType.TABLE) same error

@GeneratedValue(strategy = GenerationType.SEQUENCE) same error

@GeneratedValue(strategy = GenerationType.IDENTITY) different error:

```<code>...
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column \"ID\"; SQL statement:\ninsert into names (id, name) values (null, ?) [23502-210]
...
could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
</code>```

So apparently it is not the annotation, but something else.

I'm giving up, heres my MRE: https://github.com/timo-a/duckpond-spring-backend/tree/debug/saving

答:
This is a bug on hibernate and specific to h2 database.
https://hibernate.atlassian.net/browse/HHH-14985

you can use id BIGINT GENERATED BY DEFAULT AS IDENTITY DEFAULT ON NULL PRIMARY KEY column definition as a fix.

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "id BIGINT GENERATED BY DEFAULT AS IDENTITY DEFAULT ON NULL PRIMARY KEY")
private Long id;
</code>```

Body:
I have a spring boot project with an h2 database.

I have an entity class from which the schema is to be generated:

@NoArgsConstructor
@Entity
@Table(name = "NAMES")
public class Name {

    @Id
    @GeneratedValue
    public Long id;

    @Column(nullable = false)
    public String name;

    public Name(String name) {
        this.name = name;
    }

}

And I have a data.sql file:

insert into names (id, name) values (1, 'Alex');
insert into names (id, name) values (2, 'Bob');

my application.properties is:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.defer-datasource-initialization=true
spring.jpa.show-sql=true

The application starts up just fine, I can confirm with localhost:8080/h2-console that the data is loaded into the database.
But I cannot save new data into the table with

//public interface NameRepository extends CrudRepository<Name,Long> {}

@RestController
@Service
public class MyController {

  @Autowired
  private final NameRepository nameRepository;

  @PostMapping("/triggerError")
  public ResponseEntity<Void> trigger() {

    Name newName = new Name("Chris");
    nameRepository.save(newName);
    return ResponseEntity.ok().build();
  }
}

The error message is:

could not execute statement; SQL [n/a]; constraint [\"PRIMARY KEY ON PUBLIC.NAMES(ID) ( /* key:1 */ CAST(1 AS BIGINT), 'Alex')\"; SQL statement:
insert into names (name, id) values (?, ?) [23505-210]];

I assume that this means that spring wants to insert the new name at id=1, not realizing that ids 1 and 2 are already in use. I guess the right parameters to @GeneratedValue could fix it but I do not understand what they mean and which one to choose.

Trial and error:

@GeneratedValue(strategy = GenerationType.AUTO) is the default, see above.

@GeneratedValue(strategy = GenerationType.TABLE) same error

@GeneratedValue(strategy = GenerationType.SEQUENCE) same error

@GeneratedValue(strategy = GenerationType.IDENTITY) different error:

...
Caused by: org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: NULL not allowed for column \"ID\"; SQL statement:\ninsert into names (id, name) values (null, ?) [23502-210]
...
could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

So apparently it is not the annotation, but something else.

I'm giving up, heres my MRE: https://github.com/timo-a/duckpond-spring-backend/tree/debug/saving

Body:
This is a bug on hibernate and specific to h2 database.
https://hibernate.atlassian.net/browse/HHH-14985

you can use id BIGINT GENERATED BY DEFAULT AS IDENTITY DEFAULT ON NULL PRIMARY KEY column definition as a fix.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(columnDefinition = "id BIGINT GENERATED BY DEFAULT AS IDENTITY DEFAULT ON NULL PRIMARY KEY")
private Long id;


问:
Bing Virtual Earth 7.0 calculate area
I have a map where i have created pushPin for all the places i have checked in on facebook. I want to zoom in on the area where i have the most checkinplaces (pushPins).

I could have a static zoom level and calculate some kind of median value but if i check in 20 times in Paris and 20 times in Los Angeles I'd end up somewhere in the middle of the Atlantic Ocean (or the North Pacific or something).

I have an array with all the locations (longitudes and latitudes) to play with.

答:
You can create a bounding box that covers the extent of the pushpins in your array using the LocationRect.fromLocations() method (http://msdn.microsoft.com/en-us/library/gg427621.aspx).

Then, simply centre the map on this view by passing the LocationRect to the "bounds" property of the map.setView method. (http://msdn.microsoft.com/en-us/library/gg427628.aspx)

Title: Bing Virtual Earth 7.0 calculate area


问:
How to create a shopping report using information from a text file
like this

Shopping report

Name1

Thing1 number1 cost1

Thing11 number11 cost11
the amount to be paid

Name2

Thing2 number2 cost2

Thing22 number22 cost22

the amount to be paid

text file

Petrov pen 10 151000

Borzov paper 20 20000

Butar case-boks 5 5000

Semerik pen2 500 250000

Petrov pen(oil) 100 10000

Borzov paper 40 40000

Butar book 5 15000

Semerik hat 500 250000

答:
You would do it like this:

```<code>path = "C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\Stack overflow\\textfile.txt"
newpath = "C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\Stack overflow\\textfileout.txt"
text = open(path, "r")
textinfo = text.readlines()
dictofinfo = {}
for line in textinfo:
  line = line.strip()
  lineaslist = line.split(" ")
  name = lineaslist[0]
  if not(name in dictofinfo.keys()):
    dictofinfo[lineaslist[0]] = [lineaslist[1:]]
  else:
    dictofinfo[lineaslist[0]].append(lineaslist[1:])
text.close()

out = open(newpath, "w")
for entry in dictofinfo:
  totaltobepayed = 0
  out.write(entry + "\n")
  for seperateentry in dictofinfo[entry]:
    totaltobepayed += int(seperateentry[2])
    out.write(" ".join(seperateentry) + "\n")
  out.write(str(totaltobepayed) + "\n")
out.close()
</code>```

Replace the path variable with the path to your text file.

Body:
You would do it like this:

path = "C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\Stack overflow\\textfile.txt"
newpath = "C:\\Users\\User\\AppData\\Local\\Programs\\Python\\Python38\\Stack overflow\\textfileout.txt"
text = open(path, "r")
textinfo = text.readlines()
dictofinfo = {}
for line in textinfo:
  line = line.strip()
  lineaslist = line.split(" ")
  name = lineaslist[0]
  if not(name in dictofinfo.keys()):
    dictofinfo[lineaslist[0]] = [lineaslist[1:]]
  else:
    dictofinfo[lineaslist[0]].append(lineaslist[1:])
text.close()

out = open(newpath, "w")
for entry in dictofinfo:
  totaltobepayed = 0
  out.write(entry + "\n")
  for seperateentry in dictofinfo[entry]:
    totaltobepayed += int(seperateentry[2])
    out.write(" ".join(seperateentry) + "\n")
  out.write(str(totaltobepayed) + "\n")
out.close()

Replace the path variable with the path to your text file.