问:
pygame Sprite causes maximum recursion depth exceeded
My problem:

So I am programing a game right now and I am at the start of it. So I just wanted to draw a sprite on my screen which is called in an other Filer but I always get the error that the line 13 repeated 491 times more.

This is the code:

import pygame

class Start(pygame.sprite.Sprite):

    def __init__(self,surface):
        super().__init__()
        self.display_surface = surface
        self.image = pygame.image.load("Pygame-Graphics/Start.png").convert_alpha()
        self.rect = self.image.get_rect(topleft = (500,400))
        self.start = pygame.sprite.GroupSingle()

        self_sprite = Start(self.rect)
        self.start.add(self_sprite)

    def draw(self):
        self.start.update()
        self.start.draw(self.display_surface)
```

So i except, that when i call the function draw from an other file that my sprite is being drawn on my screen.

Body:
My problem:

So I am programing a game right now and I am at the start of it. So I just wanted to draw a sprite on my screen which is called in an other Filer but I always get the error that the line 13 repeated 491 times more.

This is the code:

import pygame

class Start(pygame.sprite.Sprite):

    def __init__(self,surface):
        super().__init__()
        self.display_surface = surface
        self.image = pygame.image.load("Pygame-Graphics/Start.png").convert_alpha()
        self.rect = self.image.get_rect(topleft = (500,400))
        self.start = pygame.sprite.GroupSingle()

        self_sprite = Start(self.rect)
        self.start.add(self_sprite)

    def draw(self):
        self.start.update()
        self.start.draw(self.display_surface)

So i except, that when i call the function draw from an other file that my sprite is being drawn on my screen.


来源: stackexchange

问:
How do I seperate an array so the data shows up as individual list items?
I am struggling re-writing some older code I made in vue. I have a form which allows the user to enter multiple email recipients. The problem is that the array in which these emails are stored outputs them as one single item.

How do I seperate these email addresses?
This is my code. I know that Vue has something called Split, but I am not sure where I could  use it here (or if it would change anything).

```<code>    <template>
  <b-form-group :label="label">
    <vue-tags-input
      v-model="inputValue"
      :tags="tags"
      :autocomplete-min-length="0"
      :add-on-key="[',', 13]"
      :autocomplete-items="filteredAutocompleteItems"
      :placeholder="$t('addEmailAddressesHere')"
      data-test-id="send-doc-email-to"
      @before-adding-tag="addTag"
      @tags-changed="tagsChanged"
      class="mw-100"
    />
  </b-form-group>
</template>

<script>
  import {propertyService} from '@/services/property';
  import {tenancyService} from '@/services/tenancy';
  import {unitService} from '@/services/unit';
  import {userService} from '@/services/user';
  import VueTagsInput from '@johmun/vue-tags-input';

  export default {
    components: {
      VueTagsInput
    },
    props: {
      value: Array,
      label: String,
      entityId: String,
      entityType: String,
      prefill: {
        type: Boolean,
        default: false
      },
      asNotification: {
        type: Boolean,
        default: false
      },
      includeUser: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        inputValue: '',
        autocompleteItems: []
      };
    },
    computed: {
      tags() {
        return (this.value || []).map(this.setText);
      },
      filteredAutocompleteItems() {
        return this.autocompleteItems.filter(autocompleteItem =>
          autocompleteItem.text.toUpperCase().includes(this.inputValue.toUpperCase()));
      }
    },
    methods: {
      addTag({tag, addTag}) {
        if (!tag.recipients) {
          tag.recipients = [{emailAddress: tag.text}];
        }
        addTag(tag);
      },
      setText(tag) {
        tag.text = [tag.description, tag.recipients.map(recipient => recipient.emailAddress).join(', ')].filter(Boolean).join(' | ');
        return tag;
      },
      tagsChanged(newTags) {
        this.$emit('input', newTags);
      },
      load() {
        switch (this.entityType) {
          case 'TENANCY':
            userService.getCurrentUser().then(userResult => {
              tenancyService.getTenants(this.entityId).then(result => {
                const defaultTags = [];
                const recipients = result.data
                  .map(tenant => tenant.legalEntity)
                  .filter(legalEntity => legalEntity.email || (!legalEntity.email && this.asNotification ? legalEntity.name : null))
                  .map(legalEntity => ({
                    emailAddress: legalEntity.email || (!legalEntity.email && this.asNotification ? legalEntity.name.concat(' ', `(${this.$t('letterMail').toLowerCase()})`) : null),
                    legalEntityId: legalEntity.id
                  }));
                if (recipients.length) {
                  defaultTags.push(this.setText({description: this.$t('tenants'), recipients}));
                }
                this.autocompleteItems.push(...defaultTags);
                if (this.includeUser) {
                  defaultTags.push(this.setText({
                    description: this.$t('user'),
                    recipients: [{emailAddress: userResult.data.email}]
                  }));
                }
                if (this.prefill) {
                  this.tagsChanged(defaultTags);
                }
                tenancyService.getUnits(this.entityId).then(result =>
                  result.data.forEach(unitTenancy => this.addPropertyContactsToAutocompleteItems(unitTenancy.unit.propertyId)));
              });
            });
            break;
          case 'UNIT':
            unitService.get(this.entityId).then(result =>
              this.addPropertyContactsToAutocompleteItems(result.data.propertyId));
            break;
          case 'PROPERTY':
            this.addPropertyContactsToAutocompleteItems(this.entityId);
            break;
        }
      },
      addPropertyContactsToAutocompleteItems(propertyId) {
        propertyService.listContacts(propertyId).then(result => {
          this.autocompleteItems.push(...result.data
            .filter(contact => contact.email)
            .map(contact => this.setText({
              description: contact.profession ? this.$t(`model.contact.professions.${contact.profession}`) : null,
              recipients: [{emailAddress: contact.email, legalEntityId: contact.id}]
            }))
          );
        });
      }
    },
    created() {
      this.load();
    }
  };
</script>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am struggling re-writing some older code I made in vue. I have a form which allows the user to enter multiple email recipients. The problem is that the array in which these emails are stored outputs them as one single item.

How do I seperate these email addresses?
This is my code. I know that Vue has something called Split, but I am not sure where I could  use it here (or if it would change anything).

    <template>

    <vue-tags-input
      v-model="inputValue"
      :tags="tags"
      :autocomplete-min-length="0"
      :add-on-key="[',', 13]"
      :autocomplete-items="filteredAutocompleteItems"
      :placeholder="$t('addEmailAddressesHere')"
      data-test-id="send-doc-email-to"
      @before-adding-tag="addTag"
      @tags-changed="tagsChanged"
      class="mw-100"
    />

</template>


问:
Is there any way to include formatting in the sphinx_toolbox.collapse extension's collapse block?
This question is about https://sphinx-toolbox.readthedocs.io/en/latest/extensions/collapse.html.

I need to make individual words bold or italic. I've tried surrounding the text with asterisks, but they aren't processed. I've tried creating custom roles such as :bold: and :italic:, but they aren't processed either. Is there any way to do this?

EDIT: Specifically, I have tried both this:

```<code>.. collapse:: **id**: *String*
</code>```

And this:

```<code>.. role:: bold
   :class: bold

.. role:: italic
   :class: italic

.. collapse:: :bold:`id` :italic:`String`
</code>```

In both cases, the text of the collapse string was output entirely literally, asterisks and fancy-quotes and all.

Body:
This question is about https://sphinx-toolbox.readthedocs.io/en/latest/extensions/collapse.html.

I need to make individual words bold or italic. I've tried surrounding the text with asterisks, but they aren't processed. I've tried creating custom roles such as :bold: and :italic:, but they aren't processed either. Is there any way to do this?

EDIT: Specifically, I have tried both this:

.. collapse:: **id**: *String*

And this:

.. role:: bold
   :class: bold

.. role:: italic
   :class: italic

.. collapse:: :bold:`id` :italic:`String`

In both cases, the text of the collapse string was output entirely literally, asterisks and fancy-quotes and all.


问:
Typscript: Gernic types mixed with specifc
I want to read from a CSV file different articles. The header looks like e.g.

```<code>"verf.", Bestellnummer", "Name", "Notiz",
</code>```

I'm not sure at which position the field appears, i.e. I want to set the colPos dynamically. Additonally I don't want to be dependent on German or English labels, i.e. I want to provide predefined fixed set for the one or the other usage. Therefore I thought have an interface like

```<code>export interface foodFileStructure<T > {
    colName: string;
    colType: T;
    colPos: number;
}
</code>```

and a more or less generic Article like

```<code>export interface FoodsoftArticleGeneric {
    available: foodFileStructure<boolean>;
    id: foodFileStructure<number | undefined>;
    name: foodFileStructure<string>;
    note: foodFileStructure<string>;
}
</code>```

and reading one row of data:FoodsoftArticleGeneric which is either of type German or English.

I struggle how to set now the specfics, e.g. for column Notiz. This would be of type string. I want to have FoodsoftArticleGerman with colName = Notiz and a FoodsoftArticleEnglish with colName=Note.

So, basically colName and colType are fixed (hardcoded) while colPos would be set dynamically when using an instance of FoodsoftArticleGerman (or FoodsoftArticleEnglish).

I know I can define them as const with the specific value. But I have no clue how to define a Generic with specific value.

Body:
I want to read from a CSV file different articles. The header looks like e.g.

"verf.", Bestellnummer", "Name", "Notiz",

I'm not sure at which position the field appears, i.e. I want to set the colPos dynamically. Additonally I don't want to be dependent on German or English labels, i.e. I want to provide predefined fixed set for the one or the other usage. Therefore I thought have an interface like

export interface foodFileStructure<T > {
    colName: string;
    colType: T;
    colPos: number;
}

and a more or less generic Article like

export interface FoodsoftArticleGeneric {
    available: foodFileStructure<boolean>;
    id: foodFileStructure<number | undefined>;
    name: foodFileStructure<string>;
    note: foodFileStructure<string>;
}

and reading one row of data:FoodsoftArticleGeneric which is either of type German or English.

I struggle how to set now the specfics, e.g. for column Notiz. This would be of type string. I want to have FoodsoftArticleGerman with colName = Notiz and a FoodsoftArticleEnglish with colName=Note.

