问:
How to prevent react being refresh after receiving response from server side when form being submitted
Am having issues with reactjs and nodejs, I want to upload image and at the same time save user input into database. I was able to accomplish all these but the problem is if I completely fill the form and hit submit button data will successfully submitted but react page is refreshing and I user e.preventDefault() and  e.stopPropagation() function all still same thing and also I wrap my ___handleSubmit() but onClick={ (e) => { this.___handleSubmit(e)}} and all still same thing.

React Code

```<code>  __handleSubmit = async (e) => {
e.preventDefault();
e.stopPropagation();

const formData = new FormData();
formData.append("collection_title", this.state.collection_title);
formData.append("collection_description",this.state.collection_description);
formData.append("quiz_category", this.state.quiz_category);
formData.append("visibility", this.state.visibility);
formData.append("selectedCover", this.state.selectedCover);
formData.append("User_ID", this.state.user_data.User_ID);

quiz.createQuizCollection(formData, CollectionResponse => {
  if (CollectionResponse)
    if (CollectionResponse && CollectionResponse[0].error) {
      toast.error(`Message: ${CollectionResponse[0].message}`);
    } else {
      toast.success(`Message: ${CollectionResponse[0].message}`);
      this.setState({ Collection_ID: CollectionResponse[0].Collection_ID });
      this.props.history.push(`/create/${CollectionResponse[0].Collection_ID}`);
    }
});
</code>```

};

Node Code

```<code>app.post("/api/create-collection", (req, res) => {

       if (req.files === null) {
       const col_res = {
         message: "Collection cover image can not be empty, Please Upload Cover Image",
         error: true,
         collectionStatus: false,
         nums_row: 0,
         Collection_ID: ''
       };
       return res.status(200).json({ Response: col_res }, 500, 'Content-Type', 'application/json');
   } else {

        const selectedImage = req.files.selectedCover;
        const collection_title_slug = dataValidation.convertToSlug(req.body.collection_title);
        const collection_path = __dirname+"/../client/public/images/"+collection_title_slug;

        if (!fs.existsSync(collection_path)){
            fs.mkdirSync(collection_path);
        }
        selectedImage.mv(`${collection_path}/${selectedImage.name}`,err => {
            if (err) {
                const col_res = {
                    message: "Unable to upload image, Please Try Again",
                    error: true,
                    collectionStatus: false,
                    nums_row: 0,
                    Collection_ID: ""
                };
                return res.status(200).json( { Response: col_res }, 500, "Content-Type", "application/json" );
            } else {
                CollectionModel.CreateCollection(selectedImage.name, req.body, result => {
                    if (!result.error) {
                        return res.status(200).json({ Response: result }, 200, 'Content-Type', 'application/json');
                    } else {
                        return res.status(200).json({ Response: result }, 300, 'Content-Type', 'application/json');
                    }
                });
            }
        });
   }
});
</code>```

Thanks in advance...

答:
this.props.history.push is the reason.

history.push is used to change the current location

Body:
Am having issues with reactjs and nodejs, I want to upload image and at the same time save user input into database. I was able to accomplish all these but the problem is if I completely fill the form and hit submit button data will successfully submitted but react page is refreshing and I user e.preventDefault() and  e.stopPropagation() function all still same thing and also I wrap my ___handleSubmit() but onClick={ (e) => { this.___handleSubmit(e)}} and all still same thing.

React Code

  __handleSubmit = async (e) => {
e.preventDefault();
e.stopPropagation();

const formData = new FormData();
formData.append("collection_title", this.state.collection_title);
formData.append("collection_description",this.state.collection_description);
formData.append("quiz_category", this.state.quiz_category);
formData.append("visibility", this.state.visibility);
formData.append("selectedCover", this.state.selectedCover);
formData.append("User_ID", this.state.user_data.User_ID);

quiz.createQuizCollection(formData, CollectionResponse => {
  if (CollectionResponse)
    if (CollectionResponse && CollectionResponse[0].error) {
      toast.error(`Message: ${CollectionResponse[0].message}`);
    } else {
      toast.success(`Message: ${CollectionResponse[0].message}`);
      this.setState({ Collection_ID: CollectionResponse[0].Collection_ID });
      this.props.history.push(`/create/${CollectionResponse[0].Collection_ID}`);
    }
});

};

Node Code

app.post("/api/create-collection", (req, res) => {

       if (req.files === null) {
       const col_res = {
         message: "Collection cover image can not be empty, Please Upload Cover Image",
         error: true,
         collectionStatus: false,
         nums_row: 0,
         Collection_ID: ''
       };
       return res.status(200).json({ Response: col_res }, 500, 'Content-Type', 'application/json');
   } else {

        const selectedImage = req.files.selectedCover;
        const collection_title_slug = dataValidation.convertToSlug(req.body.collection_title);
        const collection_path = __dirname+"/../client/public/images/"+collection_title_slug;

        if (!fs.existsSync(collection_path)){
            fs.mkdirSync(collection_path);
        }
        selectedImage.mv(`${collection_path}/${selectedImage.name}`,err => {
            if (err) {
                const col_res = {
                    message: "Unable to upload image, Please Try Again",
                    error: true,
                    collectionStatus: false,
                    nums_row: 0,
                    Collection_ID: ""
                };
                return res.status(200).json( { Response: col_res }, 500, "Content-Type", "application/json" );
            } else {
                CollectionModel.CreateCollection(selectedImage.name, req.body, result => {
                    if (!result.error) {
                        return res.status(200).json({ Response: result }, 200, 'Content-Type', 'application/json');
                    } else {
                        return res.status(200).json({ Response: result }, 300, 'Content-Type', 'application/json');
                    }
                });
            }
        });
   }
});

Thanks in advance...


来源: stackexchange

问:
how to simplify an array of arrays with single object attribute
I have the following data structure:

```<code>$campaigns =
Array
(
[0] => Array
    (
        [subject] => cca-cpg
    )

[1] => Array
    (
        [subject] => cleanup-cpg
    )

[2] => Array
    (
        [subject] => gas-cpg
    )

[3] => Array
    (
        [subject] => pollinators-cpg
    )

)
</code>```

what I would like to end up with is:

```<code>$campaigns = ['cca-cpg','clean_up-cpg','gas-cpg','pollinators-cpg'];

this will work:
$newCampaigns=[];
for($i=0;$i<count($campaigns);$i++){
   array_push($newCampaigns,$campaigns[$i]['subject'];
}
</code>```

but I was wondering if there's a better way to do this.  The data is coming directly from a mysql database

答:
There's array_column() function for you:

