问:
How to refer to the dead letter queue created in cloud formation template in another aws account using serverless?
Serverless_resources.yml :

service: alerts14-filter-lambda

provider:
name: aws
region: eu-central-1
profile: ${self:custom.common.profile.${opt:stage}}

resources:
Resources:

```<code>DeadLetterQueue:
  Type: AWS::SQS::Queue
  Properties:
    QueueName: DLQ-Alert-Filter
    DelaySeconds: 5
    MaximumMessageSize: 2048
    MessageRetentionPeriod: 20000
    ReceiveMessageWaitTimeSeconds: 10
    VisibilityTimeout: 120
</code>```

Outputs:

```<code>Dlq:
  Value:
    'Fn::GetAtt': [ DeadLetterQueue , Arn ]
    #!Ref DeadLetterQueue.QueueName
  Export:
    Name: alert-filter-${opt:stage}-DLQ

DlqUrl:
  Value:
    'Fn::GetAtt': [ DeadLetterQueue , QueueUrl ]
    #!Ref DeadLetterQueue.QueueName
  Export:
    Name: alert-filter-${opt:stage}-DLQ-Url
</code>```

Serverless.yml :

service: alerts11-filter-lambda

provider:
name: aws
region: eu-central-1
runtime: python3.9

functions:
lambdaalertfilter:
name: alert_filter_lambda
handler: alert_filter/handler/alert_filter.lambda_handler
#role: ${self:custom.custom.role.${opt:stage}}
layers:
#- ${cf:lambdaalertfilter-${opt:stage}.TestLayerExport}
- !Ref TestLambdaLayer
events:
- sns:
arn: ${self:custom.common.sns.arn.${opt:stage}}

```<code>      redrivePolicy:
        deadLetterTargetArn:
          ${cf:alerts14-filter-lambda-falcon.Dlq}
</code>```

At the last line its throwing error.

Error:
Cannot resolve serverless.yml: Variables resolution errored with:

Cannot resolve variable at "functions.lambdaalertfilter.events.0.sns.redrivePolicy.deadLetterTargetArn": Value not found at "cf" source

I am using below command to deploy 2 files one after another :

serverless deploy -c serverless_resources.yml --stage dev1 && serverless deploy -c serverless.yml --stage dev2

Not able to refer to cloud formation template created in another account.

Body:
Serverless_resources.yml :

service: alerts14-filter-lambda

provider:
name: aws
region: eu-central-1
profile: ${self:custom.common.profile.${opt:stage}}

resources:
Resources:

DeadLetterQueue:
  Type: AWS::SQS::Queue
  Properties:
    QueueName: DLQ-Alert-Filter
    DelaySeconds: 5
    MaximumMessageSize: 2048
    MessageRetentionPeriod: 20000
    ReceiveMessageWaitTimeSeconds: 10
    VisibilityTimeout: 120

Outputs:

Dlq:
  Value:
    'Fn::GetAtt': [ DeadLetterQueue , Arn ]
    #!Ref DeadLetterQueue.QueueName
  Export:
    Name: alert-filter-${opt:stage}-DLQ

DlqUrl:
  Value:
    'Fn::GetAtt': [ DeadLetterQueue , QueueUrl ]
    #!Ref DeadLetterQueue.QueueName
  Export:
    Name: alert-filter-${opt:stage}-DLQ-Url

Serverless.yml :

service: alerts11-filter-lambda

provider:
name: aws
region: eu-central-1
runtime: python3.9

functions:
lambdaalertfilter:
name: alert_filter_lambda
handler: alert_filter/handler/alert_filter.lambda_handler
#role: ${self:custom.custom.role.${opt:stage}}
layers:
#- ${cf:lambdaalertfilter-${opt:stage}.TestLayerExport}
- !Ref TestLambdaLayer
events:
- sns:
arn: ${self:custom.common.sns.arn.${opt:stage}}

      redrivePolicy:
        deadLetterTargetArn:
          ${cf:alerts14-filter-lambda-falcon.Dlq}

At the last line its throwing error.

Error:
Cannot resolve serverless.yml: Variables resolution errored with:

Cannot resolve variable at "functions.lambdaalertfilter.events.0.sns.redrivePolicy.deadLetterTargetArn": Value not found at "cf" source

I am using below command to deploy 2 files one after another :

serverless deploy -c serverless_resources.yml --stage dev1 && serverless deploy -c serverless.yml --stage dev2

Not able to refer to cloud formation template created in another account.


来源: stackexchange

问:
How to reduce size of Tooltips on Pygal?
I am creating a World Map, where you can hover over countries and click on their tooltips to link to a seperate website with more information on them. The problem is, I find the tooltips are too big, and get in the way. How do I resolve this issue?

I tried using the tooltip_font_size command to control it, but it just does not seem to make a difference. I get the same size of the Tooltips and the text inside them no matter what value I put in there. All the tooltip_border_radius command does is change how round the borders of my tooltips are. I am quite lost here, what do I do?

This is the code I have for now, I am excluding the added portion ( myworldmap.add) since it is unnecessary here.

```<code>import pygal
myworldmap = pygal.maps.world.World() #Defining our world map
myworldmap.title = 'Our friends origins'

myworldmap.tooltip_font_size = 15 #fontsize control
myworldmap.tooltip_border_radius = 5 #bordersize control

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am creating a World Map, where you can hover over countries and click on their tooltips to link to a seperate website with more information on them. The problem is, I find the tooltips are too big, and get in the way. How do I resolve this issue?

I tried using the tooltip_font_size command to control it, but it just does not seem to make a difference. I get the same size of the Tooltips and the text inside them no matter what value I put in there. All the tooltip_border_radius command does is change how round the borders of my tooltips are. I am quite lost here, what do I do?

This is the code I have for now, I am excluding the added portion ( myworldmap.add) since it is unnecessary here.

import pygal
myworldmap = pygal.maps.world.World() #Defining our world map
myworldmap.title = 'Our friends origins'

myworldmap.tooltip_font_size = 15 #fontsize control
myworldmap.tooltip_border_radius = 5 #bordersize control


问:
How to map unknown xml structure to java object using jaxb? eg.In three level xml structure: level-1 tag known, level-2 tag unknown, level-3 tag known
I am having below xml structure. And need to unmarshall using JAXB.

`

```<code><Rule>
  <RuleNumber>5001</RuleNumber>
  **<RuleA>**
       <Match> some text-1 </Match>
       <Ignore> some text-2 </Ignore>
       <MatchWord> some text-3 </MatchWord>
  **</RuleA>**

  **<RuleB>**
       <Ignore> some text-4 </Ignore>
       <MatchWord> some text-5 </MatchWord>
  **</RuleB>**
</Rule>`
</code>```

In  the above xml , in level 1 <Rule> tag is there. It is known before unmarshalling.

In level -2 , <RuleNumber> , <RuleA> , <RuleB> tags are there. In this level-2 the Tag <RuleNumber> is known before unmarshalling but the other two tag's names are not known. i.e. <RuleA>, <RuleB> tags are not known before unmarshalling. And one more thing instead of <RuleA> or <RuleB> , the name of these tags may be any name. It may be <RuleC> or <RuleZ> or even <Rule101>, <Rule102>, <RuleA1> , <RuleZ1> etc.

In level-3 , <Match> , <Ignore>, <MatchWord> tags are there. Theses are known tags before unmarshalling.

I want to unmarshall this xml using jaxb . Here the name of the tag <RuleA> , <RuleB> are not known , the name can be anything. So how to write a class to map this kind of xml structure?. And subsequently needed to unmarshalling the data.

Is it possible to handle this scenario using JAXB ?

I know to write code for simple unknown type using  @xmlAnyElement, i.e. if unknown tags are not having any child elements.  But don't know how to approach this complex type. In my case the unknown tags having child tags.

```<code></code>```

Body:
I am having below xml structure. And need to unmarshall using JAXB.

`

<Rule>
  <RuleNumber>5001</RuleNumber>
  **<RuleA>**
       <Match> some text-1 </Match>
       <Ignore> some text-2 </Ignore>
       <MatchWord> some text-3 </MatchWord>
  **</RuleA>**

  **<RuleB>**
       <Ignore> some text-4 </Ignore>
       <MatchWord> some text-5 </MatchWord>
  **</RuleB>**
</Rule>`

In  the above xml , in level 1 <Rule> tag is there. It is known before unmarshalling.

In level -2 , <RuleNumber> , <RuleA> , <RuleB> tags are there. In this level-2 the Tag <RuleNumber> is known before unmarshalling but the other two tag's names are not known. i.e. <RuleA>, <RuleB> tags are not known before unmarshalling. And one more thing instead of <RuleA> or <RuleB> , the name of these tags may be any name. It may be <RuleC> or <RuleZ> or even <Rule101>, <Rule102>, <RuleA1> , <RuleZ1> etc.

In level-3 , <Match> , <Ignore>, <MatchWord> tags are there. Theses are known tags before unmarshalling.

I want to unmarshall this xml using jaxb . Here the name of the tag <RuleA> , <RuleB> are not known , the name can be anything. So how to write a class to map this kind of xml structure?. And subsequently needed to unmarshalling the data.

Is it possible to handle this scenario using JAXB ?

I know to write code for simple unknown type using  @xmlAnyElement, i.e. if unknown tags are not having any child elements.  But don't know how to approach this complex type. In my case the unknown tags having child tags.


问:
How to draw a pushbutton to a tableview cell?
I'm new to PySide6.
I have a table and display it with a QTableView. And my data was put into a QAbstractTableModel. like this

class MyTableModel(QAbstractTableModel):
    ...

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.table_view = QTableView()
        self.model = MyTableModel()
        self.table_view.setModel(self.model)
```
<p>Now, I want to add a <code>delete</code> button for each row to delete the related data.</p>
<p>After some searching, I know I should use <code>QStyledItemDelegate</code> but I was stuck at the <code>paint</code> method and have no idea of how to handle the click signal.</p>
<pre class="lang-py prettyprint-override"><code>class RefreshButtonDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self, painter: PySide6.QtGui.QPainter, option: PySide6.QtWidgets.QStyleOptionViewItem,
              index: Union[PySide6.QtCore.QModelIndex, PySide6.QtCore.QPersistentModelIndex]) -> None:
        # if last column
        if index.column() == index.model().columnCount() - 1:
            print(index.column())
            print('draw')
            btn = QtWidgets.QPushButton(text='delete')
            print(index.model().data(index))
        super().paint(painter, option, index)