So, basically colName and colType are fixed (hardcoded) while colPos would be set dynamically when using an instance of FoodsoftArticleGerman (or FoodsoftArticleEnglish).

I know I can define them as const with the specific value. But I have no clue how to define a Generic with specific value.


问:
How to set the Telerik Blazor FileStream Position to 0?
Anyone know how to set the Position of a Telerik Blazor FileInfoStream to 0, so that I can Copy the stream twice?

The Seek Method and so on do not work: https://docs.telerik.com/blazor-ui/knowledge-base/fileselect-stream-exception

Thx


问:
Can we Store result set post recursive CTE error of maximum recursion
I want to capture result set into table of recursive query post having maximum recursion error on query.
Tried insert result set into a temp but unable to find way out for same.

BEGIN TRY WITH NumbersCTE AS (
  SELECT 1 AS Number'
  UNION ALL
  SELECT Number + 1 FROM NumbersCTE WHERE  Number < 40000
) insert into temp23
SELECT * FROM   NumbersCTE OPTION (MAXRECURSION 100) END TRY BEGIN CATCH
SELECT SUSER_SNAME(),ERROR_NUMBER(),ERROR_STATE(),ERROR_SEVERITY(),ERROR_LINE(),ERROR_PROCEDURE(),
  ERROR_MESSAGE();
END CATCH;
```


问:
i have a blazor server application project and web api project in same solution...and i want to call the api endpoints from my blazor razor.cs file
Here is my razor.cs file and i want to call my api end point in load data function.

using Core.Models;
using Microsoft.AspNetCore.Components;

namespace AdminReview.Pages.Media
{
    public class MediaBase : ComponentBase
    {
        protected int PageSize = 10;
        protected int PageNumber = 1;
        protected int TotalPages = 0;
        protected IList<MediaModel> MediaList = new List<MediaModel>();
        [Inject] protected NavigationManager NavigationManager { get; set; }

        protected override void OnInitialized()
        {
            try
            {
                LoadData(PageSize, PageNumber, TotalPages);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        void LoadData(int pageSize, int pageNumber, int totalPages)
        {
            //MediaList = Common.MediaInst.GetAllMedia(pageSize, pageNumber,totalPages).Items.ToList();
        }

        public async Task AddMedia(int id)
        {
            NavigationManager.NavigateTo($"/mediadetails?id={id}");
        }
    }
}

```


问:
JavaMelody and Spring Session
We use Spring-session. And we use JavaMelody for monitoring sessions.

JavaMelody uses net.bull.javamelody.SessionListener for monitoring sessions. It is implementation of HttpSessionListener from servlet API.

Spring-session have SessionEventHttpSessionListenerAdapter for capability with servlet api session listeners. It listens Spring session events and submit http session events. Wherein it creates ExpiringSessionHttpSession (wrapper for spring session).

```<code>private HttpSessionEvent createHttpSessionEvent(AbstractSessionEvent event) {
    ExpiringSession session = event.getSession();
    HttpSession httpSession = new ExpiringSessionHttpSession<ExpiringSession>(session,
                this.context);
    HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession);
    return httpSessionEvent;
}
</code>```

We use SessionEventHttpSessionListenerAdapter for working net.bull.javamelody.SessionListener. Spring sessions successful displays in JavaMelody sessions view.

But we have a problem. JavaMelody button "invalidate session" doesn't work correct. JavaMelody uses http session method invalidate for handling this button. The implementation method in ExpiringSessionHttpSession (part of Spring) looks like dummy:

```<code>public void invalidate() {
    checkState();
    this.invalidated = true;
}
</code>```

In facts, it only set invalidate = true in adapter, but it is not invalidate session in Spring session registry. Real spring session continues be valid, and user can be used this session.

Could you have solution for this problem?

I found some solution but I don't think that it's good. We can override spring SessionEventHttpSessionListenerAdapter and ExpiringSessionHttpSession. And we can override method invalidate (adding call session registry). In this case, JavaMelody will invalidate session in registry.

Probably exists solution is better. I would be glad to get it.

Title: JavaMelody and Spring Session

Body:
We use Spring-session. And we use JavaMelody for monitoring sessions.

JavaMelody uses net.bull.javamelody.SessionListener for monitoring sessions. It is implementation of HttpSessionListener from servlet API.

Spring-session have SessionEventHttpSessionListenerAdapter for capability with servlet api session listeners. It listens Spring session events and submit http session events. Wherein it creates ExpiringSessionHttpSession (wrapper for spring session).

private HttpSessionEvent createHttpSessionEvent(AbstractSessionEvent event) {
    ExpiringSession session = event.getSession();
    HttpSession httpSession = new ExpiringSessionHttpSession<ExpiringSession>(session,
                this.context);
    HttpSessionEvent httpSessionEvent = new HttpSessionEvent(httpSession);
    return httpSessionEvent;
}

We use SessionEventHttpSessionListenerAdapter for working net.bull.javamelody.SessionListener. Spring sessions successful displays in JavaMelody sessions view.

But we have a problem. JavaMelody button "invalidate session" doesn't work correct. JavaMelody uses http session method invalidate for handling this button. The implementation method in ExpiringSessionHttpSession (part of Spring) looks like dummy:

public void invalidate() {
    checkState();
    this.invalidated = true;
}

In facts, it only set invalidate = true in adapter, but it is not invalidate session in Spring session registry. Real spring session continues be valid, and user can be used this session.

Could you have solution for this problem?

I found some solution but I don't think that it's good. We can override spring SessionEventHttpSessionListenerAdapter and ExpiringSessionHttpSession. And we can override method invalidate (adding call session registry). In this case, JavaMelody will invalidate session in registry.

Probably exists solution is better. I would be glad to get it.


问:
Springboot AppRun failed:Error creating bean with name 'configDataContextRefresher'
I'm working on a Spring Boot project. I got a weird error when I start AppRun
Below is the error:

```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxManagerFactory' defined in class path resource [xxDataSourceConfig.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'refreshEventListener' defined in class path resource [org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.class]: Unsatisfied dependency expressed through method 'refreshEventListener' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configDataContextRefresher' defined in class path resource [org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.context.refresh.ConfigDataContextRefresher] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@3b192d32]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:603)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)

</code>```

enter image description here

I've checked springboot version and spring cloud version:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/>
</parent>

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</code>```

I can build jar file, but I can not run the service.
Please Help! THanks a lot!

Body:
I'm working on a Spring Boot project. I got a weird error when I start AppRun
Below is the error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'xxManagerFactory' defined in class path resource [xxDataSourceConfig.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'refreshEventListener' defined in class path resource [org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.class]: Unsatisfied dependency expressed through method 'refreshEventListener' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configDataContextRefresher' defined in class path resource [org/springframework/cloud/autoconfigure/RefreshAutoConfiguration.class]: Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.cloud.context.refresh.ConfigDataContextRefresher] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@3b192d32]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:603)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)

enter image description here

I've checked springboot version and spring cloud version:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.6.RELEASE</version>
        <relativePath/>
</parent>

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR3</version>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

I can build jar file, but I can not run the service.
Please Help! THanks a lot!


问:
How to calculate the 15 minutes block average starting from 00:00 hours?
I'm trying to calculate the block averages of the iot data coming in from over 200+ devices at every 15 seconds to aws iot core and want to calculate the block average (15 minutes) for each of the device and it's parameters.

Here is my flow :-

aws iot core (ingestion) -> iot rules engine -> firehose delivery stream (900 seconds buffer and dynamic partioning data based on device name) -> s3 bucket (batched data stored in s3 bucket)

I want to calculate the average for all devices and its all parameters for eg:-

```<code>device a has this payload {
    "name" : "a",
    "voltage" : 3.4,
    "power" : 1.23,
    "time" : epoch timestamp
}

device b has this payload {
     "name" : "b",
    "voltage" : 12.90,
    "power" : 54.78,
    "time" : epoch timestamp

}
</code>```

I want to calculate and store average for each of the parameter of the device in such a way :-

Date
Block
Average Voltage
Average power

12 - Jan - 2023
00:00-00:15
23.54
32.526

12 - Jan - 2023
00:15-00:30
20.36
21.90

12 - Jan - 2023
00:30-00:45
34.36
89.24

12 - Jan - 2023
00:45-01:00
56.312
78.20

There should be 96 blocks for the entire day :-

1440 minutes in a day / 15 minutes block = 96 blocks in a day

One way i thought of implementing it is putting a s3 lambda trigger on put event on s3 read files of each entered object from s3 calculate it and store it in another s3 bucket. But it does not seem to work the way i want it to.

Any help will greatly be appreciated.

Body:
I'm trying to calculate the block averages of the iot data coming in from over 200+ devices at every 15 seconds to aws iot core and want to calculate the block average (15 minutes) for each of the device and it's parameters.

Here is my flow :-

aws iot core (ingestion) -> iot rules engine -> firehose delivery stream (900 seconds buffer and dynamic partioning data based on device name) -> s3 bucket (batched data stored in s3 bucket)

I want to calculate the average for all devices and its all parameters for eg:-

device a has this payload {
    "name" : "a",
    "voltage" : 3.4,
    "power" : 1.23,
    "time" : epoch timestamp
}

device b has this payload {
     "name" : "b",
    "voltage" : 12.90,
    "power" : 54.78,
    "time" : epoch timestamp

}

I want to calculate and store average for each of the parameter of the device in such a way :-

Date
Block
Average Voltage
Average power

12 - Jan - 2023
00:00-00:15
23.54
32.526

12 - Jan - 2023
00:15-00:30
20.36
21.90

12 - Jan - 2023
00:30-00:45
34.36
89.24

12 - Jan - 2023
00:45-01:00
56.312
78.20

There should be 96 blocks for the entire day :-

1440 minutes in a day / 15 minutes block = 96 blocks in a day

One way i thought of implementing it is putting a s3 lambda trigger on put event on s3 read files of each entered object from s3 calculate it and store it in another s3 bucket. But it does not seem to work the way i want it to.

Any help will greatly be appreciated.


问:
What does GlobalAveragePooling1D do in keras?
In the embedding example here:
https://www.tensorflow.org/text/guide/word_embeddings

```<code>result = embedding_layer(tf.constant([[0, 1, 2], [3, 4, 5]]))
result.shape
TensorShape([2, 3, 5])
</code>```

Then it explains:

```<code>When given a batch of sequences as input, an embedding layer returns a 3D floating point tensor, of shape (samples, sequence_length, embedding_dimensionality). To convert from this sequence of variable length to a fixed representation there are a variety of standard approaches. You could use an RNN, Attention, or pooling layer before passing it to a Dense layer. This tutorial uses pooling because it's the simplest.