$newCampaigns = array_column($campaigns, 'subject');
```

Source: https://www.php.net/manual/en/function.array-column.php

ContentLicense: CC BY-SA 4.0

Body:
I have the following data structure:

$campaigns =
Array
(
[0] => Array
    (
        [subject] => cca-cpg
    )

[1] => Array
    (
        [subject] => cleanup-cpg
    )

[2] => Array
    (
        [subject] => gas-cpg
    )

[3] => Array
    (
        [subject] => pollinators-cpg
    )

)

what I would like to end up with is:

$campaigns = ['cca-cpg','clean_up-cpg','gas-cpg','pollinators-cpg'];

this will work:
$newCampaigns=[];
for($i=0;$i<count($campaigns);$i++){
   array_push($newCampaigns,$campaigns[$i]['subject'];
}

but I was wondering if there's a better way to do this.  The data is coming directly from a mysql database

Body:
There's array_column() function for you:

$newCampaigns = array_column($campaigns, 'subject');

Source: https://www.php.net/manual/en/function.array-column.php


问:
How to use IMediator (MediatR) via dependency injection in Umbraco 7 controller with AutoFac?
I have set up dependency injection with Autofac for my umbracp 7.15.3 app based on this example: https://gosudev.com/blog/software-development/umbraco-cms/umbraco-web-api-and-mvc-dependency-injection-with-autofac/

The example works well with the sample controller the same like here: https://github.com/gosudev/UmbracoCMSDIMixedMode/blob/master/src/UmbracoCMSDIMixedMode/UmbracoCMSDIMixedMode.Web/Controllers/Api/SampleWebApiController.cs

I need to use other services and am trying to use IMediator (MediatR) so I modified the above controller to:

```<code>public class SampleWebApiController : UmbracoApiController
{
    private readonly IMediator _mediator;
    private readonly ISampleService _sampleService;

    public SampleWebApiController(ISampleService sampleService, IMediator mediator)
    {
        _sampleService = sampleService;
    }

    //http://localhost:60580/umbraco/api/SampleWebApi/Get
    [System.Web.Http.HttpGet]
    public JsonResult Get()
    {
        return new JsonResult() { Data = new { items = _sampleService.GetItems() }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}
</code>```

and WebModule (https://github.com/gosudev/UmbracoCMSDIMixedMode/blob/master/src/UmbracoCMSDIMixedMode/UmbracoCMSDIMixedMode.Web/WebModule.cs) to:

```<code>    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<SampleService>().As<ISampleService>();
        builder.RegisterType<Mediator>().As<IMediator>();

        builder.Register(c => UmbracoContext.Current).AsSelf();
    }
</code>```

At this point the controller stops working and I am getting an error message:

```<code>{
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred when trying to create a controller of type 'SampleWebApiController'. Make sure that the controller has a parameterless public constructor.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "An exception was thrown while activating MyDomain.Controllers.SampleWebApiController -> MediatR.Mediator.",
    "ExceptionType": "Autofac.Core.DependencyResolutionException",
    "StackTrace": "   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget)\r\n   at Autofac.Core.Resolving.InstanceLookup.Execute()\r\n   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)\r\n   at Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest request)\r\n   at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(ResolveRequest request)\r\n   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)\r\n   at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)\r\n   at Autofac.Integration.WebApi.AutofacWebApiDependencyScope.GetService(Type serviceType) in C:\\projects\\autofac-webapi\\src\\Autofac.Integration.WebApi\\AutofacWebApiDependencyScope.cs:line 76\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)",
    "InnerException": {
      "Message": "An error has occurred.",
      "ExceptionMessage": "None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MediatR.Mediator' can be invoked with the available services and parameters:\r\nCannot resolve parameter 'Microsoft.Practices.ServiceLocation.ServiceLocatorProvider serviceLocatorProvider' of constructor 'Void .ctor(Microsoft.Practices.ServiceLocation.ServiceLocatorProvider)'.",
      "ExceptionType": "Autofac.Core.DependencyResolutionException",
      "StackTrace": "   at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(ConstructorInfo[] availableConstructors, IComponentContext context, IEnumerable`1 parameters)\r\n   at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)\r\n   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget)"
    }
  }
}
</code>```

Why is it wrong and how to inject another service into this and potentially other controller?

答:
I have installed MediatR.Extensions.Autofac.DependencyInjection and changed this line:

```<code>builder.RegisterType<Mediator>().As<IMediator>();
</code>```

to

```<code>builder.AddMediatR(this.GetType().Assembly);
</code>```

so the configuration is:

```<code>protected override void Load(ContainerBuilder builder)
{
    builder.RegisterType<SampleService>().As<ISampleService>();
    builder.AddMediatR(this.GetType().Assembly); //builder.RegisterType<Mediator>().As<IMediator>();

    builder.Register(c => UmbracoContext.Current).AsSelf();
}
</code>```

Body:
I have set up dependency injection with Autofac for my umbracp 7.15.3 app based on this example: https://gosudev.com/blog/software-development/umbraco-cms/umbraco-web-api-and-mvc-dependency-injection-with-autofac/

The example works well with the sample controller the same like here: https://github.com/gosudev/UmbracoCMSDIMixedMode/blob/master/src/UmbracoCMSDIMixedMode/UmbracoCMSDIMixedMode.Web/Controllers/Api/SampleWebApiController.cs

I need to use other services and am trying to use IMediator (MediatR) so I modified the above controller to:

public class SampleWebApiController : UmbracoApiController
{
    private readonly IMediator _mediator;
    private readonly ISampleService _sampleService;

    public SampleWebApiController(ISampleService sampleService, IMediator mediator)
    {
        _sampleService = sampleService;
    }

    //http://localhost:60580/umbraco/api/SampleWebApi/Get
    [System.Web.Http.HttpGet]
    public JsonResult Get()
    {
        return new JsonResult() { Data = new { items = _sampleService.GetItems() }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }
}

and WebModule (https://github.com/gosudev/UmbracoCMSDIMixedMode/blob/master/src/UmbracoCMSDIMixedMode/UmbracoCMSDIMixedMode.Web/WebModule.cs) to:

    protected override void Load(ContainerBuilder builder)
    {
        builder.RegisterType<SampleService>().As<ISampleService>();
        builder.RegisterType<Mediator>().As<IMediator>();

        builder.Register(c => UmbracoContext.Current).AsSelf();
    }

At this point the controller stops working and I am getting an error message:

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "An error occurred when trying to create a controller of type 'SampleWebApiController'. Make sure that the controller has a parameterless public constructor.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": "   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n   at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()",
  "InnerException": {
    "Message": "An error has occurred.",
    "ExceptionMessage": "An exception was thrown while activating MyDomain.Controllers.SampleWebApiController -> MediatR.Mediator.",
    "ExceptionType": "Autofac.Core.DependencyResolutionException",
    "StackTrace": "   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget)\r\n   at Autofac.Core.Resolving.InstanceLookup.Execute()\r\n   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, ResolveRequest request)\r\n   at Autofac.Core.Resolving.ResolveOperation.Execute(ResolveRequest request)\r\n   at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(ResolveRequest request)\r\n   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance)\r\n   at Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters)\r\n   at Autofac.Integration.WebApi.AutofacWebApiDependencyScope.GetService(Type serviceType) in C:\\projects\\autofac-webapi\\src\\Autofac.Integration.WebApi\\AutofacWebApiDependencyScope.cs:line 76\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)",
    "InnerException": {
      "Message": "An error has occurred.",
      "ExceptionMessage": "None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'MediatR.Mediator' can be invoked with the available services and parameters:\r\nCannot resolve parameter 'Microsoft.Practices.ServiceLocation.ServiceLocatorProvider serviceLocatorProvider' of constructor 'Void .ctor(Microsoft.Practices.ServiceLocation.ServiceLocatorProvider)'.",
      "ExceptionType": "Autofac.Core.DependencyResolutionException",
      "StackTrace": "   at Autofac.Core.Activators.Reflection.ReflectionActivator.GetValidConstructorBindings(ConstructorInfo[] availableConstructors, IComponentContext context, IEnumerable`1 parameters)\r\n   at Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters)\r\n   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget)"
    }
  }
}

Why is it wrong and how to inject another service into this and potentially other controller?

Body:
I have installed MediatR.Extensions.Autofac.DependencyInjection and changed this line:

builder.RegisterType<Mediator>().As<IMediator>();

to

builder.AddMediatR(this.GetType().Assembly);

so the configuration is:

protected override void Load(ContainerBuilder builder)
{
    builder.RegisterType<SampleService>().As<ISampleService>();
    builder.AddMediatR(this.GetType().Assembly); //builder.RegisterType<Mediator>().As<IMediator>();

    builder.Register(c => UmbracoContext.Current).AsSelf();
}


问:
Store heroku pg backup on own S3 bucket
Heroku offers automatic and scheduled backups of your PG database.
https://devcenter.heroku.com/articles/heroku-postgres-data-safety-and-continuous-protection

GBackups will launch a dedicated dyno to take a dump of your database
  and upload it to S3

Simple question: Is it possible to upload a scheduled PG backup to one's OWN S3 Bucket? Simply to have control over the backup files and to not be limited in Storage space. Researching this topic did not provide me with an answer if this is possible.

答:
You can do it by using Heroku scheduler and a bash script.

```<code># Set the script to fail fast if there
# is an error or a missing variable

set -eu
set -o pipefail

#!/bin/sh

# Download the latest backup from
# Heroku and gzip it

heroku pg:backups:download --output=/tmp/pg_backup.dump --app $APP_NAME
gzip /tmp/pg_backup.dump

# Encrypt the gzipped backup file
# using GPG passphrase

gpg --yes --batch --passphrase=$PG_BACKUP_PASSWORD -c /tmp/pg_backup.dump.gz

# Remove the plaintext backup file

rm /tmp/pg_backup.dump.gz

# Generate backup filename based
# on the current date

BACKUP_FILE_NAME="heroku-backup-$(date '+%Y-%m-%d_%H.%M').gpg"

# Upload the file to S3 using
# AWS CLI

aws s3 cp /tmp/pg_backup.dump.gz.gpg "s3://${S3_BUCKET_NAME}/${BACKUP_FILE_NAME}"

# Remove the encrypted backup file

rm /tmp/pg_backup.dump.gz.gpg
</code>```

You can check out this tutorial for detailed step by step explanation.

ContentLicense: CC BY-SA 3.0

Title: Store heroku pg backup on own S3 bucket

Body:
You can do it by using Heroku scheduler and a bash script.

# Set the script to fail fast if there
# is an error or a missing variable

set -eu
set -o pipefail

#!/bin/sh

# Download the latest backup from
# Heroku and gzip it

heroku pg:backups:download --output=/tmp/pg_backup.dump --app $APP_NAME
gzip /tmp/pg_backup.dump

# Encrypt the gzipped backup file
# using GPG passphrase

gpg --yes --batch --passphrase=$PG_BACKUP_PASSWORD -c /tmp/pg_backup.dump.gz

# Remove the plaintext backup file

rm /tmp/pg_backup.dump.gz

# Generate backup filename based
# on the current date

BACKUP_FILE_NAME="heroku-backup-$(date '+%Y-%m-%d_%H.%M').gpg"

# Upload the file to S3 using
# AWS CLI

aws s3 cp /tmp/pg_backup.dump.gz.gpg "s3://${S3_BUCKET_NAME}/${BACKUP_FILE_NAME}"

# Remove the encrypted backup file

rm /tmp/pg_backup.dump.gz.gpg

You can check out this tutorial for detailed step by step explanation.


问:
Make Right Answers Green and Wrong Answers Red for JS Quiz
I have a quiz system that is created in JS. I am using input elements to display each quiz option. I am trying to make it so when you click submit, it will loop through each input element and set the styling of the input text to green if it is a correct answer and red if it an incorrect answer. I am having trouble actually getting the text that is next to the input value however.

Below is a picture of the quiz:
https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899

HTML:

```<code><!DOCTYPE html>
<html>
<head>

<link href ="style.css" rel ="stylesheet">
<!-- <link href="https://fonts.googleapis.com/css?family=OpenSans" rel="stylesheet"> -->
<script src = "main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>
<h1>Chapter 1 Quiz</h1>

<form id = "quiz" name = "quiz">
<p class = "questions">What is the capital of Rhode Island?</p>
<input id = "textbox" type = "text" name = "question1">

<p class = "questions">What is the capital of Connecticut?</p>
<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford<br>

<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford<br>

<p class = "questions">What is the capital of New York?</p>
<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany<br>
<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's<br>

<input id = "button" type = "button" value = "Finish" onclick = "check();">
</form>

<div id = "after_submit">
<p id = "number_correct"></p>
<p id = "message"></p>
</div>
</html>

</body>

</code>```

JAVASCRIPT:

```<code>
function check(){

    var question1 = document.quiz.question1.value;
    var question2 = document.quiz.question2.value;
    var question3 = document.quiz.question3.value;
    var correct = 0;
    var total_questions = 3;

    if (question1 == "Providence") {
        correct++;
}
    if (question2 == "Hartford") {
        correct++;
}
    if (question3 == "Albany") {
        correct++;
    }

    var score;

    if (correct == 0) {
        score = 2;
    }

    if (correct > 0 && correct < total_questions) {
        score = 1;
    }

    if (correct == total_questions) {
        score = 0;
    }

    $( "input" ).each(function( index ) {
        console.log( index + ": " + $( this ).val() );
        // CHANGE THE STYLING HERE. VAL DOES NOT GET THE TEXT OF INPUT AND NIETHER DOES .text()
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }

</code>```

I was thinking I could store the correct answers in the array and if the input has the value then change the styling of the text to green otherwise change it to red.

答:
hi that is be done by just adding one else condition

style

```<code>.mystyle{
    border-color: red;
}

if (question2 == "Hartford") {
    correct++;
}
else{
var element = document.getElementById("textbox");
 element.classList.add("mystyle");
}
</code>```

check my fiddle here
click

Body:
I have a quiz system that is created in JS. I am using input elements to display each quiz option. I am trying to make it so when you click submit, it will loop through each input element and set the styling of the input text to green if it is a correct answer and red if it an incorrect answer. I am having trouble actually getting the text that is next to the input value however.

