问:
Jenkins error "No such property: docker for class: groovy.lang.Binding"
I'm trying to follow this tutorial to create a simple docker environment in as part of my Jenkins pipeline build.

I'm trying to build a couple of Docker images just as a test before I do my maven build.  At the moment I have the following Groovy for my Jenkinsfile:

```<code>#!groovy

node {

  stage 'Building docker env'
  def dbImage = docker.build('oracle', 'docker/oracle')
  def wlpImage = docker.build('liberty', 'docker/liberty')

  stage 'Running maven build'
  git url: 'https://mysite/myproject.git', branch: 'docker'
  def mvnHome = tool 'maven 3.3.9'
  sh "${mvnHome}/bin/mvn -B clean install"
}
</code>```

I'm trying to have the Docker build look in the directory "docker/oracle" and call the Dockerfile in that directory, and build the Docker images named oracle, and liberty.  At the moment though it's giving me this error:

```<code>Running on master in /root/.jenkins/workspace/pipeline_test
[Pipeline] {
[Pipeline] stage (Building docker env)
Using the ‘stage’ step without a block argument is deprecated
Entering stage Building docker env
Proceeding
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: docker for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224)
    at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:221)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:28)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
...
</code>```

Any ideas what could be the problem with the docker build command I'm using? (or could it be something I forgot to install in Jenkins?)

答: I had the same issue but after I installed the Docker Pipeline plugin as @Affes Salem suggested it is working now.</p>

Body:
I'm trying to follow this tutorial to create a simple docker environment in as part of my Jenkins pipeline build.

I'm trying to build a couple of Docker images just as a test before I do my maven build.  At the moment I have the following Groovy for my Jenkinsfile:

#!groovy

node {

  stage 'Building docker env'
  def dbImage = docker.build('oracle', 'docker/oracle')
  def wlpImage = docker.build('liberty', 'docker/liberty')

  stage 'Running maven build'
  git url: 'https://mysite/myproject.git', branch: 'docker'
  def mvnHome = tool 'maven 3.3.9'
  sh "${mvnHome}/bin/mvn -B clean install"
}

I'm trying to have the Docker build look in the directory "docker/oracle" and call the Dockerfile in that directory, and build the Docker images named oracle, and liberty.  At the moment though it's giving me this error:

Running on master in /root/.jenkins/workspace/pipeline_test
[Pipeline] {
[Pipeline] stage (Building docker env)
Using the ‘stage’ step without a block argument is deprecated
Entering stage Building docker env
Proceeding
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
groovy.lang.MissingPropertyException: No such property: docker for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224)
    at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:221)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:28)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
...

Any ideas what could be the problem with the docker build command I'm using? (or could it be something I forgot to install in Jenkins?)


来源: stackexchange

问:
SQL convert String date of style d-MMM-yyyy to DATE
I'm importing a CSV file and one of the fields is a non-standard date string with entries like 7-Dec-2021

Any ideas for to convert this into a DATETIME object that I can insert into my SQL table? Standard CAST/CONVERT didn't work.

Microsoft SQL Server 2012 - 11.0.2100.60

答:
TRY_CONVERT seems to be working here:

SELECT TRY_CONVERT(datetime, '7-Dec-2021');  -- 2021-12-07 00:00:00.000
```
<p><strong>Edit:</strong></p>
<p>Your input date almost matches format mask 106, once we replace the dashes with spaces.  Consider this solution:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT dt, CONVERT(datetime, REPLACE(dt, '-', ' '), 106) AS dt_out
FROM yourTable;
</code>```

This outputs 2021-12-07 00:00:00.000 for dt_out on SQL Server 2014, and should behave the same way on SQL Server 2012.

ContentLicense: CC BY-SA 4.0

Body:
TRY_CONVERT seems to be working here:

SELECT TRY_CONVERT(datetime, '7-Dec-2021');  -- 2021-12-07 00:00:00.000

Edit:

Your input date almost matches format mask 106, once we replace the dashes with spaces.  Consider this solution:

SELECT dt, CONVERT(datetime, REPLACE(dt, '-', ' '), 106) AS dt_out
FROM yourTable;

This outputs 2021-12-07 00:00:00.000 for dt_out on SQL Server 2014, and should behave the same way on SQL Server 2012.


问:
Atom gpp-compiler is giving "'C:\Users\adminUser' is not recognized as an internal or..." error
Whenever I try to compile and run a hello world C++ program I just get a command prompt with the error 'C:\Users\adminUser' is not recognized as an internal or external command, operable program or batch file.
A picture of the command prompt error.

I tried adding and taking away the gpp-compiler from the user PATH. Unfortunately, that didn't work. Thanks in advance for any help.

This is the code I am trying to compile and run:

```<code>#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World";
    return 0;
}
</code>```

答:
Make Sure

"C:\MinGW\bin" & "C:\MinGW" Register on Path

Check the c/c++ file not use symbol Otherwise Rename it

Body:
Whenever I try to compile and run a hello world C++ program I just get a command prompt with the error 'C:\Users\adminUser' is not recognized as an internal or external command, operable program or batch file.
A picture of the command prompt error.

I tried adding and taking away the gpp-compiler from the user PATH. Unfortunately, that didn't work. Thanks in advance for any help.

This is the code I am trying to compile and run:

#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World";
    return 0;
}


问:
if radio box checked send different email fields
```<code><form method="post" action="" id="infoform">
<label for="first">
    First Name</label>
<input type="text" name="first" id="first" class="field validate[required]">
</br>
<label for="surname">
    Last Name</label>
<input type="text" name="surname" id="surname" class="field validate[required]"> </br>
    <label for="email">
        Email</label>
    <input type="text" name="email" id="email" class=" field email validate[required,custom[email]]">
        </br>
        <div class="radios">
            <input id="test2" checked="checked" type="radio" name="message" value="register" />
        Register for Updates</input>
    <input id="test1" type="radio" name="message" value="msgs" />
    Send a Message</input>
</div>
<div class="msg">
    <label for="message" id="messagelabel">
        Message</label>
    <textarea type="text" name="message" id="message"></textarea>
</div>
<input id="submit" type="submit" value=""><div class="test3">
    <a class="sbmt">Register</a></div>
    <div class="test4">
        <a class="sbmt">Send</a></div>
</input>
</form>
</code>```

If the radio box 'test1' is checked, then  the div msg appears. This is then sent via ajax to an email php script:

```<code><?php
    $EmailTo = "matt@explosivetitles.com";
    $adminSubject = "Civitas Message";

    $firstName = Trim(stripslashes($_POST['first']));
    $Surname = Trim(stripslashes($_POST['surname']));
    $Email = Trim(stripslashes($_POST['email']));
    $Message = Trim(stripslashes($_POST['message']));

    $adminheaders = 'From: "Civitas website" <info@civitas.com>';

    $adminBody .= "First Name: ";
    $adminBody .= $firstName;
    $adminBody .= "\n";
    $adminBody .= "Surname: ";
    $adminBody .= $Surname;
    $adminBody .= "\n";
    $adminBody .= "Email: ";
    $adminBody .= $Email;
    $adminBody .= "\n";
    $adminBody .= "Message: ";
    $adminBody .= $Message;
    $adminBody .= "\n";

    $adminMail = mail($EmailTo, $adminSubject, $adminBody, $adminheaders);

    if ($adminMail){
        echo "true";
    }
    else{
      echo "false";
    }
?>
</code>```

However I only want the "message" part of the email to be sent if the message box is showing. How can I do this?