The GlobalAveragePooling1D layer returns a fixed-length output vector for each example by averaging over the sequence dimension. This allows the model to handle input of variable length, in the simplest way possible.
</code>```

Then the code:

```<code>embedding_dim=16

model = Sequential([
  vectorize_layer,
  Embedding(vocab_size, embedding_dim, name="embedding"),
  GlobalAveragePooling1D(),
  Dense(16, activation='relu'),
  Dense(1)
])
</code>```

The GlobalAveragePooling1D should calculate a single integer for each word's embedding of dimension = n. I don't understand this part:

```<code>This allows the model to handle input of variable length, in the simplest way possible.
</code>```

Similarly:

```<code>To convert from this sequence of variable length to a fixed representation there are a variety of standard approaches.
</code>```

In each embedding layer, input length is already fixed by the parameter 'input_length'. Truncation and padding are used to ensure the fixed length of the input. So what does it mean by saying GlobalAveragePooling1D is used to convert from this sequence of variable length to a fixed representation? What does the 'variable length' mean here?

Body:
In the embedding example here:
https://www.tensorflow.org/text/guide/word_embeddings

result = embedding_layer(tf.constant([[0, 1, 2], [3, 4, 5]]))
result.shape
TensorShape([2, 3, 5])

Then it explains:

When given a batch of sequences as input, an embedding layer returns a 3D floating point tensor, of shape (samples, sequence_length, embedding_dimensionality). To convert from this sequence of variable length to a fixed representation there are a variety of standard approaches. You could use an RNN, Attention, or pooling layer before passing it to a Dense layer. This tutorial uses pooling because it's the simplest.

The GlobalAveragePooling1D layer returns a fixed-length output vector for each example by averaging over the sequence dimension. This allows the model to handle input of variable length, in the simplest way possible.

Then the code:

embedding_dim=16

model = Sequential([
  vectorize_layer,
  Embedding(vocab_size, embedding_dim, name="embedding"),
  GlobalAveragePooling1D(),
  Dense(16, activation='relu'),
  Dense(1)
])

The GlobalAveragePooling1D should calculate a single integer for each word's embedding of dimension = n. I don't understand this part:

This allows the model to handle input of variable length, in the simplest way possible.

Similarly:

To convert from this sequence of variable length to a fixed representation there are a variety of standard approaches.

In each embedding layer, input length is already fixed by the parameter 'input_length'. Truncation and padding are used to ensure the fixed length of the input. So what does it mean by saying GlobalAveragePooling1D is used to convert from this sequence of variable length to a fixed representation? What does the 'variable length' mean here?


问:
How to compile Mapbox Android Events Repository Project? Unauthorized response for sdk-registry
Based on an critical API change by android API Level 31 (refer to this thread click here) we need to fix some lines in libtelemetry/libcore of the following repository:
https://github.com/mapbox/mapbox-events-android.
Therefore we want to compile the project by ourself as the repo does not seem to be maintained at all.

We downloaded the whole project and trying to compile in Android Studio. But we can't get rid of this error:

Could not GET 'https://api.mapbox.com/downloads/v2/releases/maven/com/mapbox/gradle/plugins/sdk-registry/0.4.0/sdk-registry-0.4.0.pom'.
Received status code 401 from server: Unauthorized

What we have already tried:

Added a new private download token in our mapbox-account

Added the following lines to the settings.xml based on this documentation (navigation-sdk for android docs)

```<code>  dependencyResolutionManagement {
      repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
      repositories {
          google()
          mavenCentral()
          maven {
              url 'https://api.mapbox.com/downloads/v2/releases/maven'
              authentication {
                  basic(BasicAuthentication)
              }
              credentials {
                  // Do not change the username below.
                  // This should always be `mapbox` (not your username).
                  username = "mapbox"
                  // Use the secret token you stored in gradle.properties as the password
                  password = "OUR_PRIVATE_TOKEN"
              }
          }
      }
  }
</code>```

any ideas what we are missing to compile the project correctly? oO

thanks in advance!

Body:
Based on an critical API change by android API Level 31 (refer to this thread click here) we need to fix some lines in libtelemetry/libcore of the following repository:
https://github.com/mapbox/mapbox-events-android.
Therefore we want to compile the project by ourself as the repo does not seem to be maintained at all.

We downloaded the whole project and trying to compile in Android Studio. But we can't get rid of this error:

Could not GET 'https://api.mapbox.com/downloads/v2/releases/maven/com/mapbox/gradle/plugins/sdk-registry/0.4.0/sdk-registry-0.4.0.pom'.
Received status code 401 from server: Unauthorized

What we have already tried:

Added a new private download token in our mapbox-account

Added the following lines to the settings.xml based on this documentation (navigation-sdk for android docs)

  dependencyResolutionManagement {
      repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
      repositories {
          google()
          mavenCentral()
          maven {
              url 'https://api.mapbox.com/downloads/v2/releases/maven'
              authentication {
                  basic(BasicAuthentication)
              }
              credentials {
                  // Do not change the username below.
                  // This should always be `mapbox` (not your username).
                  username = "mapbox"
                  // Use the secret token you stored in gradle.properties as the password
                  password = "OUR_PRIVATE_TOKEN"
              }
          }
      }
  }

any ideas what we are missing to compile the project correctly? oO

thanks in advance!


问:
how to test unsubscribeFocus & unsubscribeBlur with Jest?
i got an error with this message :

TypeError: this.unsubscribeFocus is not a function Jest

what i want to test is this code

```<code>componentWillUnmount() {
        // Remove the event listener
        this.unsubscribeFocus();
        this.unsubscribeBlur();
    }
</code>```

then on file test.js

```<code>    test('componentWillUnmount as expected', async () => {
      class Foo extends React.Component {
        // constructor(props) {
        //   this.unsubscribeFocus = jest.fn();
        //   this.unsubscribeFocus = jest.fn();
        // }

        unsubscribeFocus = () => {};
        unsubscribeBlur = () => {};

        render() {
          return (<ReservationNotFound />)
        }
      }
      wrapper.unmount();
      const componentWillUnmount = wrapper.instance().componentWillUnmount();
      expect(componentWillUnmount).not.toEqual(null);
    });
  });
</code>```

but at the wrapper.unmount i got an error that like this

so how to solve this unsubscribeFocus & unsubscribeBlur with jest when it will unmount?

Body:
i got an error with this message :

TypeError: this.unsubscribeFocus is not a function Jest

what i want to test is this code

componentWillUnmount() {
        // Remove the event listener
        this.unsubscribeFocus();
        this.unsubscribeBlur();
    }

then on file test.js

    test('componentWillUnmount as expected', async () => {
      class Foo extends React.Component {
        // constructor(props) {
        //   this.unsubscribeFocus = jest.fn();
        //   this.unsubscribeFocus = jest.fn();
        // }

        unsubscribeFocus = () => {};
        unsubscribeBlur = () => {};

        render() {
          return (<ReservationNotFound />)
        }
      }
      wrapper.unmount();
      const componentWillUnmount = wrapper.instance().componentWillUnmount();
      expect(componentWillUnmount).not.toEqual(null);
    });
  });

but at the wrapper.unmount i got an error that like this

so how to solve this unsubscribeFocus & unsubscribeBlur with jest when it will unmount?


问:
Service to Service secure communication among services run behind spring cloud gateway
I have couple of microservices running behind the Spring cloud gateway and all microservices run behind are protected by OAuth2 protocol using spring authorization server. Everything is working fine but few of the microservices would like to exchange data with each other but these resource servers are protected.

I have created the registered client (for each microservice with their own client id & client secret) at authorization server and as well as respective OAuth2 client configuration at each service. I have configured this setup with Webclient to fetch data from other services needed as follows

```<code>@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }

    @Bean
    public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
                new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oauth2Client.setDefaultClientRegistrationId("server");

        return WebClient.builder()
                .apply(oauth2Client.oauth2Configuration())
                .build();
    }

    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository) {

        OAuth2AuthorizedClientProvider authorizedClientProvider =
                OAuth2AuthorizedClientProviderBuilder.builder()
                        .clientCredentials()
                        .build();
        DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
                clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        return authorizedClientManager;
    }

....
....
application.yml (similar config. for resource-client2)
spring:
  security:
    oauth2:
      client:
        registration:
          server:
            scope: ROLE_RESOURCE_CLIENT1
            client-id: resource-client1
            client-secret: '{noop}secret1'
            client-authentication-method: basic
            authorization-grant-type: client_credentials
            client-name: resource-client1-client-credentials
        provider:
          server:
            token-uri: http://localhost:9001/oauth2/token

      resourceserver:
        jwt:
          issuer-uri: http://localhost:9001
</code>```

and at authorization server, the client configuration is as follows

```<code>private final static RegisteredClient resource1ServiceClient = RegisteredClient.withId("2")
            .clientId("resource-client1")
            .clientSecret("{noop}secret1")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .build();

    private final static RegisteredClient resource2ServiceClient = RegisteredClient.withId("3")
            .clientId("resource-client2")
            .clientSecret("{noop}secret2")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .build();
</code>```

when I'm trying to do rest call using webclient from resource client1 to resource client2, I'm getting NPE error because the spring authorization server is not providing the access token.
error is

```<code>java.lang.NullPointerException: Cannot invoke "org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse.getAccessToken()" because "tokenResponse" is null
    at org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider.authorize(ClientCredentialsOAuth2AuthorizedClientProvider.java:87) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
    *__checkpoint ⇢ Request to GET http://localhost:8082/hello2 [DefaultWebClient]