Below is a picture of the quiz:
https://gyazo.com/1ba5245de2c5c6f96bd728e31aeb0899

HTML:

<!DOCTYPE html>

<link href ="style.css" rel ="stylesheet">

Chapter 1 Quiz

<form id = "quiz" name = "quiz">

What is the capital of Rhode Island?

<input id = "textbox" type = "text" name = "question1">

What is the capital of Connecticut?

<input type = "radio" id = "mc" name = "question2" value = "Hartford"> Hartford

<input type = "radio" id = "mc" name = "question2" value = "Heartford"> Heartford

What is the capital of New York?

<input type = "radio" id = "mc" name = "question3" value = "Albany"> Albany

<input type = "radio" id = "mc" name = "question3" value = "All Benny's"> All Benny's

<input id = "button" type = "button" value = "Finish" onclick = "check();">
</form>

JAVASCRIPT:

function check(){

    var question1 = document.quiz.question1.value;
    var question2 = document.quiz.question2.value;
    var question3 = document.quiz.question3.value;
    var correct = 0;
    var total_questions = 3;

    if (question1 == "Providence") {
        correct++;
}
    if (question2 == "Hartford") {
        correct++;
}
    if (question3 == "Albany") {
        correct++;
    }

    var score;

    if (correct == 0) {
        score = 2;
    }

    if (correct > 0 && correct < total_questions) {
        score = 1;
    }

    if (correct == total_questions) {
        score = 0;
    }

    $( "input" ).each(function( index ) {
        console.log( index + ": " + $( this ).val() );
        // CHANGE THE STYLING HERE. VAL DOES NOT GET THE TEXT OF INPUT AND NIETHER DOES .text()
    });

    document.getElementById("after_submit").style.visibility = "visible";

    document.getElementById("message").innerHTML = "Correct Answers:";
    document.getElementById("number_correct").innerHTML = "Score: " + correct + " / " + total_questions + " (" + Math.trunc((correct / total_questions)*100) + "%)";

    }

I was thinking I could store the correct answers in the array and if the input has the value then change the styling of the text to green otherwise change it to red.

Body:
hi that is be done by just adding one else condition

style

.mystyle{
    border-color: red;
}

if (question2 == "Hartford") {
    correct++;
}
else{
var element = document.getElementById("textbox");
 element.classList.add("mystyle");
}

check my fiddle here
click


问:
Using PWA in ASPNET Webform
I have an old project that use aspnet webform,how can I use PWA in it?
the second is Can I use the PWA in website without ssl?

I used pwa in aspnet core,and I Know how to implement it by using manifest.json file and installing pwa nuget package,however I don't know how to use in my old project

答:
yes you can , there is some steps to make it .
use this site its explained step by step PWA

and you should have ssl for your website.it's not work without ssl.

Title: Using PWA in ASPNET Webform


问:
Shortcut Key using C#
I want to create a simple application that having a send keys (like a shortcut keys). The case is, whenever the created application is inactive window, The system still recognize the pressed keys of the user as long as the system is running.

In short, It is simply like pressing (window + D) that show your desktop immediately whenever on what application/window are you in.

Can anyone help me on how can I do this in C# 2005

答:
Use the following:

```<code>[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
</code>```

and

```<code>[Flags]
public enum ModifierKeys : uint
{
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}

private ModifierKeys _getModifierKeys(bool isAlt, bool isCtrl, bool isShift, bool isWin)
{
    return (isAlt ? ModifierKeys.Alt : 0) |
            (isCtrl ? ModifierKeys.Control : 0) |
            (isShift ? ModifierKeys.Shift : 0) |
            (isWin ? ModifierKeys.Win : 0);
}
</code>```

then, to register your hotkey,

```<code>RegisterHotKey(hWndNotify, id,
                    (uint)_getModifierKeys(_isAlt, _isCtrl, _isShift, _isWin),
                    (uint)_key);
</code>```

in the host hWnd, listen for WM_HOTKEYREADY, then check for matches to your hotkey using

```<code>public bool Matches(ref Message m)
{
    Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
    ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);

    if ((key == Key) &&
        (modifier == Modifier))
    {
        return true;
    }

    return false;
}
</code>```

Title: Shortcut Key using C#

Body:
Use the following:

[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

and

[Flags]
public enum ModifierKeys : uint
{
    Alt = 1,
    Control = 2,
    Shift = 4,
    Win = 8
}

private ModifierKeys _getModifierKeys(bool isAlt, bool isCtrl, bool isShift, bool isWin)
{
    return (isAlt ? ModifierKeys.Alt : 0) |
            (isCtrl ? ModifierKeys.Control : 0) |
            (isShift ? ModifierKeys.Shift : 0) |
            (isWin ? ModifierKeys.Win : 0);
}

then, to register your hotkey,

RegisterHotKey(hWndNotify, id,
                    (uint)_getModifierKeys(_isAlt, _isCtrl, _isShift, _isWin),
                    (uint)_key);

in the host hWnd, listen for WM_HOTKEYREADY, then check for matches to your hotkey using

public bool Matches(ref Message m)
{
    Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
    ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);

    if ((key == Key) &&
        (modifier == Modifier))
    {
        return true;
    }

    return false;
}


问:
Required parameters exception doesn't work in spring boot 2.x
In my spring boot application, I tried to handled the Required parameter exception. This question may be duplicated. But the answers posted don't help me.

My controller

```<code> @GetMapping("/test")
    public ObjectId test(@RequestBody OIdLGroupIds OIdLGroupIds,@RequestParam ObjectId _id){
        return videoService.test();
    }
</code>```

My global exception handler is like following.

```<code>@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
    List<String> details = new ArrayList<>();
    details.add(ex.getLocalizedMessage());
    ErrorResponse error = new ErrorResponse("Server Error", details);
    return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(NotFoundHandler.class)
public final ResponseEntity<Object> handleRecordNotFoundException(NotFoundHandler ex, WebRequest request) {

    Map<String, Object> body = new LinkedHashMap<>();
    body.put("timestamp", LocalDateTime.now());
    body.put("message", "Record not found");

    List<String> details = new ArrayList<>();
    details.add(ex.getLocalizedMessage());
    ErrorResponse error = new ErrorResponse("Record Not Found", details);
    return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers,
        HttpStatus status, WebRequest request) {

    Map<String, Object> body = new LinkedHashMap<>();
    body.put("timestamp", LocalDate.now());
    body.put("status", status.value());

    Set<String> errors = ex.getBindingResult()
            .getFieldErrors()
            .stream()
            .map(x -> x.getDefaultMessage())
            .collect(Collectors.toSet());

    body.put("details", errors);

    return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }
}
</code>```

It doesn't throw any details (Body is blank). But the response status is 400 Bad Request. But when I comment all above codes, it throws default exceptions with body.

I tried this also

```<code>@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String name = ex.getParameterName();
        System.out.println(name);
        logger.error(name + " parameter is missing");

        return super.handleMissingServletRequestParameter(ex, headers, status, request);
    }
</code>```

I have tried in many ways, But no luck. Did I miss anything? Please help me. Thanks in advance.

答:
Empty request body raises HttpMessageNotReadableException.

```<code>@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
        String name = ex.getParameterName();
        System.out.println(name);
        logger.error(name + " parameter is missing");

        return super.handleMissingServletRequestParameter(ex, headers, status, request);
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(
        HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        System.out.println(ex.getMessage());
        logger.error("Request body is missing");

        return super.handleHttpMessageNotReadable(ex,  headers, status, request);
    }

}
</code>```

If you allow empty body, use @RequestBody(required = false).

Body:
In my spring boot application, I tried to handled the Required parameter exception. This question may be duplicated. But the answers posted don't help me.

My controller

 @GetMapping("/test")
    public ObjectId test(@RequestBody OIdLGroupIds OIdLGroupIds,@RequestParam ObjectId _id){
        return videoService.test();
    }

My global exception handler is like following.

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
    List<String> details = new ArrayList<>();
    details.add(ex.getLocalizedMessage());
    ErrorResponse error = new ErrorResponse("Server Error", details);
    return new ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(NotFoundHandler.class)
public final ResponseEntity<Object> handleRecordNotFoundException(NotFoundHandler ex, WebRequest request) {

    Map<String, Object> body = new LinkedHashMap<>();
    body.put("timestamp", LocalDateTime.now());
    body.put("message", "Record not found");

    List<String> details = new ArrayList<>();
    details.add(ex.getLocalizedMessage());
    ErrorResponse error = new ErrorResponse("Record Not Found", details);
    return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
        MethodArgumentNotValidException ex, HttpHeaders headers,
        HttpStatus status, WebRequest request) {

    Map<String, Object> body = new LinkedHashMap<>();
    body.put("timestamp", LocalDate.now());
    body.put("status", status.value());

    Set<String> errors = ex.getBindingResult()
            .getFieldErrors()
            .stream()
            .map(x -> x.getDefaultMessage())
            .collect(Collectors.toSet());

    body.put("details", errors);

    return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
    }
}

It doesn't throw any details (Body is blank). But the response status is 400 Bad Request. But when I comment all above codes, it throws default exceptions with body.

I tried this also

@Override
protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        String name = ex.getParameterName();
        System.out.println(name);
        logger.error(name + " parameter is missing");

        return super.handleMissingServletRequestParameter(ex, headers, status, request);
    }

I have tried in many ways, But no luck. Did I miss anything? Please help me. Thanks in advance.

Body:
Empty request body raises HttpMessageNotReadableException.

@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
        String name = ex.getParameterName();
        System.out.println(name);
        logger.error(name + " parameter is missing");

        return super.handleMissingServletRequestParameter(ex, headers, status, request);
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(
        HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        System.out.println(ex.getMessage());
        logger.error("Request body is missing");

        return super.handleHttpMessageNotReadable(ex,  headers, status, request);
    }

}

If you allow empty body, use @RequestBody(required = false).


问:
Java Generic Array Class Cast Exception
I'm creating a tree map class with the following method for obtaining an array of values:

```<code>@SuppressWarnings("unchecked")
public V[] values() {
    V[] values = (V[]) new Object[size()];
    //System.out.println(values.getClass().getName());
    return values(root, 0, values);
}
</code>```

Now, when I try to access an element in this array I get a Class Cast Exception.