答:
PHP does not look at the id of an element, instead, when a POST or GET method is sent, it looks at the name attribute. In the code you have written, you have two input elements, textarea and the radio input with the same name, "message". When both are sent, the $_POST variable becomes an array and uses the name attribute as an index for the value submitted, and PHP arrays cannot have duplicate indexes, therefore to over come this problem you rename one. For your radio input I suggest the name attribute be set to type.

```<code><?php
    $send           = "matt@explosivetitles.com";
    $subject        = "Civitas Message";
    $details        = array (
        "first"     => @$_POST["first"],
        "surname"   => @$_POST["surname"],
        "email"     => @$_POST["email"],
        "message"   => @$_POST["message"]
    );
    foreach ($details as $index => $value) {
        $details[$index] = trim ( stripslashes ($value));
    }
    if (@$_POST["type"] == "register") {
        // Whatever happens when they select "register"
    } else if (@$_POST["type"] == "msgs") {
        $header     = "From 'Civitas website' <info@civitas.com>";
        $body       = $details["first"] . " " . $details["surname"] . " "
                    . "<" . $details["email"] . ">"
                    . "Message: \n"
                    . $details["message"];

        $mail       = mail ($send, $subject, $body, $header);
        if ($mail) {
            return true;
        } else {
            return false;
        }
    }
?>
</code>```

Also, your code hurts my eyes, so I rewrote it.

ContentLicense: CC BY-SA 3.0

Body:
<form method="post" action="" id="infoform">

    First Name
<input type="text" name="first" id="first" class="field validate[required]">

    Last Name
<input type="text" name="surname" id="surname" class="field validate[required]">

        Email
    <input type="text" name="email" id="email" class=" field email validate[required,custom[email]]">

            <input id="test2" checked="checked" type="radio" name="message" value="register" />
        Register for Updates</input>
    <input id="test1" type="radio" name="message" value="msgs" />
    Send a Message</input>

        Message
    <textarea type="text" name="message" id="message"></textarea>

<input id="submit" type="submit" value="">

    Register

        Send

</input>
</form>

If the radio box 'test1' is checked, then  the div msg appears. This is then sent via ajax to an email php script:

<?php
    $EmailTo = "matt@explosivetitles.com";
    $adminSubject = "Civitas Message";

    $firstName = Trim(stripslashes($_POST['first']));
    $Surname = Trim(stripslashes($_POST['surname']));
    $Email = Trim(stripslashes($_POST['email']));
    $Message = Trim(stripslashes($_POST['message']));

    $adminheaders = 'From: "Civitas website" <info@civitas.com>';

    $adminBody .= "First Name: ";
    $adminBody .= $firstName;
    $adminBody .= "\n";
    $adminBody .= "Surname: ";
    $adminBody .= $Surname;
    $adminBody .= "\n";
    $adminBody .= "Email: ";
    $adminBody .= $Email;
    $adminBody .= "\n";
    $adminBody .= "Message: ";
    $adminBody .= $Message;
    $adminBody .= "\n";

    $adminMail = mail($EmailTo, $adminSubject, $adminBody, $adminheaders);

    if ($adminMail){
        echo "true";
    }
    else{
      echo "false";
    }
?>

However I only want the "message" part of the email to be sent if the message box is showing. How can I do this?

Body:
PHP does not look at the id of an element, instead, when a POST or GET method is sent, it looks at the name attribute. In the code you have written, you have two input elements, textarea and the radio input with the same name, "message". When both are sent, the $_POST variable becomes an array and uses the name attribute as an index for the value submitted, and PHP arrays cannot have duplicate indexes, therefore to over come this problem you rename one. For your radio input I suggest the name attribute be set to type.

<?php
    $send           = "matt@explosivetitles.com";
    $subject        = "Civitas Message";
    $details        = array (
        "first"     => @$_POST["first"],
        "surname"   => @$_POST["surname"],
        "email"     => @$_POST["email"],
        "message"   => @$_POST["message"]
    );
    foreach ($details as $index => $value) {
        $details[$index] = trim ( stripslashes ($value));
    }
    if (@$_POST["type"] == "register") {
        // Whatever happens when they select "register"
    } else if (@$_POST["type"] == "msgs") {
        $header     = "From 'Civitas website' <info@civitas.com>";
        $body       = $details["first"] . " " . $details["surname"] . " "
                    . "<" . $details["email"] . ">"
                    . "Message: \n"
                    . $details["message"];

        $mail       = mail ($send, $subject, $body, $header);
        if ($mail) {
            return true;
        } else {
            return false;
        }
    }
?>

Also, your code hurts my eyes, so I rewrote it.


问:
Will an implicit stack switch occur when switching from compatibility mode to 64-bit mode at the same privilege level?
When switching from compatibility mode to 64-bit mode at the same privilege level by a far call, fields such as BASE or LIMIT in segment registers are ignored, and 64-bit pointer registers are all available. However, if the BASE field is ignored, the stack base address will become 0x0 implicitly, which means an implicit stack switch will be raised, am I right?
And if my understanding is correct, how does the CPU switch back to the original stack when returning via the ret instruction?</p>

答:
The SDM does use the term "implicit stack switch" to describe this behavior, but only when the call is performed using a call gate.

... when using a call gate to perform a far call to a segment at the same privilege level, an implicit stack switch occurs as a result of entering 64-bit mode. The SS selector is unchanged, but stack segment accesses use a segment base of 0x0, the limit is ignored, and the default stack size is 64 bits. The full value of RSP is used for the offset, of which the upper 32 bits are undefined.

Although the SDM doesn't describe the behavior when the call is performed without using a call gate, the behavior I observe is the same.
The return address (cs:rip) is pushed to the new stack (ignoring ss.base) and a far ret to return to the 32 bit code works. And of course the 32 bit code continues to use ss.base as usual.

(In my test, the upper bits of RSP were 0 before entering compatibility mode, and remain 0 when performing the call back into 64-bit mode.)

Here are memory dumps after running a program that does the following:

ss.base = 0x80

esp = 8385f118

push 32323232

push esp

far call to 64-bit code (return address is 20:776bb1e2)

push 64646464

push rsp

far call to 32-bit code (return address is 38:776bb208)

push 30303030

push esp

add esp, 8

far ret

add rsp, 10

far ret

push 31313131

push esp

```<code>8385f0f0: 00000000 00000000 8385f100 00000000
8385f100: 64646464 00000000 776bb1e2 00000020
8385f110: 00000000 00000000 00000000 00000000
8385f120: 00000000 00000000 00000000 00000000

8385f160: 00000000 00000000 8385f0ec 30303030
8385f170: 776bb208 00000038 00000000 00000000
8385f180: 00000000 00000000 8385f10c 31313131
8385f190: 8385f114 32323232 00000000 00000000
</code>```

Body:
The SDM does use the term "implicit stack switch" to describe this behavior, but only when the call is performed using a call gate.

... when using a call gate to perform a far call to a segment at the same privilege level, an implicit stack switch occurs as a result of entering 64-bit mode. The SS selector is unchanged, but stack segment accesses use a segment base of 0x0, the limit is ignored, and the default stack size is 64 bits. The full value of RSP is used for the offset, of which the upper 32 bits are undefined.

Although the SDM doesn't describe the behavior when the call is performed without using a call gate, the behavior I observe is the same.
The return address (cs:rip) is pushed to the new stack (ignoring ss.base) and a far ret to return to the 32 bit code works. And of course the 32 bit code continues to use ss.base as usual.

(In my test, the upper bits of RSP were 0 before entering compatibility mode, and remain 0 when performing the call back into 64-bit mode.)

Here are memory dumps after running a program that does the following:

ss.base = 0x80

esp = 8385f118

push 32323232

push esp

far call to 64-bit code (return address is 20:776bb1e2)

push 64646464

push rsp

far call to 32-bit code (return address is 38:776bb208)