Original Stack Trace:
        at org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider.authorize(ClientCredentialsOAuth2AuthorizedClientProvider.java:87) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at org.springframework.security.oauth2.client.DelegatingOAuth2AuthorizedClientProvider.authorize(DelegatingOAuth2AuthorizedClientProvider.java:71) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager.authorize(DefaultOAuth2AuthorizedClientManager.java:176) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.lambda$authorizeClient$22(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:485) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at reactor.core.publisher.MonoSupplier.call(MonoSupplier.java:67) ~[reactor-core-3.5.1.jar:3.5.1]
</code>```

Not sure what went wrong with my setup or missing the logic to get it done. using latest spring version & spring authorization server version 1.0.0 . kindly help

Body:
I have couple of microservices running behind the Spring cloud gateway and all microservices run behind are protected by OAuth2 protocol using spring authorization server. Everything is working fine but few of the microservices would like to exchange data with each other but these resource servers are protected.

I have created the registered client (for each microservice with their own client id & client secret) at authorization server and as well as respective OAuth2 client configuration at each service. I have configured this setup with Webclient to fetch data from other services needed as follows

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Bean
    SecurityFilterChain defaultFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }

    @Bean
    public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
                new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        oauth2Client.setDefaultClientRegistrationId("server");

        return WebClient.builder()
                .apply(oauth2Client.oauth2Configuration())
                .build();
    }

    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository) {

        OAuth2AuthorizedClientProvider authorizedClientProvider =
                OAuth2AuthorizedClientProviderBuilder.builder()
                        .clientCredentials()
                        .build();
        DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
                clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        return authorizedClientManager;
    }

....
....
application.yml (similar config. for resource-client2)
spring:
  security:
    oauth2:
      client:
        registration:
          server:
            scope: ROLE_RESOURCE_CLIENT1
            client-id: resource-client1
            client-secret: '{noop}secret1'
            client-authentication-method: basic
            authorization-grant-type: client_credentials
            client-name: resource-client1-client-credentials
        provider:
          server:
            token-uri: http://localhost:9001/oauth2/token

      resourceserver:
        jwt:
          issuer-uri: http://localhost:9001

and at authorization server, the client configuration is as follows

private final static RegisteredClient resource1ServiceClient = RegisteredClient.withId("2")
            .clientId("resource-client1")
            .clientSecret("{noop}secret1")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .build();

    private final static RegisteredClient resource2ServiceClient = RegisteredClient.withId("3")
            .clientId("resource-client2")
            .clientSecret("{noop}secret2")
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .build();

when I'm trying to do rest call using webclient from resource client1 to resource client2, I'm getting NPE error because the spring authorization server is not providing the access token.
error is

java.lang.NullPointerException: Cannot invoke "org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse.getAccessToken()" because "tokenResponse" is null
    at org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider.authorize(ClientCredentialsOAuth2AuthorizedClientProvider.java:87) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
    Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException:
Error has been observed at the following site(s):
    *__checkpoint ⇢ Request to GET http://localhost:8082/hello2 [DefaultWebClient]
Original Stack Trace:
        at org.springframework.security.oauth2.client.ClientCredentialsOAuth2AuthorizedClientProvider.authorize(ClientCredentialsOAuth2AuthorizedClientProvider.java:87) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at org.springframework.security.oauth2.client.DelegatingOAuth2AuthorizedClientProvider.authorize(DelegatingOAuth2AuthorizedClientProvider.java:71) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager.authorize(DefaultOAuth2AuthorizedClientManager.java:176) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.lambda$authorizeClient$22(ServletOAuth2AuthorizedClientExchangeFilterFunction.java:485) ~[spring-security-oauth2-client-6.0.1.jar:6.0.1]
        at reactor.core.publisher.MonoSupplier.call(MonoSupplier.java:67) ~[reactor-core-3.5.1.jar:3.5.1]

Not sure what went wrong with my setup or missing the logic to get it done. using latest spring version & spring authorization server version 1.0.0 . kindly help


问:
How to automatically expand rows based on an intervall of accounts 3000-3999 (accounting)?
I'm trying to figure out how one can expand rows automatically using formulas or appscript in Google Sheets.

The goal is to create a standard Profit and Loss report with automatic expanding rows based on intervalls, such as 3000 - 3999 for revenue. The issue today is that, by not using Pivot tables, i cant get the rows to expand and push the other rows underneath downwards. I have to manually insert a new account and rows if new accounts are added.

Does anyone have any tips? Is there an add-on or an appscript that allows us to perform such an action?

I've tried using Filter/Sort function with empty spaces underneath each group to make room for new accounts and hidden the rows, but its not a very scalable solution. I've also tried using Pivot tables but cant expand rows automatically that way either. I get a #ref if the rows collide with new accounts.

3000
3001
3002
(blank)
(blank)
(blank)


问:
I have this Dataset, I want to convert it into this New Dataset?
This is my Dataset

Expected Dataset

This is just a Demo Dataset, I have a large dataset with millions of rows, I want to classify my shares as share bought and sold for every row, if the type is P it should be added in the column of bought and vice versa, similarly, if a row is empty it should just enter 0 in those two columns. Please suggest something without any loops as it's a pretty huge dataset.
The Dataset is almost for millions of rows, so we need something proper which will be directly applicable for dataset.

Only For loop has been tried, but takes too much time.


问:
Use multiple Cache AWS Memory Databases in Laravel
Is there anyway to configure multiple databases for AWS Memory Databases?
And when I runphp artisan cache:clear, it should not truncate my "specific AWS Memory Database".

Idea is one database will be use for Cache purpose and another db of AWS Memory database will be use as database purpose, data will not be deleted from this database.

I have tried using multiple connection for cache and its working fine, the block is only php artisan cache:clear is truncating both databses.


问:
I am trying to debug my Ruby project, but getting error "evaluation memory limit is ineffective mri < 2.0"
In my project we have used cucumber with bdd framework, when i try to debug it's not redirecting to step definition file, script terminating abruptly.


问:
Tkinter treeview gets the style of first treeview inspite of having its own style
The first treeview which had a particular style was:

class tree:
    def __init__(self):
        self.tree = ttk.Treeview(frametree,height=28)
        self.tree.grid(row=1,column=0,padx=2)
        self.tree.column("#0",width=250, stretch=NO)
        self.tree.bind("<ButtonRelease-1>", self.OnClick)
        self.tree.tag_configure('highlight', background='lightblue')
        style_def = ttk.Style(frametree)
        style_def.configure("Treeview", background="#FFDEAD",fieldbackground="#FFDEAD", foreground="Black", font=(None, 14), sheight=14, rowheight=30)
        style_def.configure("Treeview.Heading",font=(None, 12))
```
<p>The following code was used for showing the treeview:</p>
<pre class="lang-py prettyprint-override"><code># for displaying treeview
#tree000 = tree()
if __name__ == "__main__":
    tree000 = tree()
</code>```

The another table was styled in different way as follows:

style_wear = ttk.Style(firsttreeframe)
style_wear.configure("Treeview.Heading", font=(None, 13))
style_wear.configure("Treeview", font=(None, 12))
tree02 = ttk.Treeview(firsttreeframe, column=("c1", "c2","c3", "c4","c5", "c6","c7", "c8","c9","c10", "c11","c12", "c13","c14", "c15","c16", "c17","c18"), show='headings', height=5)
```
<p>And finally used grid method to place the treeview table.</p>
<pre class="lang-py prettyprint-override"><code>tree02['show']='headings'
tree02.grid(row=1,column=0,columnspan=4,sticky=EW)
</code>```

But tree1 gets the style of first tree. I don't know why maybe because of treeview display method.

I tried running placing the treeview in separate project It works fine as you can see:

In app
first tree:

Second tree:

You can see both has same style
In separate project:

I want my app to show this style to the second tree but it gets the style of the first tree.
Please help me with this.

Body:
The first treeview which had a particular style was:

class tree:
    def __init__(self):
        self.tree = ttk.Treeview(frametree,height=28)
        self.tree.grid(row=1,column=0,padx=2)
        self.tree.column("#0",width=250, stretch=NO)
        self.tree.bind("<ButtonRelease-1>", self.OnClick)
        self.tree.tag_configure('highlight', background='lightblue')
        style_def = ttk.Style(frametree)
        style_def.configure("Treeview", background="#FFDEAD",fieldbackground="#FFDEAD", foreground="Black", font=(None, 14), sheight=14, rowheight=30)
        style_def.configure("Treeview.Heading",font=(None, 12))

The following code was used for showing the treeview:

# for displaying treeview
#tree000 = tree()
if __name__ == "__main__":
    tree000 = tree()

The another table was styled in different way as follows:

style_wear = ttk.Style(firsttreeframe)
style_wear.configure("Treeview.Heading", font=(None, 13))
style_wear.configure("Treeview", font=(None, 12))
tree02 = ttk.Treeview(firsttreeframe, column=("c1", "c2","c3", "c4","c5", "c6","c7", "c8","c9","c10", "c11","c12", "c13","c14", "c15","c16", "c17","c18"), show='headings', height=5)

And finally used grid method to place the treeview table.

tree02['show']='headings'
tree02.grid(row=1,column=0,columnspan=4,sticky=EW)

But tree1 gets the style of first tree. I don't know why maybe because of treeview display method.

I tried running placing the treeview in separate project It works fine as you can see:

In app
first tree:

Second tree:

You can see both has same style
In separate project:

I want my app to show this style to the second tree but it gets the style of the first tree.
Please help me with this.


问:
How to use `pylint` on code supporting multiple Python versions?
Since hashlib.file_digest was introduced only in Python 3.11, I use a fallback to the previous code:

if sys.version_info < (3, 11):
    digest = hashlib.sha256()
    digest.update(file.read())
else:
    digest = hashlib.file_digest(file, hashlib.sha256)
```

Running pylint on Python 3.10 on this file, I get the following error:

Module 'hashlib' has no 'file_digest' member (no-member)

I can add # pylint: disable=no-member to the bottom branch of the code, but then I will get

Useless suppression of 'no-member' (useless-suppression)

when pylint is run in Python 3.11.

Body:
Since hashlib.file_digest was introduced only in Python 3.11, I use a fallback to the previous code:

if sys.version_info < (3, 11):
    digest = hashlib.sha256()
    digest.update(file.read())