```<code>private AVLTreeMap<Integer, Integer> rankingMap;
...
System.out.println(rankingMap.values()[0]); //Exception on this line
</code>```

yeilds

```<code>Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Integer;
</code>```

Could anyone explain why this is happening and how to fix it?

Thanks.

Edit: here is the entire tree map class

```<code>import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

public class AVLTreeMap<K extends Comparable<K> , V> implements /*Map<K, V>,*/ Serializable{
    private AVLTreeNode<K, V> root;
    private int size;

    public AVLTreeMap(){
        root = null;
        size = 0;
    }

    public int size(){
        return size;
    }

    public void add(K key, V val){
        root = insert(key, val, root);
        size++;
    }

    private AVLTreeNode<K, V> insert(K key, V val, AVLTreeNode<K, V> currNode){
        //AVLTreeNode<K, V> node = new AVLTreeNode<>(key, val);
        if(currNode == null) {
            return new AVLTreeNode<K, V>(key, val);
        }else if(currNode.key.compareTo(key) > 0){
            currNode.left = insert(key, val, currNode.left);
        }else if(currNode.key.compareTo(key) < 0) {
            currNode.right = insert(key, val, currNode.right);
        }else if(currNode.key.compareTo(key) == 0) {
            currNode.addDup(val);
        }
        updateNode(currNode);
        return rebalance(currNode);
    }

    private int balanceFactor(AVLTreeNode<K, V> node) {
        if(node.left == null && node.right == null){
            return 0;
        }else if(node.left == null){
            return -node.right.height;
        }else if(node.right == null){
            return node.left.height;
        }else {
            return node.left.height - node.right.height;
        }
    }

    private AVLTreeNode<K, V> rotateRight(AVLTreeNode<K, V> node){
        AVLTreeNode<K, V> swapNode = node.left;
        node.left = swapNode.right;
        swapNode.right = node;
        updateNode(node);
        updateNode(swapNode);
        return swapNode;
    }

    private AVLTreeNode<K, V> rotateLeft(AVLTreeNode<K, V> node){
        AVLTreeNode<K, V> swapNode = node.right;
        node.right = swapNode.left;
        swapNode.left = node;
        updateNode(node);
        updateNode(swapNode);
        return swapNode;
    }

    private void updateNode(AVLTreeNode<K, V> node){
        if(node.left == null && node.right == null){
            node.height = 1;
            node.size = 1;
        }else if(node.left == null){
            node.height = node.right.height + 1;
            node.size = node.right.size + 1;
        }else if(node.right == null){
            node.height = node.left.height + 1;
            node.size = node.left.size + 1;
        }else {
            node.height = Math.max(node.left.height, node.right.height) + 1;
            node.size = node.left.size + node.right.height + 1;
        }
    }

    private AVLTreeNode<K, V> rebalance(AVLTreeNode<K, V> node) {
        if (balanceFactor(node) < -1) {
            if (balanceFactor(node.right) > 0) {
                node.right = rotateRight(node.right);
            }
            node = rotateLeft(node);
        }
        else if (balanceFactor(node) > 1) {
            if (balanceFactor(node.left) < 0) {
                node.left = rotateLeft(node.left);
            }
            node = rotateRight(node);
        }
        return node;
    }

    public String tree(){
        return tree(root, 0, false);
    }

    private String tree(AVLTreeNode<K, V> node, int tabs, boolean left){
        String s = "\n";
        for (int i = 0; i < tabs - 1; i++) {
            s+="        ";
        }
        s += "----";
        if(node.left == null && node.right == null){
            return s + "|"  + node.toString();
        }else if(node.left == null){
            return s + "        |null" + s + "|" +  node.toString() + "|" + tree(node.right, tabs + 1, false);
        }else if(node.right == null){
            return tree(node.left, tabs + 1, true) + s + "|"+ node.toString() + "|" + s+  "        |null";
        }
        return tree(node.left, tabs + 1, true)  + s + "|"+ node.toString() +"|" + tree(node.right, tabs + 1, false);
    }

    @SuppressWarnings("unchecked")
    public K[] keys() {
        K[] keys = (K[]) new Comparable[size()]; //https://stackoverflow.com/questions/34827626/cannot-be-cast-to-ljava-lang-comparable
        return keys(root, 0, keys);
    }

    private K[] keys(AVLTreeNode<K, V> node, int idx, K[] keys){
        if (node != null) {
            keys = keys(node.left, idx, keys);
            idx += (node.left != null) ? node.left.size : 0;
            keys[idx++] = node.key;
            for (int i = 0; i < node.dups; i++) {
                keys[idx++] = node.key;
            }
            keys = keys(node.right, idx, keys);
        }
        return keys;
    }

    @SuppressWarnings("unchecked")
    public V[] values() {
        V[] values = (V[]) new Object[size()];
        //System.out.println(values.getClass().getName());
        return values(root, 0, values);
    }

    private V[] values(AVLTreeNode<K, V> node, int idx, V[] values){
        if (node != null) {
            values = values(node.left, idx, values);
            idx += (node.left != null) ? node.left.size : 0;
            values[idx++] = node.val;
            addDuplicates(node, values, idx);
            idx += node.dups;
            values = values(node.right, idx, values);
        }
        return values;
    }

    private void addDuplicates(AVLTreeNode<K, V> node, V[] arr, int idx){
        DuplicateNode<V> dup = node.nextDup;
        for (int i = 0; i < node.dups; i++) {
            arr[idx++] = dup.val;
            dup = dup.next;
        }
    }

    private static class AVLTreeNode<K, V>{
        public int height;
        public AVLTreeNode<K, V> left;
        public AVLTreeNode<K, V> right;
        public K key;
        public V val;
        public int dups;
        public int size;
        public DuplicateNode<V> nextDup;

        public AVLTreeNode(K key, V val){
            this.key = key;
            this.val =val;
            left = null;
            right = null;
            size = 1;
            height = 1;
            dups = 0;
            nextDup = null;
        }

        public void addDup(V val){
            DuplicateNode<V> dup = new DuplicateNode<>(val);
            dup.next = nextDup;
            nextDup = dup;
            dups++;
            size++;
        }

        public String toString(){
            return key.toString();
        }
    }

    private static class DuplicateNode<V>{
        public V val;
        public DuplicateNode<V> next;

        public DuplicateNode(V val){
            this.val = val;
            next = null;
        }
    }
}
</code>```

I get an array of the correct values but incorrect types.

答:
You might value to consider why java.util.Collection.toArray has two overloads:

One taking no arguments, returns Object[]

One taking an array argument T[], and returns an array of type T[].

The reason is that it's not possible to construct a generic array. If it were possible, the second method wouldn't be necessary.

You need to take the same (or similar) approach: pass a V[] as a parameter that you can use to construct the array instance:

```<code>public V[] values(V[] array) {
    // Basically, this: http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/share/classes/java/util/AbstractCollection.java#l176
    V[] values = (V[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size());

    //System.out.println(values.getClass().getName());
    return values(root, 0, values);
}
</code>```

There are alternatives. For example, you could pass a IntFunction<V[]> (or a V[], or a V, or a Class<V>):

```<code>public V[] values(IntFunction<V[]> arraySupplier) {
    V[] values = arraySupplier.apply(size());

    //System.out.println(values.getClass().getName());
    return values(root, 0, values);
}
</code>```

If you don't want to pass it to the method, you could pass it to the constructor, and use that in values():

```<code>public AVLTreeMap(IntFunction<V[]> arraySupplier){
  this.arraySupplier = arraySupplier;  // Assign to a field
}

public V[] values() {
    V[] values = arraySupplier.apply(size());
    // ...
}
</code>```

You should choose your approach based on how burdensome it is to construct and use the class.

Title: Java Generic Array Class Cast Exception

Body:
I'm creating a tree map class with the following method for obtaining an array of values:

@SuppressWarnings("unchecked")
public V[] values() {
    V[] values = (V[]) new Object[size()];
    //System.out.println(values.getClass().getName());
    return values(root, 0, values);
}

Now, when I try to access an element in this array I get a Class Cast Exception.

private AVLTreeMap<Integer, Integer> rankingMap;
...
System.out.println(rankingMap.values()[0]); //Exception on this line

yeilds

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Integer;

Could anyone explain why this is happening and how to fix it?

Thanks.

Edit: here is the entire tree map class

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

public class AVLTreeMap<K extends Comparable<K> , V> implements /*Map<K, V>,*/ Serializable{
    private AVLTreeNode<K, V> root;
    private int size;

    public AVLTreeMap(){
        root = null;
        size = 0;
    }

    public int size(){
        return size;
    }

    public void add(K key, V val){
        root = insert(key, val, root);
        size++;
    }

    private AVLTreeNode<K, V> insert(K key, V val, AVLTreeNode<K, V> currNode){
        //AVLTreeNode<K, V> node = new AVLTreeNode<>(key, val);
        if(currNode == null) {
            return new AVLTreeNode<K, V>(key, val);
        }else if(currNode.key.compareTo(key) > 0){
            currNode.left = insert(key, val, currNode.left);
        }else if(currNode.key.compareTo(key) < 0) {
            currNode.right = insert(key, val, currNode.right);
        }else if(currNode.key.compareTo(key) == 0) {
            currNode.addDup(val);
        }
        updateNode(currNode);
        return rebalance(currNode);
    }

    private int balanceFactor(AVLTreeNode<K, V> node) {
        if(node.left == null && node.right == null){
            return 0;
        }else if(node.left == null){
            return -node.right.height;
        }else if(node.right == null){
            return node.left.height;
        }else {
            return node.left.height - node.right.height;
        }
    }

    private AVLTreeNode<K, V> rotateRight(AVLTreeNode<K, V> node){
        AVLTreeNode<K, V> swapNode = node.left;
        node.left = swapNode.right;
        swapNode.right = node;
        updateNode(node);
        updateNode(swapNode);
        return swapNode;
    }

    private AVLTreeNode<K, V> rotateLeft(AVLTreeNode<K, V> node){
        AVLTreeNode<K, V> swapNode = node.right;
        node.right = swapNode.left;
        swapNode.left = node;
        updateNode(node);
        updateNode(swapNode);
        return swapNode;
    }

