问:
Why is using isampler2D causing my shader to fail to compile in WebGL2?
I have a fragment shader which is failing to compile in a WebGL 2 context:

```<code>#version 300 es
precision highp float;
uniform isampler2D tex_in;
out vec2 outColor;
void main() {
    outColor = vec2(0.0, 0.0);
}
</code>```

When I gl.compileShader this shader, gl.getShaderParameter(glFragmentShader, GL.COMPILE_STATUS) returns false. If I change isampler2D to sampler2D, the compile succeeds instead.

According to the webgl 2 quick reference, isampler2D is a supported keyword. What am I doing wrong?

答:
Rather than just point out the specific issue it's just a good practice to print the shader log when gl.getShaderParameter(shader, GL.COMPILE_STATUS) is false

example

const gl = document.createElement('canvas').getContext('webgl2');
const s = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(s, `#version 300 es
precision highp float;
uniform isampler2D tex_in;
out vec2 outColor;
void main() {
    outColor = vec2(0.0, 0.0);
}`);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
  throw new Error(gl.getShaderInfoLog(s));
}```
</div>
</div>
</p>

<p>prints</p>

```Uncaught Error: ERROR: 0:3: 'isampler2D' : No precision specified
```

So the issue is you didn't specify a precision

Body:
I have a fragment shader which is failing to compile in a WebGL 2 context:

#version 300 es
precision highp float;
uniform isampler2D tex_in;
out vec2 outColor;
void main() {
    outColor = vec2(0.0, 0.0);
}

When I gl.compileShader this shader, gl.getShaderParameter(glFragmentShader, GL.COMPILE_STATUS) returns false. If I change isampler2D to sampler2D, the compile succeeds instead.

According to the webgl 2 quick reference, isampler2D is a supported keyword. What am I doing wrong?

Body:
Rather than just point out the specific issue it's just a good practice to print the shader log when gl.getShaderParameter(shader, GL.COMPILE_STATUS) is false

example

const gl = document.createElement('canvas').getContext('webgl2');
const s = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(s, `#version 300 es
precision highp float;
uniform isampler2D tex_in;
out vec2 outColor;
void main() {
    outColor = vec2(0.0, 0.0);
}`);
gl.compileShader(s);
if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
  throw new Error(gl.getShaderInfoLog(s));
}

prints

Uncaught Error: ERROR: 0:3: 'isampler2D' : No precision specified

So the issue is you didn't specify a precision


来源: stackexchange

问:
React-native-image-picker image fileName is null
developers, I am using react-native-image-picker to upload images to the Nodejs server and MongoDB, when I select an image on react native app it is showing image fileName="null" on the console log. I am struggling for 3 weeks and couldn't find any solution. Below I have posted the console.log result:

```<code>Response =  {"fileName": null, "fileSize": 13712705, "height": 3024, "isVertical": false, "origURL": "assets-library://asset/asset.HEIC?id=CC95F08C-88C3-4012-9D6D-64A413D254B3&ext=HEIC", "type": "image/jpeg", "uri": "file:///Users/shinobi/Library/Developer/CoreSimulator/Devices/9DBEA6D8-101E-4B9C-9DB0-D1CABA724AAF/data/Containers/Data/Application/44C0E455-2A43-40A3-A2EE-213A39B7743C/tmp/35A90028-55FA-4218-8FB7-34EB1DE62F58.jpg", "width": 4032}
</code>```

Below is my react-native-image-picker code:

```<code>const ChangeTasbir = ({navigation, route}, props) => {

  const [image, setImage] = useState(null);
  const [id, setId] = useState(getDetails('id'));
  const [isuploading, setIsuploading] = useState(false);

  const selectImage = () => {
    const options = {
      noData: true,
    };
    ImagePicker.showImagePicker(options, response => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        const source = {
          uri: response.uri,
          fileName: response.fileName,
          data: response.data,
        };

        // You can also display the image using data:
        // const source = { uri: 'data:image/jpeg;base64,' + response.data };

        setImage(source);
      }
    });
  };
</code>```

答:
I'm using this options in my React native application on Android and works ok.

const options = {
      mediaTypes: 'Images',
      quality: 0.1,
    };

    ImagePicker.launchImageLibrary(options, (response) => {
      if (response.didCancel !== true) {
        this.setState({ profilePic: response, errorPic: false });

      }
    });
```

ContentLicense: CC BY-SA 4.0

Body:
developers, I am using react-native-image-picker to upload images to the Nodejs server and MongoDB, when I select an image on react native app it is showing image fileName="null" on the console log. I am struggling for 3 weeks and couldn't find any solution. Below I have posted the console.log result:

Response =  {"fileName": null, "fileSize": 13712705, "height": 3024, "isVertical": false, "origURL": "assets-library://asset/asset.HEIC?id=CC95F08C-88C3-4012-9D6D-64A413D254B3&ext=HEIC", "type": "image/jpeg", "uri": "file:///Users/shinobi/Library/Developer/CoreSimulator/Devices/9DBEA6D8-101E-4B9C-9DB0-D1CABA724AAF/data/Containers/Data/Application/44C0E455-2A43-40A3-A2EE-213A39B7743C/tmp/35A90028-55FA-4218-8FB7-34EB1DE62F58.jpg", "width": 4032}

Below is my react-native-image-picker code:

const ChangeTasbir = ({navigation, route}, props) => {

  const [image, setImage] = useState(null);
  const [id, setId] = useState(getDetails('id'));
  const [isuploading, setIsuploading] = useState(false);

  const selectImage = () => {
    const options = {
      noData: true,
    };
    ImagePicker.showImagePicker(options, response => {
      console.log('Response = ', response);

      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      } else {
        const source = {
          uri: response.uri,
          fileName: response.fileName,
          data: response.data,
        };

        // You can also display the image using data:
        // const source = { uri: 'data:image/jpeg;base64,' + response.data };

        setImage(source);
      }
    });
  };


问:
How to set a custom Content-Type with fastify in NestJS?
I have an application in NestJS using Fastify. I want to set a the Content-Type to application/hal+json in my responses. I have the following code in a NestJS interceptor:

@Injectable()
export class SampleInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    context.switchToHttp().getResponse()
      .header('Content-Type', 'application/hal+json; charset=utf-8');

    return next.handle().pipe(
      map((data) => {
        const serializer = MyCustomSerializer();
        return serializer.serialize(data);
      })
    );
  }
}
```

<p>However, I have the following error because I defined the Content-Type:</p>

<pre class="lang-sh prettyprint-override"><code>FastifyError [FST_ERR_REP_INVALID_PAYLOAD_TYPE]: FST_ERR_REP_INVALID_PAYLOAD_TYPE: Attempted to send payload of invalid type 'object'. Expected a string or Buffer.
    at onSendEnd (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:363:11)
    at onSendHook (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:325:5)
    at _Reply.Reply.send (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:151:3)
    at FastifyAdapter.reply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/platform-fastify/adapters/fastify-adapter.js:37:25)
    at RouterResponseController.apply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-response-controller.js:10:36)
    at /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:163:48
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
    at async /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:46:13
    at async Object.<anonymous> (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-proxy.js:8:17)
</code>```

After some investigation, I noticed that if I do not define the Content-Type, the payload is a string representation of my JSON response. If not, the payload is an object. This happens because this code in fastify never runs and never serializes the payload as string.

Here is a repository for you to easily replicate the issue.

Is there a way to solve this issue?

答: To my understanding, so long as what you return from the interceptor is a string, Nest (and Fastify) will treat it like a string and return it however you want. I have an example where I'm returning an XML string so long as an incoming accept header is setup to ask for XML data back (content negotiation) and Fastify is returning it just fine, so as long as you strinigfy whatever your serializer returns, you shouldn't have a problem with a custom (different) header

Body:
I have an application in NestJS using Fastify. I want to set a the Content-Type to application/hal+json in my responses. I have the following code in a NestJS interceptor:

@Injectable()
export class SampleInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {

    context.switchToHttp().getResponse()
      .header('Content-Type', 'application/hal+json; charset=utf-8');

    return next.handle().pipe(
      map((data) => {
        const serializer = MyCustomSerializer();
        return serializer.serialize(data);
      })
    );
  }
}

However, I have the following error because I defined the Content-Type:

FastifyError [FST_ERR_REP_INVALID_PAYLOAD_TYPE]: FST_ERR_REP_INVALID_PAYLOAD_TYPE: Attempted to send payload of invalid type 'object'. Expected a string or Buffer.
    at onSendEnd (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:363:11)
    at onSendHook (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:325:5)
    at _Reply.Reply.send (/home/user/Projects/nestjs-fastify-sample/node_modules/fastify/lib/reply.js:151:3)
    at FastifyAdapter.reply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/platform-fastify/adapters/fastify-adapter.js:37:25)
    at RouterResponseController.apply (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-response-controller.js:10:36)
    at /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:163:48
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
    at async /home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-execution-context.js:46:13
    at async Object.<anonymous> (/home/user/Projects/nestjs-fastify-sample/node_modules/@nestjs/core/router/router-proxy.js:8:17)

After some investigation, I noticed that if I do not define the Content-Type, the payload is a string representation of my JSON response. If not, the payload is an object. This happens because this code in fastify never runs and never serializes the payload as string.