else:
    digest = hashlib.file_digest(file, hashlib.sha256)

Running pylint on Python 3.10 on this file, I get the following error:

Module 'hashlib' has no 'file_digest' member (no-member)

I can add # pylint: disable=no-member to the bottom branch of the code, but then I will get

Useless suppression of 'no-member' (useless-suppression)

when pylint is run in Python 3.11.


问:
Impersonation with Keycloak and Apache Mellon in PHP
I'm currently working on an application that uses the Mellon and Keycloak as the identity provider, using SAML for the authentication flow. I'm trying to implement an impersonation feature in my application that would allow a user with certain privileges (e.g. an administrator) to temporarily take on the identity of another user without requiring the original user to log out.

I'm wondering if it is possible to use the Mellon to implement this feature, and if so, what would be the best approach to do so. I've been reading through the Mellon documentation and searching online for examples, but so far I haven't been able to find much information on how to implement impersonation with Mellon.

If anyone has experience with using Mellon and Keycloak together and can provide some guidance or pointers on how to implement impersonation in this setup, I would really appreciate it.

Thank you for your time and help!


问:
How to pass string literals on onclick function in blazor?
I have the following code:

```<code> <MudPaper Class="d-flex flex-row pt-6 pb-4" Style="height:100px;" @onclick="View">

 </MudPaper>

   private async Task View()
    {
        NavManager.NavigateTo("/someurl");
    }

</code>```

This works properly.

If I have to pass parameters to the function how would I do that. I tried the following :

```<code><MudPaper Class="d-flex flex-row pt-6 pb-4" Style="height:100px;" @onclick="View("someurl")">

 </MudPaper>

   private async Task View(string url)
    {
        NavManager.NavigateTo("/"+url);
    }
</code>```

obviously at this place its throwing errors.

@onclick="View("someurl")">

I tried replacing with single quotes, doesnot work either

Body:
I have the following code:

 <MudPaper Class="d-flex flex-row pt-6 pb-4" Style="height:100px;" @onclick="View">

 </MudPaper>

   private async Task View()
    {
        NavManager.NavigateTo("/someurl");
    }

This works properly.

If I have to pass parameters to the function how would I do that. I tried the following :

<MudPaper Class="d-flex flex-row pt-6 pb-4" Style="height:100px;" @onclick="View("someurl")">

 </MudPaper>

   private async Task View(string url)
    {
        NavManager.NavigateTo("/"+url);
    }

obviously at this place its throwing errors.

@onclick="View("someurl")">

I tried replacing with single quotes, doesnot work either


问:
Running "docker exec" displays "bash-4.2" in "Shell command prompt"

docker run -itd --restart always --network host --name test_db -h test_db -v share:/home/share -v /etc/timezone:/etc/timezone -v /etc/localtime:/etc/localtime -v /sys/fs/cgroup:/sys/fs/cgroup:ro --privileged mariadb_10.8 init
```

Running docker exec -it test_db bash displays root@test_db in the shell command prompt, but after someday bash-4.2 appeared.
And there is no ll command and no /root folder

How to fix it?

Thanks in advance.
Regards

Body:
docker run -itd --restart always --network host --name test_db -h test_db -v share:/home/share -v /etc/timezone:/etc/timezone -v /etc/localtime:/etc/localtime -v /sys/fs/cgroup:/sys/fs/cgroup:ro --privileged mariadb_10.8 init

Running docker exec -it test_db bash displays root@test_db in the shell command prompt, but after someday bash-4.2 appeared.
And there is no ll command and no /root folder

How to fix it?

Thanks in advance.
Regards


问:
C++ Builder 11.2 assigning C++ method to Delphi event
We have an older project with mixed C++/Delphi code. We are trying to compile it with the latest C++Builder.

This code was OK with RAD Studio 10.1:

NewObject->OnDraw = (TDrawEvent)&(CObj->MyVRMLShapeDraw);
```
<p>Edit: actual declarations:</p>
<pre class="lang-pascal prettyprint-override"><code>TDrawEvent = procedure (Sender: TGLObject; Face: GLenum; Draft: boolean; State: TGLDrawState ) of object;

private
  FOnDraw: TDrawEvent;
published
  property OnDraw: TDrawEvent read FOnDraw write FOnDraw;
</code>```

class TManager : public TBaseObject {
public:
    void __fastcall MyVRMLShapeDraw(TGLObject *Sender, DWORD Face, bool Draft, char DrawState);
```

Where NewObject is a class instance from a Delphi class, TDrawEvent is a Delphi event method type (TMethod basically with some parameters), CObj is our C++ object, MyDraw is its C++ method.

TGLDrawState is an enum with a few values.

The latest C++Builder compiler drops this error message:

[bcc64 Error] xy.cpp(1021): cannot compile this unexpected cast lvalue yet

How can we solve this? Is it possible at all to call a C++ method from Delphi code in the usual event handler method style?

EDIT: I solved it with wrapping the call in a global function, but if someone knows the elegant syntax of this, it would be appreciated.

EDIT: My mistake - the newer 11.2 compiler required using unsigned instead of DWORD, and glclasses::TGLDrawState instead of char in the C++ method parameter list. Older compilers accepted less strict type matching.

Body:
We have an older project with mixed C++/Delphi code. We are trying to compile it with the latest C++Builder.

This code was OK with RAD Studio 10.1:

NewObject->OnDraw = (TDrawEvent)&(CObj->MyVRMLShapeDraw);

Edit: actual declarations:

TDrawEvent = procedure (Sender: TGLObject; Face: GLenum; Draft: boolean; State: TGLDrawState ) of object;

private
  FOnDraw: TDrawEvent;
published
  property OnDraw: TDrawEvent read FOnDraw write FOnDraw;

class TManager : public TBaseObject {
public:
    void __fastcall MyVRMLShapeDraw(TGLObject *Sender, DWORD Face, bool Draft, char DrawState);

Where NewObject is a class instance from a Delphi class, TDrawEvent is a Delphi event method type (TMethod basically with some parameters), CObj is our C++ object, MyDraw is its C++ method.

TGLDrawState is an enum with a few values.

The latest C++Builder compiler drops this error message:

[bcc64 Error] xy.cpp(1021): cannot compile this unexpected cast lvalue yet

How can we solve this? Is it possible at all to call a C++ method from Delphi code in the usual event handler method style?

EDIT: I solved it with wrapping the call in a global function, but if someone knows the elegant syntax of this, it would be appreciated.

EDIT: My mistake - the newer 11.2 compiler required using unsigned instead of DWORD, and glclasses::TGLDrawState instead of char in the C++ method parameter list. Older compilers accepted less strict type matching.


问:
pre-trained SSD + segmentation
I am training a pre-trained model from the TensorFlow zoo. I want to do segmentation to the existing model. how do I do it?

The model I am using is SSD MobileNet V2 FPNLite 320x320

Title: pre-trained SSD + segmentation


问:
mfc assert failed asserted fail at wincore.cpp line 1846
I have domodal issue by using cpropertysheet object.domodal in dlg object.
the specific assertion failed message is as follow
ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)());
Is there anyone expericing the same problem?

expect to pop up the sheet doing other operation the code is following

```<code> IMPLEMENT_DYNAMIC(msheet, CPropertySheet)
    #if 1
    msheet::msheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage)
        :CPropertySheet(nIDCaption, pParentWnd, iSelectPage)
    {
        //CAdminDebug AdminDebugDlg;
        //this->AddPage(&AdminDebugDlg);
        AddPage(&AdminDebugDlg);
    }
    #endif

    msheet::msheet(LPCTSTR pszCaption,CWnd* pParentWnd, UINT iSelectPage)
        :CPropertySheet(pszCaption, pParentWnd, iSelectPage)
    {
        //CAdminDebug AdminDebugDlg;
        //this->AddPage(&AdminDebugDlg);
        AddPage(&AdminDebugDlg);
    }
    msheet::~msheet()
    {
    }
    BEGIN_MESSAGE_MAP(msheet, msheet)
        //{{AFX_MSG_MAP(CMyPropertySheet)
            // NOTE - the ClassWizard will add and remove mapping macros here.
        //}}AFX_MSG_MAP
        ON_BN_CLICKED(IDCANCEL, &msheet::OnCancel)
    END_MESSAGE_MAP()
    #if 1
    BOOL msheet::OnInitDialog(void)
    {
        BOOL bResult = CPropertySheet::OnInitDialog();
    #if 0
        CWnd *pWnd = GetDlgItem (IDOK);
        pWnd->ShowWindow (FALSE);
        //pWnd = GetDlgItem (IDHELP);
        //pWnd->ShowWindow (FALSE);
    #endif
    #if 0
        this->GetDlgItem(IDOK)->ShowWindow(SW_HIDE);
    #endif
    #if 1
        CWnd *pWnd = GetDlgItem (IDOK);
        if(pWnd && pWnd->GetSafeHwnd())
        pWnd->ShowWindow (FALSE);
    #endif
        return bResult;
    }
    #endif
    void msheet::OnCancel()
    {
         int kk=1;
         msheet::OnClose();

    }
    void CAXToolDlg::OnBnClickedButton1()
    {
        // TODO: Add your control notification handler code here
        msheet msheet(_T("hello"), NULL,0);
        msheet.DoModal();
    }
    BEGIN_MESSAGE_MAP(CAXToolDlg, CDialog)
        ON_BN_CLICKED(IDC_BUTTON1, &CAXToolDlg::OnBnClickedButton1)
    END_MESSAGE_MAP()
</code>```

Body:
I have domodal issue by using cpropertysheet object.domodal in dlg object.
the specific assertion failed message is as follow
ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)());
Is there anyone expericing the same problem?