    private void updateNode(AVLTreeNode<K, V> node){
        if(node.left == null && node.right == null){
            node.height = 1;
            node.size = 1;
        }else if(node.left == null){
            node.height = node.right.height + 1;
            node.size = node.right.size + 1;
        }else if(node.right == null){
            node.height = node.left.height + 1;
            node.size = node.left.size + 1;
        }else {
            node.height = Math.max(node.left.height, node.right.height) + 1;
            node.size = node.left.size + node.right.height + 1;
        }
    }

    private AVLTreeNode<K, V> rebalance(AVLTreeNode<K, V> node) {
        if (balanceFactor(node) < -1) {
            if (balanceFactor(node.right) > 0) {
                node.right = rotateRight(node.right);
            }
            node = rotateLeft(node);
        }
        else if (balanceFactor(node) > 1) {
            if (balanceFactor(node.left) < 0) {
                node.left = rotateLeft(node.left);
            }
            node = rotateRight(node);
        }
        return node;
    }

    public String tree(){
        return tree(root, 0, false);
    }

    private String tree(AVLTreeNode<K, V> node, int tabs, boolean left){
        String s = "\n";
        for (int i = 0; i < tabs - 1; i++) {
            s+="        ";
        }
        s += "----";
        if(node.left == null && node.right == null){
            return s + "|"  + node.toString();
        }else if(node.left == null){
            return s + "        |null" + s + "|" +  node.toString() + "|" + tree(node.right, tabs + 1, false);
        }else if(node.right == null){
            return tree(node.left, tabs + 1, true) + s + "|"+ node.toString() + "|" + s+  "        |null";
        }
        return tree(node.left, tabs + 1, true)  + s + "|"+ node.toString() +"|" + tree(node.right, tabs + 1, false);
    }

    @SuppressWarnings("unchecked")
    public K[] keys() {
        K[] keys = (K[]) new Comparable[size()]; //https://stackoverflow.com/questions/34827626/cannot-be-cast-to-ljava-lang-comparable
        return keys(root, 0, keys);
    }

    private K[] keys(AVLTreeNode<K, V> node, int idx, K[] keys){
        if (node != null) {
            keys = keys(node.left, idx, keys);
            idx += (node.left != null) ? node.left.size : 0;
            keys[idx++] = node.key;
            for (int i = 0; i < node.dups; i++) {
                keys[idx++] = node.key;
            }
            keys = keys(node.right, idx, keys);
        }
        return keys;
    }

    @SuppressWarnings("unchecked")
    public V[] values() {
        V[] values = (V[]) new Object[size()];
        //System.out.println(values.getClass().getName());
        return values(root, 0, values);
    }

    private V[] values(AVLTreeNode<K, V> node, int idx, V[] values){
        if (node != null) {
            values = values(node.left, idx, values);
            idx += (node.left != null) ? node.left.size : 0;
            values[idx++] = node.val;
            addDuplicates(node, values, idx);
            idx += node.dups;
            values = values(node.right, idx, values);
        }
        return values;
    }

    private void addDuplicates(AVLTreeNode<K, V> node, V[] arr, int idx){
        DuplicateNode<V> dup = node.nextDup;
        for (int i = 0; i < node.dups; i++) {
            arr[idx++] = dup.val;
            dup = dup.next;
        }
    }

    private static class AVLTreeNode<K, V>{
        public int height;
        public AVLTreeNode<K, V> left;
        public AVLTreeNode<K, V> right;
        public K key;
        public V val;
        public int dups;
        public int size;
        public DuplicateNode<V> nextDup;

        public AVLTreeNode(K key, V val){
            this.key = key;
            this.val =val;
            left = null;
            right = null;
            size = 1;
            height = 1;
            dups = 0;
            nextDup = null;
        }

        public void addDup(V val){
            DuplicateNode<V> dup = new DuplicateNode<>(val);
            dup.next = nextDup;
            nextDup = dup;
            dups++;
            size++;
        }

        public String toString(){
            return key.toString();
        }
    }

    private static class DuplicateNode<V>{
        public V val;
        public DuplicateNode<V> next;

        public DuplicateNode(V val){
            this.val = val;
            next = null;
        }
    }
}

I get an array of the correct values but incorrect types.

Body:
You might value to consider why java.util.Collection.toArray has two overloads:

One taking no arguments, returns Object[]

One taking an array argument T[], and returns an array of type T[].

The reason is that it's not possible to construct a generic array. If it were possible, the second method wouldn't be necessary.

You need to take the same (or similar) approach: pass a V[] as a parameter that you can use to construct the array instance:

public V[] values(V[] array) {
    // Basically, this: http://hg.openjdk.java.net/jdk7/jdk7/jdk/file/9b8c96f96a0f/src/share/classes/java/util/AbstractCollection.java#l176
    V[] values = (V[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size());

    //System.out.println(values.getClass().getName());
    return values(root, 0, values);
}

There are alternatives. For example, you could pass a IntFunction<V[]> (or a V[], or a V, or a Class<V>):

public V[] values(IntFunction<V[]> arraySupplier) {
    V[] values = arraySupplier.apply(size());

    //System.out.println(values.getClass().getName());
    return values(root, 0, values);
}

If you don't want to pass it to the method, you could pass it to the constructor, and use that in values():

public AVLTreeMap(IntFunction<V[]> arraySupplier){
  this.arraySupplier = arraySupplier;  // Assign to a field
}

public V[] values() {
    V[] values = arraySupplier.apply(size());
    // ...
}

You should choose your approach based on how burdensome it is to construct and use the class.


问:
BaseHTTPRequestHandler hangs on self.rfile.read()
I implemented a python server using the BaseHTTPRequestHandler and it, often times, will hang while reading from the socket fileobject. It doesnt seem to matter how many bytes I read. I could read 30k bytes and it wont hang or I could read 7k bytes and it would hang. It is reading a Base64 string encoded image so i understand if it takes a second or two to read but it literally just hangs.

And then sometimes, when I press CTRL-C, it'll unhang and magically read everything. It's really bizarre. Any help will be appreciated. Thanks. Also, this is python2.7.

Code:

```<code>def do_POST(self):
    print self.rfile
    # Processing HTTP POST request data
    content_len = int(self.headers.getheader('content-length'))
    print 'Reading from HTTP header. Size: %s' % (content_len)

    # THIS IS WHERE IT HANGS
    post_body_json = self.rfile.read(content_len)

    print 'Got it. Moving on, now.'
    post_body = json.loads(post_body_json)
    image_data = post_body.get('img_string_b64', 'No Image String')

    print 'Decoding image string.'
    # Processing image data
    image_name = 'image.jpg'
    decoded_str = base64.decodestring(image_data)
    self.write_image_to_system(decoded_str, image_name)

    print 'Getting text translation.'
    opencv_handler = OpenCVHandler()
    # Get translation from OpenCV then play text audio
    text_trans = opencv_handler.get_text_translation_from_image(image_name)
    opencv_handler.play_audio_translation_from_text(text_trans)

    # Responding to the POST requester.
    # text_trans = 'Translated'
    response = text_trans
    self.send_response(200)  # OK
    self.send_header('Content-type', 'text/html')
    self.end_headers()
    self.wfile.write(response)

    return
</code>```

答:
I had the same issue with the call self.rfile.read(length), blocking for AJAX requests in POST.
This was due to an earlier statement :

```<code>form = cgi.FieldStorage(
    fp=self.rfile,
    headers=self.headers,
    environ={'REQUEST_METHOD': 'POST'}
)
</code>```

Once this is removed, it worked.
I hope it helps.

Body:
I implemented a python server using the BaseHTTPRequestHandler and it, often times, will hang while reading from the socket fileobject. It doesnt seem to matter how many bytes I read. I could read 30k bytes and it wont hang or I could read 7k bytes and it would hang. It is reading a Base64 string encoded image so i understand if it takes a second or two to read but it literally just hangs.

And then sometimes, when I press CTRL-C, it'll unhang and magically read everything. It's really bizarre. Any help will be appreciated. Thanks. Also, this is python2.7.

Code:

def do_POST(self):
    print self.rfile
    # Processing HTTP POST request data
    content_len = int(self.headers.getheader('content-length'))
    print 'Reading from HTTP header. Size: %s' % (content_len)

    # THIS IS WHERE IT HANGS
    post_body_json = self.rfile.read(content_len)

    print 'Got it. Moving on, now.'
    post_body = json.loads(post_body_json)
    image_data = post_body.get('img_string_b64', 'No Image String')

    print 'Decoding image string.'
    # Processing image data
    image_name = 'image.jpg'
    decoded_str = base64.decodestring(image_data)
    self.write_image_to_system(decoded_str, image_name)

    print 'Getting text translation.'
    opencv_handler = OpenCVHandler()
    # Get translation from OpenCV then play text audio
    text_trans = opencv_handler.get_text_translation_from_image(image_name)
    opencv_handler.play_audio_translation_from_text(text_trans)

    # Responding to the POST requester.
    # text_trans = 'Translated'
    response = text_trans
    self.send_response(200)  # OK
    self.send_header('Content-type', 'text/html')
    self.end_headers()
    self.wfile.write(response)

    return

Body:
I had the same issue with the call self.rfile.read(length), blocking for AJAX requests in POST.
This was due to an earlier statement :

form = cgi.FieldStorage(
    fp=self.rfile,
    headers=self.headers,
    environ={'REQUEST_METHOD': 'POST'}
)

Once this is removed, it worked.
I hope it helps.


问:
Is there a shortcut to hide the side bar in Visual Studio Code?
It'd be handy if there was a keyboard shortcut for hiding and showing the sidebar. Sublime has cmd+k+b and it's a quick way of gaining some screen real estate when you need it. Anybody know if this exists or if the user can add it manually to VS Code?

答:
No need to edit Settings.json directly

Do the following:

Open the Keyboard Shortcuts by pressing ctrl+k & ctrl+s

Search: "Toggle Activity Bar Visibility"

Enter the keyboard shortcut

Done!

Activity bar visibility in visual studio code


问:
Place default profile image based on gender in django
I need help on selecting a default profile picture depending on the gender of the user..
I have three default images in my media folder that i want to use as defaults, namely "00.png, 01.png, and 02.png".

models.py

GenderChoice = (
    ('others', 'Others'),
    ('male', 'Male'),
    ('female' :'Female')
)

class User(AbstractBaseUser):
    gender = models.CharField(choice=GenderChoice)
    pro_pic = models.ImageField(upload_to ="", default ="00.png")
```

what I want is if a user selects gender="others" then 00.png should be saved as default and if they select male the 01.png should be selected as default..

Please help

答:
This becomes much easier if you think of it as "I want to show a different default based on gender if the user does not have an image uploaded":

from django.templatetags.static import static
class User(AbstractBaseUser):
    gender = models.CharField(choice=GenderChoice)
    pro_pic = models.ImageField(upload_to ="", null=True)
    default_pic_mapping = { 'others': '00.png', 'male': '01.png', 'female': '02.png'}

    def get_profile_pic_url(self):
        if not self.pro_pic:
            return static('img/{}'.format(self.default_pic_mapping[self.gender]))
        return self.pro_pic.url
```

Body:
I need help on selecting a default profile picture depending on the gender of the user..
I have three default images in my media folder that i want to use as defaults, namely "00.png, 01.png, and 02.png".

models.py

GenderChoice = (
    ('others', 'Others'),
    ('male', 'Male'),
    ('female' :'Female')
)

class User(AbstractBaseUser):
    gender = models.CharField(choice=GenderChoice)
    pro_pic = models.ImageField(upload_to ="", default ="00.png")

what I want is if a user selects gender="others" then 00.png should be saved as default and if they select male the 01.png should be selected as default..

Please help


问:
get id attribute of selected items in drop down box
I have many drop down boxes with the name emp .so in the below code i am trying to print the id of the boxes but some how it is printing empty what am i doing wrong here</p>

```<code>  var selected_emp = $('select[name="emp"]');
     selected_emp.children('option:selected').each(function() {
        if($(this).val() != '' && $(this).val() != null)
        {
           alert($(this).attr('id'));
        }
     });
</code>```

答:
It's working for me: http://jsfiddle.net/zdU9K/

Or do you want it to alert when the select box changes?

Body:
I have many drop down boxes with the name emp .so in the below code i am trying to print the id of the boxes but some how it is printing empty what am i doing wrong here

  var selected_emp = $('select[name="emp"]');
     selected_emp.children('option:selected').each(function() {
        if($(this).val() != '' && $(this).val() != null)
        {
           alert($(this).attr('id'));
        }
     });


问:
top command in shell script
I am trying to get first 5 lines of top command through expect script. Im calling this expect script from a shell script along with some other stuff.

top | head -5 gives me below output ie without cpu stats-

top - 09:10:58 up 46 days, 17:03, 12 users,  load average: 0.01, 0.02,
  0.00 Tasks: 138 total,   1 running, 137 sleeping,   0 stopped,   0 zombie

Mem:  16432400k total,  8408096k used,  8024304k free,   609200k
  buffers Swap:  6290736k total,        0k used,  6290736k free,
  6754356k cached

If I run just top command on that remote server I can see there is a 2-3 second delay before the CPU states line is updated, can some one please help me to get all 5 lines with updated cpu states? Below is my expect script -

```<code>#!/usr/bin/expect -f
set user1 abc
set pass1 pass
set timeout 8
match_max 1000
spawn ssh -C -o stricthostkeychecking=no $user1@<ip>
expect "*?assword:*"
send  "$pass3\r"
expect "?xterm*"
send "\r"
send "top | head -5\r"
expect eof
</code>```

答:
```<code>top -b -n 2 -u $(whoami) | grep -A6 -B5 PID |tail -12
</code>```

Adjust below values as per requirement.

grep

  -A$after_lines_count

  -B$before_lines_count

tail -$($after+$before + 1)

tail value should be [ before lines count + after lines count + 1 (PID match line) ]

If you don't want user specific details.

```<code>  top -b -n 2 | grep -A6 -B5 PID |tail -12
</code>```

Note: Number of top iterations are 2 (top -n 2) i.e, it takes 6 sec to display output ( depends on delay set per iteration)

Title: top command in shell script

Body:
I am trying to get first 5 lines of top command through expect script. Im calling this expect script from a shell script along with some other stuff.

top | head -5 gives me below output ie without cpu stats-

top - 09:10:58 up 46 days, 17:03, 12 users,  load average: 0.01, 0.02,
  0.00 Tasks: 138 total,   1 running, 137 sleeping,   0 stopped,   0 zombie

Mem:  16432400k total,  8408096k used,  8024304k free,   609200k
  buffers Swap:  6290736k total,        0k used,  6290736k free,
  6754356k cached

If I run just top command on that remote server I can see there is a 2-3 second delay before the CPU states line is updated, can some one please help me to get all 5 lines with updated cpu states? Below is my expect script -

#!/usr/bin/expect -f
set user1 abc
set pass1 pass
set timeout 8
match_max 1000
spawn ssh -C -o stricthostkeychecking=no $user1@<ip>
expect "*?assword:*"
send  "$pass3\r"
expect "?xterm*"
send "\r"
send "top | head -5\r"
expect eof

Body:
top -b -n 2 -u $(whoami) | grep -A6 -B5 PID |tail -12

Adjust below values as per requirement.

grep

  -A$after_lines_count

  -B$before_lines_count

tail -$($after+$before + 1)

tail value should be [ before lines count + after lines count + 1 (PID match line) ]

If you don't want user specific details.

  top -b -n 2 | grep -A6 -B5 PID |tail -12

Note: Number of top iterations are 2 (top -n 2) i.e, it takes 6 sec to display output ( depends on delay set per iteration)


问:
Infinity loop after componentDidUpdate() in ReactJS
I have React JS app, which updating boostrap grid table with entries from ASP .NET Core Web API.

And I need to update the grid with new entries after inserting. I did that with help of componentDidUpdate() and using refreshList() function there, but I am getting an infinity loop of refreshList() function.

Any thoughts about how to update the grid without that loop?

import React, {Component} from 'react';
import {Table, Container} from 'react-bootstrap';
import {Button, ButtonToolbar} from 'react-bootstrap';

import {AddDepModal} from './AddDepModal';
import {EditDepModal} from './EditDepModal';

export class Department extends Component {

    constructor(props){
        super(props);
        this.state = {deps:[], addModalShow: false, editModalShow: false}
    }

    componentDidMount()
    {
        this.refreshList();
    }
    refreshList()
    {
       fetch("https://localhost:5001/api/departments")
       .then(response=> response.json())
       .then(data=> {
        this.setState({deps:data});
       });
    }

    componentDidUpdate()
    {
        this.refreshList();
    }

    render(){

     const {deps, depid, depname} = this.state;
     let addModalClose = () => this.setState({addModalShow:false})
     let editModalClose = () => this.setState({editModalShow:false})
    return (

            DepartmentID
            DepartmentName
            Options

        {deps.map(dep=>

            {dep.id}
            {dep.name}

                <ButtonToolbar>
                    <Button
                    className ="mr-2" variant ="info"
                    onClick = {() => this.setState({editModalShow:true, depid: dep.id, depname: dep.name})}
                    >
                        Edit
                    </Button>
                    <EditDepModal
                    show = {this.state.editModalShow}
                    onHide = {editModalClose}
                    depid = {depid}
                    depname = {depname}/>
                </ButtonToolbar>

            )}

     <ButtonToolbar>
    <Button variant = "primary" onClick = {() => this.setState({addModalShow: true})}>Add Department</Button>
    <AddDepModal
    show ={this.state.addModalShow}
    onHide ={addModalClose}/>
</ButtonToolbar>

    )
    }
}```

答:
The problem is you are calling refreshList in componentDidMount and componentDidUpdate. As described in the documentation: https://reactjs.org/docs/react-component.html#componentdidupdate

you should at some condition to avoid an infinity loop in componentDidUpdate.


问:
kubectl no matches for kind Service in version apps/v1
I'm new to Kubernetes. I'm making my first ever attempt to deploy an application to Kubernetes and expose it to the public. However, when I try and deploy my configuration, I get this error:

error: unable to recognize "deployment.yml": no matches for kind "Service" in version "apps/v1"

So, let's run through the details.

I'm on Ubuntu 18.04. I'm using MiniKube with VirtualBox as the HyperVisor driver. Here is all the version info:

```<code>MiniKube = v1.11.0
VirtualBox = 6.1.0
Kubectl = Client Version 1.18.3, Server Version 1.18.3
</code>```

The app I'm trying to deploy is a super-simple express.js app that returns Hello World on request.

```<code>const express = require('express');

const app = express();

app.get('/hello', (req, res) => res.send('Hello World'));

app.listen(3000, () => console.log('Running'));
</code>```

I have a build script I've used for deploying express apps to docker before that zips up all the source files. Then I've got my Dockerfile:

```<code>FROM node:12.16.1

WORKDIR /usr/src/app

COPY ./build/TestServer-*.zip ./TestServer.zip
RUN unzip TestServer.zip

RUN yarn

CMD ["yarn", "start"]
</code>```

So now I run some commands. eval $(minikube docker-env) makes me use MiniKube's docker environment so I don't need to deploy this container to the cloud. docker build -t testserver:v1 . builds and tags the container.

Now, let's go to my deployment.yml file:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: testserver
spec:
  replicas: 1
  selector:
    matchLabels:
      app: testserver
  template:
    metadata:
      labels:
        app: testserver
    spec:
      containers:
        - name: testserver
          image: testserver:v1
          ports:
            - containerPort: 3000
          env:
          imagePullPolicy: Never
---
apiVersion: apps/v1
kind: Service
metadata:
  name: testserver
spec:
  selector:
    app: testserver
  ports:
    - port: 80
      targetPort: 3000
  type: LoadBalancer
</code>```

I'm trying to create a deployment with a pod and a service to expose it. I'm sure there are various issues in here, this is the newest part to me and I'm still trying to learn and understand the spec. However, the problem I'm asking for help with occurs when I try to use this config. I run the create command, and get the error.

kubectl create -f deployment.yml

```<code>deployment.apps/testserver created
error: unable to recognize "deployment.yml": no matches for kind "Service" in version "apps/v1"
</code>```

The result of this is I see my app listed as a deployment and as a pod, but the service part has failed. I've been scouring the internet for documentation on why this is happening, but I've got nothing.

答:
A service is of apiVersion: v1 instead of apiVersion: apps/v1 (like a deployment). You can check it in the official docs. You  also need to use a Service of type NodePort (or ClusterIP) if you want to expose your deployment. Type LoadBalancer will not  work  in minikube. This is mostly used in k8s clusters managed in the cloud where a service of type LoadBalancer will create a loadbalancer (like an ALB in AWS).

To check the apigroup of a resource you can use: kubectl api-resources

Body:
I'm new to Kubernetes. I'm making my first ever attempt to deploy an application to Kubernetes and expose it to the public. However, when I try and deploy my configuration, I get this error:

error: unable to recognize "deployment.yml": no matches for kind "Service" in version "apps/v1"

So, let's run through the details.

I'm on Ubuntu 18.04. I'm using MiniKube with VirtualBox as the HyperVisor driver. Here is all the version info:

MiniKube = v1.11.0
VirtualBox = 6.1.0
Kubectl = Client Version 1.18.3, Server Version 1.18.3

The app I'm trying to deploy is a super-simple express.js app that returns Hello World on request.

const express = require('express');

const app = express();

app.get('/hello', (req, res) => res.send('Hello World'));

app.listen(3000, () => console.log('Running'));

I have a build script I've used for deploying express apps to docker before that zips up all the source files. Then I've got my Dockerfile:

FROM node:12.16.1

WORKDIR /usr/src/app

COPY ./build/TestServer-*.zip ./TestServer.zip
RUN unzip TestServer.zip

RUN yarn

CMD ["yarn", "start"]

So now I run some commands. eval $(minikube docker-env) makes me use MiniKube's docker environment so I don't need to deploy this container to the cloud. docker build -t testserver:v1 . builds and tags the container.

Now, let's go to my deployment.yml file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: testserver
spec:
  replicas: 1
  selector:
    matchLabels:
      app: testserver
  template:
    metadata:
      labels:
        app: testserver
    spec:
      containers:
        - name: testserver
          image: testserver:v1
          ports:
            - containerPort: 3000
          env:
          imagePullPolicy: Never
---
apiVersion: apps/v1
kind: Service
metadata:
  name: testserver
spec:
  selector:
    app: testserver
  ports:
    - port: 80
      targetPort: 3000
  type: LoadBalancer

I'm trying to create a deployment with a pod and a service to expose it. I'm sure there are various issues in here, this is the newest part to me and I'm still trying to learn and understand the spec. However, the problem I'm asking for help with occurs when I try to use this config. I run the create command, and get the error.

kubectl create -f deployment.yml

deployment.apps/testserver created
error: unable to recognize "deployment.yml": no matches for kind "Service" in version "apps/v1"

The result of this is I see my app listed as a deployment and as a pod, but the service part has failed. I've been scouring the internet for documentation on why this is happening, but I've got nothing.


问:
Python code which implements voting button option for an outlook mail
I am working on an automation script which should take certain email-ids from an excel/csv sheet and send a mail to these email-ids which should have a voting option. I came across a package pyoutlook but I doubt if i can do any such task.

If not python, i can automate in any other programming language as well.

答:
You can automate Outlook from Python:

```<code>import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional

mail.VotingOptions = "Yes;No"

mail.Send()
</code>```

The MailItem.VotingOptions property sets a string specifying a delimited string containing the voting options for the mail message. This property uses the character specified in the value name, sList, under HKEY_CURRENT_USER\Control Panel\International in the Windows registry, as the delimiter for multiple voting options.

You may find the Send Outlook Email Via Python? page helpful.

Body:
You can automate Outlook from Python:

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional

mail.VotingOptions = "Yes;No"

mail.Send()

The MailItem.VotingOptions property sets a string specifying a delimited string containing the voting options for the mail message. This property uses the character specified in the value name, sList, under HKEY_CURRENT_USER\Control Panel\International in the Windows registry, as the delimiter for multiple voting options.

You may find the Send Outlook Email Via Python? page helpful.


问:
Error after I log in with my Google Account in Google Sheet API
I'm trying to manipulate a Google Sheet through Java, but there's a error after I log in with my Google Account:

```<code>Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at com.esdras.caixaipm.DeskIPM.main(DeskIPM.java:75)
</code>```

In this is my PSVM:

```<code>public static void main(String[] args) throws IOException, GeneralSecurityException {
    sheetsService = getSheetsService();
    String range = "A2:A4";

    ValueRange response = sheetsService.spreadsheets().values()
            .get(SPREADSHEET_ID, range)
            .execute();

    List<List<Object>> values = response.getValues();

    if (values == null || values.isEmpty()){
        System.out.println("No data found!");
    }else{
        for (List row : values) {
            System.out.printf("%s %s %s \n", row.get(1), row.get(2), row.get(3));
        }
    }

}
</code>```

I think the problem is in the for structure, but I can't fix it.

答:
The error I was getting was because of the "row.get()"

I edited the code to this:

```<code>for (List row : values) {
            System.out.println(row.get(0));
        }
</code>```

Instead of:

```<code>for (List row : values) {
            System.out.printf("%s %s %s \n", row.get(1), row.get(2), row.get(3));
        }
</code>```

Thanks... :)