Here is a repository for you to easily replicate the issue.

Is there a way to solve this issue?


问:
Basic Javascript Question
I'm messing around with the Head First Javascript book. So my question is why doesn't the if clause in my function turnSad() trigger? UPDATE I've tried this in Chrome and FF4. Also, if I were to comment out the if statement, the function will work.

```<code><script type="text/javascript">

    function turnSad() {
        if (document.getElementById("rockImg").src == "rock_happy.png")
            document.getElementById("rockImg").src = "rock.png";
    }

    function touchRock() {
        var userName = prompt("What is your name?", "Enter your name here");

        if (userName) {
            alert("It is nice to meet you " + userName + ".");
            document.getElementById("rockImg").src = "rock_happy.png";
        }
        setTimeout("turnSad();", 1000);
    }

</script>
<img id="rockImg" src="rock.png" alt="iRock"  style="cursor:pointer"
    onclick="touchRock();" />
</code>```

答: Which browser are you using? IE might turn the filename into uppercase ("ROCK_HAPPY.PNG"). Use developer tools (press Refresh button in the tools toolbar) to determine what the real "src" attribute is, or just do alert(document.getElementById().src)

ContentLicense: CC BY-SA 3.0

Title: Basic Javascript Question


问:
Some model properties always null on post, modelbinding issue
I am making a part of a website where you can update your profile. The profile is tied to the user which is an extension of Microsofts Identity.

The problem is that LastName and FirstName is always null after making a post request.
I would like to think that if this was a ModelState error I would have caught it through !ModelState.IsValid.

https://i.gyazo.com/eea1e3465427eba5a731947473fca821.mp4

Model

```<code>using Microsoft.AspNetCore.Identity;
using System;
namespace Certificate_Wiki.Models {
    public class CertificateUser : IdentityUser {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Website { get; set; }
        public string Occupation { get; set; }
        public string Country { get; set; }
        public string Description { get; set; }
        public String ProfilePictureUrl { get; set; }
        public Byte[] ProfilePicture { get; set; }
        public bool isPrivate { get; set; }
    }
}
</code>```

cshtml

```<code>@{
    ViewData["Title"] = "Edit Profile";
}
@model Certificate_Wiki.Models.CertificateUser
<link rel="stylesheet" href="~/css/pages/ProfileEdit.css" media="all" />

<div class="background"></div>
<div class="content">
    <div class="content-image">
        <img src="~/images/profile/Component 1 – 1.png" alt="" />
    </div>
    <div class="content-profile">
        <div class="profile-image">
            <img src="https://www.pngitem.com/pimgs/m/78-786293_1240-x-1240-0-avatar-profile-icon-png.png" alt="error loading image" />
        </div>
        <div class="profile-form">
            <h2>@User.Identity.Name</h2>
            <div asp-validation-summary="All">
            </div>
            <form asp-action="Edit" method="post">

                <div class="form-row">
                    <label>First Name</label>
                    <input asp-for="FirstName" type="text" name="name" />
                </div>
                <div class="form-row">
                    <label>Last Name</label>
                    <input asp-for="LastName" type="text" name="name" />
                </div>
                <div class="form-row">
                    <label>Occupation</label>
                    <input asp-for="Occupation" type="text" name="occupation" />
                </div>
                <div class="form-row">
                    <label>Website</label>
                    <input asp-for="Website" type="url" name="website" />
                </div>
                <div class="form-row">
                    <label>Country</label>
                    <input asp-for="Country" type="text" name="Country" />
                </div>
                <div class="form-row">
                    <label>Profile Description</label>
                    <textarea asp-for="Description" type="text" name="description"></textarea>
                </div>
                <div class="form-row">
                    <label>Private Profile</label>
                    <input asp-for="isPrivate" type="checkbox" name="Private" />
                </div>

                <div class="form-row">
                    <button type="submit">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>
</code>```

Controller

[HttpGet]
[Authorize]
[Route("Profile/edit")]
public async Task<IActionResult> EditAsync()
{
    var Profile = await userManager.FindByEmailAsync(User.Identity.Name);
    if (Profile == null) { return View(); }

    return View(Profile);
}

[ValidateAntiForgeryToken]
[HttpPost]
[Authorize]
[Route("Profile/edit")]
public async Task<IActionResult> EditAsync([FromForm]CertificateUser model)
{
    //TODO
    //Remove CW from single-line if
    if (!ModelState.IsValid) { Console.WriteLine("Modelstate invalid"); return View(model); }

    var Profile = await userManager.FindByEmailAsync(User.Identity.Name);
    if (Profile == null) { return View(); }

    //Update database
    Profile.FirstName = model.FirstName;
    Profile.LastName = model.LastName;
    Profile.Description = model.Description;
    Profile.Country = model.Country;
    Profile.Occupation = model.Occupation;
    Profile.Website = model.Website;
    await userManager.UpdateAsync(Profile);

    Console.WriteLine("Update success");

    return RedirectToAction("Index");
}
```

Note, While I am at it I would also like to ask if there is a "better" or a rather clean way to update the user without profile... = model... for every property to be updated.

答:
If you use the asp-for attribute for input box, then you shouldn't use the name attribute in the same time (or at least use the same value for it).

In your example you set FirstName for asp-for and then just name for the name attribute of the input for FirstName.

Body:
I am making a part of a website where you can update your profile. The profile is tied to the user which is an extension of Microsofts Identity.

The problem is that LastName and FirstName is always null after making a post request.
I would like to think that if this was a ModelState error I would have caught it through !ModelState.IsValid.

https://i.gyazo.com/eea1e3465427eba5a731947473fca821.mp4

Model

using Microsoft.AspNetCore.Identity;
using System;
namespace Certificate_Wiki.Models {
    public class CertificateUser : IdentityUser {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Website { get; set; }
        public string Occupation { get; set; }
        public string Country { get; set; }
        public string Description { get; set; }
        public String ProfilePictureUrl { get; set; }
        public Byte[] ProfilePicture { get; set; }
        public bool isPrivate { get; set; }
    }
}

cshtml

@{
    ViewData["Title"] = "Edit Profile";
}
@model Certificate_Wiki.Models.CertificateUser
<link rel="stylesheet" href="~/css/pages/ProfileEdit.css" media="all" />

@User.Identity.Name

            <form asp-action="Edit" method="post">

                    First Name
                    <input asp-for="FirstName" type="text" name="name" />

                    Last Name
                    <input asp-for="LastName" type="text" name="name" />

                    Occupation
                    <input asp-for="Occupation" type="text" name="occupation" />

                    Website
                    <input asp-for="Website" type="url" name="website" />

                    Country
                    <input asp-for="Country" type="text" name="Country" />

                    Profile Description
                    <textarea asp-for="Description" type="text" name="description"></textarea>

                    Private Profile
                    <input asp-for="isPrivate" type="checkbox" name="Private" />

                    <button type="submit">Save</button>

            </form>

Controller

[HttpGet]
[Authorize]
[Route("Profile/edit")]
public async Task<IActionResult> EditAsync()
{
    var Profile = await userManager.FindByEmailAsync(User.Identity.Name);
    if (Profile == null) { return View(); }

    return View(Profile);
}

[ValidateAntiForgeryToken]
[HttpPost]
[Authorize]
[Route("Profile/edit")]
public async Task<IActionResult> EditAsync([FromForm]CertificateUser model)
{
    //TODO
    //Remove CW from single-line if
    if (!ModelState.IsValid) { Console.WriteLine("Modelstate invalid"); return View(model); }

    var Profile = await userManager.FindByEmailAsync(User.Identity.Name);
    if (Profile == null) { return View(); }

    //Update database
    Profile.FirstName = model.FirstName;
    Profile.LastName = model.LastName;
    Profile.Description = model.Description;
    Profile.Country = model.Country;
    Profile.Occupation = model.Occupation;
    Profile.Website = model.Website;
    await userManager.UpdateAsync(Profile);

    Console.WriteLine("Update success");

    return RedirectToAction("Index");
}

Note, While I am at it I would also like to ask if there is a "better" or a rather clean way to update the user without profile... = model... for every property to be updated.


问:
Why am I get a syntax error here when I am equating a variable containing an integer and a variable containing a numerical input from the user?
I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,

```<code>if guess.isdigit():
     guess = int(guess)
</code>```

Please help

```<code>import random
a = random.randint(1,10)

print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")

if question_one == "Yes":
    print("Let's go!")
else:
    print("That sucks!")
    exit()
guess = None
while guess != a:
    guess = (input("Alright, guess a number from 1-10"))
    if guess.isdigit():
        guess = int(guess)

    if guess > a:
        guess = int(input("Guess lower!"))
    elif guess < a:
        guess = int(input("Guess higher!"))
    else guess == a:
        print("you got it!")
