问:
certbot unable to authenticate some domain in ec2 mern stack
I am developing a MERN stack application

I deployed the mern stack to ec2 instance

It is working fine with http but I want to add ssl using certbot

I am getting the error below

```<code>Certbot failed to authenticate some domains (authenticator: nginx). The Certificate Authority reported these problems:
  Domain: xxxx.name.ng
  Type:   unauthorized
  Detail: x.x.x.x: Invalid response from xxx/.well-known/acme-challenge/Qyrdk8rF0jwZasZ0sjj575yKwgOvdmphCDcla5b40ZE: "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"/><link rel=\"icon\" href=\"/favicon.ico\"/><meta name=\"viewport\" content="
</code>```

I created A record using the ip address of the ec2 instance on my domain name provider platform

```<code>server {
        listen 80;
        listen [::]:80;

        root /var/www/html;

        server_name www.xxxxxx.ng xxxxxxx.name.ng;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                proxy_pass http://localhost:7500;    # or which other port your app runs on
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
    }
}
</code>```

Body:
I am developing a MERN stack application

I deployed the mern stack to ec2 instance

It is working fine with http but I want to add ssl using certbot

I am getting the error below

Certbot failed to authenticate some domains (authenticator: nginx). The Certificate Authority reported these problems:
  Domain: xxxx.name.ng
  Type:   unauthorized
  Detail: x.x.x.x: Invalid response from xxx/.well-known/acme-challenge/Qyrdk8rF0jwZasZ0sjj575yKwgOvdmphCDcla5b40ZE: "<!doctype html><meta charset=\"utf-8\"/><link rel=\"icon\" href=\"/favicon.ico\"/><meta name=\"viewport\" content="

I created A record using the ip address of the ec2 instance on my domain name provider platform

server {
        listen 80;
        listen [::]:80;

        root /var/www/html;

        server_name www.xxxxxx.ng xxxxxxx.name.ng;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                proxy_pass http://localhost:7500;    # or which other port your app runs on
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection 'upgrade';
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
    }
}


来源: stackexchange

问:
why my flutter_background_fetch not work when app is terminate?
Hi I want my android app work in background even if the program completely close(terminate). I use the flutter_background_fetch for it. the notification show every 15 min correctly in app is open or go to background, But when I terminate app the background_fetch not work and not show the notification or do anything anymore.
here this my main file config:

```<code>void main() async {

  WidgetsFlutterBinding.ensureInitialized();
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
  initializeNotificationService();
  runApp(const MyApp());
}

@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
  String taskId = task.taskId;
  bool isTimeout = task.timeout;
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing and immediately .finish(taskId)
    BackgroundFetch.finish(taskId);
    return;
  }
  // Do your work here...
  BackgroundFetch.finish(taskId);
}
</code>```

and this is part of my controller body for background_fetch:

```<code>class Controller extends GetxController {

  @override
  void onInit() {
    // TODO: implement onInit

    super.onInit();
    startListeningNotificationEvents();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    var status = await BackgroundFetch.configure(
        BackgroundFetchConfig(
          minimumFetchInterval: 15,
          forceAlarmManager: false,
          stopOnTerminate: false,
          startOnBoot: true,
          enableHeadless: true,
          requiresBatteryNotLow: false,
          requiresCharging: false,
          requiresStorageNotLow: false,
          requiresDeviceIdle: false,
          requiredNetworkType: NetworkType.NONE,

        ),
        _onBackgroundFetch,
        _onBackgroundFetchTimeout);
    BackgroundFetch.scheduleTask(TaskConfig(
        taskId: "test",
        delay: 1000,
        periodic: false,
        stopOnTerminate: false,
        enableHeadless: true));
    BackgroundFetch.start();
  }

  void _onBackgroundFetchTimeout(String taskId) {
    //BackgroundFetch.finish(taskId);

    }

      void _onBackgroundFetch(String taskId) async {
        if (taskId == "test") {

  random();
      createNotification();
    }
  }

}
</code>```

in the document said if we want app work even after terminate, we should set the "stopOnTerminate" equals false. but still not working. how can fix this? please help.

ContentLicense: CC BY-SA 4.0

Body:
Hi I want my android app work in background even if the program completely close(terminate). I use the flutter_background_fetch for it. the notification show every 15 min correctly in app is open or go to background, But when I terminate app the background_fetch not work and not show the notification or do anything anymore.
here this my main file config:

void main() async {

  WidgetsFlutterBinding.ensureInitialized();
  BackgroundFetch.registerHeadlessTask(backgroundFetchHeadlessTask);
  initializeNotificationService();
  runApp(const MyApp());
}

@pragma('vm:entry-point')
void backgroundFetchHeadlessTask(HeadlessTask task) async {
  String taskId = task.taskId;
  bool isTimeout = task.timeout;
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing and immediately .finish(taskId)
    BackgroundFetch.finish(taskId);
    return;
  }
  // Do your work here...
  BackgroundFetch.finish(taskId);
}

and this is part of my controller body for background_fetch:

class Controller extends GetxController {

  @override
  void onInit() {
    // TODO: implement onInit

    super.onInit();
    startListeningNotificationEvents();
    initPlatformState();
  }

  Future<void> initPlatformState() async {
    var status = await BackgroundFetch.configure(
        BackgroundFetchConfig(
          minimumFetchInterval: 15,
          forceAlarmManager: false,
          stopOnTerminate: false,
          startOnBoot: true,
          enableHeadless: true,
          requiresBatteryNotLow: false,
          requiresCharging: false,
          requiresStorageNotLow: false,
          requiresDeviceIdle: false,
          requiredNetworkType: NetworkType.NONE,

        ),
        _onBackgroundFetch,
        _onBackgroundFetchTimeout);
    BackgroundFetch.scheduleTask(TaskConfig(
        taskId: "test",
        delay: 1000,
        periodic: false,
        stopOnTerminate: false,
        enableHeadless: true));
    BackgroundFetch.start();
  }

  void _onBackgroundFetchTimeout(String taskId) {
    //BackgroundFetch.finish(taskId);

    }

      void _onBackgroundFetch(String taskId) async {
        if (taskId == "test") {

  random();
      createNotification();
    }
  }

}

in the document said if we want app work even after terminate, we should set the "stopOnTerminate" equals false. but still not working. how can fix this? please help.


问:
Is there any way to retrieve your own tweet organic_metrics and at the same time the referenced_tweets without theirs Twiter API V2
I am trying to request my own timeline tweets organic_metrics by adding them on the tweet.fields. By doing so, I retrieve them as expected.

The problem is that if I add the expansions referenced_tweets.id,referenced_tweets.id.author_id  to the query I get a Field Authorization Error because (I presume) its attempting to retrieve the organic_metrics from the referenced tweets.

Here is an error example:

```<code>  {
    "resource_type": "tweet",
    "field": "organic_metrics.like_count",
    "parameter": "referenced_tweets.id",
    "resource_id": "1602665220689764353",
    "title": "Field Authorization Error",
    "section": "includes",
    "detail": "Sorry, you are not authorized to access 'organic_metrics.like_count' on the Tweet with referenced_tweets.id : [1602665220689764353].",
    "value": "1602665220689764353",
    "type": "https://api.twitter.com/2/problems/not-authorized-for-field"
  },
</code>```

With this error the referenced_tweets do not come in the response and therefore I am unable to retrieve my own tweets organic_metrics and the referenced_tweets in the same response.
I am forced to do x2 queries

I understand I can not access the organic_metrics on the referenced_tweets and I don't want to, I just need my own organic_metrics.

Is there any way to tell the API that I just want the organic_metrics of my tweets while at the same time retrieve the referenced_tweets without organic_metrics?

Body:
I am trying to request my own timeline tweets organic_metrics by adding them on the tweet.fields. By doing so, I retrieve them as expected.

The problem is that if I add the expansions referenced_tweets.id,referenced_tweets.id.author_id  to the query I get a Field Authorization Error because (I presume) its attempting to retrieve the organic_metrics from the referenced tweets.

Here is an error example:

  {
    "resource_type": "tweet",
    "field": "organic_metrics.like_count",
    "parameter": "referenced_tweets.id",
    "resource_id": "1602665220689764353",
    "title": "Field Authorization Error",
    "section": "includes",
    "detail": "Sorry, you are not authorized to access 'organic_metrics.like_count' on the Tweet with referenced_tweets.id : [1602665220689764353].",
    "value": "1602665220689764353",
    "type": "https://api.twitter.com/2/problems/not-authorized-for-field"
  },

With this error the referenced_tweets do not come in the response and therefore I am unable to retrieve my own tweets organic_metrics and the referenced_tweets in the same response.
I am forced to do x2 queries

I understand I can not access the organic_metrics on the referenced_tweets and I don't want to, I just need my own organic_metrics.

Is there any way to tell the API that I just want the organic_metrics of my tweets while at the same time retrieve the referenced_tweets without organic_metrics?


问:
Error while writing unit tests for nested function in python
I have a function which reads data from db, modifies it and writes it back to another db. I am trying to write unit tests for this

```<code>import file1
import file2
def update_func(query):
    max_date = file1.get_cutover_date()
    data_dataframe = file2.get_dataframe_from_db(query)
    transformed_dataframe = modify_df(data_dataframe)
    df1 = transformed_dataframe.filter(transformed_dataframe['date']>max_date)
    write_to_db(df1)
</code>```

I tried to patch the function calls.

```<code>@patch('file2.get_dataframe_from_db')
@patch('file1.get_cutover_date')
test_update_func(patched_get_cutover, patched_get_df):
    patched_get_cutover.return_value = '2015-01-01 00:00:00'
    response = [Row(id=1,date='2016-10-12 00:00:00')]
    response_df = spark.createDataFrame(response)
    patched_get_df.return_value = response_df
    update_func('test_query')
    patched_get_cutover.assert_called
    patched_get_df.assert_called
</code>```

But I am getting TypeError: '>' not supported between instances of MagicMock and MagicMock

Body:
I have a function which reads data from db, modifies it and writes it back to another db. I am trying to write unit tests for this

import file1
import file2
def update_func(query):
    max_date = file1.get_cutover_date()
    data_dataframe = file2.get_dataframe_from_db(query)
    transformed_dataframe = modify_df(data_dataframe)
    df1 = transformed_dataframe.filter(transformed_dataframe['date']>max_date)
    write_to_db(df1)