Body:
I'm trying to manipulate a Google Sheet through Java, but there's a error after I log in with my Google Account:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    at java.util.ArrayList.get(ArrayList.java:433)
    at com.esdras.caixaipm.DeskIPM.main(DeskIPM.java:75)

In this is my PSVM:

public static void main(String[] args) throws IOException, GeneralSecurityException {
    sheetsService = getSheetsService();
    String range = "A2:A4";

    ValueRange response = sheetsService.spreadsheets().values()
            .get(SPREADSHEET_ID, range)
            .execute();

    List<List<Object>> values = response.getValues();

    if (values == null || values.isEmpty()){
        System.out.println("No data found!");
    }else{
        for (List row : values) {
            System.out.printf("%s %s %s \n", row.get(1), row.get(2), row.get(3));
        }
    }

}

I think the problem is in the for structure, but I can't fix it.

Body:
The error I was getting was because of the "row.get()"

I edited the code to this:

for (List row : values) {
            System.out.println(row.get(0));
        }

Instead of:

for (List row : values) {
            System.out.printf("%s %s %s \n", row.get(1), row.get(2), row.get(3));
        }

Thanks... :)


问:
prevent closing Foundation modal when clicking outside of the modal
I don't want the modal to go away when I click on the background. I'd like it to keep display until I click the button inside the modal. Here is a codepen link

http://codepen.io/anon/pen/JdNXGd

here is the angular code

```<code>app = angular.module('app', ['ngAnimate']);
app.directive('modal', function() {
  return {
    restrict: 'E',
    scope: {
      show: '='
    },
    replace: true, // Replace with the template below
    transclude: true, // we want to insert custom content inside the directive
    link: function(scope, element, attrs) {
      scope.hideModal = function() {
        scope.show = false;
      };
    },
    template: "<div class='ng-modal' ng-show='show'>"+
                "<div class='reveal-modal' data-options='close_on_background_click:false' ng-show='show'>"+
                  "<div ng-transclude></div>"+
                  "<a class='close-reveal-modal' ng-click='hideModal()'>×</a>"+
                "</div>"+
                "<div class='reveal-modal-bg' ng-click='hideModal()'></div>"+
              "</div>"
  };
});

app.controller('AppCtrl', ['$scope', function($scope) {
  $scope.modalShown = false;
  $scope.toggleModal = function() {
    $scope.modalShown = !$scope.modalShown;
  };
}]);
</code>```