</code>```

答: else doesn't let you define a condition. else will execute if all other conditionals return false. You should change that last else to elif. Or you can simply leave out the conditional guess == a all together. If it is not greater than or less than, the only other thing it can be is equal to.

Body:
I am just learning the basics of Python and created a number guessing game. I want the user to be able to guess the number as many times as possible until they guess correctly. I did this through a while loop but the code, "else guess == a:" near the end is giving me a syntax error. I am confused because the while loop ensures that the input guess is an integer by the if statement,

if guess.isdigit():
     guess = int(guess)

Please help

import random
a = random.randint(1,10)

print("this is a number guessing game")
question_one = input("Would you like to play? Yes or No?:")

if question_one == "Yes":
    print("Let's go!")
else:
    print("That sucks!")
    exit()
guess = None
while guess != a:
    guess = (input("Alright, guess a number from 1-10"))
    if guess.isdigit():
        guess = int(guess)

    if guess > a:
        guess = int(input("Guess lower!"))
    elif guess < a:
        guess = int(input("Guess higher!"))
    else guess == a:
        print("you got it!")


问:
symfony/encore: Hide warning of dependency
I am struggling to hide a warning that comes from a dependency I can not fix.

Things I've tried:

configuring the webpack config stats option; but I saw later that Encore essentially disables the warnings output already (when looking at the output of Encore.getWebpackConfig()).

writing a transformer for the friendly-errors-plugin used by encore; settings the warning I do not want to see to null. After transformations however the null values are not filtreed out, leading to a crash (kind of makes sense, as they are not filters; but was worth a shot)

What confuses me that apparently the friendly-errors-webpack-plugin takes its input from the webpack output see source, but the warnings still show up even if I disable all with stats: false.

In short; how can I hide this warning:

```<code> WARNING  Compiled with 1 warnings                                                                                8:44:25 AM

 warning  in ./node_modules/moment/locale/en-SG.js

There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* /home/famoser/Repos/mangelio/web/node_modules/moment/locale/en-SG.js
    Used by 2 module(s), i. e.
    /home/famoser/Repos/mangelio/web/node_modules/moment/locale sync /^\.\/.*$/
* /home/famoser/Repos/mangelio/web/node_modules/moment/locale/en-sg.js
    Used by 2 module(s), i. e.
    /home/famoser/Repos/mangelio/web/node_modules/moment/locale sync /^\.\/.*$/
</code>```

答: Yes, remove folder node_modules and yarn/npm install resolves the issue, thanks!</p>

Body:
I am struggling to hide a warning that comes from a dependency I can not fix.

Things I've tried:

configuring the webpack config stats option; but I saw later that Encore essentially disables the warnings output already (when looking at the output of Encore.getWebpackConfig()).

writing a transformer for the friendly-errors-plugin used by encore; settings the warning I do not want to see to null. After transformations however the null values are not filtreed out, leading to a crash (kind of makes sense, as they are not filters; but was worth a shot)

What confuses me that apparently the friendly-errors-webpack-plugin takes its input from the webpack output see source, but the warnings still show up even if I disable all with stats: false.

In short; how can I hide this warning:

 WARNING  Compiled with 1 warnings                                                                                8:44:25 AM

 warning  in ./node_modules/moment/locale/en-SG.js

There are multiple modules with names that only differ in casing.
This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
Use equal casing. Compare these module identifiers:
* /home/famoser/Repos/mangelio/web/node_modules/moment/locale/en-SG.js
    Used by 2 module(s), i. e.
    /home/famoser/Repos/mangelio/web/node_modules/moment/locale sync /^\.\/.*$/
* /home/famoser/Repos/mangelio/web/node_modules/moment/locale/en-sg.js
    Used by 2 module(s), i. e.
    /home/famoser/Repos/mangelio/web/node_modules/moment/locale sync /^\.\/.*$/


问:
What's the fastest way to do these tasks?
I originally have some time series data, which looks like this and have to do the following:

First import it as dataframe

Set date column as datetime index

Add some indicators such as moving average etc, as new columns

Do some rounding (values of the whole column)

Shift a column one row up or down (just to manipulate the data)

Then convert the df to list (because I need to loop it based on some conditions, it's a lot faster than looping a df because I need speed)

But now I want to convert df to dict instead of list because I want to keep the column names, it's more convenient

But now I found out that convert to dict takes a lot longer than list. Even I do it manually instead of using python built-in method.

My question is, is there a better way to do it? Maybe not to import as dataframe in the first place? And still able to do Point 2 to Point 5? At the end I need to convert to dict which allows me to do the loop, keep the column names as keys? THanks.

P.S. the dict should look something like this, the format is similar to df, each row is basically the date with the corresponding data.

答:
On item #7: If you want to convert to a dictionary, you can use df.to_dict()

On item #6: You don't need to convert the df to a list or loop over it: Here are better options. Look for the second answer (it says DON'T)


问:
How to tell forfiles to execute command in PATH?
I'm missing something (obvious?) about escaping my strings or spaces in the following Windows Server 2k3 batch command.

```<code>FORFILES -m *.wsp -c "CMD /C C:\Program^ Files\Common^ Files\Microsoft^ Shared\web^ server^ extensions\12\bin\stsadm.exe^ -o^ addsolution^ -filename^ @FILE"
</code>```

Results in the following error

```<code>'C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\bin\stsadm.exe -o addsolution -filename "foobar.wsp"' is not recognized as an internal or external command,operable program or batch file.
</code>```

But I can't figure out why. I'm working off Mr. Simon Sheppard's fine documentation

答:
Another possible answer is to use the old 8.3 names you get by doing dir /X.

Like:  C:\PROGRA~1 instead of C:\Program Files.

OwnerDisplayName: Noel

Body:
I'm missing something (obvious?) about escaping my strings or spaces in the following Windows Server 2k3 batch command.

FORFILES -m *.wsp -c "CMD /C C:\Program^ Files\Common^ Files\Microsoft^ Shared\web^ server^ extensions\12\bin\stsadm.exe^ -o^ addsolution^ -filename^ @FILE"

Results in the following error

'C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\bin\stsadm.exe -o addsolution -filename "foobar.wsp"' is not recognized as an internal or external command,operable program or batch file.

But I can't figure out why. I'm working off Mr. Simon Sheppard's fine documentation

LastEditorDisplayName: Noel

OwnerDisplayName: Randy Scott

ContentLicense: CC BY-SA 2.5


问:
Javascript date countdown with custom date

var timer;

var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));

timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();

  if (difference <= 0) {

    // Timer done
    clearInterval(timer);

  } else {

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);

    hours %= 24;
    minutes %= 60;
    seconds %= 60;

    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #f5f5f5;
}
#timer {
  font-family: Arial, sans-serif;
  font-size: 20px;
  color: #999;
  letter-spacing: -1px;
}
#timer span {
  font-size: 60px;
  color: #333;
  margin: 0 3px 0 15px;
}
#timer span:first-child {
  margin-left: 0;
}
  </code>```

  days
  hours
  minutes
  seconds

```

答:
setDate() sets only Day of the current month in date object. You can directly provide your date string in YYYY-MM-DD format to Date() while creating new object.

var timer;

var compareDate = new Date('2020-06-02');
// compareDate.setDate(Date.parse('2020-06-02'));

timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();

  if (difference <= 0) {

    // Timer done
    clearInterval(timer);

  } else {

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);

    hours %= 24;
    minutes %= 60;
    seconds %= 60;

    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #f5f5f5;
}
#timer {
  font-family: Arial, sans-serif;
  font-size: 20px;
  color: #999;
  letter-spacing: -1px;
}
#timer span {
  font-size: 60px;
  color: #333;
  margin: 0 3px 0 15px;
}
#timer span:first-child {
  margin-left: 0;
}</code>```

  days
  hours
  minutes
  seconds