I tried to patch the function calls.

@patch('file2.get_dataframe_from_db')
@patch('file1.get_cutover_date')
test_update_func(patched_get_cutover, patched_get_df):
    patched_get_cutover.return_value = '2015-01-01 00:00:00'
    response = [Row(id=1,date='2016-10-12 00:00:00')]
    response_df = spark.createDataFrame(response)
    patched_get_df.return_value = response_df
    update_func('test_query')
    patched_get_cutover.assert_called
    patched_get_df.assert_called

But I am getting TypeError: '>' not supported between instances of MagicMock and MagicMock


问:
How to get order_meta node in woocommerce api?
when i am getting the api payload,

when i am trying to access wocommerce api, i am getting all the orders details under product_meta node.
https://example.com/wc-api/v3/orders/?fields=order_meta,product_meta&filter[meta]=true&consumer_secret=xxx&consumer_key=xxx

i got this results
see the output here in postman

But i want this all details comes under order_meta node like this:
"

```<code>order_meta":{
            "card_message":"Happy Birthday Lina!!! Love Dave and Louis x",
            "delivery_date":"01\/09\/2023",
            "order_notes":"Deliver to front desk"
         }
      },
</code>```

please help me out.

Body:
when i am getting the api payload,

when i am trying to access wocommerce api, i am getting all the orders details under product_meta node.
https://example.com/wc-api/v3/orders/?fields=order_meta,product_meta&filter[meta]=true&consumer_secret=xxx&consumer_key=xxx

i got this results
see the output here in postman

But i want this all details comes under order_meta node like this:
"

order_meta":{
            "card_message":"Happy Birthday Lina!!! Love Dave and Louis x",
            "delivery_date":"01\/09\/2023",
            "order_notes":"Deliver to front desk"
         }
      },

please help me out.


问:
Split list column in a dataframe into separate 1/0 entry columns
I had a column in a dataframe with list entries. I wanted to create separate 1/0 columns based on the values in the list.

Input DF:

```<code>| Contract|  list             |
|---------|-------------------|
|  1      | [16a1,16a2,17b1]  |
|  2      | []                |
|  3      | [16a1,7b1]        |
</code>```

Expected output:

```<code>| Contract|  list             | 16a1 | 16a2| 17b1| 7b1 |
|---------|-------------------|------|-----|-----|-----|
|  1      | [16a1,16a2,17b1]  |  1   |  1  |  1  |  0  |
|  2      | []                |  0   |  0  |  0  |  0  |
|  3      | [16a1,7b1]        |  1   |  0  |  0  |  1  |
</code>```

I don't have any idea as to how to proceed.

I tried using numpy where condition to search for specific key words and create column but not of much help

Body:
I had a column in a dataframe with list entries. I wanted to create separate 1/0 columns based on the values in the list.

Input DF:

| Contract|  list             |
|---------|-------------------|
|  1      | [16a1,16a2,17b1]  |
|  2      | []                |
|  3      | [16a1,7b1]        |

Expected output:

| Contract|  list             | 16a1 | 16a2| 17b1| 7b1 |
|---------|-------------------|------|-----|-----|-----|
|  1      | [16a1,16a2,17b1]  |  1   |  1  |  1  |  0  |
|  2      | []                |  0   |  0  |  0  |  0  |
|  3      | [16a1,7b1]        |  1   |  0  |  0  |  1  |

I don't have any idea as to how to proceed.

I tried using numpy where condition to search for specific key words and create column but not of much help


问:
What is the difference between Android AOSP software stack architecture and Android OS four-layer architecture?
What is the difference between Android AOSP software stack architecture and Android OS four-layer (platform architecture) architecture? I'm trying to get a better understanding of the differences between the following two architectures. Please explain the purpose/usage of the AOSP architecture compared with the platform architecture.

Thank you

Please explain the purpose/usage of the AOSP architecture compared with the platform architecture.


问:
Images and Buttons not filling grid cells WPF XAML
So I have 2 similar problems with the below image. The image is of a UserControl that has been added to a viewbox inside another UserControl:

Image

The button in the top-left does not fill the whole of the grid cell, but the image within it fills the whole button .I have been trying out different methods of binding button images. This is why this is not the same for the other buttons in the grid. However I can't see how they should differ

The black images on the centre top, left, right, and bottom buttons don't fill their buttons. However, when editing the code, the designer shows them filling those buttons. The code for these is identical to the ContentControl above, but has an image path linking to a completely black image instead.

Was wondering if these problems might be related or have a similar fix? I've tried using extra viewboxes and stretch to fill/ alignment parameters but they seem to make no difference.

EDIT:

Implementing Location.xaml in parent UserControl:

```<code><Viewbox Grid.Row="1" Grid.Column="1" Grid.RowSpan="2" Margin="10 10 10 10">
            <ContentControl Content="{Binding CurrentLocationViewModel}">
                <ContentControl.Resources>
                    <DataTemplate DataType="{x:Type locationViewModel:SmallRoomViewModel}">
                        <locationView:SmallRoomView/>
                    </DataTemplate>

                    <DataTemplate DataType="{x:Type locationViewModel:LargeRoomViewModel}">
                        <locationView:LargeRoomView/>
                    </DataTemplate>
                </ContentControl.Resources>
            </ContentControl>
        </Viewbox>
</code>```

SmallRoomView.xaml (the UserControl in the image):

```<code> <Grid>
        <Grid.Resources>
            <Button x:Key="wallTile" x:Shared="false" PreviewMouseDown="OnMouseDown" Style="{StaticResource appWallTile}"/>
            <Button x:Key="floorTile" x:Shared="false" PreviewMouseDown="OnMouseDown" Style="{StaticResource appFloorTile}"/>
            <Button x:Key="doorTile" x:Shared="false"  PreviewMouseDown="OnMouseDown" Style="{StaticResource appDoorTile}"/>
        </Grid.Resources>

    <Button Grid.Row="0" Grid.Column="0" PreviewMouseDown="OnMouseDown">
        <Image Stretch="Fill" Source="{Binding tile0_0}"/>
    </Button>

    <ContentControl Grid.Row="0" Grid.Column="2" Content="{StaticResource doorTile}"/>
    <ContentControl Grid.Row="0" Grid.Column="3" Content="{StaticResource wallTile}"/>
    ...
</Grid>

</code>```

App.xaml:

```<code><Style x:Key="appDoorTile" TargetType="Button" x:Shared="false">
            <Setter Property="Content">
                <Setter.Value>
                    <Image Stretch="Fill" Source="./AllResources/images/tiles/doorTile.png"/>
                </Setter.Value>
            </Setter>
        </Style>
        <Style x:Key="appFloorTile" TargetType="Button" x:Shared="false">
            <Setter Property="Content">
                <Setter.Value>
                    <Image Stretch="Fill" Source="./AllResources/images/tiles/floors/floorTile.png"/>
                </Setter.Value>
            </Setter>
        </Style>

        <Style x:Key="appWallTile" TargetType="Button" x:Shared="false">
            <Setter Property="Content">
                <Setter.Value>
                    <Image Stretch="Fill" Source="./AllResources/images/tiles/walls/wallTile.png"/>
                </Setter.Value>
            </Setter>
        </Style>
</code>```

Body:
So I have 2 similar problems with the below image. The image is of a UserControl that has been added to a viewbox inside another UserControl:

Image

The button in the top-left does not fill the whole of the grid cell, but the image within it fills the whole button .I have been trying out different methods of binding button images. This is why this is not the same for the other buttons in the grid. However I can't see how they should differ

The black images on the centre top, left, right, and bottom buttons don't fill their buttons. However, when editing the code, the designer shows them filling those buttons. The code for these is identical to the ContentControl above, but has an image path linking to a completely black image instead.

Was wondering if these problems might be related or have a similar fix? I've tried using extra viewboxes and stretch to fill/ alignment parameters but they seem to make no difference.

EDIT:

Implementing Location.xaml in parent UserControl:

<Viewbox Grid.Row="1" Grid.Column="1" Grid.RowSpan="2" Margin="10 10 10 10">
            <ContentControl Content="{Binding CurrentLocationViewModel}">
                <ContentControl.Resources>
                    <DataTemplate DataType="{x:Type locationViewModel:SmallRoomViewModel}">
                        <locationView:SmallRoomView/>
                    </DataTemplate>

                    <DataTemplate DataType="{x:Type locationViewModel:LargeRoomViewModel}">
                        <locationView:LargeRoomView/>
                    </DataTemplate>
                </ContentControl.Resources>
            </ContentControl>
        </Viewbox>

SmallRoomView.xaml (the UserControl in the image):

 <Grid>
        <Grid.Resources>
            <Button x:Key="wallTile" x:Shared="false" PreviewMouseDown="OnMouseDown" Style="{StaticResource appWallTile}"/>
            <Button x:Key="floorTile" x:Shared="false" PreviewMouseDown="OnMouseDown" Style="{StaticResource appFloorTile}"/>
            <Button x:Key="doorTile" x:Shared="false"  PreviewMouseDown="OnMouseDown" Style="{StaticResource appDoorTile}"/>
        </Grid.Resources>

    <Button Grid.Row="0" Grid.Column="0" PreviewMouseDown="OnMouseDown">
        <Image Stretch="Fill" Source="{Binding tile0_0}"/>
    </Button>

    <ContentControl Grid.Row="0" Grid.Column="2" Content="{StaticResource doorTile}"/>
    <ContentControl Grid.Row="0" Grid.Column="3" Content="{StaticResource wallTile}"/>
    ...
</Grid>

App.xaml:


问:
Unexpected unity HorizontalLayout behavior when using spacings and/or paddings
I've build simple chat UI where instead of text input you have options for my game. And it works. Kind of. The problem is when adding elements instead of just shrinking already existing elements to keep spacing and padding HorizontalLayout additionaly expands itself.

With 1 Element

With 2 Element

Sidebar's width with 1 element

Sidebar's width with 2 elements

Chat UI Inspector

Main Section Inspector

Sidebar Inspector

Responses Box Inspector

