问:
XPath for paragraph following a header?
This is the Page Code

O que é Cicatri Renov ?

Nada como ter um leave-in de tratamento como aliado para reparar os danos do cabelo. Cicatri Renov além de ser um reparador para cabelos danificados, também serve como protetor térmico. Sua fórmula conta com 10 principais benefícios que os fios necessitam:

Reparação instantânea;

Selagem das pontas;

100% mais brilho;

Maciez profunda;

Toque deslizante;

Desembaraço imediato;

10x menos quebra;

Antifrizz;

Antiumidade;

Proteção térmica.

Para que serve o Cicatri Renov?

O leave-in Elseve pode ser utilizado em todos os tipos de cabelo, atendendo principalmente os danificados. Traz proteção, reparação e revitalização aos fios. Pode ser usado com o cabelo seco ou molhado, antes ou depois do secador.

Benefícios

O Leave-In Cicatri Renov faz uma plástica capilar instantânea nos fios, sem pesar.

Sela as pontas duplas e o frizz.

Repara instantaneamente, com um toque deslizante.

Proteção térmica.

Como usar o Cicatri Renov?

Distribua uma pequena quantidade nos fios secos ou úmidos, do comprimento às pontas. Não enxágue!

Dica: Como proteção térmica, pode ser usado antes ou depois de escova ou chapinha.

Precaução

Caso o produto caia nos olhos, lave-os imediatamente com água.

Mantenha fora do alcance de crianças.

Composição

Aqua/water, Dimethicone, Cetearyl Alcohol, Phenyl Trimethicone, Amodimethicone, Quaternium-33, Phenoxyethanol, Steareth-20, Acetic Acid, Ppg-1 Trideceth-6, Behentrimonium Methosulfate, Trideceth-5, Trideceth-10, Polyquaternium-37, Chlorhexidine Digluconate, Dimethiconol, Limonene, Linalool, Benzyl Salicylate, Benzyl Alcohol, Propylene Glycol Dicaprilate/dicaprate, 2-oleamido-1,3-octa-decanediol, Alpha-isomethyl Ionone, Geraniol, Cetyl Alcohol, Citronellol, Citral, Hexyl Cinnamal, Glycerin, Glyceryl , Linoleate, Glyceryl Oleate, Glyceryl Linoleate, Parfim/ Fragrance.

```

I want to make an XPath for Octoparse. I want to make an XPath that only selects a text that matches a specific heading. In my case it is "Composição" and the text is under the
.

答:
This XPath,

```<code>//p[preceding-sibling::*[1][self::h2][.='Composição']]
</code>```

will select all p elements whose immediately preceding sibling is an h2 element with string value of "Composição".

Title: XPath for paragraph following a header?

Body:
This is the Page Code

O que é Cicatri Renov ?

Nada como ter um leave-in de tratamento como aliado para reparar os danos do cabelo. Cicatri Renov além de ser um reparador para cabelos danificados, também serve como protetor térmico. Sua fórmula conta com 10 principais benefícios que os fios necessitam:

Reparação instantânea;

Selagem das pontas;

100% mais brilho;

Maciez profunda;

Toque deslizante;

Desembaraço imediato;

10x menos quebra;

Antifrizz;

Antiumidade;

Proteção térmica.

Para que serve o Cicatri Renov?

O leave-in Elseve pode ser utilizado em todos os tipos de cabelo, atendendo principalmente os danificados. Traz proteção, reparação e revitalização aos fios. Pode ser usado com o cabelo seco ou molhado, antes ou depois do secador.

Benefícios

O Leave-In Cicatri Renov faz uma plástica capilar instantânea nos fios, sem pesar.

Sela as pontas duplas e o frizz.

Repara instantaneamente, com um toque deslizante.

Proteção térmica.

Como usar o Cicatri Renov?

Distribua uma pequena quantidade nos fios secos ou úmidos, do comprimento às pontas. Não enxágue!

Dica: Como proteção térmica, pode ser usado antes ou depois de escova ou chapinha.

Precaução

Caso o produto caia nos olhos, lave-os imediatamente com água.

Mantenha fora do alcance de crianças.

Composição

Aqua/water, Dimethicone, Cetearyl Alcohol, Phenyl Trimethicone, Amodimethicone, Quaternium-33, Phenoxyethanol, Steareth-20, Acetic Acid, Ppg-1 Trideceth-6, Behentrimonium Methosulfate, Trideceth-5, Trideceth-10, Polyquaternium-37, Chlorhexidine Digluconate, Dimethiconol, Limonene, Linalool, Benzyl Salicylate, Benzyl Alcohol, Propylene Glycol Dicaprilate/dicaprate, 2-oleamido-1,3-octa-decanediol, Alpha-isomethyl Ionone, Geraniol, Cetyl Alcohol, Citronellol, Citral, Hexyl Cinnamal, Glycerin, Glyceryl , Linoleate, Glyceryl Oleate, Glyceryl Linoleate, Parfim/ Fragrance.

I want to make an XPath for Octoparse. I want to make an XPath that only selects a text that matches a specific heading. In my case it is "Composição" and the text is under the
.

Body:
This XPath,

//p[preceding-sibling::*[1][self::h2][.='Composição']]

will select all p elements whose immediately preceding sibling is an h2 element with string value of "Composição".


来源: stackexchange

问:
Why functions that produce LiveData or Flow, don't have to be called from CoroutineScope?
When we usually use Room, we use Kotlin Coroutine and make a DAO to access Room and to get the result. most of functions usually have suspend modifier at the beginning of function but LiveData and Flow.
for instance, let's take a look these two code below.

```<code>@Query("SELECT * FROM MockTable")
suspend fun allMockDataWithSuspend(): List<MockData>

@Query("SELECT * FROM MockTable")
fun allMockData(): Flow<List<MockData>> // or LiveData<List<MockData>>
</code>```

when we use suspend modifier, we need to call the function in coroutine scope because the function has suspend modifier. but we don't need to call the function in coroutine when the function's result is LiveData or Flow even though it's I/O access.

How is this possible?

答:
The LiveData and the Kotlin's Flows are basically kind of observables, which means something will happen at some point in time and these observables will notify it.

So when we think through the angle of observability, from the user point of view we just need to keep a box ready and open to catch the observables when it arrives, until it comes let the box be closed (suspend state)

Android way of observing is done via LiveData

```<code>lveViewmodel.liveData.observe(this, {

  })
</code>```

Kotlin way of observing is done via Flow ( One of the use-case of flow is acting like an observable)

```<code>lveViewmodel.stateFlow.collect {
               //suspendable block
            }