答:
as far as I can tell the answer you've put doesn't work for newer versions of Foundation - the only reference I could find when searching around for backdrop: 'static' was for bootstrap modals. The foundation docs are also pretty unhelpful, having only a passing mention of an options parameter (https://get.foundation/sites/docs/reveal.html#advanced-options) without specifying what the possible options are.

However I dug around in the source code and found these options, here they are in case anybody else is trying to do this: (I'm using foundation-sites 6.4x, with some jQuery)

let $modal = $('.my-modal');

let revealModal = new Foundation.Reveal(
  $modal, {
  closeOnClick: false,
  closeOnEsc:   false
});

revealModal.open();```

Body:
I don't want the modal to go away when I click on the background. I'd like it to keep display until I click the button inside the modal. Here is a codepen link

http://codepen.io/anon/pen/JdNXGd

here is the angular code

app = angular.module('app', ['ngAnimate']);
app.directive('modal', function() {
  return {
    restrict: 'E',
    scope: {
      show: '='
    },
    replace: true, // Replace with the template below
    transclude: true, // we want to insert custom content inside the directive
    link: function(scope, element, attrs) {
      scope.hideModal = function() {
        scope.show = false;
      };
    },
    template: "
"+
                "
"+
                  "

"+
                  "×"+
                "
"+
                "

"+
              "
"
  };
});

app.controller('AppCtrl', ['$scope', function($scope) {
  $scope.modalShown = false;
  $scope.toggleModal = function() {
    $scope.modalShown = !$scope.modalShown;
  };
}]);


问:
Powershell ps1 script runs bat file but CMD screen closes after execution
This is my code:

```<code>set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait

set-location C:\
</code>```

When executed in powershell, the system opens a Command prompt window and executes the bat file without issue. The problem is that the window closes and I cannot see if there was an error if it succeeds.

I want to keep the CMD window open.

I also tried at the end of the bat file:

```<code>:END
cmd /k

</code>```

but no luck.

答:
Thank you mklement0 with your post gave me the solution I wanted. This is how I solved it.

```<code>set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait -NoNewWindow
set-location C:\
</code>```

-NoNewWindow allowed me to run my batch in the same powershell window getting the feedback of the bat file. That way I have errors if any and success status if no errors.

Thanks!

Body:
This is my code:

set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait

set-location C:\

When executed in powershell, the system opens a Command prompt window and executes the bat file without issue. The problem is that the window closes and I cannot see if there was an error if it succeeds.

I want to keep the CMD window open.

I also tried at the end of the bat file:

:END
cmd /k

but no luck.

Body:
Thank you mklement0 with your post gave me the solution I wanted. This is how I solved it.

set-location [PATH]
$A = Start-Process -FilePath .\refresh.bat -Wait -NoNewWindow
set-location C:\

-NoNewWindow allowed me to run my batch in the same powershell window getting the feedback of the bat file. That way I have errors if any and success status if no errors.

Thanks!


问:
OpenQA.Selenium.NoSuchElementException: Unable to locate element error while locating an element on a page using Selenium and C#
I am trying to scrape the text 睡觉 within the page edited out the site

It has the css selector:

```<code>#autocplt_wrap > ul:nth-child(1) > li:nth-child(1) > span:nth-child(1) > a:nth-child(1)
</code>```

And x-Path:

```<code>/html/body/div[2]/div[1]/div[3]/div[2]/div[1]/div/div[1]/div[2]/div/div/ul[1]/li/span/a[1]
</code>```

My code is:

```<code>IWebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
//load webdriver
driver.Manage();
driver.Navigate().GoToUrl("https://dict.naver.com/linedict/zhendict/#/cnen/home");
driver.FindElement(By.ClassName("ac_input")).SendKeys("睡觉" + Keys.Enter);
driver.FindElement(By.CssSelector("#autocplt_wrap > ul:nth-child(1) > li:nth-child(1) > span:nth-child(1) > a:nth-child(1)"));
</code>```

No matter what I try I always get the error:

```<code>Unhandled exception. OpenQA.Selenium.NoSuchElementException: Unable to locate element: #autocplt_wrap > ul:nth-child(1) >
li:nth-child(1) > span:nth-child(1) > a:nth-child(1)
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.By.<>c__DisplayClass29_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)
</code>```

答:
The desired element is a dynamic element so to extract the text 睡觉 you have to induce WebDriverWait for the desired ElementIsVisible() and you can use either of the following Locator Strategies:

CssSelector:

```<code>Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("a.srchword[data-entryid]"))).GetAttribute("innerHTML"));
</code>```

XPath:

```<code>Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[@class='srchword' and @data-entryid]"))).GetAttribute("innerHTML"));
</code>```

Using DotNetSeleniumExtras.WaitHelpers with nuget

CssSelector:

```<code>Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("a.srchword[data-entryid]"))).GetAttribute("innerHTML"));
</code>```

XPath:

```<code>Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//a[@class='srchword' and @data-entryid]"))).GetAttribute("innerHTML"));
</code>```

You can find a relevant discussion in WebDriverWait is not waiting for the element I specify

Reference

You can find a couple of relevant discussions on NoSuchElementException in:

NoSuchElementException, Selenium unable to locate element

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

Body:
I am trying to scrape the text 睡觉 within the page edited out the site

It has the css selector:

#autocplt_wrap > ul:nth-child(1) > li:nth-child(1) > span:nth-child(1) > a:nth-child(1)

And x-Path:

/html/body/div[2]/div[1]/div[3]/div[2]/div[1]/div/div[1]/div[2]/div/div/ul[1]/li/span/a[1]

My code is:

IWebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
//load webdriver
driver.Manage();
driver.Navigate().GoToUrl("https://dict.naver.com/linedict/zhendict/#/cnen/home");
driver.FindElement(By.ClassName("ac_input")).SendKeys("睡觉" + Keys.Enter);
driver.FindElement(By.CssSelector("#autocplt_wrap > ul:nth-child(1) > li:nth-child(1) > span:nth-child(1) > a:nth-child(1)"));

No matter what I try I always get the error:

Unhandled exception. OpenQA.Selenium.NoSuchElementException: Unable to locate element: #autocplt_wrap > ul:nth-child(1) >
li:nth-child(1) > span:nth-child(1) > a:nth-child(1)
   at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
   at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(String mechanism, String value)
   at OpenQA.Selenium.By.<>c__DisplayClass29_0.<CssSelector>b__0(ISearchContext context)
   at OpenQA.Selenium.By.FindElement(ISearchContext context)
   at OpenQA.Selenium.Remote.RemoteWebDriver.FindElement(By by)

Body:
The desired element is a dynamic element so to extract the text 睡觉 you have to induce WebDriverWait for the desired ElementIsVisible() and you can use either of the following Locator Strategies:

CssSelector:

Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("a.srchword[data-entryid]"))).GetAttribute("innerHTML"));

XPath:

Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//a[@class='srchword' and @data-entryid]"))).GetAttribute("innerHTML"));

Using DotNetSeleniumExtras.WaitHelpers with nuget

CssSelector:

Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("a.srchword[data-entryid]"))).GetAttribute("innerHTML"));

XPath:

Console.WriteLine(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.XPath("//a[@class='srchword' and @data-entryid]"))).GetAttribute("innerHTML"));

You can find a relevant discussion in WebDriverWait is not waiting for the element I specify

Reference

You can find a couple of relevant discussions on NoSuchElementException in:

NoSuchElementException, Selenium unable to locate element

Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome


问:
asp.net event handler for table click is called twice
I have a table with some column in a asp.net mvc core project.

My view file looks like this

```<code>    <h1>Items</h1>
<div class="panel-body">
    <table class="table table-bordered table-responsive table-hover">
        <thead>
            <tr>
                <th>Id</th>
                <th>Title</th>

                <th>Rating</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Items)
            {
                <tr onclick="location.href='@(Url.Action("ShowItemDetails", "Item", new {Id = item.FilmId}))'">
                    <td>@item.Id</td>
                    <td>@item.Title</td>

                    <td>@item.Rating</td>
                    <td>@Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>

                </tr>
            }
        </tbody>
    </table>
</div>
</code>```

The problem is that when i click on a row, the controller method ShowItemDetails is called twice(!).
I can not see from the code above why this happens. Also, clicking on Edit or Rate this calls first ShowItemDetails and then immediately  Edit or RateItem method in controller. Any suggestion how this can be solved?

答:
The problem seems to be caused be something i thought was irrelevant

having a null image cause the method to be called twice. Setting it to
 solves this.
Need to add code to check for Model.Image != null
Very strange!!</p>

Body:
I have a table with some column in a asp.net mvc core project.

My view file looks like this

Items

                Id
                Title

                Rating

            @foreach (var item in Model.Items)
            {

                    @item.Id
                    @item.Title

                    @item.Rating
                    @Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id })

            }

The problem is that when i click on a row, the controller method ShowItemDetails is called twice(!).
I can not see from the code above why this happens. Also, clicking on Edit or Rate this calls first ShowItemDetails and then immediately  Edit or RateItem method in controller. Any suggestion how this can be solved?


答:
You're calling this.refreshList(); which does some thing and then set the state. After the state is set, render functions is called and in turn componentDidUpdate is called again, setting the infinite loop. To make it work, compare from the previous props and then call the this.refreshList();  if needed.

```<code>componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.depid !== prevProps.depid) { //Replace `depid` with the props you like to compare changes. If that is changed, then only call
    this.refreshList();
  }
}
</code>```

You may call setState() immediately in componentDidUpdate() but note
  that it must be wrapped in a condition like in the example above, or
  you’ll cause an infinite loop. It would also cause an extra
  re-rendering which, while not visible to the user, can affect the
  component performance. If you’re trying to “mirror” some state to a
  prop coming from above, consider using the prop directly instead. Read
  more about why copying props into state causes bugs.

see the docs: https://reactjs.org/docs/react-component.html#componentdidupdate

Title: Infinity loop after componentDidUpdate() in ReactJS

Body:
I have React JS app, which updating boostrap grid table with entries from ASP .NET Core Web API.

And I need to update the grid with new entries after inserting. I did that with help of componentDidUpdate() and using refreshList() function there, but I am getting an infinity loop of refreshList() function.

Any thoughts about how to update the grid without that loop?

import React, {Component} from 'react';
import {Table, Container} from 'react-bootstrap';
import {Button, ButtonToolbar} from 'react-bootstrap';

import {AddDepModal} from './AddDepModal';
import {EditDepModal} from './EditDepModal';

export class Department extends Component {

    constructor(props){
        super(props);
        this.state = {deps:[], addModalShow: false, editModalShow: false}
    }

    componentDidMount()
    {
        this.refreshList();
    }
    refreshList()
    {
       fetch("https://localhost:5001/api/departments")
       .then(response=> response.json())
       .then(data=> {
        this.setState({deps:data});
       });
    }

    componentDidUpdate()
    {
        this.refreshList();
    }

    render(){

     const {deps, depid, depname} = this.state;
     let addModalClose = () => this.setState({addModalShow:false})
     let editModalClose = () => this.setState({editModalShow:false})
    return (

            DepartmentID
            DepartmentName
            Options

        {deps.map(dep=>

            {dep.id}
            {dep.name}

                <ButtonToolbar>
                    <Button
                    className ="mr-2" variant ="info"
                    onClick = {() => this.setState({editModalShow:true, depid: dep.id, depname: dep.name})}
                    >
                        Edit
                    </Button>
                    <EditDepModal
                    show = {this.state.editModalShow}
                    onHide = {editModalClose}
                    depid = {depid}
                    depname = {depname}/>
                </ButtonToolbar>

            )}

     <ButtonToolbar>
    <Button variant = "primary" onClick = {() => this.setState({addModalShow: true})}>Add Department</Button>
    <AddDepModal
    show ={this.state.addModalShow}
    onHide ={addModalClose}/>
</ButtonToolbar>

    )
    }
}

Body:
You're calling this.refreshList(); which does some thing and then set the state. After the state is set, render functions is called and in turn componentDidUpdate is called again, setting the infinite loop. To make it work, compare from the previous props and then call the this.refreshList();  if needed.

componentDidUpdate(prevProps) {
  // Typical usage (don't forget to compare props):
  if (this.props.depid !== prevProps.depid) { //Replace `depid` with the props you like to compare changes. If that is changed, then only call
    this.refreshList();
  }
}

You may call setState() immediately in componentDidUpdate() but note
  that it must be wrapped in a condition like in the example above, or
  you’ll cause an infinite loop. It would also cause an extra
  re-rendering which, while not visible to the user, can affect the
  component performance. If you’re trying to “mirror” some state to a
  prop coming from above, consider using the prop directly instead. Read
  more about why copying props into state causes bugs.

see the docs: https://reactjs.org/docs/react-component.html#componentdidupdate


问:
InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/index.c6592bb6.ts') is not a valid name
I have a react app that I am trying to convert to use typescript

but I'm getting the following error: InvalidCharacterError: Failed to execute 'createElement' on 'Document': The tag name provided ('/static/media/index.c6592bb6.ts') is not a valid name.

What does this error even mean? It looks like it doesn't like the typescript extension

Any ideas how to fix?

答:
Just in case it hasn't been specified before, I had the same issue with Home document and it was because I used this:

```<code><Route path="/" component="{Home}" />
</code>```

Instead of this

```<code><Route path="/" component={Home} />
</code>```

Note the quote marks. Hope this helps someone.

Body:
Just in case it hasn't been specified before, I had the same issue with Home document and it was because I used this:

<Route path="/" component="{Home}" />

Instead of this

<Route path="/" component={Home} />

Note the quote marks. Hope this helps someone.