i.stack.imgur.com/AQSLW.png  (Can't upload > 8 links)

As you can see width of sidebar decreased on the second screenshot.

The question: How do i keep HorizontalLayout's width without disabling paddings and spacing?

I have already tried: Messing around with other layout elements, but it seems that problem exists only when paddings and/or spacings are set.


问:
APIM endpoint is not working through latest elastic client library
I am using latest "Elastic.Clients.Elasticsearch" library in .NET console application to talk to my elastic latest version 8.X. However, in my scenario I will not be talking directly to elastic I have a middle layer APIM endpoint. This is working fine when I am using NEST package with EnableAPIVersioningHeader setting. But in case of new library it throws 404 "resource not found error". Please can you let me know what are the changes that needs to be done to get this working.

Note: I am removing NEST package dependency from code, as Elastic will not support it in the future.

Sample Code:

```<code>public static ElasticsearchClient NewSearchClusterClient
        {
            get
            {
                var connectionSettings = new ElasticsearchClientSettings(new Uri("<apimendpoint>"));
                connectionSettings.MaximumRetries(5);
                connectionSettings.DefaultIndex("test");
                connectionSettings.IncludeServerStackTraceOnError(true);
                connectionSettings.EnableTcpStats(true);
                connectionSettings.DisableDirectStreaming(true);
                NameValueCollection collection = new NameValueCollection
                {

                };
                connectionSettings.GlobalHeaders(collection);

                var client = new ElasticsearchClient(connectionSettings);
                return client;
            }
        }
</code>```

Call this --> var respone = NewSearchClusterClient.Search(q => q.Query(m => m.MatchAll()));

Body:
I am using latest "Elastic.Clients.Elasticsearch" library in .NET console application to talk to my elastic latest version 8.X. However, in my scenario I will not be talking directly to elastic I have a middle layer APIM endpoint. This is working fine when I am using NEST package with EnableAPIVersioningHeader setting. But in case of new library it throws 404 "resource not found error". Please can you let me know what are the changes that needs to be done to get this working.

Note: I am removing NEST package dependency from code, as Elastic will not support it in the future.

Sample Code:

public static ElasticsearchClient NewSearchClusterClient
        {
            get
            {
                var connectionSettings = new ElasticsearchClientSettings(new Uri("<apimendpoint>"));
                connectionSettings.MaximumRetries(5);
                connectionSettings.DefaultIndex("test");
                connectionSettings.IncludeServerStackTraceOnError(true);
                connectionSettings.EnableTcpStats(true);
                connectionSettings.DisableDirectStreaming(true);
                NameValueCollection collection = new NameValueCollection
                {

                };
                connectionSettings.GlobalHeaders(collection);

                var client = new ElasticsearchClient(connectionSettings);
                return client;
            }
        }

Call this --> var respone = NewSearchClusterClient.Search(q => q.Query(m => m.MatchAll()));


问:
VUE Js Cannot Scroll using router link
My Page View cannot be scroll on mobile view if it was loaded from router link from different page, need to be refreshed then it can be scrolled.

this is how I call the page

```<code><router-link
:to="{ name: 'catalogue.categorizedproduct', params: { category: kategori.nama_kategori } }" style="text-decoration:none;">
<i class="bi bi-caret-right-fill"></i>category.category_name}}
</router-link>
</code>```

there was 2 error, CORS and 'asynchronous response by returning true, but the message channel closed before a response was received' . Fixed the CORS problem but the other remain.

Title: VUE Js Cannot Scroll using router link

Body:
My Page View cannot be scroll on mobile view if it was loaded from router link from different page, need to be refreshed then it can be scrolled.

this is how I call the page

<router-link
:to="{ name: 'catalogue.categorizedproduct', params: { category: kategori.nama_kategori } }" style="text-decoration:none;">
category.category_name}}
</router-link>

there was 2 error, CORS and 'asynchronous response by returning true, but the message channel closed before a response was received' . Fixed the CORS problem but the other remain.


问:
when I try to get a data from the firebase I get error in the console
I have a 'products' collection in the firebase ,in my project I have a Products page that contain a list of all the products name each name is a link for edit product page ,in the edit product page I want to took the id from the URL Through use params, and get all the data about this product but I have error in the console that said :
Uncaught (in promise) Type Error: firebase__WEBPACK_IMPORTED_MODULE_1_.default. Collection is not a function
at fetch Data

this is my code in the firebase page:

```<code>import { initializeApp } from "firebase/app";
import {getFirestore} from "firebase/firestore"

const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxxx.firebaseapp.com",
projectId: "xxxxxx",
storageBucket: "xxxx.appspot.com",
messagingSenderId: "xxx",
appId: "xxxxxx",
measurementId: "xxxxxx"
};

const app = initializeApp(firebaseConfig);
const dB = getFirestore(app)

export default db
</code>```

and that the code in the editproduct page :

```<code>import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import dB from '../firebase';

const EditProduct = () => {
  const { id } = useParams();
  const [product, setProduct] = useState({});

  useEffect(() => {
    const fetchData = async () => {
      const snapshot = await dB.collection('Products').doc(id).get();
      setProduct(snapshot.data)
    }
    fetchData();
  }, [id])
}
</code>```

Body:
I have a 'products' collection in the firebase ,in my project I have a Products page that contain a list of all the products name each name is a link for edit product page ,in the edit product page I want to took the id from the URL Through use params, and get all the data about this product but I have error in the console that said :
Uncaught (in promise) Type Error: firebase__WEBPACK_IMPORTED_MODULE_1_.default. Collection is not a function
at fetch Data

this is my code in the firebase page:

import { initializeApp } from "firebase/app";
import {getFirestore} from "firebase/firestore"

const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxxx.firebaseapp.com",
projectId: "xxxxxx",
storageBucket: "xxxx.appspot.com",
messagingSenderId: "xxx",
appId: "xxxxxx",
measurementId: "xxxxxx"
};

const app = initializeApp(firebaseConfig);
const dB = getFirestore(app)

export default db

and that the code in the editproduct page :

import React, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import dB from '../firebase';

const EditProduct = () => {
  const { id } = useParams();
  const [product, setProduct] = useState({});

  useEffect(() => {
    const fetchData = async () => {
      const snapshot = await dB.collection('Products').doc(id).get();
      setProduct(snapshot.data)
    }
    fetchData();
  }, [id])
}


问:
libodbc++ - Memory Leak
`I am facing memory leak on each connection creation with database in libodbc++ library (0.2.5). I have copied valgrind log here. Used the below code to create and delete the connection. Any suggestion to fix the issue. Is libodbc++ stable to use ?

Sample Code:

```<code>`while(1)
{
    Connection* con = DriverManager::getConnection(ConnectionString);
    if(con != NULL)
    {
        delete con;
        con = NULL;
    }
}`
</code>```

Valgrind Log:
==7534== 283,173,984 (1,074,640 direct, 282,099,344 indirect) bytes in 9,595 blocks are definitely lost in loss record 7,279 of 7,279 ==7534== at 0x4CE9B0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==7534== by 0x6FEB3B7: __gconv_open (gconv_open.c:74) ==7534== by 0x6FEB070: iconv_open (iconv_open.c:40) ==7534== by 0x3172BEB: unicode_setup (__info.c:601) ==7534== by 0x3136BD7: __SQLAllocHandle (SQLAllocHandle.c:492) ==7534== by 0x310DC4F: odbc::DriverManager::_createConnection() (drivermanager.cpp:140) ==7534== by 0x310DDBC: odbc::DriverManager::getConnection(std::__cxx11::basic_string<char,     std::char_traits\<char="">, std::allocator\<char> > const&, std::__cxx11::basic_string<char, std::char_traits\<char="">, std::allocator\<char> > const&, std::__cxx11::basic_string<char, std::char_traits\<char="">, std::allocator\<char> > const&) (drivermanager.cpp:183) ==7534== by 0x</char></char,></char></char,></char></char,>

I have tried debugging libodbc++ library. SQLAllocHandle and SQLFreeHandle called properly for each connections and SQLFreeHandle returns SQL_SUCCESS. Memory not released by SQLFreeHandle. I didnt face connection leak. `

Title: libodbc++ - Memory Leak

Body:
`I am facing memory leak on each connection creation with database in libodbc++ library (0.2.5). I have copied valgrind log here. Used the below code to create and delete the connection. Any suggestion to fix the issue. Is libodbc++ stable to use ?

Sample Code:

`while(1)
{
    Connection* con = DriverManager::getConnection(ConnectionString);
    if(con != NULL)
    {
        delete con;
        con = NULL;
    }
}`

Valgrind Log:
==7534== 283,173,984 (1,074,640 direct, 282,099,344 indirect) bytes in 9,595 blocks are definitely lost in loss record 7,279 of 7,279 ==7534== at 0x4CE9B0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==7534== by 0x6FEB3B7: __gconv_open (gconv_open.c:74) ==7534== by 0x6FEB070: iconv_open (iconv_open.c:40) ==7534== by 0x3172BEB: unicode_setup (__info.c:601) ==7534== by 0x3136BD7: __SQLAllocHandle (SQLAllocHandle.c:492) ==7534== by 0x310DC4F: odbc::DriverManager::_createConnection() (drivermanager.cpp:140) ==7534== by 0x310DDBC: odbc::DriverManager::getConnection(std::__cxx11::basic_string<char,     std::char_traits\<char="">, std::allocator\<char> > const&, std::__cxx11::basic_string<char, std::char_traits\<char="">, std::allocator\<char> > const&, std::__cxx11::basic_string<char, std::char_traits\<char="">, std::allocator\<char> > const&) (drivermanager.cpp:183) ==7534== by 0x</char></char,></char></char,></char></char,>

I have tried debugging libodbc++ library. SQLAllocHandle and SQLFreeHandle called properly for each connections and SQLFreeHandle returns SQL_SUCCESS. Memory not released by SQLFreeHandle. I didnt face connection leak. `


问:
Recaptcha enterprise do not execute onSucces
I am trying to implement Recaptcha Enterprise for a login.
But I the onSuccess function is not been executed and I do not get an action_token.
What is missing?

I followed this: https://cloud.google.com/recaptcha-enterprise/docs/implement-tokens#action-token. In Google cloud I have set up the keys and domain.

In the header I have added the JS file:

```<code><script src="https://www.google.com/recaptcha/enterprise.js?render=<?php echo RECAPTCHAKEY; ?>"></script>
</code>```

On the page I have implemented the example:

```<code><script>
function onSuccess(action_token) {
    alert("alert");
    const xhr = new XMLHttpRequest();
    xhr.open('GET','login.php', false);
    // Attach the action-token to the predefined request header
    xhr.setRequestHeader("X-Recaptcha-Token", action_token);
    xhr.send(null);
}

function onError(reason) {
    alert('Response promise rejected: ' + reason);
}

grecaptcha.enterprise.ready(function () {
    console.log("READY");
    document.getElementById("submit").onclick = () => {
        console.log("getElementById");
        grecaptcha.enterprise.execute('<?php echo RECAPTCHAKEY ?>', {
        }).then(onSuccess, onError);
        console.log("execute");
    };
});
</code>```

And also a form:

```<code><form id="login-form" ENCTYPE='multipart/form-data' method='post' action='' name='login'>...
<button type="submit" id="submit" name='submit' class="btn btn-primary"
                    class="g-recaptcha"
                    data-sitekey="<?php echo RECAPTCHAKEY; ?>"
                    data-callback='onSubmit'
                    data-action='submit'><?php echo $lan->getValue('login'); ?></button>
</code>```

Body:
I am trying to implement Recaptcha Enterprise for a login.
But I the onSuccess function is not been executed and I do not get an action_token.
What is missing?

I followed this: https://cloud.google.com/recaptcha-enterprise/docs/implement-tokens#action-token. In Google cloud I have set up the keys and domain.

In the header I have added the JS file:

On the page I have implemented the example:


问:
Convert 3d array (num_doc, length, 1024) of ELMo embedding into 2d array for PCA
I did an experiment for build topic modeling using ELMo embedding. I used Elmo for many language here and get 3 dimensional array as the embedding output like this (13294, 200, 1024).

I want to do the dimensionality reduction using the PCA; but the code had error:

Found array with dim 3. Estimator expected <= 2.

Can we convert the 3 dimensional array (num_doc, length, 1024) of ELMo embedding into 2 dimensional array (num_doc,1024)?

Here is the code I used to get the embedding:

e = elmo.Embedder('/content/drive/MyDrive/ELMoIndonesia/158 (1)')

def encode_elmo(elmo, text):
  vector = elmo.sents2elmo(text)
  return np.array(vector)

def token(text):
  return word_tokenize(text)

data_token = data['clean_tweet'].apply(token)

model_elmo = encode_elmo(e, data_token)

data_pad = pad_sequences(model_elmo, dtype='int32', maxlen=200, padding='post')

and here the code I used for dimensional reduction using PCA
# initialize PCA with 2 components
pca = PCA(n_components=2, random_state=None)
# pass our X to the pca and store the reduced vectors into pca_vecs
pca_vecs = pca.fit_transform(data_pad)
```


问:
php export to xls without library
I would like to export data from sql to xls (better would be xlsx) without a third party library.

This is my code:

```<code>// DB Connection included by a config.php file

$sql = $db->prepare( "SELECT * FROM myTable" );
$sql->execute();
$result = $sql->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename=Export.csv');
ExportFile($result);

function ExportFile($records) {

    $heading = false;

    foreach($records as $row) {

      if(!$heading) {
          echo implode("\t", array_keys($row)) . "\n";
          $heading = true;
      }
        echo implode("\t", array_values($row)) . "\n";
    }

}
exit;
</code>```

This works.
But if I change the header to Export.xls it works but with an "error message" of excel.

```<code>The file format and the file extension of 'Export.xls' do not match. The file may be corrupted or unsafe. You should not open it if you do not trust its source. Do you still want to open the file?
</code>```

and if I changed it to Export.xlsx:

```<code>The file 'Export.xlsx' cannot be opened by Excel because the file format or extension is invalid. Check if the file is corrupted and if the file extension matches the file format.
</code>```

How can I solve it, to realize it with xls without error message (better with xlsx)?

Title: php export to xls without library

Body:
I would like to export data from sql to xls (better would be xlsx) without a third party library.

This is my code:

// DB Connection included by a config.php file

$sql = $db->prepare( "SELECT * FROM myTable" );
$sql->execute();
$result = $sql->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename=Export.csv');
ExportFile($result);

function ExportFile($records) {

    $heading = false;

    foreach($records as $row) {

      if(!$heading) {
          echo implode("\t", array_keys($row)) . "\n";
          $heading = true;
      }
        echo implode("\t", array_values($row)) . "\n";
    }

}
exit;

This works.
But if I change the header to Export.xls it works but with an "error message" of excel.

The file format and the file extension of 'Export.xls' do not match. The file may be corrupted or unsafe. You should not open it if you do not trust its source. Do you still want to open the file?

and if I changed it to Export.xlsx:

The file 'Export.xlsx' cannot be opened by Excel because the file format or extension is invalid. Check if the file is corrupted and if the file extension matches the file format.

How can I solve it, to realize it with xls without error message (better with xlsx)?


问:
can't fetch a specific API in React
My component can't fetch data from a specific API.
I am using react, and I installed react-router-dom.

This is my App component

```<code>import Recipe from "./components/Recipe";
import RecipeItself from "./components/RecipeItself";
import { BrowserRouter, Routes, Route } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/recipes" element={<Recipe />} />
        <Route path="/recipes/:id" element={<RecipeItself />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

</code>```

I am trying to fetch data from an API.
I made a component fetching the API, and when I clicked on a div in the component, I should move to another component using router..

But it doesn't work properly. The page couldn't read the response from fetch.
So I put another API and checked that it was working. So I put my original API and it worked but when I entered the component from the previous one, it didn't!

I add pictures of my console when it failed and when it is done after replacing the API. So weird
When it failed
When I replaced the API

I am almost getting crazy. Can someone teach me?

It is the first component

```<code>import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

function RecipeCard(props) {
  // console.log(
  //   "name",
  //   props.api.name,
  //   "recipes",
  //   props.api.recipes,
  //   "then what?",
  //   props.api,
  //   "instructions1",
  //   props.api.instructions
  // );
  return (
    // Here put `link to` and give unique ids to move
    <Link to={`/recipes/${props.api.id}`}>
      <div className="recipe_card">
        <div
          className="recipe_img"
          style={{ backgroundImage: `url(${props.api.thumbnail_url})` }}
        />
        <h1>{props.api.name}</h1>
      </div>
    </Link>
  );
}

function RecipeApi(props) {
  const searchedOne = props.search;

  const [api, setApi] = useState([]);
  const options = {
    method: "GET",
    headers: {
      "X-RapidAPI-Key": process.env.REACT_APP_RECIPE_API_KEY,
      "X-RapidAPI-Host": "tasty.p.rapidapi.com",
    },
  };

  useEffect(() => {
    fetch(
      `https://tasty.p.rapidapi.com/recipes/list?from=0&size=20&q=$${searchedOne}`,
      options
    )
      .then((response) => response.json())
      .then((response) => setApi([...response.results]))
      .catch((err) => console.error(err));
  }, [searchedOne]);

  return (
    <section className="recipe_api">
      <h2 className="recepe_api_title">Here are the recipes for you!</h2>
      <div className="recipe_api_boxes">
        {searchedOne.length > 0 &&
          api.map((api) => <RecipeCard key={api.id} api={api} />)}
      </div>
    </section>
  );
}

export default React.memo(RecipeApi);
</code>```

It is the problematic component which isn't working properly

```<code>import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

export default function RecipeItself() {
  // the url of this page should be /id
  const { id } = useParams();
  const [cont, setCont] = useState([]);

  const options = {
    method: "GET",
    headers: {
      "X-RapidAPI-Key": process.env.REACT_APP_RECIPE_API_KEY,
      "X-RapidAPI-Host": "tasty.p.rapidapi.com",
    },
  };

  useEffect(() => {
    fetch(
      "https://swapi.dev/api/people/1"
// It didn't work well so I put a starwars API to check it :/
      //   `https://tasty.p.rapidapi.com/recipes/get-more-info?id=${id}`,
      //   options
    )
      .then((response) => response.json())
      .then((response) => setCont(response))
      .catch((err) => console.error(err));
  }, []);

  console.log(cont);
  //   let step = cont.instructions;
  //   console.log(step);
  //   let ingr = cont.sections[0].components;
  //   console.log(ingr);

  return (
    <div className="recipe_itself">
      <>
        {/* <div
          className="recipe_itself_img"
          style={{ backgroundImage: `url(${cont.thumbnail_url})` }}
        />
        <h2 className="recipe_itself_name">{cont.name}</h2>
        <div className="recipe_itself_cont">
          <div className="recipe_itself_ingr">
            <h3>Ingredients</h3>
            <p>{cont.yields}</p>
            {ingr.map((ingr) => (
              <ul key={ingr.id}>
                <li>{ingr.raw_text}</li>
              </ul>
            ))}
          </div>
          <div className="redipe_itself_inst">
            <h3>Instructions</h3>
            {step.map((step) => (
              <div key={step.id}>
                <h4>Step {step.position}</h4>
                <p>{step.display_text}</p>
              </div>
            ))}
          </div>
        </div> */}
      </>
    </div>
  );
}

</code>```

Title: can't fetch a specific API in React

Body:
My component can't fetch data from a specific API.
I am using react, and I installed react-router-dom.

This is my App component

import Recipe from "./components/Recipe";
import RecipeItself from "./components/RecipeItself";
import { BrowserRouter, Routes, Route } from "react-router-dom";

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/recipes" element={<Recipe />} />
        <Route path="/recipes/:id" element={<RecipeItself />} />
      </Routes>
    </BrowserRouter>
  );
}

export default App;

I am trying to fetch data from an API.
I made a component fetching the API, and when I clicked on a div in the component, I should move to another component using router..

But it doesn't work properly. The page couldn't read the response from fetch.
So I put another API and checked that it was working. So I put my original API and it worked but when I entered the component from the previous one, it didn't!

I add pictures of my console when it failed and when it is done after replacing the API. So weird
When it failed
When I replaced the API

I am almost getting crazy. Can someone teach me?

It is the first component

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";

function RecipeCard(props) {
  // console.log(
  //   "name",
  //   props.api.name,
  //   "recipes",
  //   props.api.recipes,
  //   "then what?",
  //   props.api,
  //   "instructions1",
  //   props.api.instructions
  // );
  return (
    // Here put `link to` and give unique ids to move
    <Link to={`/recipes/${props.api.id}`}>

        <div
          className="recipe_img"
          style={{ backgroundImage: `url(${props.api.thumbnail_url})` }}
        />

{props.api.name}

    </Link>
  );
}

function RecipeApi(props) {
  const searchedOne = props.search;

  const [api, setApi] = useState([]);
  const options = {
    method: "GET",
    headers: {
      "X-RapidAPI-Key": process.env.REACT_APP_RECIPE_API_KEY,
      "X-RapidAPI-Host": "tasty.p.rapidapi.com",
    },
  };

  useEffect(() => {
    fetch(
      `https://tasty.p.rapidapi.com/recipes/list?from=0&size=20&q=$${searchedOne}`,
      options
    )
      .then((response) => response.json())
      .then((response) => setApi([...response.results]))
      .catch((err) => console.error(err));
  }, [searchedOne]);

  return (

Here are the recipes for you!

        {searchedOne.length > 0 &&
          api.map((api) => <RecipeCard key={api.id} api={api} />)}

  );
}

