问:
JSON format leads to .map is not a function
With the current way strapi outputs a JSON I always get the error .map is not a function. It is a NEXT.JS Frontent. Could it be that this comes from the JSON not being output as an Array?

```<code>import React, { useEffect } from "react";

export default function Home({ posts }) {
  return (
    <div>
      {posts &&
        posts.map((post) => (
          <div key={post.id}>
            <h2>{post.title}</h2>
          </div>
        ))}
    </div>
  );
}

export async function getStaticProps() {
  // get games from the api
  const res = await fetch("http://localhost:1337/api/games");
  const posts = await res.json();
  return {
    props: { posts },
  };
}
</code>```

here I get: TypeError: posts.map is not a function

does anyone has a tip for a JS beginner how to fix that?

the JSON output is the following:

```<code>{"data":[{"id":1,"attributes":{"title":"Guild Wars 2","createdAt":"2022-02-04T20:14:17.254Z","updatedAt":"2022-02-05T10:52:55.696Z","publishedAt":"2022-02-05T10:52:55.693Z","url":"https://www.guildwars2.com","description":"Guild Wars 2 is an online role-playing game with fast-paced action combat, a rich and detailed universe of stories, awe-inspiring landscapes to explore, two challenging player vs. player modes—and no subscription fees!","free":false,"feature_combat":"Fast-paced combat and choose from an arsenal of professions, weapons, and playstyles. Attack on the move, dodge and roll away from enemy blows, and come to your allies' rescue midbattle.","feature_world":"A beautifull designed, rich and detailed universe of stories, awe-inspiring landscapes to explore.","feature_quests":"No questgivers but an exploartion oriented roam around quest system with housands of stories that change based on the actions of players like you.","feature_grouping":"In the open world, you can team up with every player you meet—no grouping required! Also offeres Raids and dungeons for groups.","feature_usp":"Quick, furious matches between small groups of players in organized PvP or join hundreds of other players in the grand battles of World vs. World"}},{"id":2,"attributes":{"title":"Firefly Online","createdAt":"2022-02-05T11:01:39.549Z","updatedAt":"2022-02-05T11:04:40.562Z","publishedAt":"2022-02-05T11:04:40.558Z","url":"www.keepflying.com","description":"\nFACTS\nOS:\nSetting:\nSci-Fi\nGenre:\nRPG\nRelease Year:\n2014\nPayment Model:\nfree to play\nPVP:\nPay for features:\nItem Shop:\nMonthly fee:\nLanguage: ","free":null,"feature_combat":"Seek out adventures","feature_world":"Assume the role of a ship captain – create a crew and customize a ship","feature_quests":"Online role playing game based on Firefly, Joss Whedon’s cult-hit television series Firefly","feature_grouping":"Hire a crew","feature_usp":"Cross-platform player experience across devices"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":2}}}
</code>```

答:
This is because posts is a JSON object and not an array that you can use the map() function with. Instead, you need to give the array to the map() function before you can pull out the titles.

To access the array of the JSON object, you can use posts['data'].

```<code>export default function Home({ posts }) {
  return (
    <div>
      {posts &&
        posts["data"].map((post) => (
          <div key={post.id}>
            <h2>{post.attributes.title}</h2>
          </div>
        ))}
    </div>
  );
}
</code>```

Body:
With the current way strapi outputs a JSON I always get the error .map is not a function. It is a NEXT.JS Frontent. Could it be that this comes from the JSON not being output as an Array?

import React, { useEffect } from "react";

export default function Home({ posts }) {
  return (

      {posts &&
        posts.map((post) => (

{post.title}

        ))}

  );
}

export async function getStaticProps() {
  // get games from the api
  const res = await fetch("http://localhost:1337/api/games");
  const posts = await res.json();
  return {
    props: { posts },
  };
}

here I get: TypeError: posts.map is not a function

does anyone has a tip for a JS beginner how to fix that?

the JSON output is the following:

{"data":[{"id":1,"attributes":{"title":"Guild Wars 2","createdAt":"2022-02-04T20:14:17.254Z","updatedAt":"2022-02-05T10:52:55.696Z","publishedAt":"2022-02-05T10:52:55.693Z","url":"https://www.guildwars2.com","description":"Guild Wars 2 is an online role-playing game with fast-paced action combat, a rich and detailed universe of stories, awe-inspiring landscapes to explore, two challenging player vs. player modes—and no subscription fees!","free":false,"feature_combat":"Fast-paced combat and choose from an arsenal of professions, weapons, and playstyles. Attack on the move, dodge and roll away from enemy blows, and come to your allies' rescue midbattle.","feature_world":"A beautifull designed, rich and detailed universe of stories, awe-inspiring landscapes to explore.","feature_quests":"No questgivers but an exploartion oriented roam around quest system with housands of stories that change based on the actions of players like you.","feature_grouping":"In the open world, you can team up with every player you meet—no grouping required! Also offeres Raids and dungeons for groups.","feature_usp":"Quick, furious matches between small groups of players in organized PvP or join hundreds of other players in the grand battles of World vs. World"}},{"id":2,"attributes":{"title":"Firefly Online","createdAt":"2022-02-05T11:01:39.549Z","updatedAt":"2022-02-05T11:04:40.562Z","publishedAt":"2022-02-05T11:04:40.558Z","url":"www.keepflying.com","description":"\nFACTS\nOS:\nSetting:\nSci-Fi\nGenre:\nRPG\nRelease Year:\n2014\nPayment Model:\nfree to play\nPVP:\nPay for features:\nItem Shop:\nMonthly fee:\nLanguage: ","free":null,"feature_combat":"Seek out adventures","feature_world":"Assume the role of a ship captain – create a crew and customize a ship","feature_quests":"Online role playing game based on Firefly, Joss Whedon’s cult-hit television series Firefly","feature_grouping":"Hire a crew","feature_usp":"Cross-platform player experience across devices"}}],"meta":{"pagination":{"page":1,"pageSize":25,"pageCount":1,"total":2}}}

Body:
This is because posts is a JSON object and not an array that you can use the map() function with. Instead, you need to give the array to the map() function before you can pull out the titles.

To access the array of the JSON object, you can use posts['data'].

export default function Home({ posts }) {
  return (
    <div>
      {posts &&
        posts["data"].map((post) => (
          <div key={post.id}>
            <h2>{post.attributes.title}</h2>
          </div>
        ))}
    </div>
  );
}


来源: stackexchange

问:
One line if statement in PHP
I'd like to to some thing similar to JavaScript's

```<code>var foo = true;
foo && doSometing();
</code>```

but this doesn't seem to work in PHP.

I'm trying to add a class to a label if a condition is met and I'd prefer to keep the embedded PHP down to a minimum for the sake of readability.

So far I've got:

```<code><?php $redText='redtext ';?>
<label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*</label>
<input name="_name" value="<?php echo $requestVars->_name; ?>"/>
</code>```

but even then the IDE is complaining that I have an if statement without braces.

答:
Ill provide with an other answer since the original question specifies the use of if() in html</p>
```<code><a class="menu-item" href="/about-us"><?= (pll_current_language() == 'en') ? 'About us' : 'Om oss' ?></a>
</code>```

ContentLicense: CC BY-SA 4.0

Title: One line if statement in PHP

Body:
I'd like to to some thing similar to JavaScript's

var foo = true;
foo && doSometing();

but this doesn't seem to work in PHP.

I'm trying to add a class to a label if a condition is met and I'd prefer to keep the embedded PHP down to a minimum for the sake of readability.

So far I've got:

<?php $redText='redtext ';?>
<label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*
<input name="_name" value="<?php echo $requestVars->_name; ?>"/>

but even then the IDE is complaining that I have an if statement without braces.

Body:
Ill provide with an other answer since the original question specifies the use of if() in html

<a class="menu-item" href="/about-us"><?= (pll_current_language() == 'en') ? 'About us' : 'Om oss' ?></a>


问:
How to give permission to applications running on GCP cloud run to access gcp services
I am developing a nodejs application that accesses secrets from gcp secret manager. I ran it locally with directing credentials using the GOOGLE_APPLICATION_CREDENTIALS variable.

Then I tried deploying this service to google cloud run, now it throws the error

```<code> Error: 7 PERMISSION_DENIED: Permission 'secretmanager.versions.access' denied
</code>```

I want to know how to add credentials to cloud-run containers. I saw some implementations where the credential file is included inside the code. what is the best practice of accessing gcp resources from cloud run container?

答:
You might like to find a service account used by your Cloud Run, and grant that service account a relevant IAM role against the desired secret - most likely a Secret Manager Secret Accessor role
(roles/secretmanager.secretAccessor).

You don’t need any credentials file. And under any circumstances, please, don't keep any credentials in a code repository.

======

Updated following @kolban comment

Body:
I am developing a nodejs application that accesses secrets from gcp secret manager. I ran it locally with directing credentials using the GOOGLE_APPLICATION_CREDENTIALS variable.

Then I tried deploying this service to google cloud run, now it throws the error

 Error: 7 PERMISSION_DENIED: Permission 'secretmanager.versions.access' denied

I want to know how to add credentials to cloud-run containers. I saw some implementations where the credential file is included inside the code. what is the best practice of accessing gcp resources from cloud run container?


问:
NestJs - Ignore Class validation in Class Validator
I have a DTO. I need to validate user entries against some strings . Those values are coming from ENV file. I got it to work, but I also need to ignore the case.

This is the value from the env file:

```<code>SEARCH_BY_LANGUAGE="Java,Javascript"
</code>```

This is my version where it works, but it is sensitive to cases:

```<code>@Expose()
@IsNotEmpty()
@ApiProperty()
@IsIn(process.env.SEARCH_BY_LANGUAGE.toLowerCase().split(","))
targetLanguage: string
</code>```

Problem with this approach is that, java and Java are treated differently.

I have tried to use the @Matches, like this:

```<code>@Expose()
@IsNotEmpty()
@ApiProperty()
@Matches(`^${process.env.SEARCH_BY_LANGUAGE.split(",")}$`, 'i')
targetLanguage: string
</code>```

But I am getting this error:

[ExceptionsHandler] Invalid flags supplied to RegExp constructor
'^Java,Javascript$' +14493m

I feel I am close, but cant figure it out.

答:
You have two possible approaches for that, the first one is @Transform() decorator from class-transformer, like Jay McDoniel commented above:

You can perform additional data transformation using @Transform decorator. For example, you want to make your Date object to be a moment object when you are transforming object from plain to class:

import { Transform } from 'class-transformer';
import * as moment from 'moment';
import { Moment } from 'moment';

export class Photo {
 id: number;

 @Type(() => Date)
 @Transform(({ value }) => moment(value), { toClassOnly: true })
 date: Moment;
}
```
<p>Now when you call plainToClass and send a plain representation of the Photo > object,
it will convert a date value in your photo object to moment date.
@Transform decorator also supports groups and versioning.</p>
</blockquote>
<p>So you would do something like this:</p>
<pre class="lang-js prettyprint-override"><code>@Transform((value) => value.toLowerCase() })
 targetLanguage: string
</code>```

Your second approach would be to use a NestJS custom interceptor and manually change your payload/data before using it

Body:
I have a DTO. I need to validate user entries against some strings . Those values are coming from ENV file. I got it to work, but I also need to ignore the case.

This is the value from the env file:

SEARCH_BY_LANGUAGE="Java,Javascript"

This is my version where it works, but it is sensitive to cases:

@Expose()
@IsNotEmpty()
@ApiProperty()
@IsIn(process.env.SEARCH_BY_LANGUAGE.toLowerCase().split(","))
targetLanguage: string

Problem with this approach is that, java and Java are treated differently.

I have tried to use the @Matches, like this:

@Expose()
@IsNotEmpty()
@ApiProperty()
@Matches(`^${process.env.SEARCH_BY_LANGUAGE.split(",")}$`, 'i')
targetLanguage: string

But I am getting this error:

[ExceptionsHandler] Invalid flags supplied to RegExp constructor
'^Java,Javascript$' +14493m

I feel I am close, but cant figure it out.

Body:
You have two possible approaches for that, the first one is @Transform() decorator from class-transformer, like Jay McDoniel commented above:

You can perform additional data transformation using @Transform decorator. For example, you want to make your Date object to be a moment object when you are transforming object from plain to class:

import { Transform } from 'class-transformer';
import * as moment from 'moment';
import { Moment } from 'moment';

export class Photo {
 id: number;

 @Type(() => Date)
 @Transform(({ value }) => moment(value), { toClassOnly: true })
 date: Moment;
}

Now when you call plainToClass and send a plain representation of the Photo > object,
it will convert a date value in your photo object to moment date.
@Transform decorator also supports groups and versioning.

So you would do something like this:

@Transform((value) => value.toLowerCase() })
 targetLanguage: string

Your second approach would be to use a NestJS custom interceptor and manually change your payload/data before using it


问:
Flask API & nginx alongside each other
I have a server that I'm trying to set up. I have a Flask server that needs to run on api.domain.com, while I have other subdomains pointing to the server. I have one problem. 2/3 subdomains have no problem using nginx. Meanwhile, my script tries to bind to port 80 on the same machine, therefore failing. Is there a way I can bind my Flask REST script to port 80 ONLY for the subdomain 'api'?
My current config is:

```<code>server {
        server_name api.domain.me;
        location / {
            error_page 404 /404.html;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_max_temp_file_size 0;
            proxy_pass http://127.0.0.1:5050/;
            proxy_cache off;
            proxy_read_timeout 240s;
    }
}
</code>```

There's a little problem though, nginx likes to turn all POST requests into GET requests, any ideas?
Thanks!

答:
There is no way binding two different applications on port 80 at the same time.

I would set up your api like this:

Bind your Flask API to Port 8080.
On NGINX you can configure you subdomain pointing to your Flask Application

```<code>upstream flask_app {
  server 127.0.0.1:8080;
}

sever {
  listen 80;
  server_name api.domain.com;

  location / {
    proxy_pass http://flask_app/;
    proxy_set_header Host $host;
  }
}
</code>```

Title: Flask API & nginx alongside each other

Body:
I have a server that I'm trying to set up. I have a Flask server that needs to run on api.domain.com, while I have other subdomains pointing to the server. I have one problem. 2/3 subdomains have no problem using nginx. Meanwhile, my script tries to bind to port 80 on the same machine, therefore failing. Is there a way I can bind my Flask REST script to port 80 ONLY for the subdomain 'api'?
My current config is:

server {
        server_name api.domain.me;
        location / {
            error_page 404 /404.html;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_max_temp_file_size 0;
            proxy_pass http://127.0.0.1:5050/;
            proxy_cache off;
            proxy_read_timeout 240s;
    }
}

There's a little problem though, nginx likes to turn all POST requests into GET requests, any ideas?
Thanks!

Body:
There is no way binding two different applications on port 80 at the same time.

I would set up your api like this:

Bind your Flask API to Port 8080.
On NGINX you can configure you subdomain pointing to your Flask Application

upstream flask_app {
  server 127.0.0.1:8080;
}

sever {
  listen 80;
  server_name api.domain.com;

  location / {
    proxy_pass http://flask_app/;
    proxy_set_header Host $host;
  }
}


问:
Slow HTTP POST request in php
I'm trying to POSTing some data (a JSON string) from a php script to a java server (all written by myself) and getting the response back.
I tried the following code:

```<code>$url="http://localhost:8000/hashmap";
$opts = array('http' => array('method' => 'POST', 'content' => $JSONDATA,'header'=>"Content-Type: application/x-www-form-urlencoded"));
$st = stream_context_create($opts);
echo file_get_contents($url, false,$st);
</code>```

Now, this code actually works (I get back as result the right answer), but file_get_contents hangs everytime 20 seconds while being executed (I printed the time before and after the instruction). The operations performed by the server are executed in a small amount of time, and I'm sure it's not normal to wait all this time to get the response.
Am I missing something?

答:
Badly mis-configured server maybe that doesn't send the right content-size and using HTTP/1.1.

Either fix the server or request the data as HTTP/1.0

ContentLicense: CC BY-SA 3.0

Title: Slow HTTP POST request in php

Body:
I'm trying to POSTing some data (a JSON string) from a php script to a java server (all written by myself) and getting the response back.
I tried the following code:

$url="http://localhost:8000/hashmap";
$opts = array('http' => array('method' => 'POST', 'content' => $JSONDATA,'header'=>"Content-Type: application/x-www-form-urlencoded"));
$st = stream_context_create($opts);
echo file_get_contents($url, false,$st);

Now, this code actually works (I get back as result the right answer), but file_get_contents hangs everytime 20 seconds while being executed (I printed the time before and after the instruction). The operations performed by the server are executed in a small amount of time, and I'm sure it's not normal to wait all this time to get the response.
Am I missing something?


问:
How to extract values from string lists in R?
I want to extract the X-squared value and p-value (number only) from three string vectors.

```<code>smr.text1

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T1"
[5] "X-squared = 0.017361, df = 1, p-value = 0.8952"
[6] ""

smr.txt2

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T2"
[5] "X-squared = 2.5679e-32, df = 1, p-value = 1"
[6] ""

smr.text3

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T3"
[5] "X-squared = 0.17857, df = 1, p-value = 0.6726"
[6] ""
</code>```

It was easy for me to extract those values from the first string vector using indexing numbers:

```<code>> c1 <- as.numeric(str_sub(smr.txt1[5], 13, 20))

> c1
</code>```

[1] 0.017361

```<code>> p1 <- as.numeric(str_sub(smr.txt1[5], -6))

> p1
</code>```

[1] 0.8952

But in the second string vector I can't really do the same since it's a scientific number. Also I could do the same with the third string vector, but is there a better way, for example using a loop to extract these values only and put them in the same data frame? Thanks in advance!

答:
While not what you've asked, it looks as though you used capture.output(.) to capture those strings. Instead of trying to extract the strings from the captured output, I suggest you get the real numbers from the objects themselves.

M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(gender = c("F", "M"),
                    party = c("Democrat","Independent", "Republican"))