</code>```

And CoroutineScope is different, it's like a grouping of certain things, here in terms of kotlin we can say grouping on coroutines and controlling them.

ContentLicense: CC BY-SA 4.0

Body:
When we usually use Room, we use Kotlin Coroutine and make a DAO to access Room and to get the result. most of functions usually have suspend modifier at the beginning of function but LiveData and Flow.
for instance, let's take a look these two code below.

@Query("SELECT * FROM MockTable")
suspend fun allMockDataWithSuspend(): List<MockData>

@Query("SELECT * FROM MockTable")
fun allMockData(): Flow<List<MockData>> // or LiveData<List<MockData>>

when we use suspend modifier, we need to call the function in coroutine scope because the function has suspend modifier. but we don't need to call the function in coroutine when the function's result is LiveData or Flow even though it's I/O access.

How is this possible?

Body:
The LiveData and the Kotlin's Flows are basically kind of observables, which means something will happen at some point in time and these observables will notify it.

So when we think through the angle of observability, from the user point of view we just need to keep a box ready and open to catch the observables when it arrives, until it comes let the box be closed (suspend state)

Android way of observing is done via LiveData

lveViewmodel.liveData.observe(this, {

  })

Kotlin way of observing is done via Flow ( One of the use-case of flow is acting like an observable)

lveViewmodel.stateFlow.collect {
               //suspendable block
            }

And CoroutineScope is different, it's like a grouping of certain things, here in terms of kotlin we can say grouping on coroutines and controlling them.


问:
Can an iframe check if itself is in viewport or not?
I'm creating an iframe with a small HTML5 video. the video shouldn't start playing unless the iframe is in the viewport.

I noticed that this isn't as easy as I would like since the iframe is like a sandboxed environment. Is it even possible for an iframe to know if it is in the viewport?

答: If the IFRAME source attribute "src" is executed in the same domain, you can do it but if the IFRAME take the src to a cross domain you need to be authorised to do it from the server where the file is hosted by configuring the CORS acceptation from your domain.</p>


问:
AWS: Permissions for exporting logs from Cloudwatch to Amazon S3
I am trying to export logs from one of my CloudWatch log groups into Amazon S3, using AWS console.

I followed the guide from AWS documentation but with little success. My organization does not allow me to manage IAM roles/policies, however I was able to find out that my role is allowed all log-related operations (logs:* on all resources within the account).

Currently, I am stuck on the following error message:

Could not create export task. PutObject call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.

My bucket policy is set in the following way:

```<code>{
    [
        ...
        {
            "Sid": "Cloudwatch Log Export 1",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-central-1.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::my-bucket"
        },
        {
            "Sid": "Cloudwatch Log Export 2",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-central-1.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::my-bucket/*"
        }
    ]
}
</code>```

Prior to editing bucket policy, my error message had been

Could not create export task. GetBucketAcl call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.

but editing the bucket policy fixed that. I would expect allowing PutObject to do the same, but this has not been the case.

Thank you for help.

答:
Please check this guide Export log data to Amazon S3 using the AWS CLI

Policy's looks like the document that you share but slight different.
Assuming that you are doing this in same account and same region, please check that you are placing the right region ( in this example is us-east-2)

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "s3:GetBucketAcl",
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::my-exported-logs",
            "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
        },
        {
            "Action": "s3:PutObject" ,
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::my-exported-logs/*",
            "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
            "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
        }
    ]
}
```

I think that bucket owner full control is not the problem here, the only chance is the region.
Anyway, take a look to the other two examples in case that you were in different accounts/ using role instead user.

This solved my issue, that was the same that you mention.

Body:
I am trying to export logs from one of my CloudWatch log groups into Amazon S3, using AWS console.

I followed the guide from AWS documentation but with little success. My organization does not allow me to manage IAM roles/policies, however I was able to find out that my role is allowed all log-related operations (logs:* on all resources within the account).

Currently, I am stuck on the following error message:

Could not create export task. PutObject call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.

My bucket policy is set in the following way:

{
    [
        ...
        {
            "Sid": "Cloudwatch Log Export 1",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-central-1.amazonaws.com"
            },
            "Action": "s3:GetBucketAcl",
            "Resource": "arn:aws:s3:::my-bucket"
        },
        {
            "Sid": "Cloudwatch Log Export 2",
            "Effect": "Allow",
            "Principal": {
                "Service": "logs.eu-central-1.amazonaws.com"
            },
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::my-bucket/*"
        }
    ]
}

Prior to editing bucket policy, my error message had been

Could not create export task. GetBucketAcl call on the given bucket failed. Please check if CloudWatch Logs has been granted permission to perform this operation.

but editing the bucket policy fixed that. I would expect allowing PutObject to do the same, but this has not been the case.

Thank you for help.

Body:
Please check this guide Export log data to Amazon S3 using the AWS CLI

Policy's looks like the document that you share but slight different.
Assuming that you are doing this in same account and same region, please check that you are placing the right region ( in this example is us-east-2)

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "s3:GetBucketAcl",
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::my-exported-logs",
            "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
        },
        {
            "Action": "s3:PutObject" ,
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::my-exported-logs/*",
            "Condition": { "StringEquals": { "s3:x-amz-acl": "bucket-owner-full-control" } },
            "Principal": { "Service": "logs.us-east-2.amazonaws.com" }
        }
    ]
}

I think that bucket owner full control is not the problem here, the only chance is the region.
Anyway, take a look to the other two examples in case that you were in different accounts/ using role instead user.

This solved my issue, that was the same that you mention.


问:
Angular-Listening to store changes & emit a value from a Service component to a different component - only after Service completes certain operations
Here we have to classes GetDataAsyncService which waits for change in the store (and not executes the block of code under it until a change in the store (    this.getDataAsyncService.getAsyncData().subscribe((data)=>{
)}). When it is called from MainComponent it will get return of(propA); (from GetDataAsyncService) before the block of code in the listener is executed - because the listener is still waiting for a change in the store.
I want to emit that observable only when that operation block is executed.

```<code>export class GetDataAsyncService {
     propA;
     constructor(private store: Store<AppState>)

     getData():Observable<any>{
       this.store.pipe(select(appState)).subscribe((val)=>{
         // operation block
         // some operations
         // some more operations
         this.propA = val.propA;
       })
       return of(propA); // this should be emitted with the latest value only when the block of code above executes - not before that
     }

}

export MainComponent implenents OnInit{
  propA: string = '';
  constructor(private getDataAsyncService: GetDataAsyncService){}

  ngOnInit(): void{
    this.getDataAsyncService.getAsyncData().subscribe((data)=>{
      this.propA = data.propA;
    })
  }
  // any operation involving propA
  // code ......

}
</code>```

答:
You can achieve that by returning the Observable itself from the getData function and mapping it to the required prop, instead of subscribe to it, like the following:

export class GetDataAsyncService {
  propA;
  constructor(private store: Store<AppState>) {}

  getData(): Observable<any> {
    return this.store.pipe(
      select(appState),
      map((val) => val.propA)
    );
  }
}

export class MainComponent implements OnInit {
  propA: string = '';
  constructor(private getDataAsyncService: GetDataAsyncService) {}

  ngOnInit(): void {
    this.getDataAsyncService.getAsyncData().subscribe((propA) => {
      this.propA = propA;
    });
  }
}
```

Body:
Here we have to classes GetDataAsyncService which waits for change in the store (and not executes the block of code under it until a change in the store (    this.getDataAsyncService.getAsyncData().subscribe((data)=>{
)}). When it is called from MainComponent it will get return of(propA); (from GetDataAsyncService) before the block of code in the listener is executed - because the listener is still waiting for a change in the store.
I want to emit that observable only when that operation block is executed.

export class GetDataAsyncService {
     propA;
     constructor(private store: Store<AppState>)

     getData():Observable<any>{
       this.store.pipe(select(appState)).subscribe((val)=>{
         // operation block
         // some operations
         // some more operations
         this.propA = val.propA;
       })
       return of(propA); // this should be emitted with the latest value only when the block of code above executes - not before that
     }

}

export MainComponent implenents OnInit{
  propA: string = '';
  constructor(private getDataAsyncService: GetDataAsyncService){}

  ngOnInit(): void{
    this.getDataAsyncService.getAsyncData().subscribe((data)=>{
      this.propA = data.propA;
    })
  }
  // any operation involving propA
  // code ......

}


问:
How to read/change local JSON for Chrome Extension?
I am developing extension and I want to read and change local JSON file in extension file directory.

How to make this?

答:
I don't know if you can store data in a JSON file, but you can always use localStorage. If you set the localStorage, the data will not disappear every time you open the extension popup.

let data = JSON.parse(localStorage.data ?? "{}");
data.say = "hello world";
localStorage.data = JSON.stringify(data);
```


问:
For every row with the same name, find the 5 lowest number Pandas Python
My data frame looks like this

```<code>Location  week  Number

Austria   1     154
Austria   2     140
Belgium   1     139
Bulgaria  2     110
Bulgaria  1     164
</code>```

the solution should look like this

```<code>Location  week  Number

Austria   3     100
Austria   2     101
Austria   1     102

Bulgaria  2     100
Bulgaria  3     101
Bulgaria  1     102
</code>```

this means that I need to display

Column 1 : I need to group the countries by name

Column 2 : Week (every country has 53 weeks assigned to them)

Column 3 : Show the numbers that occured in each of 53 weeks in an ascending order

I can not get my head around this

答:
Sort the rows in the order your like (here by Location and Number) and take the first 5 rows per group with groupby+head:

```<code>df.sort_values(by=['Location', 'Number']).groupby('Location').head(5)
</code>```

output:

```<code>   Location  week  Number
0   Austria     3     100
1   Austria     2     101
2   Austria     1     102
3  Bulgaria     2     100
4  Bulgaria     3     101
5  Bulgaria     1     102

</code>```

Body:
My data frame looks like this

Location  week  Number

Austria   1     154
Austria   2     140
Belgium   1     139
Bulgaria  2     110
Bulgaria  1     164

the solution should look like this

Location  week  Number

Austria   3     100
Austria   2     101
Austria   1     102

Bulgaria  2     100
Bulgaria  3     101
Bulgaria  1     102

this means that I need to display

Column 1 : I need to group the countries by name

Column 2 : Week (every country has 53 weeks assigned to them)

Column 3 : Show the numbers that occured in each of 53 weeks in an ascending order

I can not get my head around this

Body:
Sort the rows in the order your like (here by Location and Number) and take the first 5 rows per group with groupby+head:

df.sort_values(by=['Location', 'Number']).groupby('Location').head(5)

output:

   Location  week  Number
0   Austria     3     100
1   Austria     2     101
2   Austria     1     102
3  Bulgaria     2     100
4  Bulgaria     3     101
5  Bulgaria     1     102


问:
not getting the data from Serializer
view.py

@csrf_exempt

def blog_list(request):

```<code>if request.method == 'GET':
    post = Post.objects.all()
    serializer = BlogSerializer(post, many=True)
    return JsonResponse(serializer.data,safe=False)

elif request.method == 'POST':
    data = JSONParser().parse(request)
    serializer = BlogSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)
</code>```

class BlogSerializer(serializers.Serializer):

```<code>class Meta:
    model = Post
    fields = ['author', 'title',  'text',  'published_date']
</code>```

class Post(models.Model):

```<code>author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title
</code>```

答: You should pass request.data to serializer. Passing whole request won't return anything, because request does not have fields you declared in serializer. They are in post data.

Title: not getting the data from Serializer

Body:
view.py

@csrf_exempt

def blog_list(request):

if request.method == 'GET':
    post = Post.objects.all()
    serializer = BlogSerializer(post, many=True)
    return JsonResponse(serializer.data,safe=False)

elif request.method == 'POST':
    data = JSONParser().parse(request)
    serializer = BlogSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return JsonResponse(serializer.data, status=201)
    return JsonResponse(serializer.errors, status=400)

class BlogSerializer(serializers.Serializer):

class Meta:
    model = Post
    fields = ['author', 'title',  'text',  'published_date']

class Post(models.Model):

author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)

def publish(self):
    self.published_date = timezone.now()
    self.save()

def __str__(self):
    return self.title


问:
TimedRotatingFileHandler not working for minute intervals
I have configured a couple of TimedRotatingFileHandlers like this.

```<code>[loggers]
keys=root

[handlers]
keys=logfile, logfile_errors

[formatters]
keys=logfileformatter

[logger_root]
level=DEBUG
handlers=logfile, logfile_errors

[formatter_logfileformatter]
format=%(asctime)s %(name)-12s: %(levelname)s %(message)s

[handler_logfile]
class=handlers.TimedRotatingFileHandler
level=DEBUG
args=('./logs/log.out','S', 1, 10)
formatter=logfileformatter

[handler_logfile_errors]
class=handlers.TimedRotatingFileHandler
level=ERROR
args=('./logs/errors/log.out','M', 1, 10)
formatter=logfileformatter
</code>```

However, when I log something like this in different minutes

```<code>logging.error('MY ERROR')
</code>```

Backup files (1 per second) are created for the logfile handler but not for the logfile_errors handler (I would expect one backup file per minute in which an error was logged). Am I doing something wrong when configuring the handlers?

答:
I don't see any error in your config... it works on my machine :-)

Here is a minimal working example so you can check on your side, using your config without any modification:

```<code>import logging
import logging.config

import time

logging.config.fileConfig('mytestlog.conf')

while True:

  logging.error('other error message')
  time.sleep(0.5);

</code>```

Resulting files after running about 3 minutes:

```<code>$ ls logs | sort
errors
log.out
log.out.2022-02-09_09-54-20
log.out.2022-02-09_09-54-21
log.out.2022-02-09_09-54-22
log.out.2022-02-09_09-54-23
log.out.2022-02-09_09-54-24
log.out.2022-02-09_09-54-25
log.out.2022-02-09_09-54-26
log.out.2022-02-09_09-54-27
log.out.2022-02-09_09-54-28
log.out.2022-02-09_09-54-29

$ ls logs/errors/ | sort
log.out
log.out.2022-02-09_09-51
log.out.2022-02-09_09-52
</code>```

Sample contents:

```<code>$ cat logs/log.out.2022-02-09_09-54-20
2022-02-09 09:54:20,109 root        : ERROR other error message
2022-02-09 09:54:20,610 root        : ERROR other error message

$ cat logs/errors/log.out.2022-02-09_09-52
2022-02-09 09:52:54,367 root        : ERROR other error message
2022-02-09 09:52:54,869 root        : ERROR other error message
2022-02-09 09:52:55,370 root        : ERROR other error message
2022-02-09 09:52:55,872 root        : ERROR other error message
2022-02-09 09:52:56,373 root        : ERROR other error message
2022-02-09 09:52:56,875 root        : ERROR other error message
2022-02-09 09:52:57,376 root        : ERROR other error message
..
..
2022-02-09 09:53:52,536 root        : ERROR other error message
2022-02-09 09:53:53,037 root        : ERROR other error message
2022-02-09 09:53:53,540 root        : ERROR other error message
</code>```

Body:
I have configured a couple of TimedRotatingFileHandlers like this.

[loggers]
keys=root

[handlers]
keys=logfile, logfile_errors

[formatters]
keys=logfileformatter

[logger_root]
level=DEBUG
handlers=logfile, logfile_errors

[formatter_logfileformatter]
format=%(asctime)s %(name)-12s: %(levelname)s %(message)s

[handler_logfile]
class=handlers.TimedRotatingFileHandler
level=DEBUG
args=('./logs/log.out','S', 1, 10)
formatter=logfileformatter

[handler_logfile_errors]
class=handlers.TimedRotatingFileHandler
level=ERROR
args=('./logs/errors/log.out','M', 1, 10)
formatter=logfileformatter

However, when I log something like this in different minutes

logging.error('MY ERROR')

Backup files (1 per second) are created for the logfile handler but not for the logfile_errors handler (I would expect one backup file per minute in which an error was logged). Am I doing something wrong when configuring the handlers?

Body:
I don't see any error in your config... it works on my machine :-)

Here is a minimal working example so you can check on your side, using your config without any modification:

import logging
import logging.config

import time

logging.config.fileConfig('mytestlog.conf')

while True:

  logging.error('other error message')
  time.sleep(0.5);

Resulting files after running about 3 minutes:

$ ls logs | sort
errors
log.out
log.out.2022-02-09_09-54-20
log.out.2022-02-09_09-54-21
log.out.2022-02-09_09-54-22
log.out.2022-02-09_09-54-23
log.out.2022-02-09_09-54-24
log.out.2022-02-09_09-54-25
log.out.2022-02-09_09-54-26
log.out.2022-02-09_09-54-27
log.out.2022-02-09_09-54-28
log.out.2022-02-09_09-54-29

$ ls logs/errors/ | sort
log.out
log.out.2022-02-09_09-51
log.out.2022-02-09_09-52

Sample contents:

$ cat logs/log.out.2022-02-09_09-54-20
2022-02-09 09:54:20,109 root        : ERROR other error message
2022-02-09 09:54:20,610 root        : ERROR other error message

$ cat logs/errors/log.out.2022-02-09_09-52
2022-02-09 09:52:54,367 root        : ERROR other error message
2022-02-09 09:52:54,869 root        : ERROR other error message
2022-02-09 09:52:55,370 root        : ERROR other error message
2022-02-09 09:52:55,872 root        : ERROR other error message
2022-02-09 09:52:56,373 root        : ERROR other error message
2022-02-09 09:52:56,875 root        : ERROR other error message
2022-02-09 09:52:57,376 root        : ERROR other error message
..
..
2022-02-09 09:53:52,536 root        : ERROR other error message
2022-02-09 09:53:53,037 root        : ERROR other error message
2022-02-09 09:53:53,540 root        : ERROR other error message


问:
MY web Broswer doesn't support silver light toolkit tap event and flick event
```<code>       <controls:PivotItem Header="item1">
            <Grid>
                <phone:WebBrowser IsHitTestVisible="False" Source="www.google.com">
                    <toolkit:GestureService.GestureListener>
                        <toolkit:GestureListener Tap="onTap" Flick="GestureListener_Flick" />
                    </toolkit:GestureService.GestureListener>

                </phone:WebBrowser>
            </Grid>
        </controls:PivotItem>
</code>```

the code behind this

```<code>       private void onTap(object sender, GestureEventArgs e)
    {
        MessageBox.Show("tap");
       // Listbox.index = m.SelectedIndex;
        //  m.SelectedIndex = -1;
      //  App.Navigate(new Uri("/Home.xaml", UriKind.Relative));

    }
    private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
    {
        if (e.Direction == System.Windows.Controls.Orientation.Horizontal)
        {
            if (e.HorizontalVelocity < 0)
            {
                MessageBox.Show("right");
            }
            else
            {
                MessageBox.Show("left");
            }
        }
        else
        {
            if (e.VerticalVelocity < 0)
            {
                MessageBox.Show("up");
            }
            else
            {
                MessageBox.Show("down");
            }
        }
    }
</code>```

but it doesn't work ...
thanx in advance..

答: These events are not supported on the WebBrowser control. The main reason for this is probably that it's hard to distinguish whether the user is interacting with a webpage (scrolling or clicking a link) or whether you would like to capture the events on the control.</p>

ContentLicense: CC BY-SA 3.0

Body:
       <controls:PivotItem Header="item1">
            <Grid>
                <phone:WebBrowser IsHitTestVisible="False" Source="www.google.com">
                    <toolkit:GestureService.GestureListener>
                        <toolkit:GestureListener Tap="onTap" Flick="GestureListener_Flick" />
                    </toolkit:GestureService.GestureListener>

                </phone:WebBrowser>
            </Grid>
        </controls:PivotItem>

the code behind this

       private void onTap(object sender, GestureEventArgs e)
    {
        MessageBox.Show("tap");
       // Listbox.index = m.SelectedIndex;
        //  m.SelectedIndex = -1;
      //  App.Navigate(new Uri("/Home.xaml", UriKind.Relative));

    }
    private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
    {
        if (e.Direction == System.Windows.Controls.Orientation.Horizontal)
        {
            if (e.HorizontalVelocity < 0)
            {
                MessageBox.Show("right");
            }
            else
            {
                MessageBox.Show("left");
            }
        }
        else
        {
            if (e.VerticalVelocity < 0)
            {
                MessageBox.Show("up");
            }
            else
            {
                MessageBox.Show("down");
            }
        }
    }

but it doesn't work ...
thanx in advance..


问:
Getting error: module 'tensorflow.keras.layers' has no attribute 'Normalization'
I am using

```<code>tf.keras.layers.Normalization(axis=-1)
</code>```

and am getting the following error:

```<code>module 'tensorflow.keras.layers' has no attribute 'Normalization'
</code>```

I'm following the tensorflow tutorial available here. I went through the solution given here and updated my tensorflow to v2.6.0. But still getting the error. I am new to tensorflow. Any help would be greatly appreciated.

答: For anyone who may be looking for answer, I ditched Anconda altogether and set up everything from scratch. Thanks for all the responses.</p>

Body:
I am using

tf.keras.layers.Normalization(axis=-1)

and am getting the following error:

module 'tensorflow.keras.layers' has no attribute 'Normalization'

I'm following the tensorflow tutorial available here. I went through the solution given here and updated my tensorflow to v2.6.0. But still getting the error. I am new to tensorflow. Any help would be greatly appreciated.


问:
How do I add a listener to a search form in Angular material?
I'm working with Angular material and I have a search form. As shown in the following code, I have a button and after a click event on the button, the words written in the search form are given to the  searchProductByName method as parameters. I'd like to substitute the button with a listener that, after having written something in the form and having clicked on enter (instead of the button), grabs the things written in the search form and passes them to the searchProductByName method as parameters. Is there a way to do so?

```<code><form class="search-form" >
    <mat-form-field class="example-full-width" appearance="fill">
      <mat-label >Search</mat-label>
      <input #input type="text" ngModel name="name" class="form-control" id="name"
             aria-label="Search"
             matInput
             >
             <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

    </mat-form-field>
  </form>
</code>```

答:
If the searchPruductByName is a method that is using http request to search from backend, for example - I would suggest to also implement debounce'ing the search as well. Otherwise it would search with each keystroke. A nice elegant way would be to use a debounce decorator. https://medium.com/time-machine/how-to-implement-debounce-decorator-2e963b70cd27

<form class="search-form" >
    <input #input type="text" ngModel name="name" class="form-control" id="name"
         (input)="searchProductByName($event); onInput($event)"
         aria-label="Search"
         matInput>
  </mat-form-field>
</form>
```
<pre class="lang-js prettyprint-override"><code>onInput(event: any) {
   console.log(event.target.value);
}
</code>```

To navigate to link on pressing "Enter" add to constructor Router and then use router to navigate.

constructor(router: Router) {}

onNavigate() {
// other stuff
this.router.navigateByUrl('/products/searchProduct/by_name')
}
```
<pre class="lang-html prettyprint-override"><code><input (keyup.enter)="searchProductByName(input.value); onNavigate()">
</code>```

Body:
I'm working with Angular material and I have a search form. As shown in the following code, I have a button and after a click event on the button, the words written in the search form are given to the  searchProductByName method as parameters. I'd like to substitute the button with a listener that, after having written something in the form and having clicked on enter (instead of the button), grabs the things written in the search form and passes them to the searchProductByName method as parameters. Is there a way to do so?

<form class="search-form" >
    <mat-form-field class="example-full-width" appearance="fill">
      <mat-label >Search</mat-label>
      <input #input type="text" ngModel name="name" class="form-control" id="name"
             aria-label="Search"
             matInput
             >
             <button (click)="searchProductByName(input.value)" routerLink="/products/searchProduct/by_name"  routerLinkActive="active">Go</button>

    </mat-form-field>
  </form>

Body:
If the searchPruductByName is a method that is using http request to search from backend, for example - I would suggest to also implement debounce'ing the search as well. Otherwise it would search with each keystroke. A nice elegant way would be to use a debounce decorator. https://medium.com/time-machine/how-to-implement-debounce-decorator-2e963b70cd27

<form class="search-form" >
    <input #input type="text" ngModel name="name" class="form-control" id="name"
         (input)="searchProductByName($event); onInput($event)"
         aria-label="Search"
         matInput>
  </mat-form-field>
</form>

onInput(event: any) {
   console.log(event.target.value);
}

To navigate to link on pressing "Enter" add to constructor Router and then use router to navigate.

constructor(router: Router) {}

onNavigate() {
// other stuff
this.router.navigateByUrl('/products/searchProduct/by_name')
}

<input (keyup.enter)="searchProductByName(input.value); onNavigate()">


答:
Checking whether an element is in the viewport

Here you can find a nice implementation for checking whether an element is in the viewport:

```<code>function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}
</code>```

Reaching the parent window

Inside the iframe you can reach the parent window like this:

```<code>if (window.parent.isInViewport(document.querySelector('iframe'))) {
    //do something
}
</code>```

(in the above I'm searching for the first iframe in the parent window for the sake of simplicity, you might need to change your selector)

Yet, modern browsers only allow this kind of communication if the page the iframe points to is of the same domain the main page points to. If the two pages are of different domains, then modern browsers will throw a CORSS error.

You can have a messaging between a main page and the page loaded into the iframe as an alternative, but for that purpose the developers of the main page need to cooperate.

Title: Can an iframe check if itself is in viewport or not?

Body:
I'm creating an iframe with a small HTML5 video. the video shouldn't start playing unless the iframe is in the viewport.

I noticed that this isn't as easy as I would like since the iframe is like a sandboxed environment. Is it even possible for an iframe to know if it is in the viewport?

Body:
Checking whether an element is in the viewport

Here you can find a nice implementation for checking whether an element is in the viewport:

function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
}

Reaching the parent window

Inside the iframe you can reach the parent window like this:

if (window.parent.isInViewport(document.querySelector('iframe'))) {
    //do something
}

(in the above I'm searching for the first iframe in the parent window for the sake of simplicity, you might need to change your selector)

Yet, modern browsers only allow this kind of communication if the page the iframe points to is of the same domain the main page points to. If the two pages are of different domains, then modern browsers will throw a CORSS error.

You can have a messaging between a main page and the page loaded into the iframe as an alternative, but for that purpose the developers of the main page need to cooperate.


问:
How to create an array of objects with all objects from multiple arrays?
Given de following arrays:

```<code>const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]
</code>```

What's the best way performance-wise to generate an array of objects with a similar structure to this:

```<code>const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]

</code>```

答:
```<code>const allStudents = classes.reduce((acc,curr)=>{
  return [...acc,...curr.students]
},[])
</code>```

I think this is a simple and easy to understand way to group students in one array.

Body:
Given de following arrays:

const classes = [
  {
    students: [
       Student1,
       Student2,
    ]
  },
  {
    students: [
       Student3,
       Student4,
    ]
  }
]

What's the best way performance-wise to generate an array of objects with a similar structure to this:

const allStudents = [
  Student1,
  Student2,
  Student3,
  Student4
]

Body:
const allStudents = classes.reduce((acc,curr)=>{
  return [...acc,...curr.students]
},[])

I think this is a simple and easy to understand way to group students in one array.


问:
(watch)The expression doesn't evaluate to a function, so it can't be invoked
I'm trying to set up a theme for my flutter project, ill greatly appreciate if you kindly show me another way to do that.

```<code>import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:picpuzzle/routes/route_name.dart';
import 'package:picpuzzle/widgets/login/login_screen.dart';
import 'package:picpuzzle/widgets/main/main_page.dart';
import 'package:picpuzzle/widgets/puzzle/puzzle_list_page.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'common/constants.dart';

/// use for DarkMode,not sync  with system
final DarkModeProvider = StateProvider((ref) => false);

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  void initApp(BuildContext context) {}

  @override
  Widget build(BuildContext context) {
    /// init
    initApp(context);
    return Consumer(
      builder: (context, watch, _) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          localizationsDelegates: [
            AppLocalizations.delegate, // Add this line
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: [
            const Locale('en', ''), // English, no country code
            const Locale('ja', ''), // Japanese, no country code
          ],
          title: 'Pic Puzzle',
          initialRoute: RouteName.Login,
          routes: {
            RouteName.Login: (context) => LoginScreen(),
            RouteName.Main: (context) => MainPage(),
            RouteName.Home: (context) => PuzzleListPage(),
          },
          theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,
          // darkTheme: darkTheme,
        );
      },
    );
  }
}
</code>```

but it won't be able to make it ,becouse of this

lib/my_app.dart:49:23: Error: The method 'call' isn't defined for the
class 'WidgetRef'.
- 'WidgetRef' is from 'package:flutter_riverpod/src/consumer.dart'
('../Documents/flutter_windows_2.8.1-stable/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_riverpod-1.0.3/lib/src/consumer.dart').
Try correcting the name to the name of an existing method, or defining a method named 'call'.
theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,

答:
This part

```<code>theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,
</code>```

should be changed to:

```<code>theme: watch.watch(DarkModeProvider.state).state ? darkTheme : lightTheme,
</code>```

Body:
I'm trying to set up a theme for my flutter project, ill greatly appreciate if you kindly show me another way to do that.

import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_analytics/observer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:picpuzzle/routes/route_name.dart';
import 'package:picpuzzle/widgets/login/login_screen.dart';
import 'package:picpuzzle/widgets/main/main_page.dart';
import 'package:picpuzzle/widgets/puzzle/puzzle_list_page.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'common/constants.dart';

/// use for DarkMode,not sync  with system
final DarkModeProvider = StateProvider((ref) => false);

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  static FirebaseAnalytics analytics = FirebaseAnalytics.instance;
  static FirebaseAnalyticsObserver observer =
      FirebaseAnalyticsObserver(analytics: analytics);

  void initApp(BuildContext context) {}

  @override
  Widget build(BuildContext context) {
    /// init
    initApp(context);
    return Consumer(
      builder: (context, watch, _) {
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          localizationsDelegates: [
            AppLocalizations.delegate, // Add this line
            GlobalMaterialLocalizations.delegate,
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,
          ],
          supportedLocales: [
            const Locale('en', ''), // English, no country code
            const Locale('ja', ''), // Japanese, no country code
          ],
          title: 'Pic Puzzle',
          initialRoute: RouteName.Login,
          routes: {
            RouteName.Login: (context) => LoginScreen(),
            RouteName.Main: (context) => MainPage(),
            RouteName.Home: (context) => PuzzleListPage(),
          },
          theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,
          // darkTheme: darkTheme,
        );
      },
    );
  }
}

but it won't be able to make it ,becouse of this

lib/my_app.dart:49:23: Error: The method 'call' isn't defined for the
class 'WidgetRef'.
- 'WidgetRef' is from 'package:flutter_riverpod/src/consumer.dart'
('../Documents/flutter_windows_2.8.1-stable/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_riverpod-1.0.3/lib/src/consumer.dart').
Try correcting the name to the name of an existing method, or defining a method named 'call'.
theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,

Body:
This part

theme: watch(DarkModeProvider).state ? darkTheme : lightTheme,

should be changed to:

theme: watch.watch(DarkModeProvider.state).state ? darkTheme : lightTheme,


答:
Please note: Donot use reserved keyworks such ass class as a variable name.

Array.reduce implementation

const classes = [
  { students: [ 'Student1', 'Student2' ] },
  { students: [ 'Student3', 'Student4' ] }
];
const allStudents = classes.reduce((acc, cls) => {
  acc = cls.students ? acc.concat(cls.students) : acc;
  return acc;
}, []);
console.log(allStudents)```
</div>
</div>
</p>
<p><code>Array.flatMap</code> implementation.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const classes = [
  { students: [ 'Student1', 'Student2' ] },
  { students: [ 'Student3', 'Student4' ] }
]
const allStudents = classes.flatMap((cls) => cls.students ? cls.students : []);
console.log(allStudents);</code>```

Title: How to create an array of objects with all objects from multiple arrays?

Body:
Please note: Donot use reserved keyworks such ass class as a variable name.

Array.reduce implementation

const classes = [
  { students: [ 'Student1', 'Student2' ] },
  { students: [ 'Student3', 'Student4' ] }
];
const allStudents = classes.reduce((acc, cls) => {
  acc = cls.students ? acc.concat(cls.students) : acc;
  return acc;
}, []);
console.log(allStudents)

Array.flatMap implementation.

const classes = [
  { students: [ 'Student1', 'Student2' ] },
  { students: [ 'Student3', 'Student4' ] }
]
const allStudents = classes.flatMap((cls) => cls.students ? cls.students : []);
console.log(allStudents);


问:
Label text color is not changing in bottom navigation bar widget in scaffold, flutter
I used
selectedLabelStyle: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
color: Colors.black,
),

But the text color is still blue. Any idea how to fix it?

答:
Example

```<code>    bottomNavigationBar: new Theme(
    data: Theme.of(context).copyWith(
        // sets the background color of the `BottomNavigationBar`
        canvasColor: Colors.green,
        // sets the active color of the `BottomNavigationBar` if `Brightness` is light
        primaryColor: Colors.red,
        textTheme: Theme
            .of(context)
            .textTheme
            .copyWith(caption: new TextStyle(color: Colors.yellow))), // sets the inactive color of the `BottomNavigationBar`
    child: new BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      currentIndex: 0,
      items: [
        new BottomNavigationBarItem(
          icon: new Icon(Icons.add),
          title: new Text("Add"),
        ),
        new BottomNavigationBarItem(
          icon: new Icon(Icons.delete),
          title: new Text("Delete"),
        )
      ],
    ),
  ),
</code>```

Next One another Example:

```<code>    BottomNavigationBar(
  type: BottomNavigationBarType.fixed,
  backgroundColor: Colors.black, //
  selectedItemColor: Colors.greenAccent,
  unselectedItemColor: Colors.grey,
  items: [
    BottomNavigationBarItem(
      icon: Icon(Icons.call),
      label: 'Call',
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.message),
      label: 'Message',
    ),
  ],
)
</code>```

See On Style BottomNavigationBar in Flutter

Body:
Example

    bottomNavigationBar: new Theme(
    data: Theme.of(context).copyWith(
        // sets the background color of the `BottomNavigationBar`
        canvasColor: Colors.green,
        // sets the active color of the `BottomNavigationBar` if `Brightness` is light
        primaryColor: Colors.red,
        textTheme: Theme
            .of(context)
            .textTheme
            .copyWith(caption: new TextStyle(color: Colors.yellow))), // sets the inactive color of the `BottomNavigationBar`
    child: new BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      currentIndex: 0,
      items: [
        new BottomNavigationBarItem(
          icon: new Icon(Icons.add),
          title: new Text("Add"),
        ),
        new BottomNavigationBarItem(
          icon: new Icon(Icons.delete),
          title: new Text("Delete"),
        )
      ],
    ),
  ),

Next One another Example:

    BottomNavigationBar(
  type: BottomNavigationBarType.fixed,
  backgroundColor: Colors.black, //
  selectedItemColor: Colors.greenAccent,
  unselectedItemColor: Colors.grey,
  items: [
    BottomNavigationBarItem(
      icon: Icon(Icons.call),
      label: 'Call',
    ),
    BottomNavigationBarItem(
      icon: Icon(Icons.message),
      label: 'Message',
    ),
  ],
)

See On Style BottomNavigationBar in Flutter


问:
Quickblox flutter custom objects update not working
According to Quickblox documentation here updating a custom object from the flutter SDK can be done using this sample:

```<code>String className = "TestFlutterClass";

String id = "5d4175afa0eb4715cae5b63f";

Map<String, Object> fieldsMap = Map();
fieldsMap['testString'] = "testField1";
fieldsMap['testInteger'] = 123;
fieldsMap['testBoolean'] = true;

try {
  QBCustomObject? customObject = await QB.data.update(className, id: id, fields: fieldsMap);
} on PlatformException catch (e) {
  // Some error occurred, look at the exception message for more details
}
</code>```

This code above doesn't seem to work or return anything.

I have also tried to update the custom object by posting HTTP to the Rest API using the code below

```<code>String url = "https://api.quickblox.com/data/GAMES/61794c291558ea0059ce2c90.json";

Map map = {'data': { 'PLAYERS_STATUS': sts},};

await apiRequest(url, map);

Future<String>  apiRequest(String url, Map jsonMap) async {
    HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
    request.headers.set('content-type', 'application/json');
    request.headers.set('QB-token', session);
    request.add(utf8.encode(json.encode(jsonMap)));
    HttpClientResponse response = await request.close();
    // todo - you should check the response.statusCode
    String reply = await response.transform(utf8.decoder).join();
    httpClient.close();
    return reply;
}
</code>```

This code returns an error with message

Resource not found

Now I know that the record exists because I can see the record on my dashboard and all class permissions are open.

Any help is welcome!

答:
In Server API for updating record you need to use PUT request method. I can see you sent POST request.
Try using PUT request method instead of POST https://api.flutter.dev/flutter/dart-io/HttpClient/putUrl.html</p>

Body:
According to Quickblox documentation here updating a custom object from the flutter SDK can be done using this sample:

String className = "TestFlutterClass";

String id = "5d4175afa0eb4715cae5b63f";

Map<String, Object> fieldsMap = Map();
fieldsMap['testString'] = "testField1";
fieldsMap['testInteger'] = 123;
fieldsMap['testBoolean'] = true;

try {
  QBCustomObject? customObject = await QB.data.update(className, id: id, fields: fieldsMap);
} on PlatformException catch (e) {
  // Some error occurred, look at the exception message for more details
}

This code above doesn't seem to work or return anything.

I have also tried to update the custom object by posting HTTP to the Rest API using the code below

String url = "https://api.quickblox.com/data/GAMES/61794c291558ea0059ce2c90.json";

Map map = {'data': { 'PLAYERS_STATUS': sts},};

await apiRequest(url, map);

Future<String>  apiRequest(String url, Map jsonMap) async {
    HttpClient httpClient = new HttpClient();
    HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
    request.headers.set('content-type', 'application/json');
    request.headers.set('QB-token', session);
    request.add(utf8.encode(json.encode(jsonMap)));
    HttpClientResponse response = await request.close();
    // todo - you should check the response.statusCode
    String reply = await response.transform(utf8.decoder).join();
    httpClient.close();
    return reply;
}

This code returns an error with message

Resource not found

Now I know that the record exists because I can see the record on my dashboard and all class permissions are open.

Any help is welcome!


问:
argparse argument order issue
I am using subparsers to implement the following function:

```<code>import argparse

parser = argparse.ArgumentParser(prog='dj')
parser.add_argument('--log','-l',type=str, help='log file')
parser.add_argument('--parser','-p',type=bool, nargs='?', const=True, default=False, help='wheher parsing a dj file or not')
subparsers = parser.add_subparsers(help='execute specified command')
###############################################################################
parser_rt = subparsers.add_parser('run_test', help='kick off a case')
parser_rt.add_argument('--test', '-t', type=str, help='test case name')
parser_rt.add_argument('--config','-c', type=str, help='config name')
parser_rt.set_defaults(func=run_test)
</code>```

everything is fine when kicking off the command:

```<code>dj -p -l dj.log run_test -t testa -c configa
</code>```

or

```<code>dj -l dj.log run_test -t testa -c configa
</code>```

However, issue was popping up when running the command:

```<code>dj -l dj.log -p run_test -t testa -c configa
</code>```

Here is error:

```<code>usage: dj [-h] [--log log] [--parser [PARSER]]
       {run_test}...
dj: error: invalid choice: 'testa' (choose from 'run_test')
</code>```

It seems that the issue is related to the position of -p.

答:
By defining -p as nargs='?', const=True, default=False it still consumes the next argument, just not doing anything with it...

When it has run_test after it, it is consumed as an argument and not as a subparser and then -t is not defined either...

To overcome this, simply use the idiomatic way for defining "flag" arguments which is either store_true or store_false as the action. So to fix your parser, change to:

```<code>parser.add_argument('--parser','-p', action='store_true', help='wheher parsing a dj file or not')
</code>```

When you ran -p -l there was no issue because argparse knows to differentiate arguments using the -. So in this case -p had no value and -l started a new argument. run_test was taken as a value before argparse checked it for a subparser.

Title: argparse argument order issue

Body:
I am using subparsers to implement the following function:

import argparse

parser = argparse.ArgumentParser(prog='dj')
parser.add_argument('--log','-l',type=str, help='log file')
parser.add_argument('--parser','-p',type=bool, nargs='?', const=True, default=False, help='wheher parsing a dj file or not')
subparsers = parser.add_subparsers(help='execute specified command')
###############################################################################
parser_rt = subparsers.add_parser('run_test', help='kick off a case')
parser_rt.add_argument('--test', '-t', type=str, help='test case name')
parser_rt.add_argument('--config','-c', type=str, help='config name')
parser_rt.set_defaults(func=run_test)

everything is fine when kicking off the command:

dj -p -l dj.log run_test -t testa -c configa

or

dj -l dj.log run_test -t testa -c configa

However, issue was popping up when running the command:

dj -l dj.log -p run_test -t testa -c configa

Here is error:

usage: dj [-h] [--log log] [--parser [PARSER]]
       {run_test}...
dj: error: invalid choice: 'testa' (choose from 'run_test')

It seems that the issue is related to the position of -p.

Body:
By defining -p as nargs='?', const=True, default=False it still consumes the next argument, just not doing anything with it...

When it has run_test after it, it is consumed as an argument and not as a subparser and then -t is not defined either...

To overcome this, simply use the idiomatic way for defining "flag" arguments which is either store_true or store_false as the action. So to fix your parser, change to:

parser.add_argument('--parser','-p', action='store_true', help='wheher parsing a dj file or not')

When you ran -p -l there was no issue because argparse knows to differentiate arguments using the -. So in this case -p had no value and -l started a new argument. run_test was taken as a value before argparse checked it for a subparser.


问:
Nodejs service to query dynamoDb on different aws account
I have a nodejs service running on an EC2 in account A.
In addition, I have dynamoDB table in account B.

I want to query the table in account B, but by default, the package only gets tableName and query the current account.

Is it possible to add something like accountId to the AWS Config?

```<code>        dynamo.AWS.config.update({region: process.env.DYNAMO_DB_REGION});
</code>```

答:
What you can do is that, you can create a role which has access to the dynamo db table in other account and provide permission in first account on which ec2 instance is, to assume that role. Then you can perform queries upon other account's dynamo db table with created role's credentials by assuming the role.

I did find a reference which includes lambda function as an example, you can apply similar pattern for your node.js service on EC2, please refer to -  https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/configure-cross-account-access-to-amazon-dynamodb.html.

Body:
I have a nodejs service running on an EC2 in account A.
In addition, I have dynamoDB table in account B.

I want to query the table in account B, but by default, the package only gets tableName and query the current account.

Is it possible to add something like accountId to the AWS Config?

        dynamo.AWS.config.update({region: process.env.DYNAMO_DB_REGION});


问:
Python select.select() error 10022 on windows
I got class (subclassed from QThread), that recieve data from server at many sockets by select.select():

```<code># -*- coding: utf-8 -*-
from PyQt4.QtCore import QThread, pyqtSignal
import json
import select
class MainSocketThread(QThread) :
    disconnected_by_admin = pyqtSignal()
    disconnected_by_network = pyqtSignal(bool)

    def __init__(self, connects_dict=None) :
        QThread.__init__(self)
        self.connects = connects_dict
        if not self.connects:
            self.connects={}

    def run(self) :
        try:
            while 1 :
                inputready, outputready, exceptready = select.select(self.connects.keys(),
                    [], [])
                for s in inputready :
                    try :
                        data = self.s_[s].recv(4096)
                        if not data :
                            s.close()
                            self.connects.pop(s)
                        else :
                            cmd = json.loads(data)
                            print s, cmd, 'asd'
                            #                        ProcessCommand(s, cmd)
                    except Exception as e:
                        s.close()
                        self.connects.pop(s)
        except Exception as e:
            print e
            self.disconnected_by_network.emit(False)
        self.exec_()
</code>```

And that's how i create socket(in other class) :

```<code>self.connections_dict = {}
self.main_socket_thread = MainSocketThread(self.connections_dict)
if not self.s :
    try:
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((host, port))
    except Exception as e:
        print e, e.__class__()
        self.display_connection_status(False)
    else:
        self.connections_dict[self.s] = self
        self.main_socket_thread.start()
        self.s.send(json.dumps({'command': 'operator_insite',
                                'login': self.settings_dict['login'],
                                'password': hashlib.md5(self.settings_dict['password']).hexdigest()}))
        self.display_connection_status(True)
</code>```

But i got select.error 10022 every time trying to select from sockets. What is wrong with my code?

答:
are you sure self.connects is not empty ? This reminds me of the error you get on Windows when passing 3 empty lists to select.select().

In any case, 10022 is EINVAL meaning an invalid argument has been supplied. So I'd carefully trace the arguments passed to the function raising the exception (seeing if the sockets are open, etc...)

Body:
I got class (subclassed from QThread), that recieve data from server at many sockets by select.select():

# -*- coding: utf-8 -*-
from PyQt4.QtCore import QThread, pyqtSignal
import json
import select
class MainSocketThread(QThread) :
    disconnected_by_admin = pyqtSignal()
    disconnected_by_network = pyqtSignal(bool)

    def __init__(self, connects_dict=None) :
        QThread.__init__(self)
        self.connects = connects_dict
        if not self.connects:
            self.connects={}

    def run(self) :
        try:
            while 1 :
                inputready, outputready, exceptready = select.select(self.connects.keys(),
                    [], [])
                for s in inputready :
                    try :
                        data = self.s_[s].recv(4096)
                        if not data :
                            s.close()
                            self.connects.pop(s)
                        else :
                            cmd = json.loads(data)
                            print s, cmd, 'asd'
                            #                        ProcessCommand(s, cmd)
                    except Exception as e:
                        s.close()
                        self.connects.pop(s)
        except Exception as e:
            print e
            self.disconnected_by_network.emit(False)
        self.exec_()

And that's how i create socket(in other class) :

self.connections_dict = {}
self.main_socket_thread = MainSocketThread(self.connections_dict)
if not self.s :
    try:
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((host, port))
    except Exception as e:
        print e, e.__class__()
        self.display_connection_status(False)
    else:
        self.connections_dict[self.s] = self
        self.main_socket_thread.start()
        self.s.send(json.dumps({'command': 'operator_insite',
                                'login': self.settings_dict['login'],
                                'password': hashlib.md5(self.settings_dict['password']).hexdigest()}))
        self.display_connection_status(True)

But i got select.error 10022 every time trying to select from sockets. What is wrong with my code?


问:
Find every src value in a webpage that contains certain text javascript
I want to find and "console.log" every src value in an HTML page that has a certain text; for example (dam/etc/vsvs).
Is it possible to do it with javascript and in the console, as I'm not able to reach to source code of the page? I'm not a developer just trying to find the images I want and list them.

Any help will be appreciated.

Thanks in advance.

答:
As far as I understand, you have an HTML page and you need to grab every src value which meets some expectations (i.e. starts with smth, includes smth).

So, if you are able to run a script on the page then you can recursively go node by node and check if it has an src attribute.

```<code>const findSrc = (node) => {
  const attributesToCheck = ['src', 'srcset', 'data-srcset']

  const srcs = attributesToCheck.map(name => {
    const attr = node.getAttribute(name)

    // here is a condition for your match
    return attr?.startsWith("/etc") ? attr : false
  }).filter(Boolean)

  if (node.children) {
    return srcs.concat(Array.from(node.children).flatMap(findSrc));
  }

  return srcs;
};

console.log(findSrc(document.body));
</code>```

Body:
As far as I understand, you have an HTML page and you need to grab every src value which meets some expectations (i.e. starts with smth, includes smth).

So, if you are able to run a script on the page then you can recursively go node by node and check if it has an src attribute.

const findSrc = (node) => {
  const attributesToCheck = ['src', 'srcset', 'data-srcset']

  const srcs = attributesToCheck.map(name => {
    const attr = node.getAttribute(name)

    // here is a condition for your match
    return attr?.startsWith("/etc") ? attr : false
  }).filter(Boolean)

  if (node.children) {
    return srcs.concat(Array.from(node.children).flatMap(findSrc));
  }

  return srcs;
};

console.log(findSrc(document.body));


问:
How to Maximize, Minimize, Restore WinUI window from code
I'm creating a demo app using WinUI 3 prerelease 0.5 (project reunion).

I would like to maximize, minimize, and restore the window state from c# managed code.  Are there any examples available?

答:
Here is my implementation based on the PInvoke.User32 nuget package.

Version using Window parameter

```<code>    public void MaximizeWindow(Window window)
    {
        var windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);

        PInvoke.User32.ShowWindow(windowHandle, PInvoke.User32.WindowShowStyle.SW_MAXIMIZE);
    }
</code>```

Version using extension method

This previous code can also be transformed into an extension method for the Window class, so I can just call this.Maximize() from within the Window:

```<code>public static class WindowExtensions
{
    public static void Maximize(this Window window)
    {
        var windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);

        PInvoke.User32.ShowWindow(windowHandle, PInvoke.User32.WindowShowStyle.SW_MAXIMIZE);
    }
}
</code>```

Usage in your Window derived class:

this.Maximize();

Minize and Restore

The "PInvoke.User32.WindowShowStyle" definition used in the examples above contains also constants for SW_MINIMIZE and SW_RESTORE, but I did not test this.

Body:
Here is my implementation based on the PInvoke.User32 nuget package.

Version using Window parameter

    public void MaximizeWindow(Window window)
    {
        var windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);

        PInvoke.User32.ShowWindow(windowHandle, PInvoke.User32.WindowShowStyle.SW_MAXIMIZE);
    }

Version using extension method

This previous code can also be transformed into an extension method for the Window class, so I can just call this.Maximize() from within the Window:

public static class WindowExtensions
{
    public static void Maximize(this Window window)
    {
        var windowHandle = WinRT.Interop.WindowNative.GetWindowHandle(window);

        PInvoke.User32.ShowWindow(windowHandle, PInvoke.User32.WindowShowStyle.SW_MAXIMIZE);
    }
}

Usage in your Window derived class:

this.Maximize();

Minize and Restore

The "PInvoke.User32.WindowShowStyle" definition used in the examples above contains also constants for SW_MINIMIZE and SW_RESTORE, but I did not test this.


问:
How to make an arrayformula count values by row?
I have tried many approaches but I can't seem to figure out a solution to a fairly simple problem with an array formula it seems:

I have a sheet where I get results of individual results of runs of a certain scientific experiment by row.
Next, I'd like to count the occurrence of each output value. Output values can be a number from 1 to 10 so I'd like to individually count how many times the output has been per value.

Also, I'd be then summing up how many individual outputs have been generated in total. So I'd be counting the number of unique outputs within a row.

Now my issue is that when using Arrayformula the way I normally use it it doesn't work because it would count and sum up everything for the whole Matrix specified. However, I just want the current row to be counted. I tried using ROW to get there, but i failed.
I also tried some things like =ARRAYFORMULA(SUMIF(IF(COLUMN(B1:F1),ROW(B2:F5)),ROW(B2:F5),B2:F5)) to understand how to apply the logic, but I fail to get it working as COUNTIF version if itself.

Test Sheet

Any help and ideas would be highly appreciated!

答:
in H2 use:

```<code>=INDEX(MMULT(IF(INDIRECT("B2:F"&MAX((ROW(A2:A)*(A2:A<>""))))=""; 0; 1);
 FLATTEN(COLUMN(B:F)^0)))
</code>```

in J2 use:

```<code>=INDEX(ARRAY_CONSTRAIN(QUERY(QUERY({IFERROR(SPLIT(FLATTEN({ROW(A2:A)&"×"&B2:F}); "×"));
 {SEQUENCE(10)*9^9\SEQUENCE(10)}};
 "select count(Col1),Col1 where Col2 is not null group by Col1 pivot Col2");
 "where Col11 < 100000 offset 1"; 0); 9^9; 10))
</code>```

update:

H1:

```<code>={"Total No. of outcomes"; ARRAYFORMULA(IFNA(VLOOKUP(ROW(A2:A);
 QUERY(SPLIT(UNIQUE(FLATTEN(ROW(B2:F)&"×"&B2:F)); "×");
 "select Col1,count(Col1) where Col2 is not null group by Col1"); 2; 0)))}
</code>```

J1:

```<code>=INDEX({"Occurence of "&SEQUENCE(1; 10); ARRAY_CONSTRAIN(QUERY(QUERY({IFERROR(
 SPLIT(FLATTEN({ROW(A2:A)&"×"&B2:F}); "×")); {SEQUENCE(10)*9^9\SEQUENCE(10)}};
 "select count(Col1),Col1 where Col2 is not null group by Col1 pivot Col2");
 "where Col11 < 999999 offset 1"; 0); 9^9; 10)})
</code>```

demo sheet

Body:
in H2 use:

=INDEX(MMULT(IF(INDIRECT("B2:F"&MAX((ROW(A2:A)*(A2:A<>""))))=""; 0; 1);
 FLATTEN(COLUMN(B:F)^0)))

in J2 use:

=INDEX(ARRAY_CONSTRAIN(QUERY(QUERY({IFERROR(SPLIT(FLATTEN({ROW(A2:A)&"×"&B2:F}); "×"));
 {SEQUENCE(10)*9^9\SEQUENCE(10)}};
 "select count(Col1),Col1 where Col2 is not null group by Col1 pivot Col2");
 "where Col11 < 100000 offset 1"; 0); 9^9; 10))

update:

H1:

={"Total No. of outcomes"; ARRAYFORMULA(IFNA(VLOOKUP(ROW(A2:A);
 QUERY(SPLIT(UNIQUE(FLATTEN(ROW(B2:F)&"×"&B2:F)); "×");
 "select Col1,count(Col1) where Col2 is not null group by Col1"); 2; 0)))}

J1:

=INDEX({"Occurence of "&SEQUENCE(1; 10); ARRAY_CONSTRAIN(QUERY(QUERY({IFERROR(
 SPLIT(FLATTEN({ROW(A2:A)&"×"&B2:F}); "×")); {SEQUENCE(10)*9^9\SEQUENCE(10)}};
 "select count(Col1),Col1 where Col2 is not null group by Col1 pivot Col2");
 "where Col11 < 999999 offset 1"; 0); 9^9; 10)})

demo sheet


问:
Website recognising I am using a server whilst using selenium
I am trying to set up an automated sports betting bot using selenium and running it on selenium. When running the bot on the server the website recognises this and therefore doesn't allow me to deposit, but when running it off the server I don't run it into this problem.

I have tried using proxies and VPN's and this still doesn't fix the problem.

The website is 1xbit.com and this picture shows the error message when trying to deposit.

Code:

```<code>def get_website():
    options = webdriver.ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-logging'])
    driver = webdriver.Chrome(options=options,executable_path=pathway)
    driver.maximize_window()
    actionChains = ActionChains(driver)
    driver.get('https://1xbit.com/live/Football/')
    return driver
</code>```

Essentially, I want to add code to hide the fact I am on a server....

答:
To avoid detection add the following argument through add_argument() as follows:

--disable-blink-features=AutomationControlled

Sample Code:

```<code>options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get('https://1xbit.com/live/Football/')
</code>```

Browser Screenshot:

Body:
I am trying to set up an automated sports betting bot using selenium and running it on selenium. When running the bot on the server the website recognises this and therefore doesn't allow me to deposit, but when running it off the server I don't run it into this problem.

I have tried using proxies and VPN's and this still doesn't fix the problem.

The website is 1xbit.com and this picture shows the error message when trying to deposit.

Code:

def get_website():
    options = webdriver.ChromeOptions()
    options.add_experimental_option('excludeSwitches', ['enable-logging'])
    driver = webdriver.Chrome(options=options,executable_path=pathway)
    driver.maximize_window()
    actionChains = ActionChains(driver)
    driver.get('https://1xbit.com/live/Football/')
    return driver

Essentially, I want to add code to hide the fact I am on a server....

Body:
To avoid detection add the following argument through add_argument() as follows:

--disable-blink-features=AutomationControlled

Sample Code:

options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get('https://1xbit.com/live/Football/')

Browser Screenshot:


问:
I am trying to show data in table but i am facing this error "TypeError: Cannot read properties of undefined (reading 'map')"
I am trying to show data in table but i am facing following error:
"TypeError: Cannot read properties of undefined (reading 'map')"
Any kind of help would really be appreciated.
When I am trying to bind the data in the map an error is being shown. In short, map function is not properly working
Following is my code:

```<code>import React, { useState, useEffect } from 'react';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import '../StockPage/Stock.css'
import '../StockPage/stockValidation'
import { useFormik, Form, Field } from "formik";
import { Link} from 'react-router-dom';
import axios from "axios"

function Stock() {
    const [item, setItems] = useState({
        itemName: "",
        itemCatagory: "",
        itemPrice: "",
        stockAmount: ""
    })
    const [search,setSearch] =useState('');
    const [allItems, setAllItems] = useState()

    // On Page load display all records
    const loadItemsDetail = async () => {
        const response = fetch('http://localhost:4000/stock/list')
            .then(function (response) {
                return response.json();
            })
            .then(function (myJson) {
                setAllItems(myJson);
            });
    }
    useEffect(() => {
        loadItemsDetail();
    }, []);

    const handleChange = e => {
        const { name, value } = e.target
        setItems({
            ...item,
            [name]: value
        })
    }
    const itemSubmit = () => {

        const { itemName, itemCatagory, itemPrice, stockAmount } = item
        if (itemName && itemCatagory && itemPrice && stockAmount) {
            axios.post("http://localhost:4000/stock", item)
                .then(res => console.log(res))
        }
        else {
            alert("Invalid inputs")
        }

    }
      // Search Records here
      const searchRecords = () =>
      {
          alert(search)
          axios.get(``)
          .then(response => {
            setAllItems(response.data);
          });
      }
       // Delete Employee Record
       const deleteRecord = (productId) =>
       {
         axios.delete(``)
         .then((result)=>{
            loadItemsDetail();
         })
         .catch(()=>{
           alert('Error in the Code');
         });
       };

    return (
        <div className="Stock">
            <div className="container-fluid">
                <div className="row">
                    {/* insert area */}
                    <div className="col-lg-4">
                        <h4 className='text-center ml-4 mb-5'>Create New Records</h4>
                        {console.log("Item", item)}
                        {/* <form onSubmit={formik.handleSubmit}> */}
                        <div>
                            <div className="mx-auto w-75 ">
                                <div className="form-group ">
                                    <label htmlFor="itemName">Item Name:</label>
                                    <input type="text" className="form-control" id="id_itemName" name="itemName" value={item.itemName} onChange={handleChange}
                                        placeholder="Item Name" />

                                </div>
                                <div className="form-group ">
                                    <label htmlFor="itemCategory">Item Category</label>
                                    <input type="text" className="form-control" id="id_itemCategory" name="itemCatagory" value={item.itemCatagory} onChange={handleChange}
                                        placeholder="Item Category" />

                                </div>
                                <div className="form-group">
                                    <label htmlFor="itemPrice">Item Price</label>
                                    <input type="text" className="form-control" id="id_itemPrice" name="itemPrice" value={item.itemPrice} onChange={handleChange}
                                        placeholder="Item Price" />

                                </div>
                                <div className="form-group">
                                    <label htmlFor="stockAmount">Stock Amount</label>
                                    <input type="text" className="form-control" id="id_Amount" name="stockAmount" value={item.stockAmount} onChange={handleChange}
                                        placeholder="Amount" />

                                </div>
                            </div>
                            <div className='text-center mt-4'>
                                <button type="submit" className="btn btn-primary" onClick={itemSubmit}>Enter</button>
                            </div>

                        </div>
                    </div>
                    {/* detailed area */}
                    <div class="col-sm-8">
                        <h5 class="text-center  ml-4 mt-4  mb-5">View Records</h5>
                        <div class="input-group mb-4 mt-3">
                            <div class="form-outline">
                                <input type="text" id="form1" onChange={(e) => setSearch(e.target.value)} class="form-control" placeholder="Search Employee Here" style={{ backgroundColor: "#ececec" }} />
                            </div>
                            <button type="button" onClick={searchRecords} class="btn btn-success">
                                <i class="fa fa-search" aria-hidden="true"></i>
                            </button>
                        </div>
                        <table class="table table-hover  table-striped table-bordered ml-4 ">
                            <thead>
                                <tr>

                                <th>Item Name</th>
                                <th>Category</th>
                                <th>Item Price</th>
                                <th>Item Amount</th>
                                <th>Action</th>

                                </tr>
                            </thead>
                            <tbody>
                                {console.log(allItems)}
                                {allItems.map((name) =>

                                    <tr>
                                        <td>{name.itemName}</td>
                                        <td>{name.itemCatagory}</td>
                                        <td>{name.itemPrice}</td>
                                        <td>{name.stockAmount}</td>
                                        <td>
                                            <a className="text-danger mr-2"
                                                onClick={() => {
                                                    const confirmBox = window.confirm(
                                                        "Do you really want to delete " + name.itemName
                                                    )
                                                    if (confirmBox === true) {
                                                        deleteRecord(name.id)
                                                    }
                                                }}> <i class="far fa-trash-alt" style={{ fontSize: "18px", marginRight: "5px" }}></i> </a>

                                            <Link class=" mr-2" to={`/EditEmployee/editID/${name.id}`}>
                                                <i class="fa fa-edit" aria-hidden="true"></i>
                                            </Link>
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    )
};

export default Stock;
</code>```

error

答:
Give an empty array([]) default state to allItems like below.

```<code>const [allItems, setAllItems] = useState([]);
</code>```

Body:
I am trying to show data in table but i am facing following error:
"TypeError: Cannot read properties of undefined (reading 'map')"
Any kind of help would really be appreciated.
When I am trying to bind the data in the map an error is being shown. In short, map function is not properly working
Following is my code:

import React, { useState, useEffect } from 'react';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import '../StockPage/Stock.css'
import '../StockPage/stockValidation'
import { useFormik, Form, Field } from "formik";
import { Link} from 'react-router-dom';
import axios from "axios"

function Stock() {
    const [item, setItems] = useState({
        itemName: "",
        itemCatagory: "",
        itemPrice: "",
        stockAmount: ""
    })
    const [search,setSearch] =useState('');
    const [allItems, setAllItems] = useState()

    // On Page load display all records
    const loadItemsDetail = async () => {
        const response = fetch('http://localhost:4000/stock/list')
            .then(function (response) {
                return response.json();
            })
            .then(function (myJson) {
                setAllItems(myJson);
            });
    }
    useEffect(() => {
        loadItemsDetail();
    }, []);

    const handleChange = e => {
        const { name, value } = e.target
        setItems({
            ...item,
            [name]: value
        })
    }
    const itemSubmit = () => {

        const { itemName, itemCatagory, itemPrice, stockAmount } = item
        if (itemName && itemCatagory && itemPrice && stockAmount) {
            axios.post("http://localhost:4000/stock", item)
                .then(res => console.log(res))
        }
        else {
            alert("Invalid inputs")
        }

    }
      // Search Records here
      const searchRecords = () =>
      {
          alert(search)
          axios.get(``)
          .then(response => {
            setAllItems(response.data);
          });
      }
       // Delete Employee Record
       const deleteRecord = (productId) =>
       {
         axios.delete(``)
         .then((result)=>{
            loadItemsDetail();
         })
         .catch(()=>{
           alert('Error in the Code');
         });
       };

    return (

                    {/* insert area */}

Create New Records

                        {console.log("Item", item)}
                        {/* <form onSubmit={formik.handleSubmit}> */}

                                    Item Name:
                                    <input type="text" className="form-control" id="id_itemName" name="itemName" value={item.itemName} onChange={handleChange}
                                        placeholder="Item Name" />

                                    Item Category
                                    <input type="text" className="form-control" id="id_itemCategory" name="itemCatagory" value={item.itemCatagory} onChange={handleChange}
                                        placeholder="Item Category" />

                                    Item Price
                                    <input type="text" className="form-control" id="id_itemPrice" name="itemPrice" value={item.itemPrice} onChange={handleChange}
                                        placeholder="Item Price" />

                                    Stock Amount
                                    <input type="text" className="form-control" id="id_Amount" name="stockAmount" value={item.stockAmount} onChange={handleChange}
                                        placeholder="Amount" />

                                <button type="submit" className="btn btn-primary" onClick={itemSubmit}>Enter</button>

                    {/* detailed area */}

View Records

                                <input type="text" id="form1" onChange={(e) => setSearch(e.target.value)} class="form-control" placeholder="Search Employee Here" style={{ backgroundColor: "#ececec" }} />

                            <button type="button" onClick={searchRecords} class="btn btn-success">

                            </button>

                                Item Name
                                Category
                                Item Price
                                Item Amount
                                Action

                                {console.log(allItems)}
                                {allItems.map((name) =>

                                        {name.itemName}
                                        {name.itemCatagory}
                                        {name.itemPrice}
                                        {name.stockAmount}

                                             {
                                                    const confirmBox = window.confirm(
                                                        "Do you really want to delete " + name.itemName
                                                    )
                                                    if (confirmBox === true) {
                                                        deleteRecord(name.id)
                                                    }
                                                }}>

                                            <Link class=" mr-2" to={`/EditEmployee/editID/${name.id}`}>

                                            </Link>

                                )}

    )
};

export default Stock;

error

Body:
Give an empty array([]) default state to allItems like below.

const [allItems, setAllItems] = useState([]);


问:
How to get an enum reference from a reference to a child type of the enum?
I have an enum type Shape that contains two types Rect and Circle. now there is a function that can find &Rect or &Circle objects, how can I get them to return as &Shape?

#[derive(Debug)]
struct Rect {}

#[derive(Debug)]
struct Circle {}

#[derive(Debug)]
enum Shape {
    R(Rect),
    C(Circle),
}

struct Container {
    rects: Vec<(usize, Rect)>,
    circls: Vec<(usize, Circle)>,
}

impl Container {
    fn find_shape(&self, id: usize) -> Option<&Shape> {
        let optr = self.rects.iter().find(|x| x.0 == id);
        if let Some((_, r)) = optr {
            return Some(&Shape::R(r)); // expected struct `Rect`, found `&Rect`
        }
        let optc = self.circls.iter().find(|x| x.0 == id);
        if let Some((_, c)) = optc {
            return Some(c); // expected enum `Option<&Shape>` found reference `&Circle`
        }
        return None;
    }
}

fn main() {
    let cont = Container {
        rects: vec![(0, Rect {}), (2, Rect {})],
        circls: vec![(1, Circle {}), (3, Circle {})],
    };
    let s = cont.find_shape(1).unwrap();
    println!("shape is {:?}", s);
}
```

答:
now there is a function that can find &Rect or &Circle objects, how can I get them to return as &Shape?

It can't, in the same way you can't get e.g. an &Option<String> from an &String.

Shape is, in essence,

struct Shape {
    discr: u8,
    content: union { _1: Rect, _2: Circle }
}
```

The solution is to either modify Shape to store references, or to have a secondary type which does that (e.g. ShapeRef).

The latter is quite common.

Body:
now there is a function that can find &Rect or &Circle objects, how can I get them to return as &Shape?

It can't, in the same way you can't get e.g. an &Option<String> from an &String.

Shape is, in essence,

struct Shape {
    discr: u8,
    content: union { _1: Rect, _2: Circle }
}

The solution is to either modify Shape to store references, or to have a secondary type which does that (e.g. ShapeRef).

The latter is quite common.


问:
Angular - subject observable not responding
I have one service SelectorService where I have defined the subject and an observable.

```<code>private eventEligibleApiStatus = new Subject<any>();
public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable();
</code>```

And I have defined a method which calls the subject.next.

```<code>notifyEventEligibleApiStatus(status) {
  this.eventEligibleApiStatus.next(status);
}
</code>```

Now in another component called scheduler-component.ts, I have defined one boolean flag and an observable

```<code>  eventEligibleInProgress = false;

  eventEligibleListener: Observable<any> = this.resourceSelectorService.eventEligibleApiStatusUpdated$;
</code>```

And I am subscribing to this observable

```<code>   this.eventEligibleListener.subscribe( status => {
     this.eventEligibleInProgress = status;
   });
</code>```

From SelectorComponent, I am calling the SelectorService's, notifyEventEligibleApiStatus like this,

```<code>this.selectorService.notifyEventEligibleApiStatus(true);
</code>```

whenever the notifyEventEligibleApiStatus function is triggered, the control does not come to the eventEligibleListener.subscribe and the flag is also not changed.

What am I doing wrong here.

PS: I am new to Angular and Front End development.

答:
You have not declared eventEligibleApiStatus subject in your code. You have shared bits of codes. Try sharing complete code so that we can have a better understaning instead of guessing.

Try using behaviourSubject

```<code>private eventEligibleApiStatus = new BehaviorSubject<any>(null);
public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable();
</code>```

Body:
I have one service SelectorService where I have defined the subject and an observable.

private eventEligibleApiStatus = new Subject<any>();
public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable();

And I have defined a method which calls the subject.next.

notifyEventEligibleApiStatus(status) {
  this.eventEligibleApiStatus.next(status);
}

Now in another component called scheduler-component.ts, I have defined one boolean flag and an observable

  eventEligibleInProgress = false;

  eventEligibleListener: Observable<any> = this.resourceSelectorService.eventEligibleApiStatusUpdated$;

And I am subscribing to this observable

   this.eventEligibleListener.subscribe( status => {
     this.eventEligibleInProgress = status;
   });

From SelectorComponent, I am calling the SelectorService's, notifyEventEligibleApiStatus like this,

this.selectorService.notifyEventEligibleApiStatus(true);

whenever the notifyEventEligibleApiStatus function is triggered, the control does not come to the eventEligibleListener.subscribe and the flag is also not changed.

What am I doing wrong here.

PS: I am new to Angular and Front End development.

Body:
You have not declared eventEligibleApiStatus subject in your code. You have shared bits of codes. Try sharing complete code so that we can have a better understaning instead of guessing.

Try using behaviourSubject

private eventEligibleApiStatus = new BehaviorSubject<any>(null);
public eventEligibleApiStatusUpdated$ = this.eventEligibleApiStatus.asObservable();


问:
How can I rebuild indexes and update stats in MySQL innoDB?
I have experience with MS SQL server where it is possible and useful to update statistic and rebuild indexes. I can't find such option in MySQL innoDB, is there such option? If not, how MySQL database create an execution plan? Does the MySQL update indexes and statistic with every UPDATE and INSERT?</p>

答:
use CLI,</p>
```<code>mysqlcheck -u root -p --auto-repair --optimize --all-databases
</code>```

Body:
use CLI,

mysqlcheck -u root -p --auto-repair --optimize --all-databases


问:
Typescript, how to pass "Object is possibly null" error?
I've got the "Object is possibly null" error many times and usually I use a safety "if statement" in case it returns null.

I've got the following function:

const ModalOverlay = (props: any[]) => {
  const overlayEl = useRef(null);
    useEffect(() => {
    overlayEl.current.focus();
    });
    return
;
  }
```

<p>But <code>overlayEl.current</code> gets the error "Object is not defined". So I've tried:</p>

<pre class="lang-js prettyprint-override"><code>if (!overlayEl) {
    return null
  } else {
    useEffect(() => {
    overlayEl.current.focus();
    });
    return <div {...props} ref={overlayEl} />;
  }
</code>```

Which didn't work. I've tried also:

overlay && overlayEl.current.focus();
```

Any hints would be highly appreciated! Thanks

答:
Depends on what you prefer but a nice syntax and structure might be to create an interface:

interface divEL {
  current: HTMLDivElement | null;
}
```
<p>This will keep your declaration clear and short and you can reuse the divEl interface for similar useRef hooks.</p>
<pre class="lang-typescript prettyprint-override"><code>const overlayEl: divEL = useRef(null);
</code>```

Then add focus() like this:

overlayEl.current!.focus();
```

Body:
I've got the "Object is possibly null" error many times and usually I use a safety "if statement" in case it returns null.

I've got the following function:

const ModalOverlay = (props: any[]) => {
  const overlayEl = useRef(null);
    useEffect(() => {
    overlayEl.current.focus();
    });
    return
;
  }

But overlayEl.current gets the error "Object is not defined". So I've tried:

if (!overlayEl) {
    return null
  } else {
    useEffect(() => {
    overlayEl.current.focus();
    });
    return
;
  }

Which didn't work. I've tried also:

overlay && overlayEl.current.focus();

Any hints would be highly appreciated! Thanks

Body:
Depends on what you prefer but a nice syntax and structure might be to create an interface:

interface divEL {
  current: HTMLDivElement | null;
}

This will keep your declaration clear and short and you can reuse the divEl interface for similar useRef hooks.

const overlayEl: divEL = useRef(null);

Then add focus() like this:

overlayEl.current!.focus();


问:
promise catch: how to know if the error comes from promise rejection or from the then statement
Imagine a function that returns a promise (for example fetch from fetch API):

```<code>fetch(...)
.then((response) => {...})
.catch((error) => {...});
</code>```

How can I know if the error inside the catch statement has been originated due to a promise rejection instead from the code inside the then statement?

Something like the following will work:

```<code>let success = false;
fetch(...)
.then((response) => {success = true; ...})
.catch((error) => {if(success) ...});
</code>```

But I want to know if there is a better or more native way to do it. I have also tried to do something like:

```<code>fetch(...)
.catch((promiseError) => {...});
.then((response) => {...})
.catch((thenError) => {...});
</code>```

But I think it doesn't work because response isn't forwarded to the thenstatement (or at least that's what TS says).

Which would be the better way?

答:
if the function pass to then returns a promise,

promise
    .then(
        (async (response)=>{
            ...
        }).catch((errorFromThen) => {})
    ).catch((errorFromPromise) => {})
```
<p>or just simply</p>
<pre class="lang-js prettyprint-override"><code>promise
    .then(
        (response)=>{
            try {
                ...
            } catch (errorFromThen) {
                ...
            }
        }
    ).catch((errorFromPromise) => {})
</code>```

Body:
Imagine a function that returns a promise (for example fetch from fetch API):

fetch(...)
.then((response) => {...})
.catch((error) => {...});

How can I know if the error inside the catch statement has been originated due to a promise rejection instead from the code inside the then statement?

Something like the following will work:

let success = false;
fetch(...)
.then((response) => {success = true; ...})
.catch((error) => {if(success) ...});

But I want to know if there is a better or more native way to do it. I have also tried to do something like:

fetch(...)
.catch((promiseError) => {...});
.then((response) => {...})
.catch((thenError) => {...});

But I think it doesn't work because response isn't forwarded to the thenstatement (or at least that's what TS says).

Which would be the better way?

Body:
if the function pass to then returns a promise,

promise
    .then(
        (async (response)=>{
            ...
        }).catch((errorFromThen) => {})
    ).catch((errorFromPromise) => {})

or just simply

promise
    .then(
        (response)=>{
            try {
                ...
            } catch (errorFromThen) {
                ...
            }
        }
    ).catch((errorFromPromise) => {})