export default React.memo(RecipeApi);

It is the problematic component which isn't working properly

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

export default function RecipeItself() {
  // the url of this page should be /id
  const { id } = useParams();
  const [cont, setCont] = useState([]);

  const options = {
    method: "GET",
    headers: {
      "X-RapidAPI-Key": process.env.REACT_APP_RECIPE_API_KEY,
      "X-RapidAPI-Host": "tasty.p.rapidapi.com",
    },
  };

  useEffect(() => {
    fetch(
      "https://swapi.dev/api/people/1"
// It didn't work well so I put a starwars API to check it :/
      //   `https://tasty.p.rapidapi.com/recipes/get-more-info?id=${id}`,
      //   options
    )
      .then((response) => response.json())
      .then((response) => setCont(response))
      .catch((err) => console.error(err));
  }, []);

  console.log(cont);
  //   let step = cont.instructions;
  //   console.log(step);
  //   let ingr = cont.sections[0].components;
  //   console.log(ingr);

  return (

      <>
        {/* <div
          className="recipe_itself_img"
          style={{ backgroundImage: `url(${cont.thumbnail_url})` }}
        />

{cont.name}

Ingredients

{cont.yields}

            {ingr.map((ingr) => (

{ingr.raw_text}

            ))}

Instructions

            {step.map((step) => (

Step {step.position}

{step.display_text}

            ))}

 */}
      </>

  );
}


问:
How to validate open API standard code inside Angular application
Is there a good library or a way for validating Open API standard code while the user is typing.

For example, user is typing code and makes a mistake on line 17 like in example below


问:
Docxtemplater. Links in v3
Is there any way to add link in doc to Docxtemplater v3?

I found this package https://github.com/sujith3g/docxtemplater-link-module. But that only works in v2.

Title: Docxtemplater. Links in v3


问:
Top 10 Genre in SQL
I am trying to get the top 10 Genres from the IMDB Movies database (CSV format). Normally it is an easy task all you have to do is group and count. But in this database genre is given in quite a weird format.
Eg: Action|Adventure|Fantasy|Sci-Fi

I have tried counting using like function but with this, I can only count 1 genre which I use as the keyword in like fucntion.

If it were to be python I could have split all genre types using the split function and then it would be easy. But in SQL I don't know how would I split or how can I run all genres in like function. I also tried using IN function but it gave me a syntax error i.e can't be used like this.

```<code>select genres, count(movie_title) AS Number_of_Movie
from imdb_movies_column_drop
group by genres
order by Number_of_Movie DESC
limit 10;
</code>```

Using this code gives me this output

The output that I need is:

Genres
Number_of_Movie

Comedy
75

Romance
70

Action
66

Adventure
66

And so on.

Title: Top 10 Genre in SQL

Body:
I am trying to get the top 10 Genres from the IMDB Movies database (CSV format). Normally it is an easy task all you have to do is group and count. But in this database genre is given in quite a weird format.
Eg: Action|Adventure|Fantasy|Sci-Fi

I have tried counting using like function but with this, I can only count 1 genre which I use as the keyword in like fucntion.

If it were to be python I could have split all genre types using the split function and then it would be easy. But in SQL I don't know how would I split or how can I run all genres in like function. I also tried using IN function but it gave me a syntax error i.e can't be used like this.

select genres, count(movie_title) AS Number_of_Movie
from imdb_movies_column_drop
group by genres
order by Number_of_Movie DESC
limit 10;

Using this code gives me this output

The output that I need is:

Genres
Number_of_Movie

Comedy
75

Romance
70

Action
66

Adventure
66

And so on.


问:
How to get only recurring events from google calendar
I am working on developing integration with Google Calendar using Rest APIs. I want to know if there is any way to pull only recurring events from a Google Calendar.

I am using this API but not able to work it out so far - https://www.googleapis.com/calendar/v3/calendars/primary/events


问:
Create Google maps URL in Bitrix
I want to create a Google maps link for the CRM module of Bitrix.
For this I want to use the address fields of the company entity. How do I have to write this?
Like this only the {CompanyAddress} is resolved:

https://www.google.com/maps/search/?api=1&query={CompanyAddress}+{CompanyAddressPostalCode}+{CompanyAddressCity}

According to the documentation of Bitrix the Postal Code is in a field called "ADDRESS_POSTAL_CODE".

I created a dynamic URL in Bitrix, this should open the address of a company in Google maps.

Title: Create Google maps URL in Bitrix


问:
Entity Tracked Problem After Upgrade .net 2.0 to .net 3.1
I am using repository pattern.
After upgrade .net 2.0 to 3.1 I got following error and I changed nothing.

```<code>The instance of entity type 'Table' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
</code>```

1st solution is using AsNoTracking(). It is not a good solution, because when used this, EF don't update by field, EF update all fields. Also, I don't know which part of my code can get this error at runtime.

2nd solution is change entity state to modified. I can't apply this solution, because when I try to change state to modified I got following error. Actually I don't use any delete.

```<code>The association between entity types 'Table' and 'RelationalTable' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes.  Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.
</code>```

3rd solution is using scoped DbContext in startup.cs. It is already scoped and I also got this error on debugging I use single thread.

Finally, I didn't understand why I got this error after upgrade and how can I fix this problems, I don't want to test all operations.

Body:
I am using repository pattern.
After upgrade .net 2.0 to 3.1 I got following error and I changed nothing.

The instance of entity type 'Table' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

1st solution is using AsNoTracking(). It is not a good solution, because when used this, EF don't update by field, EF update all fields. Also, I don't know which part of my code can get this error at runtime.

2nd solution is change entity state to modified. I can't apply this solution, because when I try to change state to modified I got following error. Actually I don't use any delete.

The association between entity types 'Table' and 'RelationalTable' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable. If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes.  Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.

3rd solution is using scoped DbContext in startup.cs. It is already scoped and I also got this error on debugging I use single thread.

Finally, I didn't understand why I got this error after upgrade and how can I fix this problems, I don't want to test all operations.


问:
Data not changing upon vuejs date pickers date range selection
In my vuejs laravel based application I'm trying to fetch and display some data from a Shopify store using their admin REST API.

Following is my controller.

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ShopifyStatsController extends Controller
{
    public function fetchStats(Request $request)
    {

        if ($request->has('startDate') && $request->has('endDate')) {
            // A date range was selected
            $startDate = $request->startDate;
            $endDate = $request->endDate;
        } else {
            $startDate = Carbon::now()->format('Y-m-d');
            $endDate = Carbon::now()->format('Y-m-d');
        }

        // Set up cURL request
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN@STORE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=$startDate&created_at_max=$endDate");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));

        $response = curl_exec($ch);

        curl_close($ch);

        $orders = json_decode($response);

        $total_orders = ($orders->orders != null && !empty($orders->orders)) ? count($orders->orders) : 0;
        $total_sales = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $total_items = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $completed_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $to_be_fulfilled_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        foreach ($orders->orders as $order) {
            $total_sales += $order->total_price;
            $total_items += count($order->line_items);
            if ($order->financial_status == "paid") {
                $completed_orders++;
            }
            if ($order->fulfillment_status == null) {
                $to_be_fulfilled_orders++;
            }
        }

        $average_order_value = $total_orders > 0 ? $total_sales / $total_orders : 0;

            // Return the total sales value
            return response()->json([
                'total_sales' => $total_sales,
                'total_orders' => $total_orders,
                'total_items' => $total_items,
                'completed_orders' => $completed_orders,
                'average_order_value' => $average_order_value
        ]);
    }
}
</code>```

This is working fine.

Now then this is my index.vue

```<code><!--Shopify Widgets -->
                    <div >
                        <draggable v-model="items" :options="{ group: 'shared' }" class="d-flex">
                            <div v-for="item in items" :key="item.id" class="col-md-2 col-sm-2 col-lg-2" >
                                <component
                                    v-if="dateRange"
                                    :is="item.component"
                                    :item="item"
                                    :total-sales="item.totalSales"
                                    :count="item.count"
                                    :total-items="item.totalItems"
                                    :total-completed="item.totalCompleted"
                                    :average-value="item.averageValue"
                                />
                            </div>
                        </draggable>
                    </div>
                    <!-- End of Shopify Widgets  -->
</code>```

This is where I display my reusable stat components.

Now I have added following date picker on the top of my widgets area.

```<code><vue-ctk-date-time-picker
                    id="main-datepicker"
                    label="Select a date range"
                    v-model="value"
                    :range="true"
                    format="YYYY-MM-DD"
                    formatted="MMMM Do YYYY"
                    output-format="YYYY-MM-DD"
                    :firstDayOfWeek=1
                    :overlay="true"
                    :noClearButton="true"
                    :autoClose="false"
                    :right="true"
                    :persistent="persistent"
                    @change="fetchStats()"
                    @validate="changeDate()"
                >
                </vue-ctk-date-time-picker>