</code>```

What should I do then?

Body:
I'm new to PySide6.
I have a table and display it with a QTableView. And my data was put into a QAbstractTableModel. like this

class MyTableModel(QAbstractTableModel):
    ...

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.table_view = QTableView()
        self.model = MyTableModel()
        self.table_view.setModel(self.model)

Now, I want to add a delete button for each row to delete the related data.

After some searching, I know I should use QStyledItemDelegate but I was stuck at the paint method and have no idea of how to handle the click signal.

class RefreshButtonDelegate(QtWidgets.QStyledItemDelegate):
    def paint(self, painter: PySide6.QtGui.QPainter, option: PySide6.QtWidgets.QStyleOptionViewItem,
              index: Union[PySide6.QtCore.QModelIndex, PySide6.QtCore.QPersistentModelIndex]) -> None:
        # if last column
        if index.column() == index.model().columnCount() - 1:
            print(index.column())
            print('draw')
            btn = QtWidgets.QPushButton(text='delete')
            print(index.model().data(index))
        super().paint(painter, option, index)

What should I do then?


问:
Adding prebuilt native libraries to Android Studio project
I am currently working on a wearOS app written in Kotlin that needs to consume a native library.
I have cloned the library from github and built it. The output consists of a libs folder with 4 different subfolders containing .so files for the different ABIs and a java folder with two java classes to interact with the library.

I have been reading the android docs but I still can't figure out how I need to import these files in my project to actually use the library. I don't have a lot of experience in android development, could anybody explain to me wat to do or just point me to the right docs/integration guide?


问:
Rider fails to attach the debugger to the C# Interactive
I have a problem with attaching debugger to the C# Interactive window in Rider. In the C# Interactive window I am clicking the "Attach debugger" button:

I get the message, that the debugger is  attached to process, but after a while I get timeout error with the message, that the debugger failed to attach to the process:

Why I am getting this error? I am using Rider version 2022.2.4.


问:
Applying BiFunction to keys and values of Map<Integer, Set<Integer>> using Stream
I am struggling when it comes to using Stream on a Map with a Set. I have a method with two arguments as BiFunction<Integer, Integer, Integer> keyFunction and BiFunction<Integer, Integer, Integer> valFunction. I would like to use Stream that takes in the key from the Map(Integer) and the value(Set) and apply the function keyFunction to each of the keys (Integer) and each values within each set (Integer) and also apply the function valFunction to each of the values within the set taking in the key and the value Integers. I want it to return a new Map<Integer, Set<Integer>> after applying the keyFunction and valFunction.

Here is an example of what I am trying to accomplish:

```<code>map (Map<Integer, Set<Integer>>):
2 -> {4, 5, 6},
5 -> {2, 3, 4};

(key, value) -> (2, 4), (2, 5), (2, 6), (5, 2), (5, 3), (5, 4)

keyFunction: key, val -> key + val + 2
valFunction: key, val -> key * val - 2

newMap(Map<Integer, Set<Integer>>):
8 -> {6},
9 - {8},
10 -> {10, 13},
11 -> {18}
(key, value) -> (8(2 + 4 + 2), 6(2 * 4 - 2)), (9, 8), (10, 10), (9, 8), (10, 13), (11, 18)
</code>```

Thank you!

My biggest struggle with this is having to consider both the keys and each of the values simultaneously, instead of Streaming the keys and values separately, as the BiFunction uses the values from both the keys and the values. Furthermore, this whole method is to be done within a single Stream without creating a new Map of Set outside of the Stream.

Body:
I am struggling when it comes to using Stream on a Map with a Set. I have a method with two arguments as BiFunction<Integer, Integer, Integer> keyFunction and BiFunction<Integer, Integer, Integer> valFunction. I would like to use Stream that takes in the key from the Map(Integer) and the value(Set) and apply the function keyFunction to each of the keys (Integer) and each values within each set (Integer) and also apply the function valFunction to each of the values within the set taking in the key and the value Integers. I want it to return a new Map<Integer, Set<Integer>> after applying the keyFunction and valFunction.

Here is an example of what I am trying to accomplish:

map (Map<Integer, Set<Integer>>):
2 -> {4, 5, 6},
5 -> {2, 3, 4};

(key, value) -> (2, 4), (2, 5), (2, 6), (5, 2), (5, 3), (5, 4)

keyFunction: key, val -> key + val + 2
valFunction: key, val -> key * val - 2

newMap(Map<Integer, Set<Integer>>):
8 -> {6},
9 - {8},
10 -> {10, 13},
11 -> {18}
(key, value) -> (8(2 + 4 + 2), 6(2 * 4 - 2)), (9, 8), (10, 10), (9, 8), (10, 13), (11, 18)

Thank you!

My biggest struggle with this is having to consider both the keys and each of the values simultaneously, instead of Streaming the keys and values separately, as the BiFunction uses the values from both the keys and the values. Furthermore, this whole method is to be done within a single Stream without creating a new Map of Set outside of the Stream.


问:
Is there any way to clear the .Net string intern pool?
I have an application that, over time, adds more and more strings into the string intern pool. The interned strings are added by various libraries (not necessarily mine), so I can't control the amount of string being added. The application's private bytes seem to grow at about 5 GB per 24 hours. Memory profiling shown that the strings being held are held by the intern pool (no other reference to them).

Is there a way to periodically empty the intern pool every X hours?

I would like to emphasize that the memory growth occurs because of the interned string pool growth. To verify this I have written the following simple program:

```<code>static void Main(string[] args)
    {
        for (int i = 0; i < 100000; i++)
        {
            string str = i.ToString().PadLeft(1000);
            string.Intern(str);
        }

        Console.WriteLine("all strings interned");
        Console.ReadLine();
    }
</code>```

That quickly grows the memory to 200MB, and remains constant at that size until closed (even though the interned strings have no reference other than the interned string pool).

Body:
I have an application that, over time, adds more and more strings into the string intern pool. The interned strings are added by various libraries (not necessarily mine), so I can't control the amount of string being added. The application's private bytes seem to grow at about 5 GB per 24 hours. Memory profiling shown that the strings being held are held by the intern pool (no other reference to them).

Is there a way to periodically empty the intern pool every X hours?

I would like to emphasize that the memory growth occurs because of the interned string pool growth. To verify this I have written the following simple program:

static void Main(string[] args)
    {
        for (int i = 0; i < 100000; i++)
        {
            string str = i.ToString().PadLeft(1000);
            string.Intern(str);
        }

        Console.WriteLine("all strings interned");
        Console.ReadLine();
    }

That quickly grows the memory to 200MB, and remains constant at that size until closed (even though the interned strings have no reference other than the interned string pool).


问:
Not getting the table data with table header in proper format in Laravel 'friendofphp/goutte' web-scraping
```<code>$client = new Client();

$crawler = $client->request('GET', 'https://scholar.google.com/citations?user=EnegzCwAAAAJ&hl=en&oi=ao');
$crawler->filter('#gsc_a_t')->each(function ($item) {
    $header = $item->filter('th')->first();
    $data = $item->filter('td')->first();
    $this->results[$header->text()] = $item->filter('td')->first()->text();

    dd($item->filter('#gsc_a_b')->text());
});
</code>```

Getting the data in a clumsy format and I wanted to print whole table data in exact format as its shown on the website with the links on it. I searched a lot but didn't find any solution.

I want to store tr in tr[] td in td[] and tabledatalinks in tdlink[] and then just display the exact format as its shown in my view.

Body:
$client = new Client();

$crawler = $client->request('GET', 'https://scholar.google.com/citations?user=EnegzCwAAAAJ&hl=en&oi=ao');
$crawler->filter('#gsc_a_t')->each(function ($item) {
    $header = $item->filter('th')->first();
    $data = $item->filter('td')->first();
    $this->results[$header->text()] = $item->filter('td')->first()->text();

    dd($item->filter('#gsc_a_b')->text());
});

Getting the data in a clumsy format and I wanted to print whole table data in exact format as its shown on the website with the links on it. I searched a lot but didn't find any solution.

I want to store tr in tr[] td in td[] and tabledatalinks in tdlink[] and then just display the exact format as its shown in my view.


问:
How to use a custom asset image as a navigation bar in flutter
how to use an image that I design  and use it as the navigation UI image Design bar in my flutter project?

i would like to put this image as shown about at the bottom of the screen where the bottom nav bar should be

but the problem is it has a white space around it, I have search for something similar with other questions that has been answered but haven't seen a solution for this.

```<code>import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(
              "assets/images/bg.png",
            ),
            fit: BoxFit.cover,
          ),
        ),
        child: Center(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 250),
                child: Container(
                  height: 200,
                  width: 200,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                        "assets/images/logo.png",
                      ),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: IconButton(
                  icon: Image.asset('assets/images/google_signin.png'),
                  iconSize: 200,
                  onPressed: () {},
                ),
              ),
              Image(image: Image.asset('assets/images/bottom_bar'),
              position: Bottom)
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