```

Body:
var timer;

var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));

timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();

  if (difference <= 0) {

    // Timer done
    clearInterval(timer);

  } else {

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);

    hours %= 24;
    minutes %= 60;
    seconds %= 60;

    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}

body {
  background: #f5f5f5;
}
#timer {
  font-family: Arial, sans-serif;
  font-size: 20px;
  color: #999;
  letter-spacing: -1px;
}
#timer span {
  font-size: 60px;
  color: #333;
  margin: 0 3px 0 15px;
}
#timer span:first-child {
  margin-left: 0;
}

  days
  hours
  minutes
  seconds

Body:
setDate() sets only Day of the current month in date object. You can directly provide your date string in YYYY-MM-DD format to Date() while creating new object.

var timer;

var compareDate = new Date('2020-06-02');
// compareDate.setDate(Date.parse('2020-06-02'));

timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();

  if (difference <= 0) {

    // Timer done
    clearInterval(timer);

  } else {

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);

    hours %= 24;
    minutes %= 60;
    seconds %= 60;

    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}

body {
  background: #f5f5f5;
}
#timer {
  font-family: Arial, sans-serif;
  font-size: 20px;
  color: #999;
  letter-spacing: -1px;
}
#timer span {
  font-size: 60px;
  color: #333;
  margin: 0 3px 0 15px;
}
#timer span:first-child {
  margin-left: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">
  <span id="days"></span>days
  <span id="hours"></span>hours
  <span id="minutes"></span>minutes
  <span id="seconds"></span>seconds
</div>


问:
How to catch ScrollToPosition event in a CFormView?
I'm implementing a vertical scrolling mechanism using OnVScroll.

Some buttons in my dialog call ScrollToPosition () function. The particularity of this function is that it changes the configuration of the scroll bar without notifying OnVScroll. This makes my job a lot more complicated.

Question :

How can I catch ScrollToPosition () event ?

Environment details:

Windows 7

Visual studio 2010

MFC

答:
Why not override the ScrollToPosition method in your CFormView class?

```<code>void CMyView::ScrollToPosition( POINT pt )
{
    // Do something

    // Call base class
    CFormView::ScrollToPosition( pt );
}
</code>```

Body:
Why not override the ScrollToPosition method in your CFormView class?

void CMyView::ScrollToPosition( POINT pt )
{
    // Do something

    // Call base class
    CFormView::ScrollToPosition( pt );
}


问:
Can anyone explain this two line briefly?
```<code> BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 int t = Integer.parseInt(br.readLine());
</code>```

答:
```<code>BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
</code>```

The line above creates a new input reader.

```<code>int t = Integer.parseInt(br.readLine());
</code>```

br.readLine() reads a string input from the user. Integer.parseInt() converts the string input to an integer, and then after that, it is stored in the variable t.

That's pretty much it. Perhaps you could tell us what is it in particular that you don't understand?

Body:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

The line above creates a new input reader.

int t = Integer.parseInt(br.readLine());

br.readLine() reads a string input from the user. Integer.parseInt() converts the string input to an integer, and then after that, it is stored in the variable t.

That's pretty much it. Perhaps you could tell us what is it in particular that you don't understand?


问:
My input is not proceeding to the next page
I have created a form where the user will enter some information and the email will have to be validated before the user can proceed to the next page (thankyou.html) however when i input every thing correctly into the form the email gets validated but i cannot get to the next page...i cant figure out what im doing wrong. Any help would be appreciated and thank you in advance.</p>

```<code><script type = "text/javascript">

    function validate()
        {
            var text = document.getElementById("text1").value;
            var regx = /^([a-zA-Z0-9\.-]+)@([a-zA-Z0-9-]+)\.([a-z]{3})$/;
            var uname = document.getElementById("name");
            var title = document.getElementById("title1");
            var comment = document.getElementById("cmt");

        if(regx.test(text))
            {
            document.getElementById("lbltext").innerHTML="you may proceed";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="green";
            }
        else{
            document.getElementById("lbltext").innerHTML="invalid email";
            document.getElementById("lbltext").style.visibility="visible";
            document.getElementById("lbltext").style.color="black";
            }

        }

</script>
</head>

<body>
<form onsubmit = "return validate()" action = "thankyou.html" class = "input"><br><br>
    <p style = "text-decoration: underline; color: white;">comment :</p><br>
    <input id= "name" placeholder= "Name" type= "text" style = "height: 25px; width:250px;"/><br><br>
    <input id = "text1" placeholder = "Email" type= "text" style = "height: 25px; width: 250px;"/><p style = "font-size: 25px; color: red; display: inline-block;">*</p><label id= "lbltext" style = "color: black;visibility: hidden"></label><br><br>
    <input id= "title1" placeholder= "title" type= "text" style = "height: 25px; width: 500px;"/><br><br>
    <textarea id= "cmt" placeholder= "Comment" type= "text" style = "height: 250px; width: 500px;"></textarea><br><br>
    <button onClick="validate()" type="button" style = "color: white; font-weight: bold; background-color:  #9933ff; width: 75px; height: 30px;float: right; margin-right: 90px; border:thick; border-color: black;">Submit</button>
    </form>
</body>
</code>```

答:
Also it looks like you're just going to the tankyou.html immediately after validation. It seems to me like you don't need the green 'you may proceed'. You could clean up your code a little.</p>

```<code>    if(regx.test(text) === false)
    {
        document.getElementById("lbltext").innerHTML="invalid email";
        document.getElementById("lbltext").style.visibility="visible";
        document.getElementById("lbltext").style.color="black";
        return false;
    }
    else
    {
        return true;
    }
</code>```

Body:
I have created a form where the user will enter some information and the email will have to be validated before the user can proceed to the next page (thankyou.html) however when i input every thing correctly into the form the email gets validated but i cannot get to the next page...i cant figure out what im doing wrong. Any help would be appreciated and thank you in advance.

<form onsubmit = "return validate()" action = "thankyou.html" class = "input">

comment :

    <input id= "name" placeholder= "Name" type= "text" style = "height: 25px; width:250px;"/>

    <input id = "text1" placeholder = "Email" type= "text" style = "height: 25px; width: 250px;"/>
*

    <input id= "title1" placeholder= "title" type= "text" style = "height: 25px; width: 500px;"/>

    <textarea id= "cmt" placeholder= "Comment" type= "text" style = "height: 250px; width: 500px;"></textarea>

    <button onClick="validate()" type="button" style = "color: white; font-weight: bold; background-color:  #9933ff; width: 75px; height: 30px;float: right; margin-right: 90px; border:thick; border-color: black;">Submit</button>
    </form>

Body:
Also it looks like you're just going to the tankyou.html immediately after validation. It seems to me like you don't need the green 'you may proceed'. You could clean up your code a little.

    if(regx.test(text) === false)
    {
        document.getElementById("lbltext").innerHTML="invalid email";
        document.getElementById("lbltext").style.visibility="visible";
        document.getElementById("lbltext").style.color="black";
        return false;
    }
    else
    {
        return true;
    }


问:
Are data type identifiers necessary when declaring a function in C?
I'm very new to C programming and am confused as to why functions like int main(){} include "int"? As far as I can tell, it functions fine without the data type, and leaving out the data type would make it easier to read and would be similar to languages I'm already familiar with like JS. What am I missing?

答:
When you omit the return type for a function in C, it is defaulted to int and
any calls to this function that expect anything that cannot be typecast to int will get compiler warning/error. Its good programming practise to include function return type since not all functions always return int.

would be similar to languages I'm already familiar with like JS

No it is not similar. In languages like JS, they can return any data type and the rest of the code knows what to expect depending on the function and arguments. However in C, omitting return type does not mean it can return any datatype. It means it can return only int. So in your case, it would be even more confusing.


答:
When accessing the src property (not the attribute), browsers may automatically resolve relative paths and give back the absolute path including the protocol, domain, port, etc.

To get or change the attribute value, use getAttribute and setAttribute.

```<code>image.getAttribute("src");

image.setAttribute("src", "someImage.png");
</code>```

See this example.

Title: Basic Javascript Question

Body: I'm messing around with the Head First Javascript book. So my question is why doesn't the if clause in my function turnSad() trigger? UPDATE I've tried this in Chrome and FF4. Also, if I were to comment out the if statement, the function will work.

Body:
When accessing the src property (not the attribute), browsers may automatically resolve relative paths and give back the absolute path including the protocol, domain, port, etc.

To get or change the attribute value, use getAttribute and setAttribute.

image.getAttribute("src");

image.setAttribute("src", "someImage.png");

See this example.


答: If you have the last else, the code inside the else will be executed if any other condition goes false. So I think if you change the last else with an elif we work properly.</p>

Title: Why am I get a syntax error here when I am equating a variable containing an integer and a variable containing a numerical input from the user?


问:
how to make chown command worked in nfs share folder
I am make a nfs file share and using it in kubernetes pods, but when I start pods, it give me tips :

```<code>2020-05-31 03:00:06+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
chown: changing ownership of '/var/lib/mysql/': Operation not permitted
</code>```

I searching from internet and understand the nfs default map other root login to nfsnobody account, if the privillege not correct, this error should happen, but I follow the steps and still not solve it. This is the ways I having tried:

1 addd unsecure config no_root_squash in /etc/exports:

```<code>/mnt/data/apollodb/apollopv *(rw,sync,no_subtree_check,no_root_squash)
</code>```

2 remove the PVC and PV and directly using nfs in pod like this:

```<code>volumes:
        - name: apollo-mysql-persistent-storage
          nfs:
            server: 192.168.64.237
            path: /mnt/data/apollodb/apollopv
      containers:
        - name: mysql
          image: 'mysql:5.7'
          ports:
            - name: mysql
              containerPort: 3306
              protocol: TCP
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: gfwge4LucnXwfefewegLwAd29QqJn4
          resources: {}
          volumeMounts:
            - name: apollo-mysql-persistent-storage
              mountPath: /var/lib/mysql
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}
      schedulerName: default-scheduler