</code>```

And in my data() I have the following

```<code>data() {
    return {
        dateRange: [
            // Default start date as today
            new Date().toISOString().substring(0, 10),
            // Default end date as today
            new Date().toISOString().substring(0, 10)
        ],
        // other properties here
    }
},
</code>```

And this is my fetchStats() method

```<code>fetchStats(){
        if (this.dateRange === undefined || this.dateRange[0] === this.dateRange[1]) {
            // Fetch today's orders and sales data from the Laravel controller
            axios.get('/shopify-stats').then(response => {
                // Update the count and total sales values in the items array
                this.items[0].count = response.data.total_orders;
                this.items[1].totalSales = response.data.total_sales;
                this.items[2].totalItems = response.data.total_items;
                this.items[3].totalCompleted = response.data.completed_orders;
                this.items[4].averageValue = response.data.average_order_value;
            });
        } else {
            // Fetch the orders and sales data for the selected date range from the Laravel controller
            axios.post('/shopify-stats', {
                startDate: this.dateRange[0],
                endDate: this.dateRange[1]
            }).then(response => {
                // Update the count and total sales values in the items array
                this.items[0].count = response.data.total_orders;
                this.items[1].totalSales = response.data.total_sales;
                this.items[2].totalItems = response.data.total_items;
                this.items[3].totalCompleted = response.data.completed_orders;
                this.items[4].averageValue = response.data.average_order_value;
            });
        }
    },
</code>```

And I have following in my routes.

```<code>Route::get('/shopify-stats', 'ShopifyStatsController@fetchStats')->name('shopify-stats');
Route::post('/shopify-stats', 'ShopifyStatsController@fetchStats');
</code>```

In my index.vue, I have other function called changeDate() which I have created ealier

```<code>changeDate() {
            this.responsive = false;
            this.start = this.value.start;
            this.end = this.value.end;
            if (this.end != null) {
                this.persistent = false;
                this.componentKey += 1;
                if (this.start != null && this.end != null) {
                    window.setTimeout(() => {
                        setTimeout(function () {
                            this.responsive = true;
                            this.loading = false;
                        }.bind(this), 1000)
                    }, 500);
                }
            } else {
                this.persistent = true;
            }
        },
</code>```

But, when ever I try to select a date range it doesn't work properly, at least it's not sending the start end dates to the back end as well...What I'm doing wrong and how can I make this work??

Body:
In my vuejs laravel based application I'm trying to fetch and display some data from a Shopify store using their admin REST API.

Following is my controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Carbon\Carbon;

class ShopifyStatsController extends Controller
{
    public function fetchStats(Request $request)
    {

        if ($request->has('startDate') && $request->has('endDate')) {
            // A date range was selected
            $startDate = $request->startDate;
            $endDate = $request->endDate;
        } else {
            $startDate = Carbon::now()->format('Y-m-d');
            $endDate = Carbon::now()->format('Y-m-d');
        }

        // Set up cURL request
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN@STORE_NAME.myshopify.com/admin/orders.json?status=any&created_at_min=$startDate&created_at_max=$endDate");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));

        $response = curl_exec($ch);

        curl_close($ch);

        $orders = json_decode($response);

        $total_orders = ($orders->orders != null && !empty($orders->orders)) ? count($orders->orders) : 0;
        $total_sales = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $total_items = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $completed_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        $to_be_fulfilled_orders = ($orders->orders != null && !empty($orders->orders)) ? 0 : 0;
        foreach ($orders->orders as $order) {
            $total_sales += $order->total_price;
            $total_items += count($order->line_items);
            if ($order->financial_status == "paid") {
                $completed_orders++;
            }
            if ($order->fulfillment_status == null) {
                $to_be_fulfilled_orders++;
            }
        }

        $average_order_value = $total_orders > 0 ? $total_sales / $total_orders : 0;

            // Return the total sales value
            return response()->json([
                'total_sales' => $total_sales,
                'total_orders' => $total_orders,
                'total_items' => $total_items,
                'completed_orders' => $completed_orders,
                'average_order_value' => $average_order_value
        ]);
    }
}

This is working fine.

Now then this is my index.vue

                        <draggable v-model="items" :options="{ group: 'shared' }" class="d-flex">

                                <component
                                    v-if="dateRange"
                                    :is="item.component"
                                    :item="item"
                                    :total-sales="item.totalSales"
                                    :count="item.count"
                                    :total-items="item.totalItems"
                                    :total-completed="item.totalCompleted"
                                    :average-value="item.averageValue"
                                />

                        </draggable>

This is where I display my reusable stat components.

Now I have added following date picker on the top of my widgets area.

<vue-ctk-date-time-picker
                    id="main-datepicker"
                    label="Select a date range"
                    v-model="value"
                    :range="true"
                    format="YYYY-MM-DD"
                    formatted="MMMM Do YYYY"
                    output-format="YYYY-MM-DD"
                    :firstDayOfWeek=1
                    :overlay="true"
                    :noClearButton="true"
                    :autoClose="false"
                    :right="true"
                    :persistent="persistent"
                    @change="fetchStats()"
                    @validate="changeDate()"
                >
                </vue-ctk-date-time-picker>

And in my data() I have the following

data() {
    return {
        dateRange: [
            // Default start date as today
            new Date().toISOString().substring(0, 10),
            // Default end date as today
            new Date().toISOString().substring(0, 10)
        ],
        // other properties here
    }
},

And this is my fetchStats() method

fetchStats(){
        if (this.dateRange === undefined || this.dateRange[0] === this.dateRange[1]) {
            // Fetch today's orders and sales data from the Laravel controller
            axios.get('/shopify-stats').then(response => {
                // Update the count and total sales values in the items array
                this.items[0].count = response.data.total_orders;
                this.items[1].totalSales = response.data.total_sales;
                this.items[2].totalItems = response.data.total_items;
                this.items[3].totalCompleted = response.data.completed_orders;
                this.items[4].averageValue = response.data.average_order_value;
            });
        } else {
            // Fetch the orders and sales data for the selected date range from the Laravel controller
            axios.post('/shopify-stats', {
                startDate: this.dateRange[0],
                endDate: this.dateRange[1]
            }).then(response => {
                // Update the count and total sales values in the items array
                this.items[0].count = response.data.total_orders;
                this.items[1].totalSales = response.data.total_sales;
                this.items[2].totalItems = response.data.total_items;
                this.items[3].totalCompleted = response.data.completed_orders;
                this.items[4].averageValue = response.data.average_order_value;
            });
        }
    },

And I have following in my routes.

Route::get('/shopify-stats', 'ShopifyStatsController@fetchStats')->name('shopify-stats');
Route::post('/shopify-stats', 'ShopifyStatsController@fetchStats');

In my index.vue, I have other function called changeDate() which I have created ealier

changeDate() {
            this.responsive = false;
            this.start = this.value.start;
            this.end = this.value.end;
            if (this.end != null) {
                this.persistent = false;
                this.componentKey += 1;
                if (this.start != null && this.end != null) {
                    window.setTimeout(() => {
                        setTimeout(function () {
                            this.responsive = true;
                            this.loading = false;
                        }.bind(this), 1000)
                    }, 500);
                }
            } else {
                this.persistent = true;
            }
        },

But, when ever I try to select a date range it doesn't work properly, at least it's not sending the start end dates to the back end as well...What I'm doing wrong and how can I make this work??


问:
Does Python BackgroundScheduler works in a separate thread?
I use APScheduler on Python. Scheduler is imported as:

from apscheduler.schedulers.background import BackgroundScheduler

Does Python BackgroundScheduler works in a separate thread?

I ask because when main thread is blocked then scheduler tasks aren't executing. It looks like that main thread's block causes block of BackgroundScheduler.

Main thread is blocked by long SQL script execution if it makes sense.


问:
Implement Next-Auth to consume protected routes of custom Laravel Backend
I'm very new to Next-Auth.

Here's my tech stack:

Laravel as the Backend

Laravel Passport for OAuth

Next.js 13 (App Directory)

Next-Auth 4.18.8

What I'm trying to achieve?

I already have the backend developed in Laravel, I wan to use Next.js just for serving to the end user.
I've configured custom OAuth provider in pages/api/auth/[...nextauth].ts like this:

import NextAuth, { NextAuthOptions } from "next-auth"
export const authOptions: NextAuthOptions = {
  providers: [
    {
      id: "I4T",
      name: "I4T",
      type: "oauth",
      authorization: {
        url: `${process.env.I4T_BACKEND_URL}/oauth/authorize`,
        params: { scope: "" }
      },
      token: `${process.env.I4T_BACKEND_URL}/oauth/token`,
      userinfo: `${process.env.I4T_BACKEND_URL}/api/user`,
      clientId: process.env.I4T_CLIENT_ID,
      clientSecret: process.env.I4T_CLIENT_SECRET,
      profile: (profile) => {
        return profile
      },

    }
  ],
}
export default NextAuth(authOptions)
```

It works as expected.

But I also want to call any subsequent protected API routes (e.g: perform some CRUD operations etc..) of the Laravel backend from the Next.js application (both Client components and Server components) and for example if any of the call returns Unauthorized I want the Next.js application to be logged out.

I'm not sure how to achieve the same in most secure way, read many articles/tutorials but all of them ends at just setting up custom OAuth provider. :(

Any help is much appricated :)

Body:
I'm very new to Next-Auth.

Here's my tech stack:

Laravel as the Backend

Laravel Passport for OAuth

Next.js 13 (App Directory)

Next-Auth 4.18.8

What I'm trying to achieve?

I already have the backend developed in Laravel, I wan to use Next.js just for serving to the end user.
I've configured custom OAuth provider in pages/api/auth/[...nextauth].ts like this:

import NextAuth, { NextAuthOptions } from "next-auth"
export const authOptions: NextAuthOptions = {
  providers: [
    {
      id: "I4T",
      name: "I4T",
      type: "oauth",
      authorization: {
        url: `${process.env.I4T_BACKEND_URL}/oauth/authorize`,
        params: { scope: "" }
      },
      token: `${process.env.I4T_BACKEND_URL}/oauth/token`,
      userinfo: `${process.env.I4T_BACKEND_URL}/api/user`,
      clientId: process.env.I4T_CLIENT_ID,
      clientSecret: process.env.I4T_CLIENT_SECRET,
      profile: (profile) => {
        return profile
      },

    }
  ],
}
export default NextAuth(authOptions)

It works as expected.

But I also want to call any subsequent protected API routes (e.g: perform some CRUD operations etc..) of the Laravel backend from the Next.js application (both Client components and Server components) and for example if any of the call returns Unauthorized I want the Next.js application to be logged out.