expect to pop up the sheet doing other operation the code is following

 IMPLEMENT_DYNAMIC(msheet, CPropertySheet)
    #if 1
    msheet::msheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage)
        :CPropertySheet(nIDCaption, pParentWnd, iSelectPage)
    {
        //CAdminDebug AdminDebugDlg;
        //this->AddPage(&AdminDebugDlg);
        AddPage(&AdminDebugDlg);
    }
    #endif

    msheet::msheet(LPCTSTR pszCaption,CWnd* pParentWnd, UINT iSelectPage)
        :CPropertySheet(pszCaption, pParentWnd, iSelectPage)
    {
        //CAdminDebug AdminDebugDlg;
        //this->AddPage(&AdminDebugDlg);
        AddPage(&AdminDebugDlg);
    }
    msheet::~msheet()
    {
    }
    BEGIN_MESSAGE_MAP(msheet, msheet)
        //{{AFX_MSG_MAP(CMyPropertySheet)
            // NOTE - the ClassWizard will add and remove mapping macros here.
        //}}AFX_MSG_MAP
        ON_BN_CLICKED(IDCANCEL, &msheet::OnCancel)
    END_MESSAGE_MAP()
    #if 1
    BOOL msheet::OnInitDialog(void)
    {
        BOOL bResult = CPropertySheet::OnInitDialog();
    #if 0
        CWnd *pWnd = GetDlgItem (IDOK);
        pWnd->ShowWindow (FALSE);
        //pWnd = GetDlgItem (IDHELP);
        //pWnd->ShowWindow (FALSE);
    #endif
    #if 0
        this->GetDlgItem(IDOK)->ShowWindow(SW_HIDE);
    #endif
    #if 1
        CWnd *pWnd = GetDlgItem (IDOK);
        if(pWnd && pWnd->GetSafeHwnd())
        pWnd->ShowWindow (FALSE);
    #endif
        return bResult;
    }
    #endif
    void msheet::OnCancel()
    {
         int kk=1;
         msheet::OnClose();

    }
    void CAXToolDlg::OnBnClickedButton1()
    {
        // TODO: Add your control notification handler code here
        msheet msheet(_T("hello"), NULL,0);
        msheet.DoModal();
    }
    BEGIN_MESSAGE_MAP(CAXToolDlg, CDialog)
        ON_BN_CLICKED(IDC_BUTTON1, &CAXToolDlg::OnBnClickedButton1)
    END_MESSAGE_MAP()


问:
Powershell invoke-webRequest - The remote server returned an error: (422) Unprocessable Entity
When I try to create an issue in redmine via the Rest Api using Powershell, I get an error: The remote server returned an error: (422) Unprocessable Entity.
In postman, this request is processed correctly.

Here is an example of script:

```<code>$Headers = @{ 'X-Redmine-API-key' = '********' }
$Uri = "https://task.test.com/issues.json"
Invoke-RestMethod $Uri -Headers $Headers -Method POST -ContentType 'application/json' -Body '{
    "issue": {
        "project_id": 316,
        "subject": "testProject",
        "priority_id": 4,
        "description": "testTask",
        "assigned_to_id": 1891,
        "custom_fields": [{
                "value": "******",
                "name": "physicalName",
                "id": 5
            },
            {
                "value": "****",
                "name": "***",
                "id": 6
            },
            {
                "value": "****",
                "name": "*****",
                "id": 10
            },
            {
                "value": "****",
                "name": "*****",
                "id": 11
            },
            {
                "value": "0",
                "name": "*******",
                "id": 16
            }
        ]
    }
}'
</code>```

Body:
When I try to create an issue in redmine via the Rest Api using Powershell, I get an error: The remote server returned an error: (422) Unprocessable Entity.
In postman, this request is processed correctly.

Here is an example of script:

$Headers = @{ 'X-Redmine-API-key' = '********' }
$Uri = "https://task.test.com/issues.json"
Invoke-RestMethod $Uri -Headers $Headers -Method POST -ContentType 'application/json' -Body '{
    "issue": {
        "project_id": 316,
        "subject": "testProject",
        "priority_id": 4,
        "description": "testTask",
        "assigned_to_id": 1891,
        "custom_fields": [{
                "value": "******",
                "name": "physicalName",
                "id": 5
            },
            {
                "value": "****",
                "name": "***",
                "id": 6
            },
            {
                "value": "****",
                "name": "*****",
                "id": 10
            },
            {
                "value": "****",
                "name": "*****",
                "id": 11
            },
            {
                "value": "0",
                "name": "*******",
                "id": 16
            }
        ]
    }
}'


问:
Why can't Eureka access the app that has successfully registered in spring microservice
This problem occurred in a specific environment: Eureka successfully registered the app (I call it A). In the vm where Eureka is located, the status of A can be accessed (the status is up). However, accessing A in spring microservice shows that target application is not online.

**Sincerely ask for your help
**

Known conditions are as follows：

1.This set of microservices works normally in other environments.

2.Visit ~/eureka/apps to see Service A successfully.

3.Visit A's ~/health on the machine where Eureka is located, and the result is UP.

4.However, the result of calling org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient#choose(java.lang.String) is null.Therefore, the error "target application is not online." will be reported (We set it ourselves).

 instance = loadBalancer.choose(applicationName);

5.If we restart eureka, the microservice can temporarily access A, but the above error will occur soon.

**Dependent version is

spring-cloud-netflix-eureka-client-2.2.8.RELEASE.jar**


问:
Facebook - Page Public Content Access Rejected
I have submitted a request for approval to have access on Pages Public Content on Facebook, I have uploaded a video of my app to show why I need this access, but I got the attached reply.
I really did not understand why it was rejected and I did not understand what should I do next.

Appreciate your help


问:
validation is not run when adding filter in wordpress for contact form 7
I have added the following code in functions.php (located in my child theme). But the validation is never run, is there something wrong with my code?</p>
```<code>    <?php

// validate personnummer
add_filter('wpcf7_validate_text*', 'validate_custom_field', 10, 2);
add_filter('wpcf7_validate_text', 'validate_custom_field', 10, 2);

function validate_custom_field($result, $tag) {
    $name = $tag['name'];
    $value = $_POST[$name];
    if ($name == 'input-personnummer' && !preg_match('/^\d{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])-\d{4}$/', $value)) {
        $result->invalidate($tag, "The personnummer field is not in the correct format.");
    }
    return $result;
}
</code>```

Body:
I have added the following code in functions.php (located in my child theme). But the validation is never run, is there something wrong with my code?

    <?php

// validate personnummer
add_filter('wpcf7_validate_text*', 'validate_custom_field', 10, 2);
add_filter('wpcf7_validate_text', 'validate_custom_field', 10, 2);

function validate_custom_field($result, $tag) {
    $name = $tag['name'];
    $value = $_POST[$name];
    if ($name == 'input-personnummer' && !preg_match('/^\d{4}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])-\d{4}$/', $value)) {
        $result->invalidate($tag, "The personnummer field is not in the correct format.");
    }
    return $result;
}


问:
docker-compose equivalent for ECS
I'm in the process of deploying my flask application that runs on gunicorn and nginx. I'm able to get the app to run locally by creating a service for the flask app and another for nginx, and I'm able to run them using docker-compose.yml file. Now I know how to deploy a single service that I run using Dockerfile to ECS; however, I'm not sure how I would do the same for multiple services, so in others words, I want to know what is the ECS equivalent to running multiple services simultaneous using docker-compose.

I've tried having two containers when defining my task definition, but for reasons I'm unable to figure out the Tasks "fails to start".
Following is my docker-compose.yml file, to give you a better idea:

```<code>version: '3'

services:
  flask_app:
    container_name: flask_app
    restart: always
    build: ./flask_app
    ports:
      - "8000:8000"
    command: gunicorn -w 3 -b 0.0.0.0:8000 wsgi:server

  nginx:
    container_name: nginx
    restart: always
    build: ./nginx
    ports:
      - "80:80"
    depends_on:
      - flask_app
</code>```

Title: docker-compose equivalent for ECS

Body:
I'm in the process of deploying my flask application that runs on gunicorn and nginx. I'm able to get the app to run locally by creating a service for the flask app and another for nginx, and I'm able to run them using docker-compose.yml file. Now I know how to deploy a single service that I run using Dockerfile to ECS; however, I'm not sure how I would do the same for multiple services, so in others words, I want to know what is the ECS equivalent to running multiple services simultaneous using docker-compose.

I've tried having two containers when defining my task definition, but for reasons I'm unable to figure out the Tasks "fails to start".
Following is my docker-compose.yml file, to give you a better idea:

version: '3'

services:
  flask_app:
    container_name: flask_app
    restart: always
    build: ./flask_app
    ports:
      - "8000:8000"
    command: gunicorn -w 3 -b 0.0.0.0:8000 wsgi:server

  nginx:
    container_name: nginx
    restart: always
    build: ./nginx
    ports:
      - "80:80"
    depends_on:
      - flask_app


问:
Need to execute existing storyboard from collectionViewCell
There is a controller ProductCardController and a collection view. It is necessary to display another storyboard when clicking on a cell. Tell me how can this be done? present is not working.

```<code>
class ItemsCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    ...
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //code here
    }

}

</code>```

present and protocol - not work

Body:
There is a controller ProductCardController and a collection view. It is necessary to display another storyboard when clicking on a cell. Tell me how can this be done? present is not working.

class ItemsCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

    ...
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //code here
    }

}

present and protocol - not work


问:
Whatsapp web js multiple sessions
I'm creating a bot using whatsapp-web.js and Express.

Here is my code:

```<code>app.post('/newWhatsappClient', async function (req, res){

 const client = new Client({
    authStrategy: new LocalAuth({clientId:req.query.name}),

  });
    client.initialize();
 await client.on('qr',qr=>{
  res.json(qr)
});

client.on('ready', () => {
console.log(client.authStrategy)
   console.log(req.query.name+'Client is ready!');

});
client.on('authenticated',(session) => {
  console.log(session) //prints undefined
});
});
</code>```

Now the question is how can I get all active sessions?
Thanks in advance.

Title: Whatsapp web js multiple sessions

Body:
I'm creating a bot using whatsapp-web.js and Express.

Here is my code:

app.post('/newWhatsappClient', async function (req, res){

 const client = new Client({
    authStrategy: new LocalAuth({clientId:req.query.name}),

  });
    client.initialize();
 await client.on('qr',qr=>{
  res.json(qr)
});

client.on('ready', () => {
console.log(client.authStrategy)
   console.log(req.query.name+'Client is ready!');

});
client.on('authenticated',(session) => {
  console.log(session) //prints undefined
});
});

Now the question is how can I get all active sessions?
Thanks in advance.