</code>```

this tell me the problem not in pod define but in the nfs config itself.

3 give every privillege using this command

```<code>chmod 777 /mnt/data/apollodb/apollopv
</code>```

4 chown to nfsnobody like this

```<code>sudo chown nfsnobody:nfsnobody -R apollodb/
sudo chown 999:999 -R apollodb
</code>```

but the problem still not solved,so what should I try to make it works?

答: You wouldn't set this via chown, you would use fsGroup security setting instead.

Body:
I am make a nfs file share and using it in kubernetes pods, but when I start pods, it give me tips :

2020-05-31 03:00:06+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
chown: changing ownership of '/var/lib/mysql/': Operation not permitted

I searching from internet and understand the nfs default map other root login to nfsnobody account, if the privillege not correct, this error should happen, but I follow the steps and still not solve it. This is the ways I having tried:

1 addd unsecure config no_root_squash in /etc/exports:

/mnt/data/apollodb/apollopv *(rw,sync,no_subtree_check,no_root_squash)

2 remove the PVC and PV and directly using nfs in pod like this:

volumes:
        - name: apollo-mysql-persistent-storage
          nfs:
            server: 192.168.64.237
            path: /mnt/data/apollodb/apollopv
      containers:
        - name: mysql
          image: 'mysql:5.7'
          ports:
            - name: mysql
              containerPort: 3306
              protocol: TCP
          env:
            - name: MYSQL_ROOT_PASSWORD
              value: gfwge4LucnXwfefewegLwAd29QqJn4
          resources: {}
          volumeMounts:
            - name: apollo-mysql-persistent-storage
              mountPath: /var/lib/mysql
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
          imagePullPolicy: IfNotPresent
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      dnsPolicy: ClusterFirst
      securityContext: {}
      schedulerName: default-scheduler

this tell me the problem not in pod define but in the nfs config itself.

3 give every privillege using this command

chmod 777 /mnt/data/apollodb/apollopv

4 chown to nfsnobody like this

sudo chown nfsnobody:nfsnobody -R apollodb/
sudo chown 999:999 -R apollodb

but the problem still not solved,so what should I try to make it works?


问:
Skipped x frames! The application may be doing too much work on its main thread. What does this error signify and how to solve this?
I'm trying to do authentication with firbase in my Flutter app. Once the user is signed in and goes to the Authenticted screen, this error shows up.
I'm using google_signin plugin with simple logics.

```<code>    bool isAuth = false;

  //check if the user is signed in
  @override
  void initState() {
    super.initState();
    googleSignIn.onCurrentUserChanged.listen((account) {
      handleSignIn(account);
    }, onError: (err) {
      print("Error signing in: $err");
    });
    //maintain the signin
    googleSignIn.signInSilently(suppressErrors: false).then((account) {
      handleSignIn(account);
    }).catchError((err) {
      print("Error signing in: $err");
    });
  }

  handleSignIn(GoogleSignInAccount account) {
    if (account != null) {
      print('User signed in!: $account');
      setState(() {
        isAuth = true;
      });
    } else {
      setState(() {
        isAuth = false;
      });
    }
  }

  //sign in using google
  login() {
    googleSignIn.signIn();
  }

  logout() {
    googleSignIn.signOut();
  }

  Widget buildAuthScreen() {
    return Center(
      child: RaisedButton(
        child: Text("LogOut"),
        onPressed: logout(),
      ),
    );
  }
</code>```

then the unauth screen has basic login layout for signining in...

答: This is something you can't control sometimes, I faced this situation where an old android phone showed it skipped 180 frames where as a new phone said it skipped 25.</p>

Body:
I'm trying to do authentication with firbase in my Flutter app. Once the user is signed in and goes to the Authenticted screen, this error shows up.
I'm using google_signin plugin with simple logics.

    bool isAuth = false;

  //check if the user is signed in
  @override
  void initState() {
    super.initState();
    googleSignIn.onCurrentUserChanged.listen((account) {
      handleSignIn(account);
    }, onError: (err) {
      print("Error signing in: $err");
    });
    //maintain the signin
    googleSignIn.signInSilently(suppressErrors: false).then((account) {
      handleSignIn(account);
    }).catchError((err) {
      print("Error signing in: $err");
    });
  }

  handleSignIn(GoogleSignInAccount account) {
    if (account != null) {
      print('User signed in!: $account');
      setState(() {
        isAuth = true;
      });
    } else {
      setState(() {
        isAuth = false;
      });
    }
  }

  //sign in using google
  login() {
    googleSignIn.signIn();
  }

  logout() {
    googleSignIn.signOut();
  }

  Widget buildAuthScreen() {
    return Center(
      child: RaisedButton(
        child: Text("LogOut"),
        onPressed: logout(),
      ),
    );
  }

then the unauth screen has basic login layout for signining in...


问:
want to display positive and negative values in different columns thru a single query
I have one column table with negative and positive values and want to display positive and negative values in different columns thru a single query.

```<code>Column
-10000
-17000
 16000
 25000
</code>```

output should be like

```<code>A        B
-----------------
-10000   16000
-17000   25000
</code>```

I am using oracle and pl sql developer.

答:
HI sara ,

just try this one

```<code>SELECT T1.POSITIVE_VALUE, T2.negetive_value
FROM (select COL positive_value, ROWNUM C1 FROM TEST_1 WHERE COL >= 0) T1
FULL OUTER JOIN (SELECT COL negetive_value, ROWNUM C2 FROM TEST_1 WHERE COL < 0) T2
ON (T1.C1 = T2.C2);
</code>```

Body:
I have one column table with negative and positive values and want to display positive and negative values in different columns thru a single query.

Column
-10000
-17000
 16000
 25000

output should be like

A        B
-----------------
-10000   16000
-17000   25000

I am using oracle and pl sql developer.

Body:
HI sara ,

just try this one

SELECT T1.POSITIVE_VALUE, T2.negetive_value
FROM (select COL positive_value, ROWNUM C1 FROM TEST_1 WHERE COL >= 0) T1
FULL OUTER JOIN (SELECT COL negetive_value, ROWNUM C2 FROM TEST_1 WHERE COL < 0) T2
ON (T1.C1 = T2.C2);


问:
JSP - Expecting "jsp:param" standard action with "name" and "value" attributes
I am using struts1.1. When i redirect to one jsp file, i got the following exception. I cannot figure out where the error is.</p>

```<code>org.apache.jasper.JasperException: /jsp/jobcard/JobCardAdd.jsp(908,3) Expecting "jsp:param" standard action with "name" and "value" attributes
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:39)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:405)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:86)
    at org.apache.jasper.compiler.Parser.parseParam(Parser.java:861)
    at org.apache.jasper.compiler.Parser.parseBody(Parser.java:1813)
    at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1069)
    at org.apache.jasper.compiler.Parser.parseInclude(Parser.java:897)
    at org.apache.jasper.compiler.Parser.parseStandardAction(Parser.java:1220)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1572)
    at org.apache.jasper.compiler.Parser.parseBody(Parser.java:1802)
    at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1069)
    at org.apache.jasper.compiler.Parser.parseCustomTag(Parser.java:1376)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1573)
    at org.apache.jasper.compiler.Parser.parseBody(Parser.java:1802)
    at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1069)
    at org.apache.jasper.compiler.Parser.parseCustomTag(Parser.java:1376)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1573)
    at org.apache.jasper.compiler.Parser.parse(Parser.java:126)
    at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:211)
    at org.apache.jasper.compiler.ParserController.parse(ParserController.java:100)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:155)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:276)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:264)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:672)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:463)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:398)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:301)
    at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069)
    at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Unknown Source)