push 30303030

push esp

add esp, 8

far ret

add rsp, 10

far ret

push 31313131

push esp

8385f0f0: 00000000 00000000 8385f100 00000000
8385f100: 64646464 00000000 776bb1e2 00000020
8385f110: 00000000 00000000 00000000 00000000
8385f120: 00000000 00000000 00000000 00000000

8385f160: 00000000 00000000 8385f0ec 30303030
8385f170: 776bb208 00000038 00000000 00000000
8385f180: 00000000 00000000 8385f10c 31313131
8385f190: 8385f114 32323232 00000000 00000000


问:
Prisma @updatedAt generates value at creation?
I tried to follow the prisma getting started here Prisma.

When I first create a user using the prisma client, the updatedAt field already has a value. I assumed it should only generate a value upon update.

Here is the main code

```<code>async function main() {
  // ... you will write your Prisma Client queries here

  await prisma.user.create({
    data: {
      email: "test@gmail1.com",
      name: "test",
    },
  });

  const users = await prisma.user.findMany();
  console.log(users);
}
</code>```

Here is the result when I run the index.ts file

```<code>[
  {
    id: 1,
    email: 'test@gmail.com',
    name: 'test',
    createdAt: 2022-02-11T03:49:00.090Z,
    updatedAt: 2022-02-11T03:49:00.090Z
  }
]
</code>```

答:
Yes, by default Prisma generates @updatedAt value when you create entities.

You can override it on your app side by passing null there (and of course then you need to make field nullable too):

```<code>  await prisma.user.create({
    data: {
      email: "test@gmail1.com",
      name: "test",
      // Just pass null here
      updatedAt: null
    },
  });
</code>```

Body:
I tried to follow the prisma getting started here Prisma.

When I first create a user using the prisma client, the updatedAt field already has a value. I assumed it should only generate a value upon update.

Here is the main code

async function main() {
  // ... you will write your Prisma Client queries here

  await prisma.user.create({
    data: {
      email: "test@gmail1.com",
      name: "test",
    },
  });

  const users = await prisma.user.findMany();
  console.log(users);
}

Here is the result when I run the index.ts file

[
  {
    id: 1,
    email: 'test@gmail.com',
    name: 'test',
    createdAt: 2022-02-11T03:49:00.090Z,
    updatedAt: 2022-02-11T03:49:00.090Z
  }
]

Body:
Yes, by default Prisma generates @updatedAt value when you create entities.

You can override it on your app side by passing null there (and of course then you need to make field nullable too):

  await prisma.user.create({
    data: {
      email: "test@gmail1.com",
      name: "test",
      // Just pass null here
      updatedAt: null
    },
  });


问:
Observables: Difference between chaining `pipe` and several function inside a single `pipe`
Is there a difference between these 2 pieces of codes:

    this.subject
      .pipe(skip(1))
      .pipe(debounceTime(200))
      .pipe(takeUntil(this.unsubscribe))
      .subscribe((value: any) => {
        // Do whatever
      });
```
<p>And:</p>
<pre class="lang-js prettyprint-override"><code>    this.subject
      .pipe(skip(1), debounceTime(200), takeUntil(this.unsubscribe))
      .subscribe((value: any) => {
        // Do whatever
      });
</code>```

答: The outcomes are equal, however multiple pipes will create multiple new  observables which of course has a runtime cost. Whether that cost is negligible in your use case is up to you and your profiling. I would recommend a single pipe as a general rule of thumb.</p>

Body:
Is there a difference between these 2 pieces of codes:

    this.subject
      .pipe(skip(1))
      .pipe(debounceTime(200))
      .pipe(takeUntil(this.unsubscribe))
      .subscribe((value: any) => {
        // Do whatever
      });

And:

    this.subject
      .pipe(skip(1), debounceTime(200), takeUntil(this.unsubscribe))
      .subscribe((value: any) => {
        // Do whatever
      });


问:
I am trying to write a program that counts the occurrences of conjunctions(or words with 1,2 or 3 letters) in C, my code runs but it shows 0 words
I've been trying to make this code for a bit of time but I can't figure it out. I have to find the occurences of conjuctions or words with one, two or three letters in a string.

Can someone please help me figure it out.

```<code>#include <stdio.h>
#include <string.h>
#include <ctype.h>

int stringwordcount(char s[100])
{
    int count = 0;

    int i;

    for(i = 0; i < strlen(s);i++){

        if((isspace(s[i]-1) || ispunct(s[i]- 1)) && isalpha(s[i]) && isalpha(s[i]+1) && isalpha(s[i]+2) && (isspace(s[i]+3) || ispunct(s[i]+3))){

            count++;

            i+=3;
        } else if((isspace(s[i]-1) || ispunct(s[i]- 1)) && isalpha(s[i]) && isalpha(s[i]+1) && (isspace(s[i]+2) || ispunct(s[i]+2))){

            count++;
            i+=2;
        } else if ((isspace(s[i]-1) || ispunct(s[i]- 1)) && isalpha(s[i]) && (isspace(s[i]+1)|| ispunct(s[i]+1))){

            count++;
            i++;
        }
        return count;
    }

}
int main()
{

    int i, ratiod;

    int maxRatio = 0;

    char maxStr[101];

    char str[101];

    while (fgets(str, 101, stdin) != NULL){

        str[strlen(str)-1] = '\0';

        ratiod = stringwordcount(str);

        if (ratiod > maxRatio){

            maxRatio = ratiod;

            strcpy(maxStr, str);

        }

    }

    printf("%d: ", ratiod);

    puts(maxStr);

    return 0;

}
</code>```

I've been trying to make this code for a bit of time but I can't figure it out. I have to find the occurences of conjuctions or words with one, two or three letters in a string.

Can someone please help me figure it out.

答:
At least this issue:

Instead of passing the index to is...(), pass the character.

```<code>    // if (isalpha(i) && ...
    if (isalpha(s[i]) && ...
</code>```

Body:
I've been trying to make this code for a bit of time but I can't figure it out. I have to find the occurences of conjuctions or words with one, two or three letters in a string.

Can someone please help me figure it out.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int stringwordcount(char s[100])
{
    int count = 0;

    int i;

    for(i = 0; i < strlen(s);i++){

        if((isspace(s[i]-1) || ispunct(s[i]- 1)) && isalpha(s[i]) && isalpha(s[i]+1) && isalpha(s[i]+2) && (isspace(s[i]+3) || ispunct(s[i]+3))){

            count++;

            i+=3;
        } else if((isspace(s[i]-1) || ispunct(s[i]- 1)) && isalpha(s[i]) && isalpha(s[i]+1) && (isspace(s[i]+2) || ispunct(s[i]+2))){

            count++;
            i+=2;
        } else if ((isspace(s[i]-1) || ispunct(s[i]- 1)) && isalpha(s[i]) && (isspace(s[i]+1)|| ispunct(s[i]+1))){

            count++;
            i++;
        }
        return count;
    }

}
int main()
{

    int i, ratiod;

    int maxRatio = 0;

    char maxStr[101];

    char str[101];

    while (fgets(str, 101, stdin) != NULL){

        str[strlen(str)-1] = '\0';

        ratiod = stringwordcount(str);

        if (ratiod > maxRatio){

            maxRatio = ratiod;

            strcpy(maxStr, str);

        }

    }

    printf("%d: ", ratiod);

    puts(maxStr);

    return 0;

}

I've been trying to make this code for a bit of time but I can't figure it out. I have to find the occurences of conjuctions or words with one, two or three letters in a string.

Can someone please help me figure it out.

Body:
At least this issue:

Instead of passing the index to is...(), pass the character.

    // if (isalpha(i) && ...
    if (isalpha(s[i]) && ...


问:
How to Verify OTP with on Same page in Django
I have a page where i want once the user click on verify email the user get and email with otp and there is also an input field from where the user is going to enter the OTP and we can  Verify Here what i did when user click on verify email he a ajax request send on the server by which a mail is send to user and then in response server is sending back the opt to client as well which i then store in a variable in the localstorage of javascript But i feel it is not safe a lot Any better way to that</p>

答: You don't need to save the OTP at all. Once the user enters the OTP and presses verify, you send the OTP to the server in an AJAX call, and then your server can perform the verification on the backend.</p>


问:
How to generate entity id on DB side?
This is my Book entity:

```<code>@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "BOOKS")
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
private String name;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "AUTHOR_ID", referencedColumnName = "Id")
private Author author;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "GENRE_ID", referencedColumnName = "Id")
private Genre genre;

}
</code>```

I try to insert new Book im my test method:

```<code>    @Test
  void insertBookTest() {
    Author a3 = new Author(3L, "New Author");
    Genre g3 = new Genre(3L, "New Genre");

    Book actualBook = new Book()
            .setId(3L)
            .setName("Good Night")
            .setAuthor(a3)
            .setGenre(g3);

    Book savedBook = bookService.insert(actualBook);

    assertEquals(actualBook.getId(), savedBook.getId());
}
</code>```

but i get exception:

org.hibernate.PersistentObjectException: detached entity passed to
persist

I use H2 version 2.0.204, it was planned to generate entity id on DB side, for this i did schema.sql

```<code>DROP TABLE IF EXISTS AUTHOR;
CREATE TABLE AUTHOR(ID BIGINT PRIMARY KEY auto_increment, NAME VARCHAR(255));

DROP TABLE IF EXISTS GENRE;
CREATE TABLE GENRE(ID BIGINT PRIMARY KEY auto_increment, NAME VARCHAR(255));

DROP TABLE IF EXISTS BOOKS;
CREATE TABLE BOOKS(
ID BIGINT PRIMARY KEY auto_increment,
NAME VARCHAR(255),
AUTHOR_ID BIGINT REFERENCES AUTHOR(ID),
GENRE_ID BIGINT REFERENCES GENRE(ID),
foreign key (GENRE_ID) references GENRE(id) on delete cascade,
foreign key (AUTHOR_ID) references AUTHOR(id) on delete cascade);
</code>```

this means that when insert a new entity I don't need to set Id, so when I move this setter

.setId(3L)

I get new exception:

NULL not allowed for column "ID"; SQL statement:
insert into books (id, author_id, genre_id, name) values (null, ?, ?, ?) [23502-204]

How can I resolve this situation?

答:
Hibernate ORM supports H2 2.*.* only since the version 5.6.5.Final. Older versions produce invalid SQL for identity columns, it is rejected by new versions of H2.

It will be better to upgrade H2 to the version 2.1.210 too, because Hibernate ORM also has some problems with indexes with H2 2.0.*.

You should normally use ID BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY instead of MySQL-style ID BIGINT PRIMARY KEY auto_increment (unless you want to use the same SQL for both MySQL and H2).

Title: How to generate entity id on DB side?

Body:
This is my Book entity:

@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "BOOKS")
public class Book {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column
private String name;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "AUTHOR_ID", referencedColumnName = "Id")
private Author author;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "GENRE_ID", referencedColumnName = "Id")
private Genre genre;

}

I try to insert new Book im my test method:

    @Test
  void insertBookTest() {
    Author a3 = new Author(3L, "New Author");
    Genre g3 = new Genre(3L, "New Genre");

    Book actualBook = new Book()
            .setId(3L)
            .setName("Good Night")
            .setAuthor(a3)
            .setGenre(g3);

    Book savedBook = bookService.insert(actualBook);

    assertEquals(actualBook.getId(), savedBook.getId());
}

but i get exception:

org.hibernate.PersistentObjectException: detached entity passed to
persist

I use H2 version 2.0.204, it was planned to generate entity id on DB side, for this i did schema.sql

DROP TABLE IF EXISTS AUTHOR;
CREATE TABLE AUTHOR(ID BIGINT PRIMARY KEY auto_increment, NAME VARCHAR(255));

DROP TABLE IF EXISTS GENRE;
CREATE TABLE GENRE(ID BIGINT PRIMARY KEY auto_increment, NAME VARCHAR(255));

DROP TABLE IF EXISTS BOOKS;
CREATE TABLE BOOKS(
ID BIGINT PRIMARY KEY auto_increment,
NAME VARCHAR(255),
AUTHOR_ID BIGINT REFERENCES AUTHOR(ID),
GENRE_ID BIGINT REFERENCES GENRE(ID),
foreign key (GENRE_ID) references GENRE(id) on delete cascade,
foreign key (AUTHOR_ID) references AUTHOR(id) on delete cascade);

this means that when insert a new entity I don't need to set Id, so when I move this setter

.setId(3L)

I get new exception:

NULL not allowed for column "ID"; SQL statement:
insert into books (id, author_id, genre_id, name) values (null, ?, ?, ?) [23502-204]

How can I resolve this situation?


问:
spanning cells interfere with the td:nth-child(even) logic
Im trying to build a timetable that includes a vertical cell-spans because u-know-why, but the (intentionally)missing cells are not counted in my :nth-child(even) - rule, which bugs the visual display of the table. To further elaborate, pay close attention to the third cell right of the spanned cell:

http://jsfiddle.net/WbtvT/

Is there any way to make the css count the missing(spanned) cells as well? Or maybe some jquery magic?

答:
There is no flexible solution here. You have to hardcode the box you want to shade yourself, if that is acceptable?

```<code>.shade {background-color:silver;} Add this line in CSS
</code>```

Ass the TD that is going to be affected the class="shade"

Do you want a flexible solution? What is your criteria

Here is jfiddle

Body:
There is no flexible solution here. You have to hardcode the box you want to shade yourself, if that is acceptable?

.shade {background-color:silver;} Add this line in CSS

Ass the TD that is going to be affected the class="shade"

Do you want a flexible solution? What is your criteria

Here is jfiddle


问:
Is it a bad idea to explicitly ignore promises?
I have an api call which triggers an async function doSomething. Inside this function I have another async function that creates a notification for the user but I do not want to wait for it until it is finished. So I removed the await statement. The code works but is this a bad idea or bad practice because I get a "Missing await for an async function call" warning.</p>
```<code>    public async createNotification(createdStuff: CreatedStuff): Promise<void> {
        const userNotification = new Notifcation(..);
        await userNotification.save();
    }

    public async doSomething(): Promise<CreatedStuff> {
        const createdStuff = await this.createStuff();
        await createdStuff.save();

        // here I removed the await statement
        this.notificationService.createNotification(createdStuff);

        return createdStuff;
    }
</code>```

答:
If createLogPlayNotification(...) rejects, you will run into an unhandledRejection event which you probably don't want as it will crash your app depending on your NodeJS version (see this link for more information).

This does not mean you have to await it, you can simply add a .catch-handler on the returned promise:

```<code>// ..
this.notificationService.createLogPlayNotification(loggedPLay)
                        .catch(err => {
                            // do something with err, e.g. log it
                         });
return createdStuff;
</code>```

Body:
I have an api call which triggers an async function doSomething. Inside this function I have another async function that creates a notification for the user but I do not want to wait for it until it is finished. So I removed the await statement. The code works but is this a bad idea or bad practice because I get a "Missing await for an async function call" warning.

    public async createNotification(createdStuff: CreatedStuff): Promise<void> {
        const userNotification = new Notifcation(..);
        await userNotification.save();
    }

    public async doSomething(): Promise<CreatedStuff> {
        const createdStuff = await this.createStuff();
        await createdStuff.save();

        // here I removed the await statement
        this.notificationService.createNotification(createdStuff);

        return createdStuff;
    }