问:
jenkins setup plugins installation failed
I am trying to setup jenkins on ec2 instance,
but when I was installing default plugins on homepage,
it failed over and over again without any prompts.
Thank you

I had tried to reboot my instance and setup a new instance, but not worked.


问:
When using Xcode 14 with Firebase the Syntax Highlighting is not working. Some Syntax Highlighting works but most Firebase related code is not white
I have been looking for a while but haven't found a solution yet. Xcode 14.2 Syntax Highlighting is not working correctly. Is anyone else experiencing this issue? Does any know how to fix this issue?

Here is an example image below. Firebase.Config() is white. All tutorials I have watched the syntax highlight works thought out. This is just one example, but for the most part, very few Firebase SDK related code has any Syntax Highlighting.

(I tried finding answers to this issue, but so far haven't found anything recent which discusses this issue.)


问:
Firestore security rules accessing arrayUnion data
I am trying to develop a chat app, for now it's purely a playground for future use.
For that app, I want to send an arrayUnion with an object inside it, that contains the message details.
On my DB, I have a document with an array of messages.
I want to impose security rules on said object, so that it'll check that it has only the items and types that I define.
Without any rules, it works as intended, but I just can't access the items in the received object in order to check them.

Here's what I'm sending on my frontend:

```<code>const message = {
      timeStamp: Timestamp.now(),
      text: currentText,
      sender: userData.uid,
    };
 await updateDoc(doc(db, 'chats', chatId), {
          messages: arrayUnion(message),
        });
</code>```

And this is the rules function that I'm trying to impose:

```<code>    function checkChatMessage(message, requestUid){
    return message.keys().hasAll(['timeStamp', 'text', 'sender']) &&
    message.timeStamp is timestamp &&
    message.text.size()>0 &&
    message.text.size()<256 &&
    message.text is string &&
    message.sender is string &&
    message.sender == reqUid;
    }
</code>```

I have tried passing that function request.arrayUnion[0], request.resource.data.message, request.resource.data.map and some more variations, but none seems to work.

Body:
I am trying to develop a chat app, for now it's purely a playground for future use.
For that app, I want to send an arrayUnion with an object inside it, that contains the message details.
On my DB, I have a document with an array of messages.
I want to impose security rules on said object, so that it'll check that it has only the items and types that I define.
Without any rules, it works as intended, but I just can't access the items in the received object in order to check them.

Here's what I'm sending on my frontend:

const message = {
      timeStamp: Timestamp.now(),
      text: currentText,
      sender: userData.uid,
    };
 await updateDoc(doc(db, 'chats', chatId), {
          messages: arrayUnion(message),
        });

And this is the rules function that I'm trying to impose:

    function checkChatMessage(message, requestUid){
    return message.keys().hasAll(['timeStamp', 'text', 'sender']) &&
    message.timeStamp is timestamp &&
    message.text.size()>0 &&
    message.text.size()<256 &&
    message.text is string &&
    message.sender is string &&
    message.sender == reqUid;
    }

I have tried passing that function request.arrayUnion[0], request.resource.data.message, request.resource.data.map and some more variations, but none seems to work.


问:
Azure APIM policy with dynamic claims in token validation
I am using APIM to expose multiple endpoints from a range of different Azure Functions as operations in the same API. Different operations in this API might have different audiences (aud) in the token based on which function is behind that particular operation.

What might differ though, is that the authorized party (azp) is not always the same. According to the OIDC documentation, this should then also be verified. In some cases, requests originate from a single page application where the token is issued on behalf of a user that signed in. In other cases, the request originates from someone integrating towards my APIs using a principal instead and a client_credentials grant type.

What I want to achieve is to have as simple a policy as possible, and still allow a range of different azp claims for a single aud claim. This is how I'm currently doing this:

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.microsoftonline.com/{{tenantId}}/v2.0/.well-known/openid-configuration" />
    <required-claims>
        <claim name="aud" match="all">
            <value>{{target-api-clientId}}</value>
        </claim>
        <claim name="azp" match="any">
            <value>{{spa-clientId}}</value>
            <value>{{integrator-clientId1}}</value>
            <value>{{integrator-clientId2}}</value>
        </claim>
    </required-claims>
</validate-jwt>
```
<p>However, this doesn't scale very well and forces me to keep duplicate policies between environments and for each new allowed authorized party I must add a new row in the <code>azp</code> claim section as a well as new named values.</p>
<p>The documentation specifies that there is a <code>separator</code> attribute for the claim element, but as far as I can tell, this only splits the claim in the incoming token on that separator character and I always only have a single <code>aud</code> and <code>azp</code> claim in the incoming tokens.</p>
<p>Is there any way for me to achieve a single API baseline policy, where each operation could set its expected required parameters? Something along these lines:</p>
<p><strong>API base policy</strong></p>
<pre class="lang-xml prettyprint-override"><code><validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.microsoftonline.com/{{tenantId}}/v2.0/.well-known/openid-configuration" />
    <required-claims>
        <claim name="aud" match="all">
            <value>@((string)context.Variables["aud"])</value>
        </claim>
        <claim name="azp" match="any">
            @((List<string>)context.Variables["azp"])
        </claim>
    </required-claims>
</validate-jwt>
</code>```

Operation specific policy

<set-variable name="aud" value="{{allowed-aud-for-this-operation}}" />
<set-variable name="azp" value="{{list-of-allowed-authorized-parties-for-this-operation}}" />
<base />
```

To further clarify what the infrastructure looks like and where requests might originate from, this might shine some light:

Is there any way to achieve dynamic token evaluation like this? If not, what are my other options? Am I approaching this problem the right way, or should I rethink?

Body:
I am using APIM to expose multiple endpoints from a range of different Azure Functions as operations in the same API. Different operations in this API might have different audiences (aud) in the token based on which function is behind that particular operation.

What might differ though, is that the authorized party (azp) is not always the same. According to the OIDC documentation, this should then also be verified. In some cases, requests originate from a single page application where the token is issued on behalf of a user that signed in. In other cases, the request originates from someone integrating towards my APIs using a principal instead and a client_credentials grant type.

What I want to achieve is to have as simple a policy as possible, and still allow a range of different azp claims for a single aud claim. This is how I'm currently doing this:

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.microsoftonline.com/{{tenantId}}/v2.0/.well-known/openid-configuration" />
    <required-claims>
        <claim name="aud" match="all">
            <value>{{target-api-clientId}}</value>
        </claim>
        <claim name="azp" match="any">
            <value>{{spa-clientId}}</value>
            <value>{{integrator-clientId1}}</value>
            <value>{{integrator-clientId2}}</value>
        </claim>
    </required-claims>
</validate-jwt>

However, this doesn't scale very well and forces me to keep duplicate policies between environments and for each new allowed authorized party I must add a new row in the azp claim section as a well as new named values.

The documentation specifies that there is a separator attribute for the claim element, but as far as I can tell, this only splits the claim in the incoming token on that separator character and I always only have a single aud and azp claim in the incoming tokens.

Is there any way for me to achieve a single API baseline policy, where each operation could set its expected required parameters? Something along these lines:

API base policy

<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
    <openid-config url="https://login.microsoftonline.com/{{tenantId}}/v2.0/.well-known/openid-configuration" />
    <required-claims>
        <claim name="aud" match="all">
            <value>@((string)context.Variables["aud"])</value>
        </claim>
        <claim name="azp" match="any">
            @((List<string>)context.Variables["azp"])
        </claim>
    </required-claims>
</validate-jwt>

Operation specific policy

<set-variable name="aud" value="{{allowed-aud-for-this-operation}}" />
<set-variable name="azp" value="{{list-of-allowed-authorized-parties-for-this-operation}}" />
<base />

To further clarify what the infrastructure looks like and where requests might originate from, this might shine some light:

Is there any way to achieve dynamic token evaluation like this? If not, what are my other options? Am I approaching this problem the right way, or should I rethink?


问:
Cloudflare HTTP Logpush endpoint
I am looking for the most efficient method of hosting a HTTP endpoint to receive Cloudflare log files.

Cloudflare Logpush now supports the ability to send logs to configurable HTTP endpoints.

Note that when using Logpush to HTTP endpoints, Cloudflare customers are expected to perform their own authentication of the pushed logs. For example, customers may specify a secret token in the URL or an HTTP header of the Logpush destination.

Enable HTTP destination

I was looking at nginx to host the end point, but the upload module is no longer supported and it looks like apache does not have such function. I have found various projects that achieve this, however most of them seem to have way more functionality than what I require. I did post the question on the Cloudflare community, but have yet to have a bite.

If you guys can suggest some simple solution to host the http endpoint, I would be very grateful.

Title: Cloudflare HTTP Logpush endpoint


问:
In ReactJS, Displaying Snackbar(mui) with mobx observer did not work
I'm new to reactjs, and I've just started using state management tool Mobx.

I'd like to show Snackbar using mobx store.

The logic is simple.

When the error was occured, it was added to mobx's observable alert list.

And, the observer component catched that change, and rebuild component.

Here is my code.

// BaseAlert.ts
interface BaseAlert {
  message: string;
  display: boolean;
}

export interface Success extends BaseAlert {
  kind: 'success';
}

export interface Info extends BaseAlert {
  kind: 'info';
}

export interface Warn extends BaseAlert {
  kind: 'warn';
}

export interface Error extends BaseAlert {
  kind: 'error';
}

export type Alert = Success | Info | Warn | Error;

export const alert = (message: string, kind: Alert['kind']): Alert =>
  ({
    message,
    kind,
    display: true,
  } as Alert);
```
<pre class="lang-js prettyprint-override"><code>// Alerts.ts
import {just, Maybe, nothing} from 'maybeasy';
import {action, computed, observable} from 'mobx';
import {Alert} from "../base/BaseAlert";

class AlertsStore {
  @observable
  alerts: Alert[] = [];

  @computed
  get current(): Maybe<Alert> {
    return this.alerts.length === 0 ? nothing() : just(this.alerts[0]);
  }

  @action
  hide = () => {
    if (this.alerts.length > 0) {
      this.alerts[0].display = false;
    }
  };

  @action
  process = () => {
    this.alerts = this.alerts.slice(1);
  };

  @action
  push = (alert: Alert) => {
    this.hide();
    this.alerts.push({...alert, display: true});
  };
}

const alertsStore = new AlertsStore();
export default alertsStore;
</code>```

// ObservableAlert.tsx
import React from 'react';
import alertsStore from "../../hook/AlertsStore";
import {Snackbar} from "@mui/material";
import {observer} from "mobx-react";

@observer
export class Alerts extends React.Component {
  render() {
    return alertsStore.current.cata({
      Just: alert => (
        <Snackbar
          anchorOrigin={{vertical: 'top', horizontal: 'right'}}
          open={alert.display}
          onClose={alertsStore.hide}
          onDragExit={alertsStore.process}
          message={alert.message}
          autoHideDuration={1000}
        />
      ),
      Nothing: () => <></>,
    });
  }
}
```
<p>And, I added the <strong>ObservableAlert</strong> component just below the App Component.</p>
<pre class="lang-js prettyprint-override"><code>// App.tsx
function App() {
  return (
    <div className="App">
      <Router>
        <Routes>
          <Route path="/*" element={<HomeView/>}>home</Route>
          <Route path="/login" element={<LoginView/>}>login</Route>
        </Routes>
      </Router>
      <Alerts/>
    </div>
  );
}
</code>```

When I input username and password in textfield and click the login button, this function is called to push alert into the alertsStore.

  async login(username: string, password: string) {
    await this.baseEventHandle({
      action: async () => {
        await this.loginUserUseCase.invoke(username, password);
      },
      onError: (error) => {
        alertsStore.push(alert(error, 'error'));
      }
    })
  }
```

I checked above function's onError inner function was worked and new Alerts Instance was added to AlertsStore's Alert list.

But, the snackbar did not show at the browser.

Could you tell me what is the problem of my code??

Body:
I'm new to reactjs, and I've just started using state management tool Mobx.

I'd like to show Snackbar using mobx store.

The logic is simple.

When the error was occured, it was added to mobx's observable alert list.

And, the observer component catched that change, and rebuild component.

Here is my code.

// BaseAlert.ts
interface BaseAlert {
  message: string;
  display: boolean;
}

export interface Success extends BaseAlert {
  kind: 'success';
}

export interface Info extends BaseAlert {
  kind: 'info';
}

export interface Warn extends BaseAlert {
  kind: 'warn';
}

export interface Error extends BaseAlert {
  kind: 'error';
}

export type Alert = Success | Info | Warn | Error;

export const alert = (message: string, kind: Alert['kind']): Alert =>
  ({
    message,
    kind,
    display: true,
  } as Alert);

// Alerts.ts
import {just, Maybe, nothing} from 'maybeasy';
import {action, computed, observable} from 'mobx';
import {Alert} from "../base/BaseAlert";

class AlertsStore {
  @observable
  alerts: Alert[] = [];

  @computed
  get current(): Maybe<Alert> {
    return this.alerts.length === 0 ? nothing() : just(this.alerts[0]);
  }

  @action
  hide = () => {
    if (this.alerts.length > 0) {
      this.alerts[0].display = false;
    }
  };

  @action
  process = () => {
    this.alerts = this.alerts.slice(1);
  };

  @action
  push = (alert: Alert) => {
    this.hide();
    this.alerts.push({...alert, display: true});
  };
}

const alertsStore = new AlertsStore();
export default alertsStore;

// ObservableAlert.tsx
import React from 'react';
import alertsStore from "../../hook/AlertsStore";
import {Snackbar} from "@mui/material";
import {observer} from "mobx-react";

@observer
export class Alerts extends React.Component {
  render() {
    return alertsStore.current.cata({
      Just: alert => (
        <Snackbar
          anchorOrigin={{vertical: 'top', horizontal: 'right'}}
          open={alert.display}
          onClose={alertsStore.hide}
          onDragExit={alertsStore.process}
          message={alert.message}
          autoHideDuration={1000}
        />
      ),
      Nothing: () => <></>,
    });
  }
}

And, I added the ObservableAlert component just below the App Component.

// App.tsx
function App() {
  return (

      <Router>
        <Routes>
          <Route path="/*" element={<HomeView/>}>home</Route>
          <Route path="/login" element={<LoginView/>}>login</Route>
        </Routes>
      </Router>
      <Alerts/>

  );
}

When I input username and password in textfield and click the login button, this function is called to push alert into the alertsStore.

  async login(username: string, password: string) {
    await this.baseEventHandle({
      action: async () => {
        await this.loginUserUseCase.invoke(username, password);
      },
      onError: (error) => {
        alertsStore.push(alert(error, 'error'));
      }
    })
  }

I checked above function's onError inner function was worked and new Alerts Instance was added to AlertsStore's Alert list.

But, the snackbar did not show at the browser.

Could you tell me what is the problem of my code??


问:
How do I parse data from a String without copying its underlying data?
I'm trying to parse a string and keep it as well as slices to it, but I couldn't convince rust...

```<code>struct CategoryAndWord<'a> { word: &'a str, category: &'a str }

struct WordsBank<'a> {
    raw_data: String,
    words: Vec<CategoryAndWord<'a>>
}

impl WordsBank<'_> {
    pub fn from(data: String) -> Self {
        let raw_data= data.to_lowercase();
        WordsBank{raw_data, words: data.lines().map(WordsBank::line_to_word).collect()}
    }

    fn line_to_word(l: &str) -> CategoryAndWord {
        let mut parts = l.split(" ");
        CategoryAndWord{
            word: parts.next().expect("Line was empty").trim(),
            category: parts.next().expect("Line did not contain ',' followed by category word").trim()
        }
    }
</code>```

To my understanding, this code fails because I move raw_data into the newly created struct, and then lines tries to work on it after the move.

But the underlying String data is still at the same place after the move, so the slices should still be valid.

How do I avoid cloning the underlying data while parsing this string?

Body:
I'm trying to parse a string and keep it as well as slices to it, but I couldn't convince rust...

struct CategoryAndWord<'a> { word: &'a str, category: &'a str }

struct WordsBank<'a> {
    raw_data: String,
    words: Vec<CategoryAndWord<'a>>
}