- ERROR Servlet.service() for servlet action threw exception
</code>```

答:
I had to change this:

<jsp:forward page='redirect.jsp'>
</jsp:forward>
```
<p>to this:</p>
<pre class="lang-html prettyprint-override"><code><jsp:forward page='redirect.jsp'/>
</code>```

Body:
I am using struts1.1. When i redirect to one jsp file, i got the following exception. I cannot figure out where the error is.

org.apache.jasper.JasperException: /jsp/jobcard/JobCardAdd.jsp(908,3) Expecting "jsp:param" standard action with "name" and "value" attributes
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:39)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:405)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:86)
    at org.apache.jasper.compiler.Parser.parseParam(Parser.java:861)
    at org.apache.jasper.compiler.Parser.parseBody(Parser.java:1813)
    at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1069)
    at org.apache.jasper.compiler.Parser.parseInclude(Parser.java:897)
    at org.apache.jasper.compiler.Parser.parseStandardAction(Parser.java:1220)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1572)
    at org.apache.jasper.compiler.Parser.parseBody(Parser.java:1802)
    at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1069)
    at org.apache.jasper.compiler.Parser.parseCustomTag(Parser.java:1376)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1573)
    at org.apache.jasper.compiler.Parser.parseBody(Parser.java:1802)
    at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:1069)
    at org.apache.jasper.compiler.Parser.parseCustomTag(Parser.java:1376)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1573)
    at org.apache.jasper.compiler.Parser.parse(Parser.java:126)
    at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:211)
    at org.apache.jasper.compiler.ParserController.parse(ParserController.java:100)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:155)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:295)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:276)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:264)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:563)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:303)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:672)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:463)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:398)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:301)
    at org.apache.struts.action.RequestProcessor.doForward(RequestProcessor.java:1069)
    at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:525)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
    at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
    at java.lang.Thread.run(Unknown Source)
- ERROR Servlet.service() for servlet action threw exception

Body:
I had to change this:

<jsp:forward page='redirect.jsp'>
</jsp:forward>

to this:

<jsp:forward page='redirect.jsp'/>


问:
C# finding the max value of ints, then outputting the variable name of the maximum
I'm looping through a 2d array, and at the end of each row I need to find the maximum value. There are 6 values in each row so using Math.Max repeating can be long. So is there anything other than Math.Max to use? After that, I don't need to know the value that is ended, instead, I need to know the variable name of the highest value. Any suggestions?

Here's my current code.

```<code>        for(int col = 0; col < geneArrays.GetLength(0); col++)
                    {
                        for(int row = 0; row < geneArrays.GetLength(1); row++)
                        {
                            float G = 0f, Y = 0f, H = 0f, X = 0f, W = 0f;
                            if (geneArrays[col][row] == 'G')
                            {
                                G += 0.6f;
                            }
                            else if (geneArrays[col][row] == 'Y')
                            {
                                Y = +0.6f;
                            }
                            else if (geneArrays[col][row] == 'H')
                            {
                                H = +0.6f;
                            }
                            else if (geneArrays[col][row] == 'X')
                            {
                                X = +0.6f;
                            }
                            else if (geneArrays[col][row] == 'W')
                            {
                                W = +0.6f;
                            }
                            string nameOfVariable = nameof(Math.Max(G,Y);
                        }
                    }
</code>```

I'm clearly using nameof incorrectly, I think the Math.Max is making it error.

答:
Math.Max returns the value of the two input values. You will only know the value of G,Y in this example.
But that makes no sense, considering you have multiple values that then are completely ignored.
I would recommend you add them to a list, and sort them so you can find the top variable:

```<code>class Program
    {
        static void Main(string[] args)
        {
            char[,] dataArray = new char[3, 10];

            //Test data input generation.
            for (int i = 0; i < 10; i++)
            {
                dataArray[0, 0] = 'G';
                dataArray[0, 1] = 'Y';
                dataArray[0, 2] = 'H';
                dataArray[0, 3] = 'X';
                dataArray[0, 4] = 'W';
                dataArray[0, 5] = 'G';
                dataArray[0, 6] = 'G';
                dataArray[0, 7] = 'Y';
                dataArray[0, 8] = 'W';
                dataArray[0, 9] = 'X';
                dataArray[1, 0] = 'G';
                dataArray[1, 1] = 'Y';
                dataArray[1, 2] = 'H';
                dataArray[1, 3] = 'X';
                dataArray[1, 4] = 'W';
                dataArray[1, 5] = 'G';
                dataArray[1, 6] = 'G';
                dataArray[1, 7] = 'Y';
                dataArray[1, 8] = 'W';
                dataArray[1, 9] = 'X';
                dataArray[2, 0] = 'G';
                dataArray[2, 1] = 'Y';
                dataArray[2, 2] = 'H';
                dataArray[2, 3] = 'X';
                dataArray[2, 4] = 'W';
                dataArray[2, 5] = 'G';
                dataArray[2, 6] = 'G';
                dataArray[2, 7] = 'Y';
                dataArray[2, 8] = 'W';
                dataArray[2, 9] = 'X';
            }

            List<List<NameAndValue>> totalList = new List<List<NameAndValue>>();

            for (int j = 0; j < 3; j++)
            {
                List<NameAndValue> geneNameValues = CreateNameAndValueList();
                for (int k = 0; k < 10; k++)
                {
                    switch (dataArray[j, k])
                    {
                        case 'G':
                            {
                                geneNameValues.First(x => x.Name.Equals('G')).Value += 0.6m;
                                break;
                            }
                        case 'Y':
                            {
                                geneNameValues.First(x => x.Name.Equals('Y')).Value += 0.6m;
                                break;
                            }
                        case 'H':
                            {
                                geneNameValues.First(x => x.Name.Equals('H')).Value += 0.6m;
                                break;
                            }
                        case 'X':
                            {
                                geneNameValues.First(x => x.Name.Equals('X')).Value += 0.6m;
                                break;
                            }
                        case 'W':
                            {
                                geneNameValues.First(x => x.Name.Equals('W')).Value += 0.6m;
                                break;
                            }
                    }
                }
                totalList.Add(geneNameValues);
            }
            int listCount = 0;
            foreach (List<NameAndValue> list in totalList)
            {
                list.Sort((x, y) => x.Value.CompareTo(y.Value));
                NameAndValue highestValue = list.Last();
                Console.WriteLine("List-count: " + listCount + " The highest value was: " + highestValue.Name + " with a score of: " + highestValue.Value);
                listCount++;
            }
        }

        public static List<NameAndValue> CreateNameAndValueList()
        {
            NameAndValue item1 = new NameAndValue() { Name = 'G', Value = 0m };
            NameAndValue item2 = new NameAndValue() { Name = 'Y', Value = 0m };
            NameAndValue item3 = new NameAndValue() { Name = 'H', Value = 0m };
            NameAndValue item4 = new NameAndValue() { Name = 'X', Value = 0m };
            NameAndValue item5 = new NameAndValue() { Name = 'W', Value = 0m };

            List<NameAndValue> valueList = new List<NameAndValue>() { item1, item2, item3, item4, item5 };
            return valueList;
        }
    }

    public class NameAndValue
    {
        public decimal Value { get; set; }
        public char Name { get; set; }
    }
</code>```

I suggest you setup a unit test for something like this:

Provide a controlled set of input data, where you are sure what the expected result should be.

Then consider your expected value borders.
Build up a enough samples that you are sure, test will catch any logic errors in it, and then proceed to start optimizing your logic. There is loads to do.

This is something of a re-write I am aware. But it does perform your requested function. Now you just need to change the hardcoded 3,10 values into your foreach system.

but without better input, I can't be arsed to write a realistic implementation.

Also I changed float to decimal C# is just bad at rounding floats. especially in calculations. If you want to see numbers that make sense to the human brain, use Decimal.

Just copy this code into a "namespace" set of {}, and it will execute. And long as the namespace is a console application :)

Body:
I'm looping through a 2d array, and at the end of each row I need to find the maximum value. There are 6 values in each row so using Math.Max repeating can be long. So is there anything other than Math.Max to use? After that, I don't need to know the value that is ended, instead, I need to know the variable name of the highest value. Any suggestions?

Here's my current code.

        for(int col = 0; col < geneArrays.GetLength(0); col++)
                    {
                        for(int row = 0; row < geneArrays.GetLength(1); row++)
                        {
                            float G = 0f, Y = 0f, H = 0f, X = 0f, W = 0f;
                            if (geneArrays[col][row] == 'G')
                            {
                                G += 0.6f;
                            }
                            else if (geneArrays[col][row] == 'Y')
                            {
                                Y = +0.6f;
                            }
                            else if (geneArrays[col][row] == 'H')
                            {
                                H = +0.6f;
                            }
                            else if (geneArrays[col][row] == 'X')
                            {
                                X = +0.6f;
                            }
                            else if (geneArrays[col][row] == 'W')
                            {
                                W = +0.6f;
                            }
                            string nameOfVariable = nameof(Math.Max(G,Y);
                        }
                    }

I'm clearly using nameof incorrectly, I think the Math.Max is making it error.

Body:
Math.Max returns the value of the two input values. You will only know the value of G,Y in this example.
But that makes no sense, considering you have multiple values that then are completely ignored.
I would recommend you add them to a list, and sort them so you can find the top variable:

class Program
    {
        static void Main(string[] args)
        {
            char[,] dataArray = new char[3, 10];

            //Test data input generation.
            for (int i = 0; i < 10; i++)
            {
                dataArray[0, 0] = 'G';
                dataArray[0, 1] = 'Y';
                dataArray[0, 2] = 'H';
                dataArray[0, 3] = 'X';
                dataArray[0, 4] = 'W';
                dataArray[0, 5] = 'G';
                dataArray[0, 6] = 'G';
                dataArray[0, 7] = 'Y';
                dataArray[0, 8] = 'W';
                dataArray[0, 9] = 'X';
                dataArray[1, 0] = 'G';
                dataArray[1, 1] = 'Y';
                dataArray[1, 2] = 'H';
                dataArray[1, 3] = 'X';
                dataArray[1, 4] = 'W';
                dataArray[1, 5] = 'G';
                dataArray[1, 6] = 'G';
                dataArray[1, 7] = 'Y';
                dataArray[1, 8] = 'W';
                dataArray[1, 9] = 'X';
                dataArray[2, 0] = 'G';
                dataArray[2, 1] = 'Y';
                dataArray[2, 2] = 'H';
                dataArray[2, 3] = 'X';
                dataArray[2, 4] = 'W';
                dataArray[2, 5] = 'G';
                dataArray[2, 6] = 'G';
                dataArray[2, 7] = 'Y';
                dataArray[2, 8] = 'W';
                dataArray[2, 9] = 'X';
            }

            List<List<NameAndValue>> totalList = new List<List<NameAndValue>>();

            for (int j = 0; j < 3; j++)
            {
                List<NameAndValue> geneNameValues = CreateNameAndValueList();
                for (int k = 0; k < 10; k++)
                {
                    switch (dataArray[j, k])
                    {
                        case 'G':
                            {
                                geneNameValues.First(x => x.Name.Equals('G')).Value += 0.6m;
                                break;
                            }
                        case 'Y':
                            {
                                geneNameValues.First(x => x.Name.Equals('Y')).Value += 0.6m;
                                break;
                            }
                        case 'H':
                            {
                                geneNameValues.First(x => x.Name.Equals('H')).Value += 0.6m;
                                break;
                            }
                        case 'X':
                            {
                                geneNameValues.First(x => x.Name.Equals('X')).Value += 0.6m;
                                break;
                            }
                        case 'W':
                            {
                                geneNameValues.First(x => x.Name.Equals('W')).Value += 0.6m;
                                break;
                            }
                    }
                }
                totalList.Add(geneNameValues);
            }
            int listCount = 0;
            foreach (List<NameAndValue> list in totalList)
            {
                list.Sort((x, y) => x.Value.CompareTo(y.Value));
                NameAndValue highestValue = list.Last();
                Console.WriteLine("List-count: " + listCount + " The highest value was: " + highestValue.Name + " with a score of: " + highestValue.Value);
                listCount++;
            }
        }

        public static List<NameAndValue> CreateNameAndValueList()
        {
            NameAndValue item1 = new NameAndValue() { Name = 'G', Value = 0m };
            NameAndValue item2 = new NameAndValue() { Name = 'Y', Value = 0m };
            NameAndValue item3 = new NameAndValue() { Name = 'H', Value = 0m };
            NameAndValue item4 = new NameAndValue() { Name = 'X', Value = 0m };
            NameAndValue item5 = new NameAndValue() { Name = 'W', Value = 0m };

            List<NameAndValue> valueList = new List<NameAndValue>() { item1, item2, item3, item4, item5 };
            return valueList;
        }
    }

    public class NameAndValue
    {
        public decimal Value { get; set; }
        public char Name { get; set; }
    }

I suggest you setup a unit test for something like this:

Provide a controlled set of input data, where you are sure what the expected result should be.

Then consider your expected value borders.
Build up a enough samples that you are sure, test will catch any logic errors in it, and then proceed to start optimizing your logic. There is loads to do.

This is something of a re-write I am aware. But it does perform your requested function. Now you just need to change the hardcoded 3,10 values into your foreach system.

but without better input, I can't be arsed to write a realistic implementation.

Also I changed float to decimal C# is just bad at rounding floats. especially in calculations. If you want to see numbers that make sense to the human brain, use Decimal.

Just copy this code into a "namespace" set of {}, and it will execute. And long as the namespace is a console application :)


问:
Spring Boot @GetMapping rule for multiple mapping
I have 3 different method in controller for get requests.

-the 1st one to get a user by id with a path variable:

```<code>@GetMapping(path="/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
</code>```

The 2nd gets a user based on the username parameter:

```<code>public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username)
</code>```

And finally another one to get all users

```<code>public ResponseEntity<List<UserInfoDTO>> getAllUsers()
</code>```

What should be the @GetMapping for the 2nd and 3rd method?

For exemple @GetMapping for all users and @GetMapping(path="/") for a user by username?

Or whatever...

Thanks.

答:
Defining the Mappings purely depends on the context of your application and its usecases.

We can define a context prefixed by users and modified mappings are show in the snippet below and at the time of invocation it can be called like mentioned in the comments,

```<code>@GetMapping(path="/users/")
public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username) {
}
// GET: <protocol>://<hostUrl>/users?username=<username>