Body:
If createLogPlayNotification(...) rejects, you will run into an unhandledRejection event which you probably don't want as it will crash your app depending on your NodeJS version (see this link for more information).

This does not mean you have to await it, you can simply add a .catch-handler on the returned promise:

// ..
this.notificationService.createLogPlayNotification(loggedPLay)
                        .catch(err => {
                            // do something with err, e.g. log it
                         });
return createdStuff;


Title: how to create weekly result from daily data using R?

Body:
I try to create a weekly cumulative result from this daily data with detail below

date    A   B   C   D   E   F   G   H
16-Jan-22   227 441 3593    2467    9   6   31  2196
17-Jan-22   224 353 3555    2162    31  5   39  2388
18-Jan-22   181 144 2734    2916    0   0   14  1753
19-Jan-22   95  433 3610    3084    42  19  10  2862
20-Jan-22   141 222 3693    3149    183 19  23  2176
21-Jan-22   247 426 3455    4016    68  0   1   2759
22-Jan-22   413 931 4435    4922    184 2   39  3993
23-Jan-22   389 1340    5433    5071    200 48  27  4495
24-Jan-22   281 940 6875    5009    343 47  71  3713
25-Jan-22   314 454 5167    4555    127 1   68  3554
26-Jan-22   315 973 5789    3809    203 1   105 4456
27-Jan-22   269 1217    6776    4578    227 91  17  5373
28-Jan-22   248 1320    5942    3569    271 91  156 4260
29-Jan-22   155 1406    6771    4328    426 44  109 4566

Body:
Solution using data.table and lubridate

library(lubridate)
library(data.table)

setDT(df)

df[, lapply(.SD, sum), by = isoweek(dmy(date))]

#    isoweek    A    B     C     D    E   F   G     H
# 1:       2  227  441  3593  2467    9   6  31  2196
# 2:       3 1690 3849 26915 25320  708  93 153 20426
# 3:       4 1582 6310 37320 25848 1597 275 526 25922


问:
Python - SMTP mail sending script is triggering multiple mails even though mail sending function is not called
I am new to python. I had a requirement to check the file modified date and compare with current date and send mail if the modified date is older than current date. Below is the script.

```<code>import os.path
from datetime import datetime
import smtplib
from smtplib import SMTPException
import logging

logging.basicConfig(
    filename="pySysLog.log",
    level=logging.INFO,
    format="%(asctime)s -  %(name)s- %(levelname)s - %(message)s"
    )

def sendmail():
    sender = 'sntspo@in.inm.com'
    receivers = ['Guru.kar@inm.com']
    message = """From: SMT Support <sntspo@in.inm.com>
To: Guruprasad <Guru.kar@inm.com>
MIME-Version: 1.0
Content-type: text/html
Subject: PIR File Not Recived from GDMIS

Hi All,</br>
</br>
Today, PIR Feed File is not received from GDMIS</br>
</br>
Regards,</br>
SMT Team
"""

    try:
        smtpObj = smtplib.SMTP('ni.gelay.inm.com')
        smtpObj.sendmail(sender, receivers, message)
        smtpObj.quit()
        logging.info("Successfully sent email")
    except SMTPException:
        logging.info("Error: unable to send email")

def checkFile():
    uplDate = str(datetime.fromtimestamp(os.path.getmtime("/home/sadm/batchscript/Report.txt")))
    currentDate = str(datetime.now())
    logging.info("Modified date of file  " + uplDate)
    logging.info("Current date  " + currentDate)
    if uplDate < currentDate:
        logging.info("File is not received from MIS")
        sendmail()
    else:
        logging.info("File is received from MIS")

checkFile()

</code>```

I am facing the following issues:

Even though sendmail() function is called only if condition is satisfied but mail is triggering

mail is triggering not once but multiple times

please help

答:
```<code>uplDate = datetime.fromtimestamp(os.path.getmtime(file_path))
    # uplDate = datetime.fromtimestamp(os.path.getmtime("HCLNotesInstall.log"))
    currentDate = datetime.now()
    logging.info("Modified date of file  " + str(uplDate.date()))
    logging.info("Current date  " + str(currentDate.date()))
    if uplDate.date() < currentDate.date():
</code>```

uplDate.date() < currentDate.date() uses a date to compare instead of a string.

Body:
I am new to python. I had a requirement to check the file modified date and compare with current date and send mail if the modified date is older than current date. Below is the script.

import os.path
from datetime import datetime
import smtplib
from smtplib import SMTPException
import logging

logging.basicConfig(
    filename="pySysLog.log",
    level=logging.INFO,
    format="%(asctime)s -  %(name)s- %(levelname)s - %(message)s"
    )

def sendmail():
    sender = 'sntspo@in.inm.com'
    receivers = ['Guru.kar@inm.com']
    message = """From: SMT Support <sntspo@in.inm.com>
To: Guruprasad <Guru.kar@inm.com>
MIME-Version: 1.0
Content-type: text/html
Subject: PIR File Not Recived from GDMIS

Hi All,

Today, PIR Feed File is not received from GDMIS

Regards,

SMT Team
"""

    try:
        smtpObj = smtplib.SMTP('ni.gelay.inm.com')
        smtpObj.sendmail(sender, receivers, message)
        smtpObj.quit()
        logging.info("Successfully sent email")
    except SMTPException:
        logging.info("Error: unable to send email")

def checkFile():
    uplDate = str(datetime.fromtimestamp(os.path.getmtime("/home/sadm/batchscript/Report.txt")))
    currentDate = str(datetime.now())
    logging.info("Modified date of file  " + uplDate)
    logging.info("Current date  " + currentDate)
    if uplDate < currentDate:
        logging.info("File is not received from MIS")
        sendmail()
    else:
        logging.info("File is received from MIS")

checkFile()

I am facing the following issues:

Even though sendmail() function is called only if condition is satisfied but mail is triggering

mail is triggering not once but multiple times

please help

Body:
uplDate = datetime.fromtimestamp(os.path.getmtime(file_path))
    # uplDate = datetime.fromtimestamp(os.path.getmtime("HCLNotesInstall.log"))
    currentDate = datetime.now()
    logging.info("Modified date of file  " + str(uplDate.date()))
    logging.info("Current date  " + str(currentDate.date()))
    if uplDate.date() < currentDate.date():

uplDate.date() < currentDate.date() uses a date to compare instead of a string.


问:
Increase Prices 10 percent by ajax in asp.net core
I have some prices in my web site(asp.net core) .I wanna to add  10 percent to all of them by click a button and change all of them just by click a button .I wrote a service to add 10 percent to each price and there is a controller and in view  I have  a button . but it does not work.How should Icorrect it?
this is my code .</p>
```<code>public interface IUpdatePricesService
{
    ResultDto Execute(RequestUpdatePricesDto request);
}
public class UpdatePricesService : IUpdatePricesService
{
    private readonly IDataBaseContext _context;
    public UpdatePricesService(IDataBaseContext context)
    {
        _context = context;
    }
    public ResultDto Execute(RequestUpdatePricesDto request)
    {
        List<UpdatePrices> updatePrices = new List<UpdatePrices>();
        UpdatePrices prices = new UpdatePrices();
        foreach (var item in request.prices)
        {
            int p = Convert.ToInt32(prices);
            p = p / 10;
            p = p + p;
            item.Price=p;

            updatePrices.Add(prices);
        };
        _context.SaveChanges();
        return new ResultDto
        {
            IsSuccess = true,
            Message = "Updated",
        };
    }
}

    private readonly IUpdatePricesService _updatePrices;

    [HttpPost]
    public IActionResult UpdatePricesInProduct()
    {

        var result = _updatePrices.Execute(new RequestUpdatePricesDto { });

        return Json(result);

    }

                                    <div class="col-xl-12 col-lg-12 col-md-12 mb-1">
                                        <fieldset class="form-group">
                                            <br />
                                            <a id="btnIncrease" class="btn btn-success col-md-12"> افزودن   </a>
                                        </fieldset>
                                    </div>
    <script>

    $(document).ready(function () {

        $('#btnIncrease').click(function () {

            $.ajax({

                contentType: 'application/x-www-form-urlencoded',
                dataType: 'json',
                url: "UpdatePricesInProduct",
                type: "POST",
                data: postData,
                cache: false,
                async: true,
                success: function (data) {
                    alert(data);
                }
            });
        })

</script>
</code>```