impl WordsBank<'_> {
    pub fn from(data: String) -> Self {
        let raw_data= data.to_lowercase();
        WordsBank{raw_data, words: data.lines().map(WordsBank::line_to_word).collect()}
    }

    fn line_to_word(l: &str) -> CategoryAndWord {
        let mut parts = l.split(" ");
        CategoryAndWord{
            word: parts.next().expect("Line was empty").trim(),
            category: parts.next().expect("Line did not contain ',' followed by category word").trim()
        }
    }

To my understanding, this code fails because I move raw_data into the newly created struct, and then lines tries to work on it after the move.

But the underlying String data is still at the same place after the move, so the slices should still be valid.

How do I avoid cloning the underlying data while parsing this string?


问:
Collision Detection algorithm for Selection advice
I don't know if this is proper platform for the question.

I'm trying to develop a collision detection algorithm.

In my system the primary host (a vehicle) is either stationary or is in motion (in xy, yz and xz plane).

Incoming projectile can either follow a strait path or non-linear trajectory (guided projectile).

Can anyone advice me on proper Collision Detection algorithm!

Initially I thought in terms of equation of a straight line in two-point and further extrapolating (using linear regression) to check if the projectile is impacting the host. This approach might work for unguided or high speed projectile but however on guided projectile this approach will not work due non-linearity and stochastic nature of real-world.

I wish to know if the projectile follows a ballistic trajectory or curved trajectory how can I detect collision. Is their any recommended algorithm.

I have created a Minimum bounding box (i.e. vehicle boundary - a cube) around my vehicle, I am having difficulty selecting/deciding on algorithm on how to track a projectile (say 400 meters away), if the projectile is converging/impacting on my vehicle boundary.


问:
java.lang.UnsatisfiedLinkError: No implementation found for java .io.FileDescriptor android_serialport_api.SerialPort.open(string ,int ,int)
while I am working  on integrating Java CCNET SDK to my Android application ,I can not run ccnet commands from my app to the cashcode .

programe to execute command

```<code>        IConnection comPort = new sPort();
        comPort.setPath(_serialPort.path);//"/dev/ttyS2"
        comPort.setBaudRate(_serialPort.baudRate);//9600
        comPort.setDelay(_serialPort.delay);//1000;
        _ccnet = new CCNET(_device, comPort);//_device=DEVICE.Bill_Validator;
try{
       Answer answer = _ccnet.RunCommand(command);
}catch{Exception e}{
Log.i(e);
}
</code>```

the above code generates the following Error

java.lang.UnsatisfiedLinkError: No implementation found for java .io.FileDescriptor android_serialport_api.SerialPort.open(string ,int ,int) (tried Java_android_1serialport_1api_SerialPort_open and Java_android_1serialport_1api_SerialPort_open_Ljava_lang_String_2ll)

**My folder structure **

Body:
while I am working  on integrating Java CCNET SDK to my Android application ,I can not run ccnet commands from my app to the cashcode .

programe to execute command

        IConnection comPort = new sPort();
        comPort.setPath(_serialPort.path);//"/dev/ttyS2"
        comPort.setBaudRate(_serialPort.baudRate);//9600
        comPort.setDelay(_serialPort.delay);//1000;
        _ccnet = new CCNET(_device, comPort);//_device=DEVICE.Bill_Validator;
try{
       Answer answer = _ccnet.RunCommand(command);
}catch{Exception e}{
Log.i(e);
}

the above code generates the following Error

java.lang.UnsatisfiedLinkError: No implementation found for java .io.FileDescriptor android_serialport_api.SerialPort.open(string ,int ,int) (tried Java_android_1serialport_1api_SerialPort_open and Java_android_1serialport_1api_SerialPort_open_Ljava_lang_String_2ll)

**My folder structure **


问:
Show welcome banner vsftpd with client lftp
I'm configuring vsftpd with vsftpd.conf and I activate the line 106 that say "ftpd_banner=message".
later I try to connect to this server with a lftp client with anonymous user and don't show the welcome banner.

lftp <IP_server> -u anonymous

If I connect with other client how ftp, I watch a banner, but not with lftp.
It is a error of lftp or I need to configure better this line ? thanks

I'm trying to show a welcome banner with lftp client