@GetMapping(path="/users")
public ResponseEntity<List<UserInfoDTO>> getAllUsers() {
}
// GET: <protocol>://<hostUrl>/users

@GetMapping(path="/users/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
// GET: <protocol>://<hostUrl>/users/<userid>
</code>```

Body:
I have 3 different method in controller for get requests.

-the 1st one to get a user by id with a path variable:

@GetMapping(path="/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)

The 2nd gets a user based on the username parameter:

public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username)

And finally another one to get all users

public ResponseEntity<List<UserInfoDTO>> getAllUsers()

What should be the @GetMapping for the 2nd and 3rd method?

For exemple @GetMapping for all users and @GetMapping(path="/") for a user by username?

Or whatever...

Thanks.

Body:
Defining the Mappings purely depends on the context of your application and its usecases.

We can define a context prefixed by users and modified mappings are show in the snippet below and at the time of invocation it can be called like mentioned in the comments,

@GetMapping(path="/users/")
public ResponseEntity<UserInfoDTO> getUserByUsername(@RequestParam String username) {
}
// GET: <protocol>://<hostUrl>/users?username=<username>

@GetMapping(path="/users")
public ResponseEntity<List<UserInfoDTO>> getAllUsers() {
}
// GET: <protocol>://<hostUrl>/users

@GetMapping(path="/users/{id}")
public ResponseEntity<UserInfoDTO> getUserById(@PathVariable Long id)
// GET: <protocol>://<hostUrl>/users/<userid>


问:
Is there an onSelect event or equivalent for HTML <select>?
I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,

<select onChange="javascript:doSomething();">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>
```

Now, doSomething() only gets triggered when the selection changes.

I want to trigger doSomething() when the user selects any option, possibly the same one again.

I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.

So, is there a way to trigger a function on every select by the user?

Update:

The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!

答:
There are a few things you want to do here to make sure it remembers older values and triggers an onchange event even if the same option is selected again.

The first thing you want is a regular onChange event:

```<code>$("#selectbox").on("change", function(){
    console.log($(this).val());
    doSomething();
});
</code>```

To have the onChange event trigger even when the same option is selected again, you can unset selected option when the dropdown receives focus by setting it to an invalid value. But you also want to store the previously selected value to restore it in case the user does not select any new option:

```<code>prev_select_option = ""; //some kind of global var

$("#selectbox").on("focus", function(){
    prev_select_option = $(this).val(); //store currently selected value
    $(this).val("unknown"); //set to an invalid value
});
</code>```

The above code will allow you to trigger onchange even if the same value is selected. However, if the user clicks outside the select box, you want to restore the previous value. We do it on onBlur:

```<code>$("#selectbox").on("blur", function(){
    if ($(this).val() == null) {
       //because we previously set an invalid value
       //and user did not select any option
        $(this).val(prev_select_option);
    }
});
</code>```

OwnerDisplayName: ePharaoh

Body:
I have an input form that lets me select from multiple options, and do something when the user changes the selection. Eg,

<select onChange="javascript:doSomething();">
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

Now, doSomething() only gets triggered when the selection changes.

I want to trigger doSomething() when the user selects any option, possibly the same one again.

I have tried using an "onClick" handler, but that gets triggered before the user starts the selection process.

So, is there a way to trigger a function on every select by the user?

Update:

The answer suggested by Darryl seemed to work, but it doesn't work consistently. Sometimes the event gets triggered as soon as user clicks the drop-down menu, even before the user has finished the selection process!

LastEditorDisplayName: ePharaoh

Body:
There are a few things you want to do here to make sure it remembers older values and triggers an onchange event even if the same option is selected again.

The first thing you want is a regular onChange event:

$("#selectbox").on("change", function(){
    console.log($(this).val());
    doSomething();
});

To have the onChange event trigger even when the same option is selected again, you can unset selected option when the dropdown receives focus by setting it to an invalid value. But you also want to store the previously selected value to restore it in case the user does not select any new option:

prev_select_option = ""; //some kind of global var

$("#selectbox").on("focus", function(){
    prev_select_option = $(this).val(); //store currently selected value
    $(this).val("unknown"); //set to an invalid value
});

The above code will allow you to trigger onchange even if the same value is selected. However, if the user clicks outside the select box, you want to restore the previous value. We do it on onBlur:

$("#selectbox").on("blur", function(){
    if ($(this).val() == null) {
       //because we previously set an invalid value
       //and user did not select any option
        $(this).val(prev_select_option);
    }
});


答:
Directly set new Date()</p>

```<code>var compareDate = new Date('2020-06-02');
</code>```

Title: Javascript date countdown with custom date

Body:
var timer;

var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));

timer = setInterval(function() {
  timeBetweenDates(compareDate);
}, 1000);

function timeBetweenDates(toDate) {
  var dateEntered = toDate;
  var now = new Date();
  var difference = dateEntered.getTime() - now.getTime();

  if (difference <= 0) {

    // Timer done
    clearInterval(timer);

  } else {

    var seconds = Math.floor(difference / 1000);
    var minutes = Math.floor(seconds / 60);
    var hours = Math.floor(minutes / 60);
    var days = Math.floor(hours / 24);

    hours %= 24;
    minutes %= 60;
    seconds %= 60;

    $("#days").text(days);
    $("#hours").text(hours);
    $("#minutes").text(minutes);
    $("#seconds").text(seconds);
  }
}

body {
  background: #f5f5f5;
}
#timer {
  font-family: Arial, sans-serif;
  font-size: 20px;
  color: #999;
  letter-spacing: -1px;
}
#timer span {
  font-size: 60px;
  color: #333;
  margin: 0 3px 0 15px;
}
#timer span:first-child {
  margin-left: 0;
}

  days
  hours
  minutes
  seconds

Body:
Directly set new Date()

var compareDate = new Date('2020-06-02');


问:
what is error can't acquire context from the given item?
I am Want to Make line Chart with Chart.js in Vue.js
I want to make this chart based on price and date
I have this Html Code :

```<code>     <div class="content">
              <section class="content">
                <div class="row">
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                <canvas ref="myChart" width="532.8" height="250"></canvas>
                </div>
                 </div>
                 </section>
        </div>
     </div>
</code>```

And I get This elements From Server :