答:
Updated Answer As Per Comment:

"In Ajax the UpatePriceByAjax controller , do not works"

It shouldn't work the way you have written that. Because your ajax request is not in correct format.

"Ajax error explanation"

If you debug your code on browser you should get either of following
error at the begining. You have written Jquery like this way
 which generating either of following error.
Additionally, your jquery has not ended correctly you have missed or
have not posted accordingly }); end braces are missing.

How to resolve that error

You should write your script using following way: So that there will be no error at the begining.

@section scripts {

}
```
<p><em><strong><code>"Another error you may get in Ajax"</code></strong></em></p>
<p><code>data: postdata</code> you haven't define what you are posting. I think for this price update request you don't need to <code>post/submit</code> any data as this method <code>UpdatePricesInProduct</code> does need anything as per your code.</p>
<p><img src="https://i.stack.imgur.com/fytZ4.png" alt="enter image description here" /></p>
<p><em><strong><code>"Finally Valid Ajax Request You should Write"</code></strong></em></p>
<pre class="lang-cs prettyprint-override"><code><div class="col-xl-12 col-lg-12 col-md-12 mb-1">
    <fieldset class="form-group">
        <br />
         افزودن
    </fieldset>
</div>
@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#btnIncrease').click(function () {
                alert("btnIncrease");
                $.ajax({
                    contenttype: 'application/x-www-form-urlencoded',
                    datatype: 'json',
                    url: "updatepricesinproduct",
                    type: "post",
                 //   data: postdata,
                    cache: false,
                    async: true,
                    success: function (data) {
                        alert(data);
                    }
                });
            });

        });
    </script>
}
</code>```

"Output:"

Note: You should have above changes to get rid of your problem and make it
workable as expected.

Previous Answer And Working Sample:

Let say I have price list in my web site like below:

If now if you would like to update all price in the list together with
just a single button click then you could follow below steps:

HTML/Ajax:

    <fieldset class="form-group">

         افزودن Update Price
    </fieldset>

```
<p><em><strong><code>Javascript/Ajax:</code></strong></em></p>
<pre class="lang-cs prettyprint-override"><code>@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {

            $("#btnIncrease").click(function (e) {
                alert("Fired!");
                $.ajax("https://localhost:44361/UserLog/UpatePriceByAjax", {
                    method: "POST",
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {

                        console.log(data);

                    }
                });
                alert("Successfully Updated");
                location.reload(true);
            });

        });
    </script>
}
</code>```

C# Asp.net Core Controller

[HttpPost]
public ActionResult UpatePriceByAjax()
{
    decimal incrementPercentage = 10;
    List<PriceUpdateTable> ExistingPriceList = _context.priceUpdateTable.ToList();

    foreach (var item in ExistingPriceList)
    {
        var updatedPricePercentage = item.Price * incrementPercentage / 100;
        item.UpdatedPrice = item.Price + updatedPricePercentage;
        _context.Update(item);

    }
    _context.SaveChanges();

    return RedirectToAction("GetUpdatedPrice");
}
```
<p><em><strong><code>C# Asp.net View</code></strong></em></p>
<pre class="lang-cs prettyprint-override"><code>@model IEnumerable<MVCApps.Models.PriceUpdateTable>

@{
    ViewData["Title"] = "GetUpdatedPrice";
}

<h2>Get Updated Price</h2>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ItemName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Price)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UpdatedPrice)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.ItemName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Price)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.UpdatedPrice)
                </td>
                <td>
                    Edit |
                    Details |
                    Delete
                </td>
            </tr>
        }
    </tbody>
</table>
</code>```

C# Asp.net Controller For Above View

public async Task<IActionResult> GetUpdatedPrice()
        {
            var updatedPrice = await _context.priceUpdateTable.ToListAsync();
            return View(updatedPrice);
        }