I'm not sure how to achieve the same in most secure way, read many articles/tutorials but all of them ends at just setting up custom OAuth provider. :(

Any help is much appricated :)


问:
Android Studio Emulator: How to get the list of running component names?
I'm following this MITMProxy tutorial where in the end of the tutorial it requires the attacker to know the component name of a running app in the end, i.e. com.criticalblue.shipfast.api_key

Since I'm running an external apk on my android studio emulator, how can I find out the component name of the specific app?


问:
Can a Euler cycle be made from a one-vertex graph?
I have the following question that I must prove or disprove:

Let =(,)be an undirected connected graph. Let  be the minimum amount of edges one needs to add to G so that the resulting graph has an Euler cycle. Then x≤floor(n/2) when n=the number of vertices.

I believe this is untrue because if I have a graph of one vertex with an edge that connects to itself, then x=1 and floor(n/2)=0, so this statement cannot hold. However, I'm wondering if a one-vertex graph truly fulfills all the requirements. Is a one-vertex graph both undirected, connected and able to be considered a Euler cycle when it loops to itself? TIA.


问:
html video tag sound not working | Safari İOS Mobile
HTML video tag audio not working in safari, what could be the reason?

```<code><video id="vid" width="100%" height="1000" data-loop="true" playsinline autoplay muted preload="metadata" data-fill-mode="fill" class="ms-slide-bgvideo">
     <source src="image/video.mp4" type="video/mp4">
     <source src="movie.ogg" type="video/ogg">
</video>
</code>```

js control

```<code>$('.video .icon .on').click(function(){
    $('video').prop('muted', true);
})

$('.video .icon .off').click(function(){
    $('video').prop('muted', false);
})
</code>```

Body:
HTML video tag audio not working in safari, what could be the reason?

<video id="vid" width="100%" height="1000" data-loop="true" playsinline autoplay muted preload="metadata" data-fill-mode="fill" class="ms-slide-bgvideo">
     <source src="image/video.mp4" type="video/mp4">
     <source src="movie.ogg" type="video/ogg">
</video>

js control

$('.video .icon .on').click(function(){
    $('video').prop('muted', true);
})

$('.video .icon .off').click(function(){
    $('video').prop('muted', false);
})


问:
Using If Then Else in Python
Disclaimer: Please pardon me if this comes out to be too basic or a stupid question. I am a complete noob trying to figure out Python on the job.
Now since that's out of the way, here is my problem.

I have 2 columns, Date and Sales. I need to split the Sales data based on a date Condition, thereby creating a new Column for Eg,

```<code>if Date >= 6/1/2022 then Sales_H2 = Sales
else Sales_H2 = 0
</code>```

I have the SAS Code with me, but I need to convert the Code into Python. I could use Pandas, Numpy, or any other library. Below is the SAS Code

```<code>data input.&dat.;
set input.&dat.;
if Period ge '6JUN2022'd then
Sales_H222=Sales;
else
Sales_H222=0;
</code>```

Title: Using If Then Else in Python

Body:
Disclaimer: Please pardon me if this comes out to be too basic or a stupid question. I am a complete noob trying to figure out Python on the job.
Now since that's out of the way, here is my problem.

I have 2 columns, Date and Sales. I need to split the Sales data based on a date Condition, thereby creating a new Column for Eg,

if Date >= 6/1/2022 then Sales_H2 = Sales
else Sales_H2 = 0

I have the SAS Code with me, but I need to convert the Code into Python. I could use Pandas, Numpy, or any other library. Below is the SAS Code

data input.&dat.;
set input.&dat.;
if Period ge '6JUN2022'd then
Sales_H222=Sales;
else
Sales_H222=0;


问:
How to transfer Keycloak Config on different enviroments
We currently have 3 Enviroments, each with a Keycloak Server set up. One for development, one for testing, and one for production.

Now to my question. How do I export/import Keycloak Realms/Clients considering that each one has different root uri's, valid redirect uri's etc...

Is it possible to parameterize that configuration, so i can simply hit export on one enviroment, and import on another? Root Uris and valid redirect Uris would come from the standalone.xml from each enviroment.

Thanks!

I allready tried looking for the export/import documentation from Keycoak and even from RedHat but i dont find anything helpfull.


问:
Elasticsearch 7 value_count is inconsistent when same items exists in a keyword/ip array
```<code>PUT test_value_count/_doc/1
{
    "ip" : [
        "2402:3a80:11e3:15eb:3bd0:28c3:77b9:786e",
        "2402:3a80:11e3:15eb:3bd0:28c3:77b9:786e"
    ],
    "count" : [ 0,1]
}

PUT test_value_count/_doc/2
{
    "ip" : [
        "192.168.1.2",
        "192.168.1.3",
        "192.168.1.1"
    ],
    "count" : [ 0,1]
}

GET test_value_count/_search?track_total_hits=true
{
    "aggs": {
        "count": {
            "value_count": {
                "field": "count"
            }
        },
            "ip": {
                "value_count": {
                    "field": "ip.keyword"
                }
            }
    },
        "size" : 0
}

----

{
    "took" : 2,
        "timed_out" : false,
        "_shards" : {
            "total" : 1,
            "successful" : 1,
            "skipped" : 0,
            "failed" : 0
        },
        "hits" : {
            "total" : {
                "value" : 2,
                "relation" : "eq"
            },
            "max_score" : null,
            "hits" : [ ]
        },
        "aggregations" : {
            "ip" : {
                "value" : 4
            },
            "count" : {
                "value" : 4
            }
        }
}

</code>```

The value_count is inconsistent when same items exists in the string array.
Any solutions ?

The result discards the same string item in the array.

Body:
PUT test_value_count/_doc/1
{
    "ip" : [
        "2402:3a80:11e3:15eb:3bd0:28c3:77b9:786e",
        "2402:3a80:11e3:15eb:3bd0:28c3:77b9:786e"
    ],
    "count" : [ 0,1]
}

PUT test_value_count/_doc/2
{
    "ip" : [
        "192.168.1.2",
        "192.168.1.3",
        "192.168.1.1"
    ],
    "count" : [ 0,1]
}

GET test_value_count/_search?track_total_hits=true
{
    "aggs": {
        "count": {
            "value_count": {
                "field": "count"
            }
        },
            "ip": {
                "value_count": {
                    "field": "ip.keyword"
                }
            }
    },
        "size" : 0
}

----

{
    "took" : 2,
        "timed_out" : false,
        "_shards" : {
            "total" : 1,
            "successful" : 1,
            "skipped" : 0,
            "failed" : 0
        },
        "hits" : {
            "total" : {
                "value" : 2,
                "relation" : "eq"
            },
            "max_score" : null,
            "hits" : [ ]
        },
        "aggregations" : {
            "ip" : {
                "value" : 4
            },
            "count" : {
                "value" : 4
            }
        }
}

The value_count is inconsistent when same items exists in the string array.
Any solutions ?

The result discards the same string item in the array.


问:
ConnectionError: getaddrinfo EAI_AGAIN error when I am trying to read data from elasticsearch
I am stuck in a super strange problem.

I am getting ConnectionError: getaddrinfo EAI_AGAIN error when I am trying to access elasticsearch on localhost whereas on production it is working completely fine.

```<code>ConnectionError: getaddrinfo EAI_AGAIN <awsHostUrl>
    at onResponse (/home/Desktop/Project/node_modules/@elastic/elasticsearch/lib/Transport.js:205:13)
    at ClientRequest.<anonymous> (/home/Desktop/Project/node_modules/@elastic/elasticsearch/lib/Connection.js:98:9)
    at ClientRequest.emit (node:events:390:28)
    at TLSSocket.socketErrorListener (node:_http_client:447:9)
    at TLSSocket.emit (node:events:390:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)
</code>```

It was working fine before but I got the mail from firestore that I need to change the security rules. Once I changed the rules after that I started facing the issue next day. I have reverted the rules still its giving the same error.

Current firestore security rules

```<code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
      allow write: if request.auth != null;
    }
  }
}
</code>```

Most strange thing is that it is working fine on production. I am just unable to figure out the error.

I am stuck on this since 2 days. It would be really great if anyone could help.

UPDATE - I found out that I am unable to access the elasticsearch on a particular wifi network, if I am changing the network then I am able to access it. But still the problem remains same that why I am unable to access on a particular network on which I was able to access till yesterday

Body:
I am stuck in a super strange problem.

I am getting ConnectionError: getaddrinfo EAI_AGAIN error when I am trying to access elasticsearch on localhost whereas on production it is working completely fine.

ConnectionError: getaddrinfo EAI_AGAIN <awsHostUrl>
    at onResponse (/home/Desktop/Project/node_modules/@elastic/elasticsearch/lib/Transport.js:205:13)
    at ClientRequest.<anonymous> (/home/Desktop/Project/node_modules/@elastic/elasticsearch/lib/Connection.js:98:9)
    at ClientRequest.emit (node:events:390:28)
    at TLSSocket.socketErrorListener (node:_http_client:447:9)
    at TLSSocket.emit (node:events:390:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

It was working fine before but I got the mail from firestore that I need to change the security rules. Once I changed the rules after that I started facing the issue next day. I have reverted the rules still its giving the same error.

Current firestore security rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read;
      allow write: if request.auth != null;
    }
  }
}

Most strange thing is that it is working fine on production. I am just unable to figure out the error.

I am stuck on this since 2 days. It would be really great if anyone could help.

UPDATE - I found out that I am unable to access the elasticsearch on a particular wifi network, if I am changing the network then I am able to access it. But still the problem remains same that why I am unable to access on a particular network on which I was able to access till yesterday


问:
gradle build failed due to the server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3) PKIX path building failed
I am trying to run gradle build for my project with gradle version 6.9 and zulu 11 but it fails with below error :

```<code>  A problem occurred configuring root project 'Auth-mapper'.
   > Could not resolve all artifacts for configuration ':classpath'.
   > Could not download commons-codec-1.11.jar (commons-codec:commons-codec:1.11)
  > Could not get resource 'https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar'.
     > Could not HEAD 'https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar'.
        > The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/6.9/userguide/build_environment.html#gradle_system_properties
           > PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification
path to requested target
</code>```

I have imported the certificate for https://repo.maven.apache.org/maven2 in cacerts of zulu-11 folder but still this issue is coming up.Also I am setting below properties in gradle.properties :