```<code>        "sells": [
    {
        "count": "24",
        "price": "966261",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "31",
        "price": "470588",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "8",
        "price": "314518",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "28",
        "price": "576605",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "18",
        "price": "645010",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "26",
        "price": "295104",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "37",
        "price": "303729",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "43",
        "price": "527718",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "35",
        "price": "274219",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "40",
        "price": "471393",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "68",
        "price": "415918",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "3",
        "price": "814208",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "41",
        "price": "839669",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "50",
        "price": "565025",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "21",
        "price": "498100",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "64",
        "price": "458680",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "36",
        "price": "372096",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "61",
        "price": "569098",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "64",
        "price": "519376",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "39",
        "price": "180493",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "39",
        "price": "595028",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "33",
        "price": "55917",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "26",
        "price": "332210",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "34",
        "price": "239726",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "65",
        "price": "984014",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "57",
        "price": "736582",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "57",
        "price": "272335",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "51",
        "price": "235936",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "54",
        "price": "85552",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "64",
        "price": "222069",
        "date": "۹۹/۰۳/۱۰"
    }
],
</code>```

And I set this Result in this.sells and set date of sells in this.dataSet and set price in this.labels.
my controller Page like this :

```<code> import Chart from "chart.js";
 import Axios from  "axios";

  export default{
      data(){
         return {
            labels: [],
            dataSet: []
       }
     },

  methods:{
      setDate() {
        for (let i = 0; i < this.sells.length; i++) {
        this.labels[i] = this.sells[i].date;
        this.dataSet[i] = this.sells[i].price;
    }
   this.createChart();

  },
    createChart() {
       var ctx = this.$refs.myChart

        console.log(ctx);//undefined
        new Chart(ctx, {
        type: "line",
        data: {
            labels: this.labels,
            datasets: [
                {
                    label: "2020 Sales",
                    data: this.dataSet,
                    borderColor: "#fff ",
                    borderWidth: "3",
                    hoverBorderColor: "#39ccaa  ",
                    backgroundColor: [
                        "#39cccc ",

                    ],
                    hoverBackgroundColor: [
                        "#f38b4a",
                        "#56d798",
                        "#ff8397",
                        "#6970d5"
                    ]

                }
            ]
        }
    });
   }

  };

 }
</code>```

I get sells From server and set to this.sells

```<code>    created(){
       Axios.get('/getHomeItem').then(response => {

        if (response.status == 200) {

               this.sells = response.data.sells;

               this.setDate();

           }
        }).catch(error => {
           if (error.response) {
           alert("مشکلی پیش آمده لطفا بعدا تلاش کنید");
        }
    });

 }
</code>```

When i run this Code i get this Error :

can't acquire context from the given item

And When I Want get console.log From this.$refs.myChart I get :

undefined

I don't know where I went wrong ?

Can anyone help?

答:
Please note that in Vue.js, you can access this.$refs.uniqueName only after the instance has been mounted.

Therefore, the code responsible for fetching the data and creating the chart should be moved from lifecycle method created to method mounted.

```<code>mounted() {
  Axios.get('/getHomeItem').then(response => {
    ...
    this.sells = response.data.sells;
    this.setDate();
    ...
  });
};
</code>```

UPDATE

Additionally to this, you should define an id on your canvas instead of ref.

```<code><canvas id="myChart" width="532.8" height="250"></canvas>
</code>```

Then you won't need var ctx = this.$refs.myChart. The chart can then be created by simply providing the canvas id instead of the rendering context.

```<code>new Chart('myChart', {...
</code>```

Body:
I am Want to Make line Chart with Chart.js in Vue.js
I want to make this chart based on price and date
I have this Html Code :

                <canvas ref="myChart" width="532.8" height="250"></canvas>

And I get This elements From Server :

        "sells": [
    {
        "count": "24",
        "price": "966261",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "31",
        "price": "470588",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "8",
        "price": "314518",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "28",
        "price": "576605",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "18",
        "price": "645010",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "26",
        "price": "295104",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "37",
        "price": "303729",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "43",
        "price": "527718",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "35",
        "price": "274219",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "40",
        "price": "471393",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "68",
        "price": "415918",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "3",
        "price": "814208",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "41",
        "price": "839669",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "50",
        "price": "565025",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "21",
        "price": "498100",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "64",
        "price": "458680",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "36",
        "price": "372096",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "61",
        "price": "569098",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "64",
        "price": "519376",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "39",
        "price": "180493",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "39",
        "price": "595028",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "33",
        "price": "55917",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "26",
        "price": "332210",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "34",
        "price": "239726",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "65",
        "price": "984014",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "57",
        "price": "736582",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "57",
        "price": "272335",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "51",
        "price": "235936",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "54",
        "price": "85552",
        "date": "۹۹/۰۳/۱۰"
    },
    {
        "count": "64",
        "price": "222069",
        "date": "۹۹/۰۳/۱۰"
    }
],

And I set this Result in this.sells and set date of sells in this.dataSet and set price in this.labels.
my controller Page like this :

 import Chart from "chart.js";
 import Axios from  "axios";

  export default{
      data(){
         return {
            labels: [],
            dataSet: []
       }
     },

  methods:{
      setDate() {
        for (let i = 0; i < this.sells.length; i++) {
        this.labels[i] = this.sells[i].date;
        this.dataSet[i] = this.sells[i].price;
    }
   this.createChart();

  },
    createChart() {
       var ctx = this.$refs.myChart

        console.log(ctx);//undefined
        new Chart(ctx, {
        type: "line",
        data: {
            labels: this.labels,
            datasets: [
                {
                    label: "2020 Sales",
                    data: this.dataSet,
                    borderColor: "#fff ",
                    borderWidth: "3",
                    hoverBorderColor: "#39ccaa  ",
                    backgroundColor: [
                        "#39cccc ",

                    ],
                    hoverBackgroundColor: [
                        "#f38b4a",
                        "#56d798",
                        "#ff8397",
                        "#6970d5"
                    ]

                }
            ]
        }
    });
   }

  };

 }

I get sells From server and set to this.sells

    created(){
       Axios.get('/getHomeItem').then(response => {

        if (response.status == 200) {

               this.sells = response.data.sells;

               this.setDate();

           }
        }).catch(error => {
           if (error.response) {
           alert("مشکلی پیش آمده لطفا بعدا تلاش کنید");
        }
    });

 }

When i run this Code i get this Error :

can't acquire context from the given item

And When I Want get console.log From this.$refs.myChart I get :

undefined

I don't know where I went wrong ?

Can anyone help?

Body:
Please note that in Vue.js, you can access this.$refs.uniqueName only after the instance has been mounted.

Therefore, the code responsible for fetching the data and creating the chart should be moved from lifecycle method created to method mounted.

mounted() {
  Axios.get('/getHomeItem').then(response => {
    ...
    this.sells = response.data.sells;
    this.setDate();
    ...
  });
};

UPDATE

Additionally to this, you should define an id on your canvas instead of ref.

<canvas id="myChart" width="532.8" height="250"></canvas>

Then you won't need var ctx = this.$refs.myChart. The chart can then be created by simply providing the canvas id instead of the rendering context.

new Chart('myChart', {...


问:
PHP Shell_Exec webpage issue
created a webpage button to launch a stress test to backend server via PHP.  Button executes script and then I get a timeout issue.  I am assuming that webpage is waiting for output, but the script will run for 2-5 minutes.  I am wanting it to run and either redirect to same page or run stress with no output etc.  I have tried a redirect but didn't work, I assume still waiting for the output before the redirect.</p>

```<code><?php
#run stress script
$output = shell_exec('stress --cpu 4 --timeout 120 2>&1');
echo "```$output```";
?>
</code>```

答:
You must run this task in background. Your output will be saved into output.txt

```<code>shell_exec("stress --cpu 4 --timeout 120 > output.txt &");
</code>```

Title: PHP Shell_Exec webpage issue

Body:
created a webpage button to launch a stress test to backend server via PHP.  Button executes script and then I get a timeout issue.  I am assuming that webpage is waiting for output, but the script will run for 2-5 minutes.  I am wanting it to run and either redirect to same page or run stress with no output etc.  I have tried a redirect but didn't work, I assume still waiting for the output before the redirect.

<?php
#run stress script
$output = shell_exec('stress --cpu 4 --timeout 120 2>&1');
echo "
$output
";
?>

Body:
You must run this task in background. Your output will be saved into output.txt

shell_exec("stress --cpu 4 --timeout 120 > output.txt &");


问:
How to make a loading animation in Console Application written in JavaScript or NodeJs?
How to make a loading animation in Console Application written in JavaScript or NodeJs?

Example animation or other animation.

```<code>1. --
2. \
3. |
4. /
5. --
</code>```

答:
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds) at each 250 ms the value in the p array is printed on the console. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. setInterval is used as a loop here. Using the clearInterval, the loop is breaked after 5000 ms using setTimeout.</p>

```<code>const P = ['\\', '|', '/', '-'];
let x = 0;
const loader = setInterval(() => {
  process.stdout.write(`\r${P[x++]}`);
  x %= P.length;
}, 250);

setTimeout(() => {
  clearInterval(loader);
}, 5000);
</code>```

Body:
How to make a loading animation in Console Application written in JavaScript or NodeJs?

Example animation or other animation.

1. --
2. \
3. |
4. /
5. --

Body:
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds) at each 250 ms the value in the p array is printed on the console. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. setInterval is used as a loop here. Using the clearInterval, the loop is breaked after 5000 ms using setTimeout.

const P = ['\\', '|', '/', '-'];
let x = 0;
const loader = setInterval(() => {
  process.stdout.write(`\r${P[x++]}`);
  x %= P.length;
}, 250);

setTimeout(() => {
  clearInterval(loader);
}, 5000);