```

Output

Note: This is scenario for you. Howevery, you can get the idea how you could implement that. Just modify the example as per your requirement.

Hope avobe steps guided you accordingly. If you encounter further concern feel free to share us.

Body:
I have some prices in my web site(asp.net core) .I wanna to add  10 percent to all of them by click a button and change all of them just by click a button .I wrote a service to add 10 percent to each price and there is a controller and in view  I have  a button . but it does not work.How should Icorrect it?
this is my code .

public interface IUpdatePricesService
{
    ResultDto Execute(RequestUpdatePricesDto request);
}
public class UpdatePricesService : IUpdatePricesService
{
    private readonly IDataBaseContext _context;
    public UpdatePricesService(IDataBaseContext context)
    {
        _context = context;
    }
    public ResultDto Execute(RequestUpdatePricesDto request)
    {
        List<UpdatePrices> updatePrices = new List<UpdatePrices>();
        UpdatePrices prices = new UpdatePrices();
        foreach (var item in request.prices)
        {
            int p = Convert.ToInt32(prices);
            p = p / 10;
            p = p + p;
            item.Price=p;

            updatePrices.Add(prices);
        };
        _context.SaveChanges();
        return new ResultDto
        {
            IsSuccess = true,
            Message = "Updated",
        };
    }
}

    private readonly IUpdatePricesService _updatePrices;

    [HttpPost]
    public IActionResult UpdatePricesInProduct()
    {

        var result = _updatePrices.Execute(new RequestUpdatePricesDto { });

        return Json(result);

    }

                                        <fieldset class="form-group">

                                             افزودن
                                        </fieldset>

Body:
Updated Answer As Per Comment:

"In Ajax the UpatePriceByAjax controller , do not works"

It shouldn't work the way you have written that. Because your ajax request is not in correct format.

"Ajax error explanation"

If you debug your code on browser you should get either of following
error at the begining. You have written Jquery like this way
<script> </script> which generating either of following error.
Additionally, your jquery has not ended correctly you have missed or
have not posted accordingly }); end braces are missing.

How to resolve that error

You should write your script using following way: So that there will be no error at the begining.

@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {
            alert("Click");// Write your code here
        });
    </script>
}

"Another error you may get in Ajax"

data: postdata you haven't define what you are posting. I think for this price update request you don't need to post/submit any data as this method UpdatePricesInProduct does need anything as per your code.

"Finally Valid Ajax Request You should Write"

<div class="col-xl-12 col-lg-12 col-md-12 mb-1">
    <fieldset class="form-group">
        <br />
        <a id="btnIncrease" class="btn btn-success col-md-12"> افزودن   </a>
    </fieldset>
</div>
@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#btnIncrease').click(function () {
                alert("btnIncrease");
                $.ajax({
                    contenttype: 'application/x-www-form-urlencoded',
                    datatype: 'json',
                    url: "updatepricesinproduct",
                    type: "post",
                 //   data: postdata,
                    cache: false,
                    async: true,
                    success: function (data) {
                        alert(data);
                    }
                });
            });

        });
    </script>
}

"Output:"

Note: You should have above changes to get rid of your problem and make it
workable as expected.

Previous Answer And Working Sample:

Let say I have price list in my web site like below:

If now if you would like to update all price in the list together with
just a single button click then you could follow below steps:

HTML/Ajax:

<div class="col-xl-12 col-lg-12 col-md-12 mb-1">
    <fieldset class="form-group">
        <br />
        <a id="btnIncrease" class="btn btn-success col-md-12"> افزودن Update Price </a>
    </fieldset>
</div>

Javascript/Ajax:

@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script>
        $(document).ready(function () {

            $("#btnIncrease").click(function (e) {
                alert("Fired!");
                $.ajax("https://localhost:44361/UserLog/UpatePriceByAjax", {
                    method: "POST",
                    dataType: "json",
                    contentType: "application/json",
                    success: function (data) {

                        console.log(data);

                    }
                });
                alert("Successfully Updated");
                location.reload(true);
            });

        });
    </script>
}

C# Asp.net Core Controller

[HttpPost]
public ActionResult UpatePriceByAjax()
{
    decimal incrementPercentage = 10;
    List<PriceUpdateTable> ExistingPriceList = _context.priceUpdateTable.ToList();

    foreach (var item in ExistingPriceList)
    {
        var updatedPricePercentage = item.Price * incrementPercentage / 100;
        item.UpdatedPrice = item.Price + updatedPricePercentage;
        _context.Update(item);

    }
    _context.SaveChanges();

    return RedirectToAction("GetUpdatedPrice");
}

C# Asp.net View

@model IEnumerable<MVCApps.Models.PriceUpdateTable>

@{
    ViewData["Title"] = "GetUpdatedPrice";
}

<h2>Get Updated Price</h2>

<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ItemName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Price)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UpdatedPrice)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.ItemName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Price)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.UpdatedPrice)
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.ItemId">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.ItemId">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.ItemId">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

C# Asp.net Controller For Above View

public async Task<IActionResult> GetUpdatedPrice()
        {
            var updatedPrice = await _context.priceUpdateTable.ToListAsync();
            return View(updatedPrice);
        }

Output

Note: This is scenario for you. Howevery, you can get the idea how you could implement that. Just modify the example as per your requirement.

Hope avobe steps guided you accordingly. If you encounter further concern feel free to share us.


问:
Docbook, images already resized
I have an issue with my docbook xmls. The basic problem is that I couldn't find yet any solution to keep the inline/mediaobject images original size (height/width). All of the images are displayed oversized in the PDF output.

The images have already been resized so there is no reason for defining the image size at every image. I want to keep the original size of the images.

Tools I use:

- Apache FOP v1.0

- xsltproc (cygwin)

- Docbook XSL Stylesheet (v1.76.1)

Is there any way to keep the original size of the images?

答:
If all you want is to get the original size of the image, you'd have to do something like this:

```<code><mediaobject>
    <imageobject>
        <imagedata fileref="path/to/image/file" format="image_format" scalefit="1" width="100%" contentdepth="100%" />
    </imageobject>
</mediaobject>
</code>```

The part to take note of is the imagedata tag with it's attribute. Please note that I used dummy values for these attributes and so you must update them to reflect your environment :D

Title: Docbook, images already resized

Body:
If all you want is to get the original size of the image, you'd have to do something like this:

<mediaobject>
    <imageobject>
        <imagedata fileref="path/to/image/file" format="image_format" scalefit="1" width="100%" contentdepth="100%" />
    </imageobject>
</mediaobject>

The part to take note of is the imagedata tag with it's attribute. Please note that I used dummy values for these attributes and so you must update them to reflect your environment :D


问:
How to increase message size in grpc using python
I am using grpc for message passing and am testing a simple server and client.  When my message size goes over the limit, I get this error. </p>

```<code>grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with
(StatusCode.INVALID_ARGUMENT,
 Received message larger than max (7309898 vs. 4194304))>
</code>```

<p>How do I increase the message size on the server and client side? </p>

答:
Adding to the existing answers, you can find a list of all key-value pair options in the github repo - see below

From the grpc-Glossary

channel_arguments
A list of key-value pairs to configure the underlying gRPC Core channel or server object. Channel arguments are meant for advanced usages and contain experimental API (some may not labeled as experimental). Full list of available channel arguments and documentation can be found under the “grpc_arg_keys” section of “grpc_types.h” header file (https://github.com/grpc/grpc/blob/v1.43.x/include/grpc/impl/codegen/grpc_types.h). For example, if you want to disable TCP port reuse, you may construct channel arguments like: options = (('grpc.so_reuseport', 0),).

Body:
I am using grpc for message passing and am testing a simple server and client.  When my message size goes over the limit, I get this error.

grpc._channel._Rendezvous: <_Rendezvous of RPC that terminated with
(StatusCode.INVALID_ARGUMENT,
 Received message larger than max (7309898 vs. 4194304))>

How do I increase the message size on the server and client side?


问:
Can't query one record in BigQuery table, but can query others
I export Google Workspace logs to BigQuery. There are a small number of top-level records and then many nested groups of records. I can query the top level of records and most sub-levels fine but I can't select the groups records. select group_id,admin.user_email,admin.group_email works fine, for example.

But when I try to run a very similar query on the Groups records it fails with Syntax error: Expected end of input but got keyword GROUPS

```<code>SELECT
  group_id,
  groups.group_email
FROM
  `workspace-analytics.workspace_prod.activity`
WHERE
  groups.group_email='group@domain.com'
LIMIT
  100;
</code>```

What am I doing wrong? Why does this record in particular refuse to work the way the others do?

答:
Answer from @MatBailie, posting it as a WikiAnswer:

The error message tells you that GROUPS is a keyword. If you quote it, then bigquery will realise its a reference and not a keyword. groups.group_email.

Because admin isn't a keyword. Imagine you had a column named from, you couldn't do SELECT from FROM table without confusing the shit out of the parser, but SELECT from FROM table isn't ambiguous at all. You can CHOOSE to quote all references regardless, but if they're keywords then they MUST be quoted.

Make sure you're quoting using backticks, the same ones you use in dataset names.

Body:
I export Google Workspace logs to BigQuery. There are a small number of top-level records and then many nested groups of records. I can query the top level of records and most sub-levels fine but I can't select the groups records. select group_id,admin.user_email,admin.group_email works fine, for example.

But when I try to run a very similar query on the Groups records it fails with Syntax error: Expected end of input but got keyword GROUPS

SELECT
  group_id,
  groups.group_email
FROM
  `workspace-analytics.workspace_prod.activity`
WHERE
  groups.group_email='group@domain.com'
LIMIT
  100;

What am I doing wrong? Why does this record in particular refuse to work the way the others do?


问:
Adding constructor to third party class/struct definition
A third party library has structs defined as

```<code>typedef struct _Example
{
  int member;
} Example;
</code>```

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks

答: Your struct has a constructor. Compiler generated for you a no-arg constructor and thats exactly what boost::serialization needs.</p>

Body:
A third party library has structs defined as

typedef struct _Example
{
  int member;
} Example;

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks


问:
Change colors of IconButton
I have the following widget implemented:

```<code>TextFormField(
                  controller: _loginPageViewModel.passwordTEC,
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: S.of(context).password,
                    suffixIcon: IconButton(
                      onPressed: _loginPageViewModel.passwordTEC.clear,
                      icon: const Icon(Icons.clear),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return S.of(context).passwordValidation;
                    }
                    return null;
                  },
                )