Body:
how to use an image that I design  and use it as the navigation UI image Design bar in my flutter project?

i would like to put this image as shown about at the bottom of the screen where the bottom nav bar should be

but the problem is it has a white space around it, I have search for something similar with other questions that has been answered but haven't seen a solution for this.

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage(
              "assets/images/bg.png",
            ),
            fit: BoxFit.cover,
          ),
        ),
        child: Center(
          child: Column(
            children: [
              Padding(
                padding: const EdgeInsets.only(top: 250),
                child: Container(
                  height: 200,
                  width: 200,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(
                        "assets/images/logo.png",
                      ),
                    ),
                  ),
                ),
              ),
              Expanded(
                child: IconButton(
                  icon: Image.asset('assets/images/google_signin.png'),
                  iconSize: 200,
                  onPressed: () {},
                ),
              ),
              Image(image: Image.asset('assets/images/bottom_bar'),
              position: Bottom)
            ],
          ),
        ),
      ),
    );
  }
}


问:
Why can't I enter USART3_IRQHandler?
```<code>#if EN_USART2
u16 _distance1=0;
u16 distance1=0;

void USART2_Init(u32 bound) {
  GPIO_InitTypeDef GPIO_InitStructure;
  USART_InitTypeDef USART_InitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  USART_InitStructure.USART_BaudRate = bound;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_Init(USART2, &USART_InitStructure);
  USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
  USART_Cmd(USART2, ENABLE);
}

void USART2_IRQHandler(void){
  u8 a;
  if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET){
    a =USART_ReceiveData(USART2);
        if(a!=0xa5) _distance1=(_distance1<<8)|a;
        else
        {
            distance1=_distance1;
            _distance1=0;
        }
  }
}
#endif

#if EN_USART3
u16 _distance2=0;
u16 distance2=0;

void USART3_Init(u32 bound) {
  GPIO_InitTypeDef GPIO_InitStructure;
  USART_InitTypeDef USART_InitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  USART_InitStructure.USART_BaudRate = bound;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_Init(USART3, &USART_InitStructure);
  USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
  USART_Cmd(USART3, ENABLE);
}

void USART3_IRQHandler(void){
  u8 a;
  if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET){
    a =USART_ReceiveData(USART3);
        if(a!=0xa5) _distance2=(_distance2<<8)|a;
        else
        {
            distance2=_distance2;
            _distance2=0;
        }
  }
}
#endif
</code>```

This is part of the code of usart.c. EN_USART2 and EN_USART3 are all 1. main.c is as follows:

```<code>#include "stm32f10x.h"
#include "delay.h"
#include "system.h"
#include "usart.h"
// Device header
int main(void)
{
    SystemInit();
    USART1_Init(115200);
    USART2_Init(115200);
    USART3_Init(115200);
    while(1)
    {
        printf("difference: %dmm\r\n",distance1-distance2);
        delay_ms(100);
    }
}

</code>```

It runs on STM32F103C8T6. PA2 and PA3 connects to an ultrasound module, and PB10 and PB11 connects to another ultrasound module. I found that the interruption service function of USART2 can be implemented, but that of USART3 cannot. Why is that? USART3 and USART2 are all written similarly. (As for how do I know that USART2 doesn't work: I added printf("p") behind a =USART_ReceiveData(USART3);, but I didn't see any "p" on the serial debug window(however, messages printed in main() all displayed well, which means that USART1 is normal).

I searched for the template code, but I can't find anything wrong in my own code.

Title: Why can't I enter USART3_IRQHandler?

Body:
#if EN_USART2
u16 _distance1=0;
u16 distance1=0;

void USART2_Init(u32 bound) {
  GPIO_InitTypeDef GPIO_InitStructure;
  USART_InitTypeDef USART_InitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

  NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  USART_InitStructure.USART_BaudRate = bound;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_Init(USART2, &USART_InitStructure);
  USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);
  USART_Cmd(USART2, ENABLE);
}

void USART2_IRQHandler(void){
  u8 a;
  if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET){
    a =USART_ReceiveData(USART2);
        if(a!=0xa5) _distance1=(_distance1<<8)|a;
        else
        {
            distance1=_distance1;
            _distance1=0;
        }
  }
}
#endif

#if EN_USART3
u16 _distance2=0;
u16 distance2=0;

void USART3_Init(u32 bound) {
  GPIO_InitTypeDef GPIO_InitStructure;
  USART_InitTypeDef USART_InitStructure;
  NVIC_InitTypeDef NVIC_InitStructure;
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
  RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;
  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  NVIC_Init(&NVIC_InitStructure);

  USART_InitStructure.USART_BaudRate = bound;
  USART_InitStructure.USART_WordLength = USART_WordLength_8b;
  USART_InitStructure.USART_StopBits = USART_StopBits_1;
  USART_InitStructure.USART_Parity = USART_Parity_No;
  USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
  USART_Init(USART3, &USART_InitStructure);
  USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);
  USART_Cmd(USART3, ENABLE);
}

void USART3_IRQHandler(void){
  u8 a;
  if(USART_GetITStatus(USART3, USART_IT_RXNE) != RESET){
    a =USART_ReceiveData(USART3);
        if(a!=0xa5) _distance2=(_distance2<<8)|a;
        else
        {
            distance2=_distance2;
            _distance2=0;
        }
  }
}
#endif

This is part of the code of usart.c. EN_USART2 and EN_USART3 are all 1. main.c is as follows:

#include "stm32f10x.h"
#include "delay.h"
#include "system.h"
#include "usart.h"
// Device header
int main(void)
{
    SystemInit();
    USART1_Init(115200);
    USART2_Init(115200);
    USART3_Init(115200);
    while(1)
    {
        printf("difference: %dmm\r\n",distance1-distance2);
        delay_ms(100);
    }
}