Xsq <- chisq.test(M)
names(Xsq)
# [1] "statistic" "parameter" "p.value"   "method"    "data.name" "observed"  "expected"  "residuals" "stdres"
Xsq[c("statistic","p.value")]
# $statistic
# X-squared
#  30.07015
# $p.value
# [1] 2.953589e-07
```
<p>Since you mention having a list of these, it's easy to work with that as well. For instance, if you have a list of test results as in</p>
<pre class="lang-r prettyprint-override"><code>Xsq2 <- lapply(list(M, M), chisq.test)
Xsq2
# [[1]]
#   Pearson's Chi-squared test
# data:  X[[i]]
# X-squared = 30.07, df = 2, p-value = 2.954e-07
# [[2]]
#   Pearson's Chi-squared test
# data:  X[[i]]
# X-squared = 30.07, df = 2, p-value = 2.954e-07
lapply(Xsq2, `[`, c("statistic", "p.value"))
# [[1]]
# [[1]]$statistic
# X-squared
#  30.07015
# [[1]]$p.value
# [1] 2.953589e-07
# [[2]]
# [[2]]$statistic
# X-squared
#  30.07015
# [[2]]$p.value
# [1] 2.953589e-07
</code>```

which can be easily converted into a data.frame with:

do.call(rbind.data.frame, lapply(Xsq2, `[`, c("statistic", "p.value")))
#   statistic      p.value
# 1  30.07015 2.953589e-07
# 2  30.07015 2.953589e-07
```

Body:
I want to extract the X-squared value and p-value (number only) from three string vectors.

smr.text1

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T1"
[5] "X-squared = 0.017361, df = 1, p-value = 0.8952"
[6] ""

smr.txt2

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T2"
[5] "X-squared = 2.5679e-32, df = 1, p-value = 1"
[6] ""

smr.text3

[1] ""
[2] "\tPearson's Chi-squared test with Yates' continuity correction"
[3] ""
[4] "data:  data$parasite and data$T3"
[5] "X-squared = 0.17857, df = 1, p-value = 0.6726"
[6] ""

It was easy for me to extract those values from the first string vector using indexing numbers:

> c1 <- as.numeric(str_sub(smr.txt1[5], 13, 20))

> c1

[1] 0.017361

> p1 <- as.numeric(str_sub(smr.txt1[5], -6))

> p1

[1] 0.8952

But in the second string vector I can't really do the same since it's a scientific number. Also I could do the same with the third string vector, but is there a better way, for example using a loop to extract these values only and put them in the same data frame? Thanks in advance!

Body:
While not what you've asked, it looks as though you used capture.output(.) to capture those strings. Instead of trying to extract the strings from the captured output, I suggest you get the real numbers from the objects themselves.

M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(gender = c("F", "M"),
                    party = c("Democrat","Independent", "Republican"))
Xsq <- chisq.test(M)
names(Xsq)
# [1] "statistic" "parameter" "p.value"   "method"    "data.name" "observed"  "expected"  "residuals" "stdres"
Xsq[c("statistic","p.value")]
# $statistic
# X-squared
#  30.07015
# $p.value
# [1] 2.953589e-07

Since you mention having a list of these, it's easy to work with that as well. For instance, if you have a list of test results as in

Xsq2 <- lapply(list(M, M), chisq.test)
Xsq2
# [[1]]
#   Pearson's Chi-squared test
# data:  X[[i]]
# X-squared = 30.07, df = 2, p-value = 2.954e-07
# [[2]]
#   Pearson's Chi-squared test
# data:  X[[i]]
# X-squared = 30.07, df = 2, p-value = 2.954e-07
lapply(Xsq2, `[`, c("statistic", "p.value"))
# [[1]]
# [[1]]$statistic
# X-squared
#  30.07015
# [[1]]$p.value
# [1] 2.953589e-07
# [[2]]
# [[2]]$statistic
# X-squared
#  30.07015
# [[2]]$p.value
# [1] 2.953589e-07

which can be easily converted into a data.frame with:

do.call(rbind.data.frame, lapply(Xsq2, `[`, c("statistic", "p.value")))
#   statistic      p.value
# 1  30.07015 2.953589e-07
# 2  30.07015 2.953589e-07


问:
object data editting form
I'm making django app which allow me to study. It has multiple tests with multiple question each. Every question has one correct answer. I'm trying to make form which allow me to edit answer If I made mistake in passing correct answer during making question.

That's what I have already made:

```<code>models.py

class Question(models.Model):

    text = models.CharField(max_length=200, null=True)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add = True)

    def get_answer(self):
        return self.answer_set.all()

    def __str__(self):
        return self.text

class Answer(models.Model):
    text = models.CharField(max_length=200)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent')
    def __str__(self):
         return self.text
</code>```
```<code>forms.py

class AnswerEditForm(ModelForm):
    class Meta:
        model = Answer
        exclude = ('question',)

</code>```
```<code>views.py

def UpdateAnswerView(request, pk):
    form = AnswerEditForm()

    if request.method == 'POST':
        form = AnswerEditForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.question = Question.objects.get(id=pk)

            obj.save()
            return redirect('home')

    context = {'form':form}
    return render(request, 'exam/update_answer.html', context)
</code>```
```<code>urls.py
urlpatterns = [
    ~some other urls~
    path('answer/edit/<int:pk>/', views.UpdateAnswerView, name='update-answer'),

]
</code>```

while I'm trying to edit answer i'm getting Question matching query does not exist. error.
Where did i make mistake ?

答:
Probably pk is None.

it is better you check your pk

```<code>def UpdateAnswerView(request, pk):
    form = AnswerEditForm()

    if request.method == 'POST' and pk is not None:
        form = AnswerEditForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            try:
               obj.question = Question.objects.get(id=pk)
               obj.save()
               return redirect('home')
            except Question.DoesNotExist:
               pass

    context = {'form':form}
    return render(request, 'exam/update_answer.html', context)
</code>```

Title: object data editting form

Body:
I'm making django app which allow me to study. It has multiple tests with multiple question each. Every question has one correct answer. I'm trying to make form which allow me to edit answer If I made mistake in passing correct answer during making question.

That's what I have already made:

models.py

class Question(models.Model):

    text = models.CharField(max_length=200, null=True)
    test = models.ForeignKey(Test, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add = True)

    def get_answer(self):
        return self.answer_set.all()

    def __str__(self):
        return self.text

class Answer(models.Model):
    text = models.CharField(max_length=200)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='parent')
    def __str__(self):
         return self.text

forms.py

class AnswerEditForm(ModelForm):
    class Meta:
        model = Answer
        exclude = ('question',)

views.py

def UpdateAnswerView(request, pk):
    form = AnswerEditForm()

    if request.method == 'POST':
        form = AnswerEditForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.question = Question.objects.get(id=pk)

            obj.save()
            return redirect('home')

    context = {'form':form}
    return render(request, 'exam/update_answer.html', context)

urls.py
urlpatterns = [
    ~some other urls~
    path('answer/edit/<int:pk>/', views.UpdateAnswerView, name='update-answer'),

]

while I'm trying to edit answer i'm getting Question matching query does not exist. error.
Where did i make mistake ?

Body:
Probably pk is None.

it is better you check your pk

def UpdateAnswerView(request, pk):
    form = AnswerEditForm()

    if request.method == 'POST' and pk is not None:
        form = AnswerEditForm(request.POST)
        if form.is_valid():
            obj = form.save(commit=False)
            try:
               obj.question = Question.objects.get(id=pk)
               obj.save()
               return redirect('home')
            except Question.DoesNotExist:
               pass

    context = {'form':form}
    return render(request, 'exam/update_answer.html', context)


问:
How do I change the linter/formatter in VS Code?
I'm on Ubuntu. Pushing Ctrl + Shift + i in VS Code auto formats the file.

I was editing a solidity contract and pushed Ctrl + Shift + i, VS Code didn't have a formatter configured so it asked me to pick one - I accidentally chose my JS prettifier extension instead of the solidity one. This badgered up my code by trying to use single quotes instead of double quotes (not allowed in solidity) and some other non-solidity friendly changes.

Pushing Ctrl + Shift + i now just auto formats with the wrong formatter with no option to pick a different one.

How can I change which linter/formatter is associated to which file types in VS Code?

答:
Solution A:

Press Ctrl+Shift+P

Then type Format Document With...

At the end of the list click on Configure Default Formatter...

Now you can choose your favorite beautifier from the list.

Solution B:

go to file -> preferences -> settings search for format, on the left side, click on Text Editor, the very first item on the right side is Editor: Default Formatter from the dropdown you can pick any document formatter which you installed before.


问:
Sceneform - How to fix leaking SceneView?
I've been using SceneView for loading 3D models for almost a year now but I never understood what caused this leak. I would implement LeakCanary, but just this one leak because I couldn't figure out how to fix the problem.

But now I want to get to the bottom of the issue and try to fix it. I've tested it on two versions of Sceneform -- 1.15.0 and the last version before being deprecated by Google 1.17.1 and the issue happens on both.

The leak happens when you load a model using SceneView in an Activity or Fragment (I've tried both) and you "exit the app" by doing the System home navigation or switching to a different app via the Recent tasks list.

The logs for the leak:

```<code>┬───
│ GC Root: System class
│
├─ android.app.ActivityThread class
│    Leaking: NO (MainActivity↓ is not leaking and a class is never leaking)
│    ↓ static ActivityThread.sCurrentActivityThread
├─ android.app.ActivityThread instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    mInitialApplication instance of android.app.Application
│    ↓ ActivityThread.mActivities
├─ android.util.ArrayMap instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ ArrayMap.mArray
├─ java.lang.Object[] array
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ Object[].[1]
├─ android.app.ActivityThread$ActivityClientRecord instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    activity instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ ActivityThread$ActivityClientRecord.activity
├─ com.example.a3dmodeltester.MainActivity instance
│    Leaking: NO (SceneView↓ is not leaking and Activity#mDestroyed is false)
│    mApplication instance of android.app.Application
│    mBase instance of android.app.ContextImpl
│    ↓ MainActivity.sceneView
├─ com.google.ar.sceneform.SceneView instance
│    Leaking: NO (View attached)
│    View is part of a window view hierarchy
│    View.mAttachInfo is not null (view attached)
│    View.mID = R.id.sceneview
│    View.mWindowAttachCount = 1
│    mContext instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ SceneView.renderer
│                ~~~~~~~~
├─ com.google.ar.sceneform.rendering.Renderer instance
│    Leaking: UNKNOWN
│    Retaining 2.9 kB in 38 objects
│    ↓ Renderer.viewAttachmentManager
│               ~~~~~~~~~~~~~~~~~~~~~
├─ com.google.ar.sceneform.rendering.ViewAttachmentManager instance
│    Leaking: UNKNOWN
│    Retaining 2.2 kB in 19 objects
│    ↓ ViewAttachmentManager.frameLayout
│                            ~~~~~~~~~~~
╰→ android.widget.FrameLayout instance
     Leaking: YES (ObjectWatcher was watching this because android.widget.
     FrameLayout received View#onDetachedFromWindow() callback)
     Retaining 1.9 kB in 15 objects
     key = 10550463-895e-443a-898f-11c5131da209
     watchDurationMillis = 5165
     retainedDurationMillis = 157
     View not part of a window view hierarchy
     View.mAttachInfo is null (view detached)
     View.mWindowAttachCount = 1
     mContext instance of com.example.a3dmodeltester.MainActivity with
     mDestroyed = false

METADATA

Build.VERSION.SDK_INT: 27
Build.MANUFACTURER: Google
LeakCanary version: 2.7
App process name: com.example.a3dmodeltester
Stats: LruCache[maxSize=3000,hits=892,misses=24408,hitRate=3%]
RandomAccess[bytes=1232425,reads=24408,travel=6462427001,range=8963521,size=1161
0814]
Heap dump reason: 1 retained objects, app is not visible
Analysis duration: 5411 ms
</code>```

Reproducing the leak:

Last version before deprecation:

```<code> implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.17.1'
 debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'
</code>```

I have also tried it with 1.15.0

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.ar.sceneform.SceneView
        android:id="@+id/sceneview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"/>
</RelativeLayout>
</code>```

MainActivity (have also tested on a fragment)

```<code>public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final Vector3   STARTING_CAMERA_POSITION = new Vector3(0f, 1f, 3f);
    private              SceneView sceneView;
    private              Node      node;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sceneView = findViewById(R.id.sceneview);
        Scene scene = sceneView.getScene();
        node = new Node();
        scene.addChild(node);

        ModelRenderable.builder()
                .setSource(this, Uri.parse("Andy.sfb"))
                .build()
                .thenAccept(renderable -> node.setRenderable(renderable))
                .exceptionally(
                        throwable -> {
                            Log.e(TAG, "Unable to load Renderable.", throwable);
                            return null;
                        });
        Camera camera = scene.getCamera();
        camera.setWorldPosition(STARTING_CAMERA_POSITION);
    }

    @Override
    public void onPause() {
        super.onPause();
        sceneView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            sceneView.resume();
        } catch (CameraNotAvailableException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sceneView.destroy();
    }
}
</code>```

The .sfb file

https://drive.google.com/file/d/1NchJ2NGNM7NZzRZkq4fewALc7m4dnGG3/view?usp=sharing

To reproduce press the Home or Recent task list button while SceneView is running

I've also tested it with only just the SceneView, but it leaks as well.

How would I fix this leak?

I've also tested it on multiple APIs, emulators, and real devices and it happens on all of them.

答:
I've tried these options to stop the leak but they do not do anything:

```<code>Scene scene = sceneView.getScene();
scene = null;
sceneView = null;
sceneView.destroy();
Renderer.destroyAllResources();
Renderer.reclaimReleasedResources();
</code>```

This however, fixes the leak for me:

Removing the sceneView.pause(); from

```<code>@Override
public void onPause()
</code>```

stops the leak when doing a System home navigation or switching to a different app via the Recent tasks list. (The question in the OP)

Adding sceneView.pause(); to

```<code>@Override
public void onDestroy()
</code>```

Prevents a leak when the activity or fragment is destroyed.

```<code>    @Override
    public void onDestroy() {
        super.onDestroy();
        sceneView.pause();
    }
</code>```

Body:
I've been using SceneView for loading 3D models for almost a year now but I never understood what caused this leak. I would implement LeakCanary, but just this one leak because I couldn't figure out how to fix the problem.

But now I want to get to the bottom of the issue and try to fix it. I've tested it on two versions of Sceneform -- 1.15.0 and the last version before being deprecated by Google 1.17.1 and the issue happens on both.

The leak happens when you load a model using SceneView in an Activity or Fragment (I've tried both) and you "exit the app" by doing the System home navigation or switching to a different app via the Recent tasks list.

The logs for the leak:

┬───
│ GC Root: System class
│
├─ android.app.ActivityThread class
│    Leaking: NO (MainActivity↓ is not leaking and a class is never leaking)
│    ↓ static ActivityThread.sCurrentActivityThread
├─ android.app.ActivityThread instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    mInitialApplication instance of android.app.Application
│    ↓ ActivityThread.mActivities
├─ android.util.ArrayMap instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ ArrayMap.mArray
├─ java.lang.Object[] array
│    Leaking: NO (MainActivity↓ is not leaking)
│    ↓ Object[].[1]
├─ android.app.ActivityThread$ActivityClientRecord instance
│    Leaking: NO (MainActivity↓ is not leaking)
│    activity instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ ActivityThread$ActivityClientRecord.activity
├─ com.example.a3dmodeltester.MainActivity instance
│    Leaking: NO (SceneView↓ is not leaking and Activity#mDestroyed is false)
│    mApplication instance of android.app.Application
│    mBase instance of android.app.ContextImpl
│    ↓ MainActivity.sceneView
├─ com.google.ar.sceneform.SceneView instance
│    Leaking: NO (View attached)
│    View is part of a window view hierarchy
│    View.mAttachInfo is not null (view attached)
│    View.mID = R.id.sceneview
│    View.mWindowAttachCount = 1
│    mContext instance of com.example.a3dmodeltester.MainActivity with
│    mDestroyed = false
│    ↓ SceneView.renderer
│                ~~~~~~~~
├─ com.google.ar.sceneform.rendering.Renderer instance
│    Leaking: UNKNOWN
│    Retaining 2.9 kB in 38 objects
│    ↓ Renderer.viewAttachmentManager
│               ~~~~~~~~~~~~~~~~~~~~~
├─ com.google.ar.sceneform.rendering.ViewAttachmentManager instance
│    Leaking: UNKNOWN
│    Retaining 2.2 kB in 19 objects
│    ↓ ViewAttachmentManager.frameLayout
│                            ~~~~~~~~~~~
╰→ android.widget.FrameLayout instance
     Leaking: YES (ObjectWatcher was watching this because android.widget.
     FrameLayout received View#onDetachedFromWindow() callback)
     Retaining 1.9 kB in 15 objects
     key = 10550463-895e-443a-898f-11c5131da209
     watchDurationMillis = 5165
     retainedDurationMillis = 157
     View not part of a window view hierarchy
     View.mAttachInfo is null (view detached)
     View.mWindowAttachCount = 1
     mContext instance of com.example.a3dmodeltester.MainActivity with
     mDestroyed = false

METADATA

Build.VERSION.SDK_INT: 27
Build.MANUFACTURER: Google
LeakCanary version: 2.7
App process name: com.example.a3dmodeltester
Stats: LruCache[maxSize=3000,hits=892,misses=24408,hitRate=3%]
RandomAccess[bytes=1232425,reads=24408,travel=6462427001,range=8963521,size=1161
0814]
Heap dump reason: 1 retained objects, app is not visible
Analysis duration: 5411 ms

Reproducing the leak:

Last version before deprecation:

 implementation 'com.google.ar.sceneform.ux:sceneform-ux:1.17.1'
 debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'

I have also tried it with 1.15.0

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.ar.sceneform.SceneView
        android:id="@+id/sceneview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"/>
</RelativeLayout>

MainActivity (have also tested on a fragment)

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private static final Vector3   STARTING_CAMERA_POSITION = new Vector3(0f, 1f, 3f);
    private              SceneView sceneView;
    private              Node      node;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sceneView = findViewById(R.id.sceneview);
        Scene scene = sceneView.getScene();
        node = new Node();
        scene.addChild(node);

        ModelRenderable.builder()
                .setSource(this, Uri.parse("Andy.sfb"))
                .build()
                .thenAccept(renderable -> node.setRenderable(renderable))
                .exceptionally(
                        throwable -> {
                            Log.e(TAG, "Unable to load Renderable.", throwable);
                            return null;
                        });
        Camera camera = scene.getCamera();
        camera.setWorldPosition(STARTING_CAMERA_POSITION);
    }

    @Override
    public void onPause() {
        super.onPause();
        sceneView.pause();
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            sceneView.resume();
        } catch (CameraNotAvailableException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sceneView.destroy();
    }
}

The .sfb file

https://drive.google.com/file/d/1NchJ2NGNM7NZzRZkq4fewALc7m4dnGG3/view?usp=sharing

To reproduce press the Home or Recent task list button while SceneView is running

I've also tested it with only just the SceneView, but it leaks as well.

How would I fix this leak?

I've also tested it on multiple APIs, emulators, and real devices and it happens on all of them.

Body:
I've tried these options to stop the leak but they do not do anything:

Scene scene = sceneView.getScene();
scene = null;
sceneView = null;
sceneView.destroy();
Renderer.destroyAllResources();
Renderer.reclaimReleasedResources();

This however, fixes the leak for me:

Removing the sceneView.pause(); from

@Override
public void onPause()

stops the leak when doing a System home navigation or switching to a different app via the Recent tasks list. (The question in the OP)

Adding sceneView.pause(); to

@Override
public void onDestroy()

Prevents a leak when the activity or fragment is destroyed.

    @Override
    public void onDestroy() {
        super.onDestroy();
        sceneView.pause();
    }


问:
How to fix hex characters
I'm trying to print the content of the image jpg file as hex. However, characters with 0 are not being displayed correctly. For example lets say we have C0 it only shows C.

Here is the code:

```<code>#include <stdio.h>
int main(){
    FILE *fp = fopen("steg.jpg", "r");
    int z = 0;
    unsigned char out;
    while(z!=-1){

        z=fscanf(fp,"%c", &out);
        if(z!=-1){
            printf("%X ", out);
        }else{
            break;
        }

    }
    fclose(fp);
    return 0;
}
</code>```

What should I do to fix this?

答:
getc each byte and print it

```<code>    int z = 0;
    unsigned char out;
    while((z = getc(fp)) != -1){
        printf("%02X ", z);
    }
</code>```

You'll want to add a counter and print newlines every so many characters.

Title: How to fix hex characters

Body:
I'm trying to print the content of the image jpg file as hex. However, characters with 0 are not being displayed correctly. For example lets say we have C0 it only shows C.

Here is the code:

#include <stdio.h>
int main(){
    FILE *fp = fopen("steg.jpg", "r");
    int z = 0;
    unsigned char out;
    while(z!=-1){

        z=fscanf(fp,"%c", &out);
        if(z!=-1){
            printf("%X ", out);
        }else{
            break;
        }

    }
    fclose(fp);
    return 0;
}

What should I do to fix this?

Body:
getc each byte and print it

    int z = 0;
    unsigned char out;
    while((z = getc(fp)) != -1){
        printf("%02X ", z);
    }

You'll want to add a counter and print newlines every so many characters.


问:
Remove one index from the array in codeigniter controller
```<code>Array (
    [issuer_id] => in.gsvm
    [org_id] => 00738648
    [doc_type] => ABCDS
    [RROLL] => 12589
    [YEAR] => 2020
)
</code>```

I want to remove org_id from array and store that data in another variable

答:
You can use unset(array) method of PHP programming language to remove an item.
for example

$dataArray = ['key1'=>'data1','key2'=>'data2'];

unset($dataArray['key1']);

Then pass the array to insert function.

 $this->db->insert('table_name',$dataArray);

You can find details example on this link: https://www.techiedelight.com/remove-elements-array-php/

Body:
Array (
    [issuer_id] => in.gsvm
    [org_id] => 00738648
    [doc_type] => ABCDS
    [RROLL] => 12589
    [YEAR] => 2020
)

I want to remove org_id from array and store that data in another variable


问:
How to start optimising/refactoring jQuery code
I have following jQuery code

```<code>$('a.editpo, a.resetpass').click(function(event){
    event.preventDefault();
    var urlToCall = $(this).attr('href');
    var hyperlinkid = '#'+$(this).attr('id');
    var targetId = $(this).attr('id').match(/\d+/);
    var targetTrDiv = '#poformloadertr_'+targetId;
    var targetTdDiv = '#poformloadertd_'+targetId;
    var currentLink = $(this).html();
    /*Todo: refactor or shorten the following statement*/
    if((currentLink=='Edit' && $('#resetuserpassform_'+targetId).is(':visible'))
        ||
       (currentLink=='Reset Pass' && $('#account-home-container-'+targetId).is(':visible'))
        ||
       ($(targetTdDiv).html() =='')
    ){
        $.ajax({
            url:urlToCall,
            success: function(html){
                $(targetTdDiv).html(html);
                $(targetTrDiv).show();
            }
        });
    }else{
        $(targetTrDiv).hide();
        $(targetTdDiv).html('');
    }
});
</code>```

The editpo and resetpass are classes applied on hyperlinks in column of table, namely Edit and Reset Pass, clicking these load up the form in a table row, ids for the respective tr and td is targetTrDiv and targetTdDiv. I am not good at JS and specially jQuery, but would still be interested in any optimisations.

But I am especially interested in reducing the condition statement.

答:
First, you can optimize the following code:

```<code>   var urlToCall = $(this).attr('href');
   var hyperlinkid = '#'+$(this).attr('id');
   var targetId = $(this).attr('id').match(/\d+/);
   var targetTrDiv = '#poformloadertr_'+targetId;
   var targetTdDiv = '#poformloadertd_'+targetId;
   var currentLink = $(this).html();
</code>```

to:

```<code>   var wrappedSet$ = $(this);

   var urlToCall = wrappedSet$.attr('href');
   var hyperlinkid = '#'+wrappedSet$.attr('id');
   var targetId = wrappedSet$.attr('id').match(/\d+/);
   var targetTrDiv = '#poformloadertr_'+targetId;
   var targetTdDiv = '#poformloadertd_'+targetId;
   var currentLink = wrappedSet$.html();
</code>```

EDIT: Also, you could remove the currentLink=='Edit' && and currentLink=='Reset Pass' && code snippets, because you can be sure that the right links were clicked using the class selector that you are using in your jQuery click handler (a.editpo, a.resetpass).

If you do that the codition statement will stays like this:

```<code>if(($('#resetuserpassform_'+targetId).is(':visible'))
        ||
       ($('#account-home-container-'+targetId).is(':visible'))
        ||
       ($(targetTdDiv).html() =='')
    ){
       /* AJAX call goes here */
    }
</code>```

Besides, and hopefully I'm wrong, it's very unlikely that the condition statement can be more optimized. The reason for concluding this is that you want to much specificity that is likely impossible to achieve in other way.

Hope it helps you.

Body:
I have following jQuery code

$('a.editpo, a.resetpass').click(function(event){
    event.preventDefault();
    var urlToCall = $(this).attr('href');
    var hyperlinkid = '#'+$(this).attr('id');
    var targetId = $(this).attr('id').match(/\d+/);
    var targetTrDiv = '#poformloadertr_'+targetId;
    var targetTdDiv = '#poformloadertd_'+targetId;
    var currentLink = $(this).html();
    /*Todo: refactor or shorten the following statement*/
    if((currentLink=='Edit' && $('#resetuserpassform_'+targetId).is(':visible'))
        ||
       (currentLink=='Reset Pass' && $('#account-home-container-'+targetId).is(':visible'))
        ||
       ($(targetTdDiv).html() =='')
    ){
        $.ajax({
            url:urlToCall,
            success: function(html){
                $(targetTdDiv).html(html);
                $(targetTrDiv).show();
            }
        });
    }else{
        $(targetTrDiv).hide();
        $(targetTdDiv).html('');
    }
});

The editpo and resetpass are classes applied on hyperlinks in column of table, namely Edit and Reset Pass, clicking these load up the form in a table row, ids for the respective tr and td is targetTrDiv and targetTdDiv. I am not good at JS and specially jQuery, but would still be interested in any optimisations.

But I am especially interested in reducing the condition statement.

Body:
First, you can optimize the following code:

   var urlToCall = $(this).attr('href');
   var hyperlinkid = '#'+$(this).attr('id');
   var targetId = $(this).attr('id').match(/\d+/);
   var targetTrDiv = '#poformloadertr_'+targetId;
   var targetTdDiv = '#poformloadertd_'+targetId;
   var currentLink = $(this).html();

to:

   var wrappedSet$ = $(this);

   var urlToCall = wrappedSet$.attr('href');
   var hyperlinkid = '#'+wrappedSet$.attr('id');
   var targetId = wrappedSet$.attr('id').match(/\d+/);
   var targetTrDiv = '#poformloadertr_'+targetId;
   var targetTdDiv = '#poformloadertd_'+targetId;
   var currentLink = wrappedSet$.html();

EDIT: Also, you could remove the currentLink=='Edit' && and currentLink=='Reset Pass' && code snippets, because you can be sure that the right links were clicked using the class selector that you are using in your jQuery click handler (a.editpo, a.resetpass).

If you do that the codition statement will stays like this:

if(($('#resetuserpassform_'+targetId).is(':visible'))
        ||
       ($('#account-home-container-'+targetId).is(':visible'))
        ||
       ($(targetTdDiv).html() =='')
    ){
       /* AJAX call goes here */
    }

Besides, and hopefully I'm wrong, it's very unlikely that the condition statement can be more optimized. The reason for concluding this is that you want to much specificity that is likely impossible to achieve in other way.

Hope it helps you.


问:
Dagger/Hilt missing binding. Repository cannot be provided without an @Provides-annotated method
I have this interface

```<code>interface ShowsScheduleRepository {
    suspend fun getShowsSchedule(medium: String, timeSlot: String): ShowsSchedule
}
</code>```

which is provided in this class

```<code>class GetShowsScheduleUseCase @Inject constructor(
    private val repository: ShowsScheduleRepository
)
</code>```

by

```<code>@Provides
@Singleton
fun provideShowsScheduleRepository(api: TDRetrofitApi): ShowsScheduleRepository {
    return ShowsScheduleRepoImpl(api)
}
</code>```

and then this class is injected in a viewModel

```<code>@HiltViewModel
class HomeFragmentViewModel @Inject constructor(
    private val getShowsSchedule: GetShowsScheduleUseCase
) : ViewModel() {
</code>```

And when I am trying to build I get the error that it cannot provide a ShowsScheduleRepository without an  @Provides-annotated method

答: Note to self: Put the AppModule file in the same Android Module where the HiltEntryPoint is</p>

Body:
I have this interface

interface ShowsScheduleRepository {
    suspend fun getShowsSchedule(medium: String, timeSlot: String): ShowsSchedule
}

which is provided in this class

class GetShowsScheduleUseCase @Inject constructor(
    private val repository: ShowsScheduleRepository
)

by

@Provides
@Singleton
fun provideShowsScheduleRepository(api: TDRetrofitApi): ShowsScheduleRepository {
    return ShowsScheduleRepoImpl(api)
}

and then this class is injected in a viewModel

@HiltViewModel
class HomeFragmentViewModel @Inject constructor(
    private val getShowsSchedule: GetShowsScheduleUseCase
) : ViewModel() {

And when I am trying to build I get the error that it cannot provide a ShowsScheduleRepository without an  @Provides-annotated method


问:
count based on column and add as new column in numpy
It should be straight forward but I cannot find the right command.
I want to add a new column (Col3) to my Numpy which counts the occurrence of a value of a column (Col2) for each row. take this example:

before:

Col1
Col2

1
4

2
4

3
1500

4
60

5
60

6
60

after:

Col1
Col2
Col3

1
4
2

2
4
2

3
1500
1

4
60
3

5
60
3

6
60
3

any idea?

答:
Using numpy:

Create a frequency dictionary based on the values on Col2

```<code>from collections import Counter
freq = Counter(arr[:,1])
</code>```

generate the values of the Col3 iterating the elements of Col2

new_col =  np.array([freq[val] if val in freq else 0 for val in arr[:,1] ]).reshape(-1,1)

concatenate the new column to the existing array

new_arr = np.concatenate([arr, new_col],axis=1)

Body:
Using numpy:

Create a frequency dictionary based on the values on Col2

from collections import Counter
freq = Counter(arr[:,1])

generate the values of the Col3 iterating the elements of Col2

new_col =  np.array([freq[val] if val in freq else 0 for val in arr[:,1] ]).reshape(-1,1)

concatenate the new column to the existing array

new_arr = np.concatenate([arr, new_col],axis=1)


问:
Pass environment variable value to Angular app from docker file
I have an Angular app where i'm trying to set the environment variable from outside of the app i.e., from docker compose file.

I'm referring below article

https://codinglatte.com/posts/angular/using-os-environment-variables-in-angular-with-docker/

docker-compose.yml

```<code>version: '3'
services:
  tomcat-server:
    image: "tomcat:latest"
    ports:
      - "8071:8080"
    environment:
      - API_URL=http://demo-production.com
</code>```

I could even see the environment variable set when I execute the below command

```<code>docker exec -it <dockerName> sh

env
</code>```

but somehow the value is not being received by Angular app, below is my Angular app code as per the above article

environment.prod.ts

```<code>export const environment = {
  production: true,
  API_URL: $ENV.API_URL,
  TEST_ENV: 'testing'
  // API_URL: 'http://production.com'
};
</code>```

typings.d.ts

```<code>declare var $ENV: Env;

interface Env {
    API_URL: string
}
</code>```

custom-webpack.config.js

```<code>const webpack =  require('webpack');
module.exports = {
        plugins: [
            new webpack.DefinePlugin({
                $ENV: {
                    API_URL: JSON.stringify(process.env.API_URL)
                }
            })
        ]
};
</code>```

Command I used to create the build

```<code>ng build --configuration=production --base-href=/demoapp/
</code>```

I couldn't figure out the issue here as the environment value set in docker file is not reflecting in my app.

Can I get some help here?

答:
The problem is that you confuse build time with run time.
What you need are variables passed at build time. You can pass them in a build command:

```<code>docker build -t my_image --build-arg API_URL=http://demo-production.com .
</code>```

The . in the end gives the context, in this case the current directory. It will expect to find a dockerfile named Dockerfile there. In the link you posted you find a dockerfile in the bottom, there you also see the environment variables defined as expected.
In that file they first use a node image to build the app WITH your env variables, and then a deploy stage where they copy the outputs to the correct location inside an nginx container.

You specify a tomcat container in the docker-compose file. That container will not build anything. Even if you would pass the arguments correctly, it has no way of knowing what to do with it.

What you should probably do is:

make a dockerfile, based on the example to first build your project, using the env variable(s).

build the image with the above command.

run a container based on the image with:

```<code>docker run --name my-container-name -p "8071:8080" my-image
</code>```

This is assuming that in the second stage of the dockerfile you use tomcat, which uses port 8080 that you are mapping.
If you would like to use docker compose it could look like:

```<code>version: '3'
services:
  tomcat-server:
    build:
      context: .
      args:
        API_URL=http://demo-production.com
    ports:
      - "8071:8080"
</code>```

This would then call the docker build and run command for you, so you obviously still need the dockerfile.

If you are interested in passing the environment variables in run time to angular it is a different thing. You can read about it here in a blog I wrote, if you want.

Body:
I have an Angular app where i'm trying to set the environment variable from outside of the app i.e., from docker compose file.

I'm referring below article

https://codinglatte.com/posts/angular/using-os-environment-variables-in-angular-with-docker/

docker-compose.yml

version: '3'
services:
  tomcat-server:
    image: "tomcat:latest"
    ports:
      - "8071:8080"
    environment:
      - API_URL=http://demo-production.com

I could even see the environment variable set when I execute the below command

docker exec -it <dockerName> sh

env

but somehow the value is not being received by Angular app, below is my Angular app code as per the above article

environment.prod.ts

export const environment = {
  production: true,
  API_URL: $ENV.API_URL,
  TEST_ENV: 'testing'
  // API_URL: 'http://production.com'
};

typings.d.ts

declare var $ENV: Env;

interface Env {
    API_URL: string
}

custom-webpack.config.js

const webpack =  require('webpack');
module.exports = {
        plugins: [
            new webpack.DefinePlugin({
                $ENV: {
                    API_URL: JSON.stringify(process.env.API_URL)
                }
            })
        ]
};

Command I used to create the build

ng build --configuration=production --base-href=/demoapp/

I couldn't figure out the issue here as the environment value set in docker file is not reflecting in my app.

Can I get some help here?

Body:
The problem is that you confuse build time with run time.
What you need are variables passed at build time. You can pass them in a build command:

docker build -t my_image --build-arg API_URL=http://demo-production.com .

The . in the end gives the context, in this case the current directory. It will expect to find a dockerfile named Dockerfile there. In the link you posted you find a dockerfile in the bottom, there you also see the environment variables defined as expected.
In that file they first use a node image to build the app WITH your env variables, and then a deploy stage where they copy the outputs to the correct location inside an nginx container.

You specify a tomcat container in the docker-compose file. That container will not build anything. Even if you would pass the arguments correctly, it has no way of knowing what to do with it.

What you should probably do is:

make a dockerfile, based on the example to first build your project, using the env variable(s).

build the image with the above command.

run a container based on the image with:

docker run --name my-container-name -p "8071:8080" my-image

This is assuming that in the second stage of the dockerfile you use tomcat, which uses port 8080 that you are mapping.
If you would like to use docker compose it could look like:

version: '3'
services:
  tomcat-server:
    build:
      context: .
      args:
        API_URL=http://demo-production.com
    ports:
      - "8071:8080"

This would then call the docker build and run command for you, so you obviously still need the dockerfile.

If you are interested in passing the environment variables in run time to angular it is a different thing. You can read about it here in a blog I wrote, if you want.


问:
Checking properties of an object based on separete view (Django|Django-Rest-Framework)
I am using django-rest-framework and React.js. I need a seperate function in the backend to check if CartItem.amount is lower then ProductStock.quantity, if CartItem.product equals ProductStock.id of course (this part does not work). For the same function I need to check if the pricing is the same as in Product model, but suprisingly this part of a function works. What can I do to make sure CartItem.amount will get lowered if it is higher than ProductStock.quantity?

Code below:

Product is a blueprint for the rest of the models.

ProductStock tracks the amount of different sizes of all of products.

CartItem is a model used for tracking how many products a user bought.

models.py

```<code>class Product(models.Model):
    name = models.CharField(max_length=150)
    price = models.IntegerField()
    slug = models.SlugField(blank=True, null=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Product, self).save()

class ProductStock(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    size = models.CharField(max_length=6)
    quantity = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.quantity} x {self.product.name}: {self.size}'

class CartItem(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    product = models.ForeignKey(ProductStock, on_delete=models.CASCADE, blank=True, null=True)
    amount = models.IntegerField(default=0, blank=True, null=True)
    size = models.CharField(max_length=10, blank=True, null=True)
    price = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return f'{self.user.email}, {self.product.product.name}, {self.product.size}: {self.amount}'

    def save(self, *args, **kwargs):
        if self.amount > self.product.quantity:
            self.amount = self.product.quantity
        self.size = self.product.size
        self.price = self.product.product.price
        super(CartItem, self).save()
</code>```

views.py

```<code>def check_cart_content(request,user_id):
    cart = CartItem.objects.filter(user=user_id)

    for item in cart:
        product_stock = ProductStock.objects.filter(product=item.product.id)
        for stock in product_stock:
            if item.amount > stock.quantity:
                item.amount = stock.quantity

            product = Product.objects.get(id=item.product.id)
            if item.price != product.price:
                item.price = product.price

            item.save()

            return JsonResponse({'success': 'Cart checked'})
</code>```

答:
You need to change indentation of JsonResponse cause it ends after first stock in product_stock. Also item.save() and more probably need indentation change. Revise that in clean Python.

```<code>def check_cart_content(request,user_id):
    cart = CartItem.objects.filter(user=user_id)

    for item in cart:
        product_stock = ProductStock.objects.filter(product=item.product.id)
        for stock in product_stock:
            if item.amount > stock.quantity:
                item.amount = stock.quantity

        product = Product.objects.get(id=item.product.id)
        if item.price != product.price:
            item.price = product.price

        item.save()

    return JsonResponse({'success': 'Cart checked'})
</code>```

You should think of rebuilding model tree, cause ProductStock with ForeignKey seems bad solution. It would be better to count in function of Product, something similar to:

```<code>def quantity(self):
    return Product.objects.all().count()
</code>```

because it works dynamically and you don't need extra objects in database.

Body:
I am using django-rest-framework and React.js. I need a seperate function in the backend to check if CartItem.amount is lower then ProductStock.quantity, if CartItem.product equals ProductStock.id of course (this part does not work). For the same function I need to check if the pricing is the same as in Product model, but suprisingly this part of a function works. What can I do to make sure CartItem.amount will get lowered if it is higher than ProductStock.quantity?

Code below:

Product is a blueprint for the rest of the models.

ProductStock tracks the amount of different sizes of all of products.

CartItem is a model used for tracking how many products a user bought.

models.py

class Product(models.Model):
    name = models.CharField(max_length=150)
    price = models.IntegerField()
    slug = models.SlugField(blank=True, null=True)

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Product, self).save()

class ProductStock(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    size = models.CharField(max_length=6)
    quantity = models.IntegerField(default=0)

    def __str__(self):
        return f'{self.quantity} x {self.product.name}: {self.size}'

class CartItem(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
    product = models.ForeignKey(ProductStock, on_delete=models.CASCADE, blank=True, null=True)
    amount = models.IntegerField(default=0, blank=True, null=True)
    size = models.CharField(max_length=10, blank=True, null=True)
    price = models.IntegerField(blank=True, null=True)

    def __str__(self):
        return f'{self.user.email}, {self.product.product.name}, {self.product.size}: {self.amount}'

    def save(self, *args, **kwargs):
        if self.amount > self.product.quantity:
            self.amount = self.product.quantity
        self.size = self.product.size
        self.price = self.product.product.price
        super(CartItem, self).save()

views.py

def check_cart_content(request,user_id):
    cart = CartItem.objects.filter(user=user_id)

    for item in cart:
        product_stock = ProductStock.objects.filter(product=item.product.id)
        for stock in product_stock:
            if item.amount > stock.quantity:
                item.amount = stock.quantity

            product = Product.objects.get(id=item.product.id)
            if item.price != product.price:
                item.price = product.price

            item.save()

            return JsonResponse({'success': 'Cart checked'})

Body:
You need to change indentation of JsonResponse cause it ends after first stock in product_stock. Also item.save() and more probably need indentation change. Revise that in clean Python.

def check_cart_content(request,user_id):
    cart = CartItem.objects.filter(user=user_id)

    for item in cart:
        product_stock = ProductStock.objects.filter(product=item.product.id)
        for stock in product_stock:
            if item.amount > stock.quantity:
                item.amount = stock.quantity

        product = Product.objects.get(id=item.product.id)
        if item.price != product.price:
            item.price = product.price

        item.save()

    return JsonResponse({'success': 'Cart checked'})

You should think of rebuilding model tree, cause ProductStock with ForeignKey seems bad solution. It would be better to count in function of Product, something similar to:

def quantity(self):
    return Product.objects.all().count()

because it works dynamically and you don't need extra objects in database.


问:
Skip a page when the back button is pressed, WP7
In the current released version of WP7 you have no programmatic control over the page stack.

I start at A, go to B, and then C.  B is the data entry page for new items, so coming back from C I want to logically land at A.  Currently I listen for navigation on B that comes from C and force another back onto A.  However, the event doesn't happen soon enough to stop the page from displaying on-screen.

A -> B -> C

C -> A

A is the top level list page.  B is the new item page.  C is the item detail page.

This only occurs on one form so far so my workaround is to override OnNavigatedTo in the page I want to skip, and call "go back" programmatically.  However, this has the undesired effect of briefly showing the page and then immediately navigating off of it.

Is there a workable way to stop the flicker?

Should my workaround instead be to take full control of page navigation, including go backs?  This will leave the page stack is a strange state, but that would be hidden from the user if I control all navigation.

I know there is a new feature in Mango to pop a page from the page stack programmatically, but I'm curious to know if there is a solution to the problem in the released version.

Another motivation for this is I don't know what version will be best to target, the latest, or the one that is just enough for the app.  For the time being I'm sticking with the live version.

答:
I have stopped the flickering by making the root frame transparent for the duration of the skip.  This example isn't straight from my code.

Firstly on the page you wish to skip, override OnNavigatedTo and test to see where you have come from (this is where my code gets specific, I keep track of where I am):

```<code>protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // If I've come from page C, go back again.
    NavigationService.GoBack();
}
</code>```

Secondly, in the main App.xaml.cs register an event handler for Navigating (I put it in public App() constructor):

```<code>RootFrame.Navigating += RootFrame_Navigating;
</code>```

Finally, flesh them out to hide the frame and show it again for the duration of the skip:

```<code>    private bool _skipped;

    private void RootFrame_Navigated(object sender, NavigationEventArgs e)
    {
        RootFrame.Opacity = 100;
        RootFrame.Navigated -= RootFrame_Navigated;
    }

    private void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        if (_skipped)
        {
            _skipped = false;
            RootFrame.Navigated += RootFrame_Navigated;
        }

        if (e.NavigationMode == NavigationMode.Back &&
            e.Uri.OriginalString.Contains("ThePage.xaml"))
        {
            RootFrame.Opacity = 0;
            _skipped = true;
        }
    }
</code>```

The code to determine when to make the page transparent is also different in my actual code, but I've added an implementation to the answer for illustration.  This is almost identical to the code in the recipe linked in another answer, but doesn't involve needing to use a third party DLL.

I provided my own answer because I've seen the sources provided in the other answers before, but never paid attention to the code for hiding the root frame.  I am not using the Non-Linear Navigation Service, just the code fragment for frame transparency (I don't need it to detect circular navigation as I'm well aware of the design choices I make in the app and can spot them myself :-)

This suffices as a workaround in the (currently) one case I have where I need to skip a page that doesn't make sense when going back.  I'd like to think when Mango comes out I will be best placed targeting the latest version, so this code will soon be defunct.

Sources:

App Hub code recipe for Non-Linear Navigation

Non-Linear Navigation Service Blog Post

Body:
I have stopped the flickering by making the root frame transparent for the duration of the skip.  This example isn't straight from my code.

Firstly on the page you wish to skip, override OnNavigatedTo and test to see where you have come from (this is where my code gets specific, I keep track of where I am):

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // If I've come from page C, go back again.
    NavigationService.GoBack();
}

Secondly, in the main App.xaml.cs register an event handler for Navigating (I put it in public App() constructor):

RootFrame.Navigating += RootFrame_Navigating;

Finally, flesh them out to hide the frame and show it again for the duration of the skip:

    private bool _skipped;

    private void RootFrame_Navigated(object sender, NavigationEventArgs e)
    {
        RootFrame.Opacity = 100;
        RootFrame.Navigated -= RootFrame_Navigated;
    }

    private void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
    {
        if (_skipped)
        {
            _skipped = false;
            RootFrame.Navigated += RootFrame_Navigated;
        }

        if (e.NavigationMode == NavigationMode.Back &&
            e.Uri.OriginalString.Contains("ThePage.xaml"))
        {
            RootFrame.Opacity = 0;
            _skipped = true;
        }
    }

The code to determine when to make the page transparent is also different in my actual code, but I've added an implementation to the answer for illustration.  This is almost identical to the code in the recipe linked in another answer, but doesn't involve needing to use a third party DLL.

I provided my own answer because I've seen the sources provided in the other answers before, but never paid attention to the code for hiding the root frame.  I am not using the Non-Linear Navigation Service, just the code fragment for frame transparency (I don't need it to detect circular navigation as I'm well aware of the design choices I make in the app and can spot them myself :-)

This suffices as a workaround in the (currently) one case I have where I need to skip a page that doesn't make sense when going back.  I'd like to think when Mango comes out I will be best placed targeting the latest version, so this code will soon be defunct.

Sources:

App Hub code recipe for Non-Linear Navigation

Non-Linear Navigation Service Blog Post


问:
 not starting where it starts where I want it to on new line
In the image you can see that if the title of the sidebar link is too long it goes to the next line. However it starts where the icon is located and not where the start of the span is. How would I style the class "side-nav-item" to where it will format where Administrator when it is shifted to the new line it starts where Give is.

      User Access

                   Give user access - Administrator

                   Remove

```

答:
try this ,</p>
```<code><span
  style="width:400px;text-align:start;height:max-content;"
>
   Give user access - Administrator
</span>
</code>```

Title: <span> not starting where it starts where I want it to on new line

Body:
try this ,

<span
  style="width:400px;text-align:start;height:max-content;"
>
   Give user access - Administrator
</span>


问:
Using an object as a value with Material-UI select and displaying text when chosen
I'm using an api, and mapping the data to create a grid of drop down options (mui select). There should be two values recorded when the value changes.

I've created an object that has all of the fields in it, which changes when the user changes a select. The only issue is that the select field doesn't show what is currently selected, but if you look at the object, it is clearly changing.

How do I get the current value for each select to show?

In the following code, test is meant to replicate the length of the array returned from the API

```<code>import * as React from 'react';
import Box from '@mui/material/Box';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import Typography from '@mui/material/Typography';

export default function BasicSelect() {
  const test='123456';

  const getDefaultSelect = () => {
    let selectArray=[]
    for (let i=0;i<test.length;i++){
      selectArray= [...selectArray,{ qty: 1, qtyUri: 'unit', qtyLabel: 'unit' }]
    }
    return selectArray
  }

  React.useEffect(() => {
    setSelectValues(getDefaultSelect())
  }, []);

  const [selectValues, setSelectValues] = React.useState([])

  const handleSelectChange = (index, eventData) => {
    const newValues = [...selectValues]
    newValues[index]={...newValues[index], qtyUri: eventData.qtyUri, qtyLabel: eventData.qtyLabel}
    setSelectValues(newValues)
  }

  return (
    <Box sx={{ minWidth: 120 }}>

      {selectValues.map((selectValue, index) => (
        <Select
          value={{qtyUri:selectValue.qtyUri, qtyLabel:selectValue.qtyLabel}}
          onChange={(eventData) => handleSelectChange(index, eventData.target.value)}
        >
          <MenuItem value={{qtyUri:'unit', qtyLabel:'Whole'}}>Whole</MenuItem>
          <MenuItem value={{qtyUri:'gram', qtyLabel:'g'}}>g</MenuItem>
          <MenuItem value={{qtyUri:'ounce', qtyLabel:'Oz'}}>Oz</MenuItem>
        </Select>
      ))}

        <Typography>
        {JSON.stringify(selectValues,null,2)}
        </Typography>
    </Box>
  );
}
</code>```

答:
You can't use the same state for your map that create the 6 select and the state for the selecting value, because you need to give a unique object to your Select value.
I explain : the mechanic for the Select is compare the value selected with the value of the select item to show the element. If you give an Array of items, he says that the comparaison ArrayAllItems and one Item is not equivalent and he creates warning and show nothing.

Example code :

```<code>import * as React from "react";
import Box from "@mui/material/Box";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import Typography from "@mui/material/Typography";

const secondTest = [

{ qtyUri: "gram", qtyLabel: "g" },
  { qtyUri: "gram", qtyLabel: "g" },
  { qtyUri: "ounce", qtyLabel: "Oz" },
];

export default function BasicSelect() {
  const [alls, setAlls] = React.useState([]);

  React.useEffect(() => {
    setAlls(getDefaultSelect());
  }, []);

  const test = "123456";

  const getDefaultSelect = () => {
    let selectArray = [];
    for (let i = 0; i < test.length; i++) {
      selectArray = [...selectArray, { qty: 1, qtyUri: "gram", qtyLabel: "g" }];
    }
    return selectArray;
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      {alls.map((element, id) => (
        <SelectComponent key={id} defaultValue={element} />
      ))}
    </Box>
  );
}

const SelectComponent = ({ defaultValue }) => {
  const [selectValue, setSelectValue] = React.useState(defaultValue);

  return (
    <Select
      value={selectValue}
      onChange={(eventData) => setSelectValue(eventData.target.value)}
    >
      {secondTest.map((item) => (
        <MenuItem key={item.qtyUri} value={item.qtyLabel}>
          {item.qtyLabel}
        </MenuItem>
      ))}
    </Select>
  );
};
</code>```

Body:
I'm using an api, and mapping the data to create a grid of drop down options (mui select). There should be two values recorded when the value changes.

I've created an object that has all of the fields in it, which changes when the user changes a select. The only issue is that the select field doesn't show what is currently selected, but if you look at the object, it is clearly changing.

How do I get the current value for each select to show?

In the following code, test is meant to replicate the length of the array returned from the API

import * as React from 'react';
import Box from '@mui/material/Box';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';
import Typography from '@mui/material/Typography';

export default function BasicSelect() {
  const test='123456';

  const getDefaultSelect = () => {
    let selectArray=[]
    for (let i=0;i<test.length;i++){
      selectArray= [...selectArray,{ qty: 1, qtyUri: 'unit', qtyLabel: 'unit' }]
    }
    return selectArray
  }

  React.useEffect(() => {
    setSelectValues(getDefaultSelect())
  }, []);

  const [selectValues, setSelectValues] = React.useState([])

  const handleSelectChange = (index, eventData) => {
    const newValues = [...selectValues]
    newValues[index]={...newValues[index], qtyUri: eventData.qtyUri, qtyLabel: eventData.qtyLabel}
    setSelectValues(newValues)
  }

  return (
    <Box sx={{ minWidth: 120 }}>

      {selectValues.map((selectValue, index) => (
        <Select
          value={{qtyUri:selectValue.qtyUri, qtyLabel:selectValue.qtyLabel}}
          onChange={(eventData) => handleSelectChange(index, eventData.target.value)}
        >
          <MenuItem value={{qtyUri:'unit', qtyLabel:'Whole'}}>Whole</MenuItem>
          <MenuItem value={{qtyUri:'gram', qtyLabel:'g'}}>g</MenuItem>
          <MenuItem value={{qtyUri:'ounce', qtyLabel:'Oz'}}>Oz</MenuItem>
        </Select>
      ))}

        <Typography>
        {JSON.stringify(selectValues,null,2)}
        </Typography>
    </Box>
  );
}

Body:
You can't use the same state for your map that create the 6 select and the state for the selecting value, because you need to give a unique object to your Select value.
I explain : the mechanic for the Select is compare the value selected with the value of the select item to show the element. If you give an Array of items, he says that the comparaison ArrayAllItems and one Item is not equivalent and he creates warning and show nothing.

Example code :

import * as React from "react";
import Box from "@mui/material/Box";
import MenuItem from "@mui/material/MenuItem";
import Select from "@mui/material/Select";
import Typography from "@mui/material/Typography";

const secondTest = [

{ qtyUri: "gram", qtyLabel: "g" },
  { qtyUri: "gram", qtyLabel: "g" },
  { qtyUri: "ounce", qtyLabel: "Oz" },
];

export default function BasicSelect() {
  const [alls, setAlls] = React.useState([]);

  React.useEffect(() => {
    setAlls(getDefaultSelect());
  }, []);

  const test = "123456";

  const getDefaultSelect = () => {
    let selectArray = [];
    for (let i = 0; i < test.length; i++) {
      selectArray = [...selectArray, { qty: 1, qtyUri: "gram", qtyLabel: "g" }];
    }
    return selectArray;
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      {alls.map((element, id) => (
        <SelectComponent key={id} defaultValue={element} />
      ))}
    </Box>
  );
}

const SelectComponent = ({ defaultValue }) => {
  const [selectValue, setSelectValue] = React.useState(defaultValue);

  return (
    <Select
      value={selectValue}
      onChange={(eventData) => setSelectValue(eventData.target.value)}
    >
      {secondTest.map((item) => (
        <MenuItem key={item.qtyUri} value={item.qtyLabel}>
          {item.qtyLabel}
        </MenuItem>
      ))}
    </Select>
  );
};


问:
Native Base: Is it possible to style Select's disabled state?
I'm using the Native Base Select component. While Select's data is loading I set isDisabled prop on Select to make the component unpressable. Problem is that by making it disabled I get a different style of Select that I can't change and adjust.

答:
You should use Pseudo Props

```<code> _disabled={{
          opacity: 30,
        }}
</code>```

Example:

```<code><Button
  _hover={{
    _text: { color: "secondary.400" },
  }}
>
</code>```

Body:
You should use Pseudo Props

 _disabled={{
          opacity: 30,
        }}

Example:

<Button
  _hover={{
    _text: { color: "secondary.400" },
  }}
>


问:
Callback function on a JTextField
I have a presenter class and several text fields in my view.

I want my presenter to say "every textfields that are listening to me, please do something now".

BUT I don't want to use Observabe/Observer, since I already use it and I don't want to get confused.

To be a bit more specific, I want the textfields to update a Map in the presenter :

Presenter.java :

```<code>public class Presenter  {

   private HashMap<String,MyObject> map;

   theMethod(){
     //to all text fields, please update the map
</code>```

Then a textfield in a panel :

```<code>JTextField tf = new JTextField("tf 1");
tf.//add something to listen to the presenter
</code>```

The beginning of the process is the method in the presenter :

theMethod() is called (not by the view)

theMethod() triggers a method linked to the TextFields

Every methods called in every TextFields are doing something

答:
Not really sure what you are asking but I see the following comment in your code

//to all text fields, please update the map

If you just want the text fields to update the map with the text in each text field then all you need is for the Presenter to have a LIst of all the text fields and then the presenter can iterate through the list and get the text of each text field and then update the map.

So your code would be something like:

```<code>Presenter presenter = new Presenter();
JTextField tf1 = new JTextField();
presenter.addPresentee( tf1 );
</code>```

All the addPresentee() method does is add the text field to the List.

Title: Callback function on a JTextField

Body:
I have a presenter class and several text fields in my view.

I want my presenter to say "every textfields that are listening to me, please do something now".

BUT I don't want to use Observabe/Observer, since I already use it and I don't want to get confused.

To be a bit more specific, I want the textfields to update a Map in the presenter :

Presenter.java :

public class Presenter  {

   private HashMap<String,MyObject> map;

   theMethod(){
     //to all text fields, please update the map

Then a textfield in a panel :

JTextField tf = new JTextField("tf 1");
tf.//add something to listen to the presenter

The beginning of the process is the method in the presenter :

theMethod() is called (not by the view)

theMethod() triggers a method linked to the TextFields

Every methods called in every TextFields are doing something

Body:
Not really sure what you are asking but I see the following comment in your code

//to all text fields, please update the map

If you just want the text fields to update the map with the text in each text field then all you need is for the Presenter to have a LIst of all the text fields and then the presenter can iterate through the list and get the text of each text field and then update the map.

So your code would be something like:

Presenter presenter = new Presenter();
JTextField tf1 = new JTextField();
presenter.addPresentee( tf1 );

All the addPresentee() method does is add the text field to the List.


问:
How i get active browser page with puppeteer?
im trying to do a auto giveaways just by clicking on a button for participate everytime the timer reset. I don't find working how i can control multiple page at the same time. i found "bringToFront()" as I understood goes from page 1 => 2 ... I used this function and another one for get current page name and i can't get page function.

(const this => "giveway" = await browser.newPage();)

If someone can help me please thanks.
Here the main code you need:

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

(async () => {
const browser = await puppeteer.launch({headless: false});
const login = await browser.newPage();
const anotherPage = await browser.newPage();

var currentPage = getActivePage(browser, 3000);
var pageNum = 1;

//Imagine idk is a giveaway website.
await login.goto('example.com');
await anotherPage.goto('idk.com');

//
  if(loaded){
    //const participateBtn =  await (don't work) =>"currentPage" (can't find it with currentPage only with anotherPage) =>".$x" ("//button[@id='giveaway-enter']")
    const participateBtn =  await currentPage.$x("//button[@id='giveaway-enter']")
      do{
        if(pageNum <= 1){
            await participateBtn[0].click();
            console.log("Click! 1");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum == 2){
            await participateBtn[0].click();
            console.log("Click! 2");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum >= 3){
            await participateBtn[0].click();
            console.log("Click! 3");
            pageNum = 1;
        }
      }while(loaded)
   }

   //Function i found.
   async function getActivePage(browser, timeout) {
   var start = new Date().getTime();
   while(new Date().getTime() - start < timeout) {
    var pages = await browser.pages();
    var arr = [];
    for (const p of pages) {
        if(await p.evaluate(() => { return document.visibilityState == 'visible' })) {
            arr.push(p);
        }
    }
    if(arr.length == 1) return arr[0];
}
throw "Unable to get active page";
}
})();
</code>```

答:
I've rewritten your code and fixes some functions and the bringToFront() function which require await since this function return as promise.

PS: I don't know if it's gonna work or not at all since i don't know the exact sites which opened by this bot.

And don't forget to choose this as the right answer if this helps you.

```<code>import puppeteer from 'puppeteer'

;(async () => {
    const browser = await puppeteer.launch({ headless: false })
    const login = await browser.newPage()
    const anotherPage = await browser.newPage()

    const getActivePage = async (browser, timeout) => {
        const pages = await browser.pages()
        let activePage
        setTimeout(() => {
            for (let i = 0; i < pages.length; i++) {
                if (await pages[i].evaluate(() => document.visibilityState === 'visible')) {
                    activePage = pages[i]
                }
            }
            throw 'Unable to get active page'
        }, timeout)
        return activePage
    }

    var currentPage = getActivePage(browser, 3000)
    var pageNum = 1

    await login.goto('https://www.', {timeout: 0, waitUntil: 'networkidle0'})
    await anotherPage.goto('idk.com', {timeout: 0, waitUntil: 'networkidle0'})

    const participateBtn = await currentPage.$x('//button[@id="giveaway-enter"]')
    do {
        if (pageNum <= 1) {
            await participateBtn[0].click()
            console.log('Click! 1')
            await currentPage.bringToFront()
            pageNum++
        } else if (pageNum == 2) {
            await participateBtn[0].click()
            console.log('Click! 2')
            await currentPage.bringToFront()
            pageNum++
        } else if (pageNum >= 3) {
            await participateBtn[0].click()
            console.log('Click! 3')
            pageNum = 1
        }
    } while (true)
})()
</code>```

Body:
im trying to do a auto giveaways just by clicking on a button for participate everytime the timer reset. I don't find working how i can control multiple page at the same time. i found "bringToFront()" as I understood goes from page 1 => 2 ... I used this function and another one for get current page name and i can't get page function.

(const this => "giveway" = await browser.newPage();)

If someone can help me please thanks.
Here the main code you need:

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless: false});
const login = await browser.newPage();
const anotherPage = await browser.newPage();

var currentPage = getActivePage(browser, 3000);
var pageNum = 1;

//Imagine idk is a giveaway website.
await login.goto('example.com');
await anotherPage.goto('idk.com');

//
  if(loaded){
    //const participateBtn =  await (don't work) =>"currentPage" (can't find it with currentPage only with anotherPage) =>".$x" ("//button[@id='giveaway-enter']")
    const participateBtn =  await currentPage.$x("//button[@id='giveaway-enter']")
      do{
        if(pageNum <= 1){
            await participateBtn[0].click();
            console.log("Click! 1");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum == 2){
            await participateBtn[0].click();
            console.log("Click! 2");
            currentPage.bringToFront(); //Ya pas sa avec currentPage
            pageNum++;
        }else if(pageNum >= 3){
            await participateBtn[0].click();
            console.log("Click! 3");
            pageNum = 1;
        }
      }while(loaded)
   }

   //Function i found.
   async function getActivePage(browser, timeout) {
   var start = new Date().getTime();
   while(new Date().getTime() - start < timeout) {
    var pages = await browser.pages();
    var arr = [];
    for (const p of pages) {
        if(await p.evaluate(() => { return document.visibilityState == 'visible' })) {
            arr.push(p);
        }
    }
    if(arr.length == 1) return arr[0];
}
throw "Unable to get active page";
}
})();

Body:
I've rewritten your code and fixes some functions and the bringToFront() function which require await since this function return as promise.

PS: I don't know if it's gonna work or not at all since i don't know the exact sites which opened by this bot.

And don't forget to choose this as the right answer if this helps you.

import puppeteer from 'puppeteer'

;(async () => {
    const browser = await puppeteer.launch({ headless: false })
    const login = await browser.newPage()
    const anotherPage = await browser.newPage()

    const getActivePage = async (browser, timeout) => {
        const pages = await browser.pages()
        let activePage
        setTimeout(() => {
            for (let i = 0; i < pages.length; i++) {
                if (await pages[i].evaluate(() => document.visibilityState === 'visible')) {
                    activePage = pages[i]
                }
            }
            throw 'Unable to get active page'
        }, timeout)
        return activePage
    }

    var currentPage = getActivePage(browser, 3000)
    var pageNum = 1

    await login.goto('https://www.', {timeout: 0, waitUntil: 'networkidle0'})
    await anotherPage.goto('idk.com', {timeout: 0, waitUntil: 'networkidle0'})

    const participateBtn = await currentPage.$x('//button[@id="giveaway-enter"]')
    do {
        if (pageNum <= 1) {
            await participateBtn[0].click()
            console.log('Click! 1')
            await currentPage.bringToFront()
            pageNum++
        } else if (pageNum == 2) {
            await participateBtn[0].click()
            console.log('Click! 2')
            await currentPage.bringToFront()
            pageNum++
        } else if (pageNum >= 3) {
            await participateBtn[0].click()
            console.log('Click! 3')
            pageNum = 1
        }
    } while (true)
})()