</code>```

At the same time I'm implementing ThemeData. I managed to changed the border color of InputDecoration, whether the TextFormField has focus or not, but the color of suffixIcon is different. Which parameters of ThemeData are connected to the color of the suffixIcon, both in normal state and when in focus? Cheers

答:
Here is the code for what you want to achieve:

You need to implement ThemeData with copyWith for that.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData().copyWith(
        scaffoldBackgroundColor: Colors.white,
        colorScheme: ThemeData().colorScheme.copyWith(primary: Colors.green),
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const TextField(
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.lock_outline),
        hintText: 'Username',
      ),
    );
  }
}
</code>```

Hope it will helps you. Do let me know if you get any problem.

Thank you :)

Title: Change colors of IconButton

Body:
I have the following widget implemented:

TextFormField(
                  controller: _loginPageViewModel.passwordTEC,
                  obscureText: true,
                  decoration: InputDecoration(
                    hintText: S.of(context).password,
                    suffixIcon: IconButton(
                      onPressed: _loginPageViewModel.passwordTEC.clear,
                      icon: const Icon(Icons.clear),
                    ),
                  ),
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return S.of(context).passwordValidation;
                    }
                    return null;
                  },
                )

At the same time I'm implementing ThemeData. I managed to changed the border color of InputDecoration, whether the TextFormField has focus or not, but the color of suffixIcon is different. Which parameters of ThemeData are connected to the color of the suffixIcon, both in normal state and when in focus? Cheers

Body:
Here is the code for what you want to achieve:

You need to implement ThemeData with copyWith for that.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData().copyWith(
        scaffoldBackgroundColor: Colors.white,
        colorScheme: ThemeData().colorScheme.copyWith(primary: Colors.green),
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const TextField(
      decoration: InputDecoration(
        prefixIcon: Icon(Icons.lock_outline),
        hintText: 'Username',
      ),
    );
  }
}

Hope it will helps you. Do let me know if you get any problem.

Thank you :)


问:
How to print first and last index of the longest sequence of same-values neighbors?
I am interested in finding the first and last index of the longest sequence of same-valued neighbours for a given list. The closest question I could find was: First and last index of a sequence, but this does not exactly answer my question.

So let's say for example:

```<code>a = [4, 6, 1, 0, 0, 0, 2, 4, 4, 1]
</code>```

I would like to output to be

```<code>[3, 5]
</code>```

Here is what I have come up with so far, and it works for this example. However, once the list changes to have a 0 somewhere before or after the sequence (non-neighbouring) it does not work anymore.

```<code># Find distinct values of a
distinct = []
for x in a:
    if x not in distinct:
        distinct.append(x)
# Check which value has the longest sequence
countMax = 0
countNow = 1
num = 0
for i in a:
    if a[i] == a[i+1]:
        countNow += 1
        num = i
    else:
        countNow = 1
    if countNow > countMax:
        countMax = countNow
longest = distinct[num-1]
# Find first index value of number with longest sequence
firstIndex = a.index(longest)
# Find last index value of number with longest sequence
a_reverse = a[::-1]
firstIndex_reverse = a_reverse.index(longest)
lastIndex = len(a) - 1 - firstIndex_reverse

print(firstIndex, lastIndex)
</code>```

I don't know how better to find the first and last index for only the sequence in question.

答:
I'd just iterate the list and keep track of everything:</p>
```<code>a = [4, 6, 1, 0, 0, 0, 2, 4, 4, 4, 4, 4, 4, 1]

# indices
best_start = 0
best_end = 0
curr_start = 0
curr_end = 0

prev_val = a[0]

for (idx, curr_val) in enumerate(a[1:]):
    curr_end = idx + 1 # +1 since slicing shifted everything
    if prev_val == curr_val:
        if curr_end - curr_start > best_end - best_start:
            best_start = curr_start
            best_end = curr_end
    else:
        curr_start = curr_end
    prev_val = curr_val

print(best_start, best_end)
</code>```

Body:
I am interested in finding the first and last index of the longest sequence of same-valued neighbours for a given list. The closest question I could find was: First and last index of a sequence, but this does not exactly answer my question.

So let's say for example:

a = [4, 6, 1, 0, 0, 0, 2, 4, 4, 1]

I would like to output to be

[3, 5]

Here is what I have come up with so far, and it works for this example. However, once the list changes to have a 0 somewhere before or after the sequence (non-neighbouring) it does not work anymore.

# Find distinct values of a
distinct = []
for x in a:
    if x not in distinct:
        distinct.append(x)
# Check which value has the longest sequence
countMax = 0
countNow = 1
num = 0
for i in a:
    if a[i] == a[i+1]:
        countNow += 1
        num = i
    else:
        countNow = 1
    if countNow > countMax:
        countMax = countNow
longest = distinct[num-1]
# Find first index value of number with longest sequence
firstIndex = a.index(longest)
# Find last index value of number with longest sequence
a_reverse = a[::-1]
firstIndex_reverse = a_reverse.index(longest)
lastIndex = len(a) - 1 - firstIndex_reverse

print(firstIndex, lastIndex)

I don't know how better to find the first and last index for only the sequence in question.

Body:
I'd just iterate the list and keep track of everything:

a = [4, 6, 1, 0, 0, 0, 2, 4, 4, 4, 4, 4, 4, 1]

# indices
best_start = 0
best_end = 0
curr_start = 0
curr_end = 0

prev_val = a[0]

for (idx, curr_val) in enumerate(a[1:]):
    curr_end = idx + 1 # +1 since slicing shifted everything
    if prev_val == curr_val:
        if curr_end - curr_start > best_end - best_start:
            best_start = curr_start
            best_end = curr_end
    else:
        curr_start = curr_end
    prev_val = curr_val

print(best_start, best_end)


问:
File upload on Swagger Editor OpenAPI 3 not showing the file browser when trying it out
I'm using Swagger Editor with OpenAPI 3.0. I need to document a route which consists of uploading an image. When attempting to "Try it out", I don't get the file browser to choose the image to upload in the request body, all I get is a JSON string with the name and type of parameter.

This is the YAML description of the route:

openapi: 3.0.0
...
paths:
  /media/upload/thumbnail:
    post:
      tags:
        - media
        - publications
      security:
        - bearerAuth: []
      summary: upload a kid's publication
      operationId: uploadPublication
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                upload:
                  type: string
                  format: binary
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    description: ObjectId of the uploaded file in db (original size)
                    example: 5a6048b3fad06019afe44f24
                  filename:
                    type: string
                    example: myPainting.png
                  thumbnail:
                    type: string
                    description: ObjectId of the uploaded file in db (thumbnai size)
                    example: 5a6048b3fad06019afe44f26
        '400':
          description: Authentication failed
```

What am I missing here?

答:
Try with

content:
          image/png:
            schema:
              properties:
                file:
                  type: string
                  format: binary
```

Body:
I'm using Swagger Editor with OpenAPI 3.0. I need to document a route which consists of uploading an image. When attempting to "Try it out", I don't get the file browser to choose the image to upload in the request body, all I get is a JSON string with the name and type of parameter.

This is the YAML description of the route:

openapi: 3.0.0
...
paths:
  /media/upload/thumbnail:
    post:
      tags:
        - media
        - publications
      security:
        - bearerAuth: []
      summary: upload a kid's publication
      operationId: uploadPublication
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                upload:
                  type: string
                  format: binary
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: string
                    description: ObjectId of the uploaded file in db (original size)
                    example: 5a6048b3fad06019afe44f24
                  filename:
                    type: string
                    example: myPainting.png
                  thumbnail:
                    type: string
                    description: ObjectId of the uploaded file in db (thumbnai size)
                    example: 5a6048b3fad06019afe44f26
        '400':
          description: Authentication failed

What am I missing here?