It runs on STM32F103C8T6. PA2 and PA3 connects to an ultrasound module, and PB10 and PB11 connects to another ultrasound module. I found that the interruption service function of USART2 can be implemented, but that of USART3 cannot. Why is that? USART3 and USART2 are all written similarly. (As for how do I know that USART2 doesn't work: I added printf("p") behind a =USART_ReceiveData(USART3);, but I didn't see any "p" on the serial debug window(however, messages printed in main() all displayed well, which means that USART1 is normal).

I searched for the template code, but I can't find anything wrong in my own code.


问:
Python dataclass evaluating type-hinted Dict fields
I am wondering what the right way to evaluate a python dataclass field type is? In particular, with Dict field types which have their key/values types specified in the dataclass; is there a way to evaluate the field's .type against a un-typed Dict (ie: catch all Dicts, regardless of key/value type)?

In the example below, a simple dataclass with two fields is created and type hinted.

# -*- Python Version: 3.7 -*-
from dataclasses import dataclass, field, fields
from typing import Dict

@dataclass
class Example:
    attr_dict_a: Dict[str, int] = field(default_factory=dict)
    attr_dict_b: Dict[int, int] = field(default_factory=dict)

```
<p>Then: is there a way to iterate over the fields and evaluate which field is a <code>Dict</code> type, but ignoring the key/value types?</p>
<pre class="lang-py prettyprint-override"><code>x = Example({"1":1}, {1:1})

# Try and evaluate field.type against an untyped Dict:
for field in fields(x):
    print(field.name, field.type, field.type == Dict)
# >>> attr_dict_a typing.Dict[str, int] False
# >>> attr_dict_b typing.Dict[int, int] False

# Try and evaluate field.type against a typed Dict:
for field in fields(x):
    print(field.name, field.type, field.type == Dict[str, int])
# >>> attr_dict_a typing.Dict[str, int] True #<----- Works if you specify the key/value types
# >>> attr_dict_b typing.Dict[int, int] False
</code>```

If I would like to just do something each time I encounter any Dict (regardless of the key/value type-hints), what would be the proper way to do that evaluation?

Body:
I am wondering what the right way to evaluate a python dataclass field type is? In particular, with Dict field types which have their key/values types specified in the dataclass; is there a way to evaluate the field's .type against a un-typed Dict (ie: catch all Dicts, regardless of key/value type)?

In the example below, a simple dataclass with two fields is created and type hinted.

# -*- Python Version: 3.7 -*-
from dataclasses import dataclass, field, fields
from typing import Dict

@dataclass
class Example:
    attr_dict_a: Dict[str, int] = field(default_factory=dict)
    attr_dict_b: Dict[int, int] = field(default_factory=dict)

Then: is there a way to iterate over the fields and evaluate which field is a Dict type, but ignoring the key/value types?

x = Example({"1":1}, {1:1})

# Try and evaluate field.type against an untyped Dict:
for field in fields(x):
    print(field.name, field.type, field.type == Dict)
# >>> attr_dict_a typing.Dict[str, int] False
# >>> attr_dict_b typing.Dict[int, int] False

# Try and evaluate field.type against a typed Dict:
for field in fields(x):
    print(field.name, field.type, field.type == Dict[str, int])
# >>> attr_dict_a typing.Dict[str, int] True #<----- Works if you specify the key/value types
# >>> attr_dict_b typing.Dict[int, int] False

If I would like to just do something each time I encounter any Dict (regardless of the key/value type-hints), what would be the proper way to do that evaluation?


问:
Accessing Vendor Payment Apply records from Transaction table via SuiteQL in Netsuite
I wanted to access Vendor Payment Apply records on the Vendor Bill Payment Record. The challenge I'm facing here is that Vendor Payment record is of type Transaction, so we can put a where condition to filter out those records, but I'm not able to figure out how to get the Vendor Payment Apply records. Basically here's something I want to achieve, something on the lines of this query:</p>
```<code>select * from transaction as t
join
    VendorPaymentApply as vpa on t.refNum = vpa.refNum  // need to find a way to access this table
where
    t.type = 'vendorPayment'
    and t.date BETWEEN (x, y)
</code>```

Body:
I wanted to access Vendor Payment Apply records on the Vendor Bill Payment Record. The challenge I'm facing here is that Vendor Payment record is of type Transaction, so we can put a where condition to filter out those records, but I'm not able to figure out how to get the Vendor Payment Apply records. Basically here's something I want to achieve, something on the lines of this query:

select * from transaction as t
join
    VendorPaymentApply as vpa on t.refNum = vpa.refNum  // need to find a way to access this table
where
    t.type = 'vendorPayment'
    and t.date BETWEEN (x, y)


问:
Can't get serilog to log to sqlserver
Help

Why can't I get serilog to log to sqlserver
I have used forever to get this to work

It logs fine to the console
I have installed the nuget packages

Serilog
Serilog.Sinks.Console
Serilog.Sinks.MSSqlServer

//First a quick test if the connection string works (db can open, and if the table exists, it works but no rows

```<code>
var connection = new ConnectionStringSettings();
connection.ConnectionString = "Data Source=server-name;Initial Catalog=db-name;Persist Security Info=True;User ID=user-name;Password='password-name'";
var sqlc = new SqlConnection(connection.ConnectionString);
string query = "select * from LogEvents";

sqlc.Open();
using (var command = new SqlCommand(query, sqlc))
{
    var reader = command.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
        }
    }
    reader.Close();
}
sqlc.Close();

var log = new LoggerConfiguration()
.WriteTo
.MSSqlServer(
connectionString: connection.ConnectionString,
sinkOptions: new MSSqlServerSinkOptions { TableName = "LogEvents", AutoCreateSqlTable = true }
)
.WriteTo.Console()
.CreateLogger();

Log.Logger = log;
Log.Information("123");
Log.CloseAndFlush();
Console.WriteLine("Hello, World!");
</code>```

Title: Can't get serilog to log to sqlserver

Body:
Help

Why can't I get serilog to log to sqlserver
I have used forever to get this to work

It logs fine to the console
I have installed the nuget packages

Serilog
Serilog.Sinks.Console
Serilog.Sinks.MSSqlServer

//First a quick test if the connection string works (db can open, and if the table exists, it works but no rows

var connection = new ConnectionStringSettings();
connection.ConnectionString = "Data Source=server-name;Initial Catalog=db-name;Persist Security Info=True;User ID=user-name;Password='password-name'";
var sqlc = new SqlConnection(connection.ConnectionString);
string query = "select * from LogEvents";

sqlc.Open();
using (var command = new SqlCommand(query, sqlc))
{
    var reader = command.ExecuteReader();

    if (reader.HasRows)
    {
        while (reader.Read())
        {
        }
    }
    reader.Close();
}
sqlc.Close();

var log = new LoggerConfiguration()
.WriteTo
.MSSqlServer(
connectionString: connection.ConnectionString,
sinkOptions: new MSSqlServerSinkOptions { TableName = "LogEvents", AutoCreateSqlTable = true }
)
.WriteTo.Console()
.CreateLogger();

Log.Logger = log;
Log.Information("123");
Log.CloseAndFlush();
Console.WriteLine("Hello, World!");


问:
how to do a refresh button on "an error has occurred " page ? flutter
i am trying to add a refresh button on a page that will appear if an error has occurred , but i want it to refresh the previous page which the error has occurred on

so first i created two stateful widgets one for operation succeeded and the other is when the operation fail , and created button on each one
if succeeded will transfer the user the the next page
if fail it supposed to refresh the previous page and go back to it

i need help with the refresh buttton is there a way to do it ?
i found this way

```<code>void updateUI(){
   setState(() {

    });
}
</code>```

but it will refresh the current page right ? which is the operation state page

or i am supposed to explicitly use for example

```<code>Navigator.push(context,
    MaterialPageRoute(builder:(context)=> homeScreen()));
</code>```

so it will go to next page and by default calling that page will update the state ?

Body:
i am trying to add a refresh button on a page that will appear if an error has occurred , but i want it to refresh the previous page which the error has occurred on

so first i created two stateful widgets one for operation succeeded and the other is when the operation fail , and created button on each one
if succeeded will transfer the user the the next page
if fail it supposed to refresh the previous page and go back to it

i need help with the refresh buttton is there a way to do it ?
i found this way

void updateUI(){
   setState(() {

    });
}

but it will refresh the current page right ? which is the operation state page

or i am supposed to explicitly use for example

Navigator.push(context,
    MaterialPageRoute(builder:(context)=> homeScreen()));

so it will go to next page and by default calling that page will update the state ?


问:
How should dynamic, system-level libraries be bundled into a Rust crate?
When creating a wrapper around a (C) library libfoo that is either itself commonly dynamically linked or links some dependencies dynamically, should the crate libfoo-sys include this library and its dependencies in some way? If so, how?

In case libfoo-sys should not include the library, how should the crate ensure a sufficiently compatible version is present on the system?
The most pragmatic thing I can think of is for  the build of dependents to fail if the relevant libfoo version is missing. An alternative would be to try to install the relevant version with common package managers instead but I'd be worried to break a crate-user's environment in that way.

I looked at some examples of wrapper crates and couldn't find any indication of them including the base library which seems odd to me. Searching for the question didn't yield any definitive answer.

Edit: I am most interested in the case of libfoo not supporting static linking at all, or very badly.


问:
How to check if a value in a cell is equal to 1 and then append the columnname of that cell to a list?
I am building a python program which assigns students to courses based on if there is capacity and if the student request the course. I am using a object oriented approach. I am using Pandas since I have been delivered an excel file with the preferences and capacities.
For the studentclass my idea is to create a method which loops over the rows(which is the courses) and append the course to a list if the course is requested.
Am i on the right path here?</p>


问:
@drawables causing lag in Layout
I did CPU profiling and found that my drawable in the XML layout is the main reason for the lag. My before removing drawable and after removing drawable CPU profiling screenshot below:

BEFORE:

AFTER:

Drawbles I am using:

1.  android:background="@drawable/containerbg" (Main container constrainLayout background. It is a shape drawble with stroke)

2.  app:drawableLeftCompat="@drawable/circledot" (It is a shape drawble. I'm using it in text view to make a dot)

3. android:progressDrawable="@drawable/progress",android:thumb="@drawable/thumb"(These are shape drawables I'm using to customize my seekbar)

4. app:icon="@drawable/share" , "@drawable/comment","@drawable/vote"(these are vector drawables I'm using in button)

I read this and I tried my best to do, but I need that drawbles for my layout please help.

Title: @drawables causing lag in Layout


问:
Missing Exception if thrown in finally
I have a code:

    class Program
    {
        public static void Main()
        {
            try
            {
                Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static void Execute()
        {
            try
            {
                Step3();
            }
            catch (Exception ex)
            {
                Console.WriteLine("catch");
                throw new Exception("1");
            }
            finally
            {
                Console.WriteLine("finally");
                throw new Exception("2");
            }

        }

        public static void Step3()
        {
            try
            {
                Console.WriteLine("Step 3");
                throw new Exception("step 3");
            }
            finally
            {
                Console.WriteLine("Step 3 finally");
            }
        }
    }
```
<p>and output:</p>
```Step 3
Step 3 finally
catch
finally
2
```

I do not understand what happened with exception throw new Exception("1");. Did it just disappear? Why?

I have read answer about specification but I'm not sure I understand what happened with throw new Exception("1"); Is it still in memory?

Title: Missing Exception if thrown in finally

Body:
I have a code:

    class Program
    {
        public static void Main()
        {
            try
            {
                Execute();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static void Execute()
        {
            try
            {
                Step3();
            }
            catch (Exception ex)
            {
                Console.WriteLine("catch");
                throw new Exception("1");
            }
            finally
            {
                Console.WriteLine("finally");
                throw new Exception("2");
            }

        }

        public static void Step3()
        {
            try
            {
                Console.WriteLine("Step 3");
                throw new Exception("step 3");
            }
            finally
            {
                Console.WriteLine("Step 3 finally");
            }
        }
    }

and output:

Step 3
Step 3 finally
catch
finally
2

I do not understand what happened with exception throw new Exception("1");. Did it just disappear? Why?

I have read answer about specification but I'm not sure I understand what happened with throw new Exception("1"); Is it still in memory?


问:
Is it possible to implement an DNS-SD mechanism for a WebSocket server?
I have a WebSocket server running on an Android device on my local network. I would like to have the ability to discover this server using DNS-based Service Discovery (DNS-SD). I believe this is possible for plain sockets but is this possible for WebSockets? If not, are there any other mechanisms besides DNS-SD that would allow me to discover a WebSocket server on a LAN besides iterating through all possible IP:port combinations? If this is possible, how can I go about naming my service so that it is discoverable?</p>


问:
React array defined with useState is not updated after trying to acces the variable
Im trying to make a calendar widget where you can click and create an event at a certain starttime, if you hold mouse down and move down, the event becomes bigger (endtime gets later). Which works in the frontend, but i'm not able to acces the event i just created in my events state.

I useState for const array of events. On mouseDown i create an event and update the events' state. Which works. On mouseMove i update the events state again by finding the event for it's key in the prevState of the events array. Which also works.
But on mouseUp i want to find the event for it's key again to return the object i just created. But my events state does not contain the event i created on the screen. This time i just want to use the already created eventObject in another function, not update it. Howcome this event is not available in my events state on mouseUp, while it was already available in my mouseMove part. It probably has someting todo with that i'm accessing events from prevState in the mousemove and im not doing that in mouseUp. But how do you acces the most recent state when you don't want to update the state at that moment? (see comments added to code).

const [key, setKey] = useState(1000);

// creating state of array of events here.
const [events, setEvents] = useState(null)

const handleClick = (e) => {
        console.log("HandleClick...");

        const eventsSameDateTime = events.filter(
            ev =>  {
            const sameGridRow =  ev.gridRowStart === getRowForEvent(e);
            const sameGridColum = ev.gridcolumn === getColumnForEvent(e);;
            return sameGridRow && sameGridColum}
        );

        const count = eventsSameDateTime.length+1;
        newEvent = {
            date: null,
            gridRowStart: getRowForEvent(e),
            gridRowEnd: getRowForEvent(e)+4,
            gridcolumn: getColumnForEvent(e),
            title: "new",
            createDate: new Date(),
            zIndex: count,
        };

        const newEvents = [...eventsSameDateTime, newEvent]
        .sort((a, b) => a.createDate.getTime() - b.createDate.getTime())
        .map((ev, i) => {
            const newKey = key+i;
            ev.key = newKey;
            setKey(prevState => prevState+i)
            ev.zIndex = i + 1;
            ev.otherEvents = count;
            return ev;
        })

        // updating the events state here onclick (initial creation)
        setEvents((prevState) => {
            const oldEvents = prevState.filter(pEv => newEvents.find(nEv => nEv.key === pEv.key) == null);
            return [...oldEvents, ...newEvents];
        })
    }

    const handleMouseDown = (e1) => {
        console.log("HandleMouseDown...");
        if (e1.target.className.includes("event-container")) {
            setKey(prevState => {
                console.log(`updating key onClick...`);
                return prevState+1;
            });
            e1.preventDefault();
            handleClick(e1);

            const handleMouseMove = (e2) => {
                console.log("HandleMouseMove...")
                e2.preventDefault();

                // updating the events array state on mousemove.(one event endstime in the array)
                setEvents((prevState) => {
                    console.log(`updating events onMove...`);

                    // the event i created on click is available in the prevState.
                    console.log("events on mouseMove: ", prevState);
                    return [...prevState].map((ev) => {
                        if (ev.key === newEvent.key) {
                            ev.gridRowEnd = getRowForEvent(e2)
                        }
                        return ev;
                    })
                })
            }
            e1.target.addEventListener('mousemove', handleMouseMove);

            const handleMouseUp = (e3) => {
                e3.preventDefault();
                console.log("HandleMouseUP");

                const removeMouseMoveAndDown = (e) => {
                    e.removeEventListener("mousemove", handleMouseMove);
                    e.removeEventListener("mouseup", handleMouseUp);
                }

                if (isEvent(e1.target)) {
                    console.log("Removing Event mouseUpDown");
                    removeMouseMoveAndDown(e1.target);
                }
                const eventContainer = findWeekElement(e1.target);
                console.log("Removing EventContainer mouseUpDown");
                removeMouseMoveAndDown(eventContainer);

                // when i log the events array, the event i created onclick is not in there.
                console.log("events on mouseUp: ", events);
                const existingEvent = events.find(ev => ev.index === key);
                props.payload.setValue(JSON.stringify(createUiEventForEvent(existingEvent)));
                props.eventActions.onCreate();
            }
            e1.target.addEventListener("mouseup", handleMouseUp);
        } else {
            console.log("nothing happens, you probably clicked an event");
        }
    }```


问:
QDirIterator problem with subdirectories on Android
I am using QDirIterator to get a list of files in a directory and in subdirectories. It works fine on Windows but on Android it only works if there are no subdirectories (or if I don't tell it to look into subdirectories). I don't know what is going on but I suspect something odd with subdirectory permissions in Android. I can demonstrate the problem with a very short bit of code using the standard Qt Widgets QMainWindow application template in Qt Creator using Qt 6.4.1 and Android 9 (I am actually working on an Amazon Fire) using arm64_v8a ABI.

The code pops up a dialog to choose a directory and then outputs the contents of that directory to the console.

```<code>MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString folder = QFileDialog::getExistingDirectory(this, "Choose a folder");
    QDirIterator dirIterator(folder, QDirIterator::Subdirectories);
    while (dirIterator.hasNext())
    {
        qDebug() << dirIterator.next();
    }
}
</code>```

This will crash if the directory has subdirectories. Changing

```<code>QDirIterator dirIterator(folder, QDirIterator::Subdirectories)
</code>```

to

```<code>QDirIterator dirIterator(folder)
</code>```

stops it crashing but also stops me getting the contents of the subdirectories. I have played around using QDir::entryInfoList() but I get exactly the same problem (and checking the source code I think this just calls QDirIterator anyway).

The nature of the crash is rather strange. It gets stuck in an endless loop in the subdirectory. So if I point it at the downloads directory and I have a subdirectory called test the output is:

```<code>D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test"
D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test/test"
D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test/test/test"
D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test/test/test/test"
</code>```

And this continues until the whole thing crashes. It is as if it never actually descends into the subdirectories and keeps listing the root directory. If there are files that would be listed before the subdirectory then these get listed again and again too as if they were in the subdirectory (which they aren't). I suppose I could work around it using opendir, readdir, closedir but this ought to be much easier and more portable in Qt, and if the problem really is permissions then using lower level Unix interfaces won't help.

Body:
I am using QDirIterator to get a list of files in a directory and in subdirectories. It works fine on Windows but on Android it only works if there are no subdirectories (or if I don't tell it to look into subdirectories). I don't know what is going on but I suspect something odd with subdirectory permissions in Android. I can demonstrate the problem with a very short bit of code using the standard Qt Widgets QMainWindow application template in Qt Creator using Qt 6.4.1 and Android 9 (I am actually working on an Amazon Fire) using arm64_v8a ABI.

The code pops up a dialog to choose a directory and then outputs the contents of that directory to the console.

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QString folder = QFileDialog::getExistingDirectory(this, "Choose a folder");
    QDirIterator dirIterator(folder, QDirIterator::Subdirectories);
    while (dirIterator.hasNext())
    {
        qDebug() << dirIterator.next();
    }
}

This will crash if the directory has subdirectories. Changing

QDirIterator dirIterator(folder, QDirIterator::Subdirectories)

to

QDirIterator dirIterator(folder)

stops it crashing but also stops me getting the contents of the subdirectories. I have played around using QDir::entryInfoList() but I get exactly the same problem (and checking the source code I think this just calls QDirIterator anyway).

The nature of the crash is rather strange. It gets stuck in an endless loop in the subdirectory. So if I point it at the downloads directory and I have a subdirectory called test the output is:

D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test"
D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test/test"
D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test/test/test"
D libqdiriterator_test_arm64-v8a.so: "content://com.android.providers.downloads.documents/tree/downloads/test/test/test/test"

And this continues until the whole thing crashes. It is as if it never actually descends into the subdirectories and keeps listing the root directory. If there are files that would be listed before the subdirectory then these get listed again and again too as if they were in the subdirectory (which they aren't). I suppose I could work around it using opendir, readdir, closedir but this ought to be much easier and more portable in Qt, and if the problem really is permissions then using lower level Unix interfaces won't help.


问:
Decrease the label size in SHAP decision plot
I want to decrease the label size of SHAP decision plots. But it is not working with the code that I tried below.

```<code>import shap
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import matplotlib.pyplot as plt

train = pd.read_csv('Data/train.csv')[:50]
test = pd.read_csv('Data/test.csv')[:50]
y_train = train['FLAG']
train.drop(columns='FLAG', inplace=True, axis=1)
y_test = test['FLAG']
test.drop(columns='FLAG', inplace=True, axis=1)

model = RandomForestClassifier()
model.fit(train, y_train)

explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(test)
shap.initjs()

def decision_plot(row_idx):
     shap.decision_plot(explainer.expected_value[1], shap_values[1][row_idx,:], test.iloc[row_idx,:], link="logit")
     ax = plt.gca()
     ax.tick_params(axis='x', labelsize=2, color='b')

     plt.savefig('output/plot.png')

decision_plot(4)

</code>```

I tried changing the axis parameters. But it is not changing the label size. Some of the label names are too long and it gets cut off when the plot is displayed. Please see the image

Body:
I want to decrease the label size of SHAP decision plots. But it is not working with the code that I tried below.

import shap
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
import matplotlib.pyplot as plt

train = pd.read_csv('Data/train.csv')[:50]
test = pd.read_csv('Data/test.csv')[:50]
y_train = train['FLAG']
train.drop(columns='FLAG', inplace=True, axis=1)
y_test = test['FLAG']
test.drop(columns='FLAG', inplace=True, axis=1)

model = RandomForestClassifier()
model.fit(train, y_train)

explainer = shap.TreeExplainer(model)
shap_values = explainer.shap_values(test)
shap.initjs()

def decision_plot(row_idx):
     shap.decision_plot(explainer.expected_value[1], shap_values[1][row_idx,:], test.iloc[row_idx,:], link="logit")
     ax = plt.gca()
     ax.tick_params(axis='x', labelsize=2, color='b')

     plt.savefig('output/plot.png')

decision_plot(4)

I tried changing the axis parameters. But it is not changing the label size. Some of the label names are too long and it gets cut off when the plot is displayed. Please see the image


问:
Is it possible to load only weights to TF-TRT model?
I have two models with the exact same architecture, but different weights as the same network is used for two different problems. We're using TF-TRT to optimize the model in order to use it on edge devices.

We'd like to be able to switch from one model to the other as fast as possible. As of now, we load the next model using tf.saved_model.load(), however, this reloads the entire model including the architecture. In order to speed up the process, we'd like to simply load the weights & switch them in the model architecture.

From what I've seen, it is possible in Keras by loading a .w1 file, but we don't have such file after converting to TF-TRT.
I've found out that TRT has a Refitter object but I don't think we can use it in this case.

I'd like to know if it is possible to switch weights of a TF-TRT model, perhaps there is something I'm missing out.

Thank you for your help.


问:
Redirect to Moodle home page by skipping login
I have a customized Moodle website for which I would like to login directly without prompting the user to provide username and password in Moddle login page.

I have a third party application which uses MySQL DB and has user table in it. Moodle application also has user details available already. No need to create user from external application, just the login is sufficient. From my application, I would like to redirect to Moodle home page by skipping login page. I read about the options about CAS server and external DB authentication in Moodle. There are no clear documents about how to set his up or which option suits my scenario.

So am confused whether should I use CAS server authentication or External DB authentication?

How can I skip the login prompt and make the user login directly by utilizing the username (and not password) ?


问:
How can I change the appearance of a Set floating filter?
I love the functionality of the Set filter in ag-grid, but I don't like how the floating filter appears as a disabled text input.  It conveys to the user that the filter cannot be used.

How can I change this appearance so that when ALL categories are selected, it says "All" instead of just being blank?


问:
Teams file consent card not sending "accept" activity to bot handler while implementing Teams Bot API , it is showing went wrong
We have a Teams bot installed for internal company use and it is capable of sending files to our users. Our application that handles the bot does not receive the file consent allow activity but decline activity is working fine , as said in the documentation we have implemented it .
will you pls help me out with the issue .

I'm using the proper documentation of Microsoft teams passing these values but not getting the result.

```<code>attachments": [{
    "contentType": "application/vnd.microsoft.teams.card.file.consent",
    "name": "result.txt",
    "content": {
        "description": "Text recognized from image",
        "sizeInBytes": 4348,
        "acceptContext": {
            "resultId": "1a1e318d-8496-471b-9612-720ee4b1b592"
        },
        "declineContext": {
            "resultId": "1a1e318d-8496-471b-9612-720ee4b1b592"
        }
    }
}]
</code>```

Body:
We have a Teams bot installed for internal company use and it is capable of sending files to our users. Our application that handles the bot does not receive the file consent allow activity but decline activity is working fine , as said in the documentation we have implemented it .
will you pls help me out with the issue .

I'm using the proper documentation of Microsoft teams passing these values but not getting the result.

attachments": [{
    "contentType": "application/vnd.microsoft.teams.card.file.consent",
    "name": "result.txt",
    "content": {
        "description": "Text recognized from image",
        "sizeInBytes": 4348,
        "acceptContext": {
            "resultId": "1a1e318d-8496-471b-9612-720ee4b1b592"
        },
        "declineContext": {
            "resultId": "1a1e318d-8496-471b-9612-720ee4b1b592"
        }
    }
}]


问:
DiscordAPIError[40060]: Interaction has already been acknowledged. I am trying to change button colour
I am trying to make a tic-tac-toe game. I found some code, but it doesn't work well. When you click on the button then it should change the button color and text. The problem is when I click

writes to discord "The application does not respond"

work fine

throw an Error

I am using discord.js 14
If you have a better code then send it here, this is the only one which I found.

Code:

 if (interaction.isButton()) {
    const collector = interaction.channel.createMessageComponentCollector();
    collector.on("collect", async (i) => {
        //loop through each action row on the embed and update it accordingly
        let newActionRowEmbeds = i.message.components.map((oldActionRow) => {
            //create a new action row to add the new data
            const updatedActionRow = new ActionRowBuilder();

            // Loop through old action row components (which are buttons in this case)
            updatedActionRow.addComponents(
                oldActionRow.components.map((buttonComponent) => {
                    //create a new button from the old button, to change it if necessary
                    const newButton = ButtonBuilder.from(buttonComponent);

                    //if this was the button that was clicked, this is the one to change!
                    if (i.component.customId == buttonComponent.customId) {
                        //If the button was a primary button then change to secondary, or vise versa
                        if (buttonComponent.style == ButtonStyle.Primary) {
                            newButton.setStyle(ButtonStyle.Secondary);
                            newButton.setLabel("X");
                        }
                    }
                    return newButton;
                })
            );
            return updatedActionRow;
        });
         // and then finally update the message
        await i.update({components: newActionRowEmbeds});
    });
}
```
<p>Error:</p>
```C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:667
        throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
              ^

DiscordAPIError[40060]: Interaction has already been acknowledged.
    at SequentialHandler.runRequest (C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:667:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.queueRequest (C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:464:14)
    at async REST.request (C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:910:22)
    at async ButtonInteraction.update (C:\Users\vojta\tictactoe\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:233:5)
    at async InteractionCollector.<anonymous> (file:///C:/Users/vojta/tictactoe/src/index.js:115:3) {
  requestBody: {
    files: [],
    json: {
      type: 7,
      data: {
        content: undefined,
        tts: false,
        nonce: undefined,
        embeds: undefined,
        components: [ { type: 1, components: [Array] } ],
        username: undefined,
        avatar_url: undefined,
        allowed_mentions: undefined,
        flags: undefined,
        message_reference: undefined,
        attachments: undefined,
        sticker_ids: undefined,
        thread_name: undefined
      }
    }
  },
  rawError: {
    message: 'Interaction has already been acknowledged.',
    code: 40060
  },
  code: 40060,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1049732802192617552/aW50ZXJhY3Rpb246MTA0OTczMjgwMjE5MjYxNzU1Mjp5d1FqWGh4bU82eVh1eVBrRWJsZnhWS2FibjZqSWNRMWhaSWN2YlZ1YU5nVHZsdEw2VUxZWGEzb0JQcHJQaUFPQVkyeHJ1NGp0WXZNUlE1all2YmkyQlA2ZHlpRUQ2ZUhDSUFUeVNWYkREaVc4OFdLWmVoMlpZUXJnQ1M5eWdyQw/callback'
}

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...
```

Body:
I am trying to make a tic-tac-toe game. I found some code, but it doesn't work well. When you click on the button then it should change the button color and text. The problem is when I click

writes to discord "The application does not respond"

work fine

throw an Error

I am using discord.js 14
If you have a better code then send it here, this is the only one which I found.

Code:

 if (interaction.isButton()) {
    const collector = interaction.channel.createMessageComponentCollector();
    collector.on("collect", async (i) => {
        //loop through each action row on the embed and update it accordingly
        let newActionRowEmbeds = i.message.components.map((oldActionRow) => {
            //create a new action row to add the new data
            const updatedActionRow = new ActionRowBuilder();

            // Loop through old action row components (which are buttons in this case)
            updatedActionRow.addComponents(
                oldActionRow.components.map((buttonComponent) => {
                    //create a new button from the old button, to change it if necessary
                    const newButton = ButtonBuilder.from(buttonComponent);

                    //if this was the button that was clicked, this is the one to change!
                    if (i.component.customId == buttonComponent.customId) {
                        //If the button was a primary button then change to secondary, or vise versa
                        if (buttonComponent.style == ButtonStyle.Primary) {
                            newButton.setStyle(ButtonStyle.Secondary);
                            newButton.setLabel("X");
                        }
                    }
                    return newButton;
                })
            );
            return updatedActionRow;
        });
         // and then finally update the message
        await i.update({components: newActionRowEmbeds});
    });
}

Error:

C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:667
        throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData);
              ^

DiscordAPIError[40060]: Interaction has already been acknowledged.
    at SequentialHandler.runRequest (C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:667:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.queueRequest (C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:464:14)
    at async REST.request (C:\Users\vojta\tictactoe\node_modules\@discordjs\rest\dist\index.js:910:22)
    at async ButtonInteraction.update (C:\Users\vojta\tictactoe\node_modules\discord.js\src\structures\interfaces\InteractionResponses.js:233:5)
    at async InteractionCollector.<anonymous> (file:///C:/Users/vojta/tictactoe/src/index.js:115:3) {
  requestBody: {
    files: [],
    json: {
      type: 7,
      data: {
        content: undefined,
        tts: false,
        nonce: undefined,
        embeds: undefined,
        components: [ { type: 1, components: [Array] } ],
        username: undefined,
        avatar_url: undefined,
        allowed_mentions: undefined,
        flags: undefined,
        message_reference: undefined,
        attachments: undefined,
        sticker_ids: undefined,
        thread_name: undefined
      }
    }
  },
  rawError: {
    message: 'Interaction has already been acknowledged.',
    code: 40060
  },
  code: 40060,
  status: 400,
  method: 'POST',
  url: 'https://discord.com/api/v10/interactions/1049732802192617552/aW50ZXJhY3Rpb246MTA0OTczMjgwMjE5MjYxNzU1Mjp5d1FqWGh4bU82eVh1eVBrRWJsZnhWS2FibjZqSWNRMWhaSWN2YlZ1YU5nVHZsdEw2VUxZWGEzb0JQcHJQaUFPQVkyeHJ1NGp0WXZNUlE1all2YmkyQlA2ZHlpRUQ2ZUhDSUFUeVNWYkREaVc4OFdLWmVoMlpZUXJnQ1M5eWdyQw/callback'
}

Node.js v18.12.1
[nodemon] app crashed - waiting for file changes before starting...


问:
How to read uncomitted updates in atlas functions
I have a cluster with 1 primary and 2 secondary nodes. Also, I have an atlas function witch uses a multi-document transaction. I faced a problem when I do an update and then read this document using .find() I always get not updated version of this document. Here is the function:

```<code>exports = async function({ query, headers, body}, response) {
  const collection = context.services.get("mongodb-atlas").db("zakhar").collection("w");

  // clean up and insert init data
  await collection.deleteMany({});
  await collection.insertOne({"name": 1, "category": "toy"});
  await collection.insertOne({"name": 2, "category": "toy"});
  await collection.insertOne({"name": 3, "category": "game"});
  await collection.insertOne({"name": 4, "category": "game"});

  const session = context.services.get("mongodb-atlas").startSession();

  const transactionOptions = {
    readPreference: "primary",
    readConcern: { level: "local" },
    writeConcern: { w: "majority" }
  };

  try {
    await session.withTransaction(async () => {
      await updateStatus(session);

    }, transactionOptions);
    return 'ok';
  } catch (err) {
    await session.abortTransaction();
    throw err;
  } finally {
    await session.endSession();
  }
};

async function updateStatus(session, ){
  const collection = context.services.get("mongodb-atlas").db("zakhar").collection("w");

  const countBeforeUpdate = await collection.find({"category": "toy"}, {}, { session }).toArray();
  console.log("countBeforeUpdate: " + countBeforeUpdate.length);

  const query = {"name": 1};
  const update = {"$set": {"category": "game"}};
  await collection.updateOne(query, update, { session })
      .then(result => {
        const { matchedCount, modifiedCount } = result;
        console.log("matchedCount: " + matchedCount);
        console.log("modifiedCount: " + modifiedCount);
      });

  const countAfterUpdate = await collection.find({"category": "toy"}, {}, { session }).toArray();
  console.log("countAfterUpdate: " + countAfterUpdate.length);

}
</code>```

And it is an output, but I expect countAfterUpdate: 1

```<code>  "countBeforeUpdate: 2",
  "matchedCount: 1",
  "modifiedCount: 1",
  "countAfterUpdate: 2"
</code>```

I tried to use all other transaction options(readPreference, readConcern, writeConcern), but nothing changed. Also tried to use session.startTransaction(...) instead of withTransaction()

Body:
I have a cluster with 1 primary and 2 secondary nodes. Also, I have an atlas function witch uses a multi-document transaction. I faced a problem when I do an update and then read this document using .find() I always get not updated version of this document. Here is the function:

exports = async function({ query, headers, body}, response) {
  const collection = context.services.get("mongodb-atlas").db("zakhar").collection("w");

  // clean up and insert init data
  await collection.deleteMany({});
  await collection.insertOne({"name": 1, "category": "toy"});
  await collection.insertOne({"name": 2, "category": "toy"});
  await collection.insertOne({"name": 3, "category": "game"});
  await collection.insertOne({"name": 4, "category": "game"});

  const session = context.services.get("mongodb-atlas").startSession();

  const transactionOptions = {
    readPreference: "primary",
    readConcern: { level: "local" },
    writeConcern: { w: "majority" }
  };

  try {
    await session.withTransaction(async () => {
      await updateStatus(session);

    }, transactionOptions);
    return 'ok';
  } catch (err) {
    await session.abortTransaction();
    throw err;
  } finally {
    await session.endSession();
  }
};

async function updateStatus(session, ){
  const collection = context.services.get("mongodb-atlas").db("zakhar").collection("w");

  const countBeforeUpdate = await collection.find({"category": "toy"}, {}, { session }).toArray();
  console.log("countBeforeUpdate: " + countBeforeUpdate.length);

  const query = {"name": 1};
  const update = {"$set": {"category": "game"}};
  await collection.updateOne(query, update, { session })
      .then(result => {
        const { matchedCount, modifiedCount } = result;
        console.log("matchedCount: " + matchedCount);
        console.log("modifiedCount: " + modifiedCount);
      });

  const countAfterUpdate = await collection.find({"category": "toy"}, {}, { session }).toArray();
  console.log("countAfterUpdate: " + countAfterUpdate.length);

}

And it is an output, but I expect countAfterUpdate: 1

  "countBeforeUpdate: 2",
  "matchedCount: 1",
  "modifiedCount: 1",
  "countAfterUpdate: 2"

I tried to use all other transaction options(readPreference, readConcern, writeConcern), but nothing changed. Also tried to use session.startTransaction(...) instead of withTransaction()


问:
Is there a workaround for using .scenePhase with SignInWithAppleButton in a NavigationStack causing a nav stack pop and login to fail?
I converted my app to use the new NavigationStack in my onboarding flow. My login view that uses SignInWithAppleButton failed. What seemed to happen is my view containing the button popped away when Apple's sign-in button was shown. This meant my handlers were gone, so none of my handlers were called. The same code outside the NavigationStack works fine.

I eventually tracked this down to a very unexpected statement.

```<code>import SwiftUI

@main
struct TestNavSignInApp: App {
    // When scenePhase isn't commented out the SignInWithAppleButton view pops off
    // and the sign-in never occurs. Comment it out, and everything works fine.
    @Environment(\.scenePhase) private var scenePhase

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @ObservedObject var onboarding = OnboardingFlow()

    var body: some View {

        NavigationStack(path: $onboarding.path) {
            Button("Start") {
                onboarding.start()
            }
            .navigationDestination(for: OnboardDestination.self) { destination in
                ViewFactory.viewForDestination(destination)
            }
        }
        .environmentObject(onboarding)
    }
}

enum OnboardDestination {
    case welcomPage
    case loginPage
}

class ViewFactory {

    @ViewBuilder
    static func viewForDestination(_ destination: OnboardDestination) -> some View {

        switch destination {
        case .welcomPage:
            WelcomeView()
        case .loginPage:
            SignInWithAppleView()
        }
    }
}

class OnboardingFlow: ObservableObject {
    @Published var path = NavigationPath()

    func gotoHomePage() {
        path.removeLast(path.count)
    }

    func gotoPrev() {
        path.removeLast()
    }

    func start() {
        path.append(OnboardDestination.welcomPage)
    }

    func next() {
        path.append(OnboardDestination.loginPage)
    }
}

struct WelcomeView: View {
    @EnvironmentObject var onboarding: OnboardingFlow

    var body: some View {
        Button("Next") {
            onboarding.next()
        }
        .navigationBarBackButtonHidden(true)
    }
}

struct SignInWithAppleView: View {
    @EnvironmentObject var onboarding: OnboardingFlow

    var body: some View {

        VStack(spacing: 18) {

            SignInWithAppleButton(
                .signIn,
                onRequest: configure,
                onCompletion: handle
            )
        }
        .navigationBarBackButtonHidden(true)
    }

    func configure(_ request: ASAuthorizationAppleIDRequest) {
        request.requestedScopes = [.email, .fullName]
    }

    func handle(_ authResult: Result<ASAuthorization, Error>) {
        print("Handle:")

        switch authResult {

        case.success(let auth):
           print("Authorization successful: \(auth)")

            switch auth.credential {

            case let credential as ASAuthorizationAppleIDCredential:
                print("credential: \(credential)")

            default:
                print("Authorization default credential: \(auth.credential.description)")
            }

        case.failure(let error):
            print("Authorization failed:error: \(error.localizedDescription)")
        }
    }
}
</code>```

I'm not sure why this would happen. While scenePhase isn't a must have, I was wondering if anyone could explain what is happening and a possible workaround?

Body:
I converted my app to use the new NavigationStack in my onboarding flow. My login view that uses SignInWithAppleButton failed. What seemed to happen is my view containing the button popped away when Apple's sign-in button was shown. This meant my handlers were gone, so none of my handlers were called. The same code outside the NavigationStack works fine.

I eventually tracked this down to a very unexpected statement.

import SwiftUI

@main
struct TestNavSignInApp: App {
    // When scenePhase isn't commented out the SignInWithAppleButton view pops off
    // and the sign-in never occurs. Comment it out, and everything works fine.
    @Environment(\.scenePhase) private var scenePhase

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

struct ContentView: View {
    @ObservedObject var onboarding = OnboardingFlow()

    var body: some View {

        NavigationStack(path: $onboarding.path) {
            Button("Start") {
                onboarding.start()
            }
            .navigationDestination(for: OnboardDestination.self) { destination in
                ViewFactory.viewForDestination(destination)
            }
        }
        .environmentObject(onboarding)
    }
}

enum OnboardDestination {
    case welcomPage
    case loginPage
}

class ViewFactory {

    @ViewBuilder
    static func viewForDestination(_ destination: OnboardDestination) -> some View {

        switch destination {
        case .welcomPage:
            WelcomeView()
        case .loginPage:
            SignInWithAppleView()
        }
    }
}

class OnboardingFlow: ObservableObject {
    @Published var path = NavigationPath()

    func gotoHomePage() {
        path.removeLast(path.count)
    }

    func gotoPrev() {
        path.removeLast()
    }

    func start() {
        path.append(OnboardDestination.welcomPage)
    }

    func next() {
        path.append(OnboardDestination.loginPage)
    }
}

struct WelcomeView: View {
    @EnvironmentObject var onboarding: OnboardingFlow

    var body: some View {
        Button("Next") {
            onboarding.next()
        }
        .navigationBarBackButtonHidden(true)
    }
}

struct SignInWithAppleView: View {
    @EnvironmentObject var onboarding: OnboardingFlow

    var body: some View {

        VStack(spacing: 18) {

            SignInWithAppleButton(
                .signIn,
                onRequest: configure,
                onCompletion: handle
            )
        }
        .navigationBarBackButtonHidden(true)
    }

    func configure(_ request: ASAuthorizationAppleIDRequest) {
        request.requestedScopes = [.email, .fullName]
    }

    func handle(_ authResult: Result<ASAuthorization, Error>) {
        print("Handle:")

        switch authResult {

        case.success(let auth):
           print("Authorization successful: \(auth)")

            switch auth.credential {

            case let credential as ASAuthorizationAppleIDCredential:
                print("credential: \(credential)")

            default:
                print("Authorization default credential: \(auth.credential.description)")
            }

        case.failure(let error):
            print("Authorization failed:error: \(error.localizedDescription)")
        }
    }
}

I'm not sure why this would happen. While scenePhase isn't a must have, I was wondering if anyone could explain what is happening and a possible workaround?


问:
How to get the Fixture of an "Object Layer"? LOVE 2d, Lua, Tiled
I'm trying to make a weirdo edition of PacMan and I need a quick way to .draw all the points (diamonds) across the whole map.
My idea was to draw a point every x,y with a loop and then check which of those collide with a wall and delete them.
The only problem is that I have no idea about how to get the Fixture of the walls.
I used Tiled with STI lib and made an collidable Object Layer.
I'm a noob and I don't know which information you need in order to help me, just tell me what you need to know.
Thank you so much

```<code>function Coin.beginContact(a, b, collision)
    for i,instance in ipairs(ActiveCoins) do
        if a == instance.physics.fixture or b == instance.physics.fixture then
            if a == Player.physics.fixture or b == Player.physics.fixture then
                instance.toBeRemoved = true
                return true
            elseif a == map.layers.Solid or b == map.layers.Solid then
                instance.toBeRemoved = true
                return true
            end
        end
    end
end
</code>```

This is how I check collision between Player and Coins, in the elseif I tried to experiment in order to get the fixture of the walls, but nada.

Body:
I'm trying to make a weirdo edition of PacMan and I need a quick way to .draw all the points (diamonds) across the whole map.
My idea was to draw a point every x,y with a loop and then check which of those collide with a wall and delete them.
The only problem is that I have no idea about how to get the Fixture of the walls.
I used Tiled with STI lib and made an collidable Object Layer.
I'm a noob and I don't know which information you need in order to help me, just tell me what you need to know.
Thank you so much

function Coin.beginContact(a, b, collision)
    for i,instance in ipairs(ActiveCoins) do
        if a == instance.physics.fixture or b == instance.physics.fixture then
            if a == Player.physics.fixture or b == Player.physics.fixture then
                instance.toBeRemoved = true
                return true
            elseif a == map.layers.Solid or b == map.layers.Solid then
                instance.toBeRemoved = true
                return true
            end
        end
    end
end

This is how I check collision between Player and Coins, in the elseif I tried to experiment in order to get the fixture of the walls, but nada.


问:
Is there a function in Google Earth Engine (javascript) that can compare two lists against one list and storing the correct match in a new list?
I need to compare two lists of items (a,b) to one list (c).

If a match is made, store it in a new list and If no match is found, keep the first list's label. Something like below-

```<code>if a = c, keep a. if a != c, look at b. if b = c, keep b. If b != c, keep a.
</code>```

I need this to run through each item in lists a and b.

Any help is appreciated thank you in advance.

I have only been able to compare one list to another list.

Body:
I need to compare two lists of items (a,b) to one list (c).

If a match is made, store it in a new list and If no match is found, keep the first list's label. Something like below-

if a = c, keep a. if a != c, look at b. if b = c, keep b. If b != c, keep a.

I need this to run through each item in lists a and b.

Any help is appreciated thank you in advance.

I have only been able to compare one list to another list.


问:
Python program to evaluate a string expression keeps returning a typeError
I am trying to write a python program to evaluate a string expression and return an output. The program works perfectly except for the part where I have to evaluate the expression written within brackets.
Here is the code responsible for evaluating the expression within brackets while following the BODMAS rule:</p>
```<code>def evaluateExpression(expression):
    for i in range(len(expression)):
        if expression[i]=="(":
            start = expression.index("(")
            for j in range(start, len(expression)):
                if(expression[j]==")"):
                    end = j
                    break
            newExp = expression[start:end]
            while "^" in newExp:
                index = newExp.index("^")
                newExp[index] = pow(newExp[index-1], newExp[index + 1])
            while "*" in newExp or "/" in newExp:
                for i in range(len(newExp)):
                    if newExp[i] == "*":
                        newExp[i] = int(newExp[i-1]) * int(newExp[i+1])
                        break
                    elif newExp[i] == "/":
                        newExp[i] = int(newExp[i-1]) / int(newExp[i+1])
                        break
            while "+" in newExp or "-" in newExp:
                for i in range(len(newExp)):
                    if newExp[i] == "+":
                        newExp[i] = int(newExp[i-1]) * int(newExp[i+1])
                        break
                    elif newExp[i] == "-":
                        newExp[i] = int(newExp[i-1]) * int(newExp[i+1])
                        break
            expression[start:end] = newExp
        else:
            pass
</code>```

Body:
I am trying to write a python program to evaluate a string expression and return an output. The program works perfectly except for the part where I have to evaluate the expression written within brackets.
Here is the code responsible for evaluating the expression within brackets while following the BODMAS rule:

def evaluateExpression(expression):
    for i in range(len(expression)):
        if expression[i]=="(":
            start = expression.index("(")
            for j in range(start, len(expression)):
                if(expression[j]==")"):
                    end = j
                    break
            newExp = expression[start:end]
            while "^" in newExp:
                index = newExp.index("^")
                newExp[index] = pow(newExp[index-1], newExp[index + 1])
            while "*" in newExp or "/" in newExp:
                for i in range(len(newExp)):
                    if newExp[i] == "*":
                        newExp[i] = int(newExp[i-1]) * int(newExp[i+1])
                        break
                    elif newExp[i] == "/":
                        newExp[i] = int(newExp[i-1]) / int(newExp[i+1])
                        break
            while "+" in newExp or "-" in newExp:
                for i in range(len(newExp)):
                    if newExp[i] == "+":
                        newExp[i] = int(newExp[i-1]) * int(newExp[i+1])
                        break
                    elif newExp[i] == "-":
                        newExp[i] = int(newExp[i-1]) * int(newExp[i+1])
                        break
            expression[start:end] = newExp
        else:
            pass


问:
Updating useContext and Redux at the same time is clearing Redux state?
In my application I am using both Redux and useContext for state management. I noticed that dispatching an action to redux to update state and updating useContext at the same time is causing Redux state to clear out. Almost seems like a re-render is happening under the hood upon updating my context. Does updating useContext re-render components??

Removing the line to update useContext state in the code gets rid of the issue. The issue has to be with updating the context.


问:
Not a manage type: class pack_name ... I inherit from the Repository (CrudRepository or JpaRepository) and an error is generated
i need help you, i am a simple project rest in java 17, but add I inherit from the Repository interface (CrudRepository or JpaRepository) and an error is generated, otherwise it does not appear.

It only happens when you inherit from crudRepository or JpaRepository, if I don't inherit nothing happens.

my pom:

i tried to use other dependency but don't work


问:
How to hide a graphique in the kelbow_visualizer while doing clustering using Python
I am using kelbow_visualizer in order to find the number of clusters in a database, I created a function that returns only the number of clusters, but the problem is even while I put show= Fasle to not display the graphic it shows it, so please if you can help me to not return it.

Here is the code I did :

```<code>def numcluster(data):
vis=kelbow_visualizer(TimeSeriesKMeans(random_state=42), data_scaled, k=(2,10), metric='distortion', distance_metric='euclidean',locate_elbow=True, timings=False, show=False)
vis.fit(data)
num_K=vis.elbow_value_
return num_K

</code>```

I was expecting to hide the graph

Body:
I am using kelbow_visualizer in order to find the number of clusters in a database, I created a function that returns only the number of clusters, but the problem is even while I put show= Fasle to not display the graphic it shows it, so please if you can help me to not return it.

Here is the code I did :

def numcluster(data):
vis=kelbow_visualizer(TimeSeriesKMeans(random_state=42), data_scaled, k=(2,10), metric='distortion', distance_metric='euclidean',locate_elbow=True, timings=False, show=False)
vis.fit(data)
num_K=vis.elbow_value_
return num_K

I was expecting to hide the graph


问:
prcomp() function is giving me error "infinite or missing values in 'x'"
Eset is an expression matrix and I'm trying to make a PCA and I keep on getting this error and I was thinking maybe it was because "exprs" is not numeric but I'm checking and it is double. how can I solve this?

```<code>Eset<-ExpressionSet(as.matrix(exp))
pData(Eset)<-meta
featureData(Eset) <- as(feat,"AnnotatedDataFrame")

exprs<- Biobase::exprs(Eset)
exprs<-t(exprs)
exprs<- as.numeric(exprs)
type(exprs)
PCA <- prcomp(exprs, scale = FALSE)
</code>```

I was not expecting this error because I made sure that "exprs" was numeric but it's still not working

Body:
Eset is an expression matrix and I'm trying to make a PCA and I keep on getting this error and I was thinking maybe it was because "exprs" is not numeric but I'm checking and it is double. how can I solve this?

Eset<-ExpressionSet(as.matrix(exp))
pData(Eset)<-meta
featureData(Eset) <- as(feat,"AnnotatedDataFrame")

exprs<- Biobase::exprs(Eset)
exprs<-t(exprs)
exprs<- as.numeric(exprs)
type(exprs)
PCA <- prcomp(exprs, scale = FALSE)

I was not expecting this error because I made sure that "exprs" was numeric but it's still not working