```<code>systemProp.javax.net.ssl.trustStore=cacerts
systemProp.javax.net.ssl.trustStorePassword=changeit
</code>```

cacerts I copied to root folder of the project where build.gradle file is.

Body:
I am trying to run gradle build for my project with gradle version 6.9 and zulu 11 but it fails with below error :

  A problem occurred configuring root project 'Auth-mapper'.
   > Could not resolve all artifacts for configuration ':classpath'.
   > Could not download commons-codec-1.11.jar (commons-codec:commons-codec:1.11)
  > Could not get resource 'https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar'.
     > Could not HEAD 'https://repo.maven.apache.org/maven2/commons-codec/commons-codec/1.11/commons-codec-1.11.jar'.
        > The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/6.9/userguide/build_environment.html#gradle_system_properties
           > PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification
path to requested target

I have imported the certificate for https://repo.maven.apache.org/maven2 in cacerts of zulu-11 folder but still this issue is coming up.Also I am setting below properties in gradle.properties :

systemProp.javax.net.ssl.trustStore=cacerts
systemProp.javax.net.ssl.trustStorePassword=changeit

cacerts I copied to root folder of the project where build.gradle file is.


问:
d3 transition of opacity for foreignObject does not work on Safari
I'm using D3 to animate some parts of a website.

To make elements appear and disappear, I do it like this:

```<code>trial
.transition()
.duration(1000)
.style("opacity", 0); //disappear
</code>```

and

```<code>trial
.transition()
.duration(1000)
.style("opacity", 1); //appear
</code>```

It appears that this does not work for Safari when using foreignObjects. In the code below, I append "foreignObject" to the group "trial" and then append "xhtml:div" to the "foreignObject".

```<code>    trial = svg.append("g");

    trial
    .append("foreignObject")
    .attr('x', 0)
    .attr('y', 0)
    .attr('width', this.widthValue)
    .attr('height', 800)
    .append("xhtml:div")
    .html(
    `
    <div class="card text-white text-center my-4 py-2" style="background-color: #415C66;">
      <div class="row g-0">
        <div class="col-md-12">
          <div class="card-body">
            This div should appear and disappear and so on...
            <hr>
            <p>Test</p>
          </div>
        </div>
      </div>
    </div>
    `
    );

    ;

    });
</code>```

Then, I animate the group trial like this:

```<code>    trial
    .transition()
    .duration(1000)
    .style("opacity", 1)
    .transition()
    .duration(1000)
    .style("opacity", 0)
    .transition()
    .duration(1000)
    .style("opacity", 1);
</code>```

This code works with Chrome, Firefox and Opera. But someone told me that things look weird on Safari. It appears that the transition does not work when using foreignObject, but it works using other things, for example circles.

If you have Safari, you can see the problem here: https://www.philosophische-insel.ch/static_pages/survival_game4

There you can see how the circle disappears and appears again, but not the div.

Below you can find a GIF that shows how it is supposed to work.

Is there a way to animate foreignObjects that also works in Safari?

Body:
I'm using D3 to animate some parts of a website.

To make elements appear and disappear, I do it like this:

trial
.transition()
.duration(1000)
.style("opacity", 0); //disappear

and

trial
.transition()
.duration(1000)
.style("opacity", 1); //appear

It appears that this does not work for Safari when using foreignObjects. In the code below, I append "foreignObject" to the group "trial" and then append "xhtml:div" to the "foreignObject".

    trial = svg.append("g");

    trial
    .append("foreignObject")
    .attr('x', 0)
    .attr('y', 0)
    .attr('width', this.widthValue)
    .attr('height', 800)
    .append("xhtml:div")
    .html(
    `

            This div should appear and disappear and so on...

Test

    `
    );

    ;

    });

Then, I animate the group trial like this:

    trial
    .transition()
    .duration(1000)
    .style("opacity", 1)
    .transition()
    .duration(1000)
    .style("opacity", 0)
    .transition()
    .duration(1000)
    .style("opacity", 1);

This code works with Chrome, Firefox and Opera. But someone told me that things look weird on Safari. It appears that the transition does not work when using foreignObject, but it works using other things, for example circles.

If you have Safari, you can see the problem here: https://www.philosophische-insel.ch/static_pages/survival_game4

There you can see how the circle disappears and appears again, but not the div.

Below you can find a GIF that shows how it is supposed to work.

Is there a way to animate foreignObjects that also works in Safari?


问:
Set "Select All Items" - Text of PrimeVue Multiselect
PrimeVue lets you add an Header to the Multiselect.
This is then displayed above the Checkbox to select all Items.

The CSS Solution for this would be something like this

```<code>div.customClassName .p-multiselect-header .p-checkbox::after {
  content: "Select all Items";
}
</code>```

but this does this does not look nice enough.

Is there a way to display a nice Label for the "Select All" Checkbox?

Body:
PrimeVue lets you add an Header to the Multiselect.
This is then displayed above the Checkbox to select all Items.

The CSS Solution for this would be something like this

div.customClassName .p-multiselect-header .p-checkbox::after {
  content: "Select all Items";
}

but this does this does not look nice enough.

Is there a way to display a nice Label for the "Select All" Checkbox?


问:
Failed to set remote answer sdp: A BUNDLE group contains a MID='' matching no m= section
I am trying to send video from raspberry pi to website using WebRTC. raspberrypi side using libary aiortc in python create answer and send to website but i got this error:

"Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: A BUNDLE group contains a MID='' matching no m= section.".

I do not understand what the problem is.

This is the process

web create offer --> web setlocaldecription(offer) and send to raspberry pi --> raspberry pi get offer from web and setRemotedecription(offer) --> raspberry create answer and setlocaldescription(answer) --> send answer to website --> website get answer and setRemoteDescription(I got this error)

my website create offer and send to raspberry pi
offer sdp:"v=0\r\no=- 7829234644314238351 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\n" type:"offer"

raspberry pi creates answer

answer sdp:"v=0\r\no=- 3882080493 3882080493 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE \r\na=msid-semantic:WMS *\r\n" type:"answer"

In my case. I try set bundlePolicy is 'balanced' and sdpSementics is 'plan-b' on website but rapberry pi havne't set.

```<code>const iceConfiguration =
  {
    bundlePolicy: 'balanced',
    sdpSemantics:'plan-b',
    iceServers: [
        {
            urls: 'stun:stun.l.google.com:19302'
        }
    ]
  }

//peerconnect STUN and TURN server
pc = new RTCPeerConnection(iceConfiguration);
</code>```

but I get the same error. I expect that the programme can setRemotedescription(answer) and send video and audio from raspberry pi to website.

Body:
I am trying to send video from raspberry pi to website using WebRTC. raspberrypi side using libary aiortc in python create answer and send to website but i got this error:

"Uncaught (in promise) DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: A BUNDLE group contains a MID='' matching no m= section.".

I do not understand what the problem is.

This is the process

web create offer --> web setlocaldecription(offer) and send to raspberry pi --> raspberry pi get offer from web and setRemotedecription(offer) --> raspberry create answer and setlocaldescription(answer) --> send answer to website --> website get answer and setRemoteDescription(I got this error)

my website create offer and send to raspberry pi
offer sdp:"v=0\r\no=- 7829234644314238351 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\n" type:"offer"

raspberry pi creates answer

answer sdp:"v=0\r\no=- 3882080493 3882080493 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\na=group:BUNDLE \r\na=msid-semantic:WMS *\r\n" type:"answer"

In my case. I try set bundlePolicy is 'balanced' and sdpSementics is 'plan-b' on website but rapberry pi havne't set.

const iceConfiguration =
  {
    bundlePolicy: 'balanced',
    sdpSemantics:'plan-b',
    iceServers: [
        {
            urls: 'stun:stun.l.google.com:19302'
        }
    ]
  }

//peerconnect STUN and TURN server
pc = new RTCPeerConnection(iceConfiguration);

but I get the same error. I expect that the programme can setRemotedescription(answer) and send video and audio from raspberry pi to website.


问:
Visual Studio Code misbehaving with Flutter
When I try to edit a flutter project like a dart file my vs code is not working properly sometimes it keeps undoing my writing
Like when I try to add a new line (hit enter)it brings back the cursor to previous line
Or when try to hit space after a keyword it won't allow that it keeps deleting the space after writing the Any other letter after keyword I am able to put a space

I tried to explain my problem as much as i could do anyone know the solution

My extensions are up to date this only happens in flutter projects other languages have no problem


问:
Is offline support required for PWA or just a recommendation?
While working on adding PWA functionality in a Next JS mono repo, I'm getting this error, from the error it looks like offline support is missing.

However, I created one dummy app https://test-repo-rishab1207.vercel.app/ where I didn't added any offline support but PWA functionality was still enabled. And in the documentation https://web.dev/install-criteria/#criteria it isn't mentioned that we require offline support. So, why I'm even getting this error?


问:
What will One of or Any of Object type will do in a Json schema
I am defining an API Spec:

If i define Type as One off or Any off? what will happen?

Under data -> I will have 3 sub objects. I want any one of the three objects at any given point in time? Can i use this functionality one of or any off to achieve this use case?

Under data -> I will have 3 sub objects. I want any one of the three objects at any given point in time? Can i use this functionality one of or any off to achieve this use case?


问:
How to interrupt/abort a 3rd party synchronous script using JavaScript
I have a 3rd party script that must remain synchronous, but I'm looking for a way to abort out of it and continue rendering the rest of the page if it takes too long to run.

I've explored using setTimeout to remove the script after a certain period of time, but the execution of the callback is delayed until the script has run so it doesn't help.


问:
Can you mock asynchronous calls with JustMock Lite?
Can you mock asynchronous calls with the nuget JustMock Lite (the free version) from Telerick?

We tried to mock the result of an asynchronous call that returned Task but we get an error that specifies that we need to use the payed version. (Telerik.JustMock.Core.ElevatedMockingException: Cannot mock 'Task')


问:
How can i stop reading "Direct touch area. Use the rotor to enable direct touch for this app" in our iOS app accessibility?
When the voice-over is ON, I am always hearing this "Direct touch area. Use the rotor to enable direct touch for this app". How can I get rid of this, this is so much annoying to the end users.

I have found this but does not help.

https://developer.apple.com/forums/thread/663529