问:
dynamically retriving the x,y position of an element in canvas
I have this code

```<code>        <Canvas x:Name="SampleCanvas" Background="#F5F7F9"  MouseLeftButtonDown="brdMovable_MouseLeftButtonDown" MouseLeftButtonUp="brdMovable_MouseLeftButtonUp" MouseMove="brdMovable_MouseMove" Height="570" Width="875">
         <chartingToolkit:Chart  x:Name="mcChart" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="190" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
          </canvas>
</code>```

Now i want to retrieve the canvas.Left position and canvas.Top positions of mcChart dynamically in codebehind.

How can i do that ?
Thanks.

答:
How about:</p>

```<code>Canvas.GetLeft(mcChart);
Canvas.GetTop(mcChart);
</code>```

Body:
I have this code

        <Canvas x:Name="SampleCanvas" Background="#F5F7F9"  MouseLeftButtonDown="brdMovable_MouseLeftButtonDown" MouseLeftButtonUp="brdMovable_MouseLeftButtonUp" MouseMove="brdMovable_MouseMove" Height="570" Width="875">
         <chartingToolkit:Chart  x:Name="mcChart" Loaded="mcChart_Loaded"  Width="400" Height="250" Canvas.Left="190" Canvas.Top="5" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown"
                             Background="LightSteelBlue">
                        <chartingToolkit:Chart.RenderTransform>
                            <ScaleTransform x:Name="scaleTransform"></ScaleTransform>
                        </chartingToolkit:Chart.RenderTransform>
                        <chartingToolkit:Chart.Series>
                            <chartingToolkit:ColumnSeries Title="Experience"  IndependentValueBinding="{Binding Path=ModelName}" DependentValueBinding="{Binding  Path=SaleCount}">
                            </chartingToolkit:ColumnSeries>
                        </chartingToolkit:Chart.Series>
                    </chartingToolkit:Chart>
          </canvas>

Now i want to retrieve the canvas.Left position and canvas.Top positions of mcChart dynamically in codebehind.

How can i do that ?
Thanks.

Body:
How about:

Canvas.GetLeft(mcChart);
Canvas.GetTop(mcChart);


来源: stackexchange

问:
dataTask in networking is not executing
In RestManager class, using URLSession I want to return AnyPublisher<Result<T, ErrorType>, Never>.

So I made this code

```<code>class RestManager {

func fetchData<T: Decodable>(url: URL) -> AnyPublisher<Result<T, ErrorType>, Never> {

    return Future<Result<T, ErrorType>, Never> { promise in
        URLSession
            .shared
            .dataTask(with: url) { data, response, error in
                if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                    if let data = try? JSONDecoder().decode(T.self, from: data!){
                        promise(.success(.success(data)))
                    }else {
                        promise(.success(.failure(.empty)))
                    }
                }
                else if let error = error as? URLError {
                    switch error.code {
                    case .notConnectedToInternet, .networkConnectionLost, .timedOut:
                        promise(.success(.failure(.noInternetConnection)))
                    case .cannotDecodeRawData, .cannotDecodeContentData:
                        promise(.success(.failure(.empty)))
                    default:
                        break
                }
                }else {
                    promise(.success(.failure(.general)))
                }
            }
    }
    .eraseToAnyPublisher()
}
}
</code>```

But when I call this function in viewModel it returns empty array, but there is not any error thrown.
I used breakpoints on if and else statements and program is actually not executing them.

答:
A standard dataTask of URLSession must be resumed

```<code>URLSession
    .shared
    .dataTask(with: url) { data, response, error in

       ...

    }
    .resume()
</code>```

An alternative is Combine's .dataTaskPublisher(for

ContentLicense: CC BY-SA 4.0

Title: dataTask in networking is not executing

Body:
In RestManager class, using URLSession I want to return AnyPublisher<Result<T, ErrorType>, Never>.

So I made this code

class RestManager {

func fetchData<T: Decodable>(url: URL) -> AnyPublisher<Result<T, ErrorType>, Never> {

    return Future<Result<T, ErrorType>, Never> { promise in
        URLSession
            .shared
            .dataTask(with: url) { data, response, error in
                if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                    if let data = try? JSONDecoder().decode(T.self, from: data!){
                        promise(.success(.success(data)))
                    }else {
                        promise(.success(.failure(.empty)))
                    }
                }
                else if let error = error as? URLError {
                    switch error.code {
                    case .notConnectedToInternet, .networkConnectionLost, .timedOut:
                        promise(.success(.failure(.noInternetConnection)))
                    case .cannotDecodeRawData, .cannotDecodeContentData:
                        promise(.success(.failure(.empty)))
                    default:
                        break
                }
                }else {
                    promise(.success(.failure(.general)))
                }
            }
    }
    .eraseToAnyPublisher()
}
}

But when I call this function in viewModel it returns empty array, but there is not any error thrown.
I used breakpoints on if and else statements and program is actually not executing them.

Body:
A standard dataTask of URLSession must be resumed

URLSession
    .shared
    .dataTask(with: url) { data, response, error in

       ...

    }
    .resume()

An alternative is Combine's .dataTaskPublisher(for


问:
How to run stm32 unit tests on Linux PC?
I am trying to unit test (using unity+ceedling) some STM32 code on my linux machine, but every time I access any register the code fails with this error:

```<code>> Produced no final test result counts in $stdout:
Segmentation fault (core dumped)
> And exited with status: [0] (count of failed tests).
> This is often a symptom of a bad memory access in source or test code
</code>```

For example this code will result in PASSED 1/1 (note that I am testing function that returns a+b and has nothing to do with STM peripherals).

```<code>#include "unity.h"
#include "sum2nums.h"
#include "stm32f4xx.h"

void test_Sum(){
    TEST_ASSERT_EQUAL_UINT32(5, Sum(3, 2));
}
</code>```

But this code will produced the error mentioned above.

```<code>#include "unity.h"
#include "sum2nums.h"
#include "stm32f4xx.h"

void test_Sum(){
    GPIOA->MODER = 1U;
    TEST_ASSERT_EQUAL_UINT32(5, Sum(3, 2));
}
</code>```

Is it even possible to test it this way or do I have to use QEMU (and how to do so without using Eclipse or any other IDE)? Note that Ceedling uses gcc, if I'd use arm-none-eabi it would produce hex file and I couldn't run that on my PC.

答:
there is a simple solution if you want to run it on PC.  You simply copy the stm32fxxx.h header from your STM library and then in that file you replace all the addresses with simple variables. For example:

```<code>volatile USART_TypeDef    usart0_base;
#define USART0_BASE       (&usart0_base) /**< USART0 base address  */
</code>```

Now you change the main header where your CPU specific include is added and and add a MOCK or some define, which will swap the hardware addressed header with this header and you can compile with your computer GCC and run as well on linux (much faster). That way you basically mocked the hardware and replaced it by simple memory.

Body:
I am trying to unit test (using unity+ceedling) some STM32 code on my linux machine, but every time I access any register the code fails with this error:

> Produced no final test result counts in $stdout:
Segmentation fault (core dumped)
> And exited with status: [0] (count of failed tests).
> This is often a symptom of a bad memory access in source or test code

For example this code will result in PASSED 1/1 (note that I am testing function that returns a+b and has nothing to do with STM peripherals).

#include "unity.h"
#include "sum2nums.h"
#include "stm32f4xx.h"

void test_Sum(){
    TEST_ASSERT_EQUAL_UINT32(5, Sum(3, 2));
}

But this code will produced the error mentioned above.

#include "unity.h"
#include "sum2nums.h"
#include "stm32f4xx.h"

void test_Sum(){
    GPIOA->MODER = 1U;
    TEST_ASSERT_EQUAL_UINT32(5, Sum(3, 2));
}

Is it even possible to test it this way or do I have to use QEMU (and how to do so without using Eclipse or any other IDE)? Note that Ceedling uses gcc, if I'd use arm-none-eabi it would produce hex file and I couldn't run that on my PC.

Body:
there is a simple solution if you want to run it on PC.  You simply copy the stm32fxxx.h header from your STM library and then in that file you replace all the addresses with simple variables. For example:

volatile USART_TypeDef    usart0_base;
#define USART0_BASE       (&usart0_base) /**< USART0 base address  */

Now you change the main header where your CPU specific include is added and and add a MOCK or some define, which will swap the hardware addressed header with this header and you can compile with your computer GCC and run as well on linux (much faster). That way you basically mocked the hardware and replaced it by simple memory.


问:
Send E-mail using SMTP with HTML Body & Signature
Managed to get this sending using Excel with SMTP.

When sending one e-mail at a time, the first one has the signature  displayed where it should be.

Second e-mail sent has the signature but adds the signature as an attachment.

Third e-mail sent has the signature but adds the signature as an attachment twice, and it will repeat the the cycle adding more signature images as attachments.

TLDR:

1 e-mail sent = 0 attachment

2 e-mails sent = 1 attachment

3 e-mails sent = 2 attachments

I don't want any attached files.

Sub SendMail()
    Set MyEmail = CreateObject("CDO.Message")
    Path = "C:\Users\Users1\Desktop\Signature\"

    Dim sh As Worksheet
    Set sh = ThisWorkbook.Sheets("Sheet1")
    Set sh2 = ThisWorkbook.Sheets("Sheet2")

    Dim nDateTime As Date, oDateTime As Date
    nDateTime = Now
    oDateTime = nDateTime - 3

    Dim last_row As Integer
    last_row = Application.CountA(sh.Range("A:A"))
    For i = 2 To last_row
    Set emailConfig = MyEmail.Configuration

With MyEmail
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl")
= redacted
    emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername")
= redacted
    emailConfig.Fields.Update
    MyEmail.Configuration.Fields.Update

End With

mail_body_message = sh2.Range("D2")
serial_number = sh.Range("A" & i).Value
mail_body_message = Replace(mail_body_message, "replace_serial_here", serial_number)
Attachment = Path + Filename
signaturelogo = "userSignature.png"

With MyEmail

Attachment = Path + Filename
signaturelogo = "userSignature.png"
Path = "C:\Users\Users1\Desktop\Signature\"
.Subject = "Hello there (HTTPS) Serial: " & serial_number
.From = "redacted"
.To = sh.Range("B" & i).Value
.HTMLBody = mail_body_message
.Attachments.Add Path & signaturelogo, 0

End With

If sh.Range("C" & i).Value <= oDateTime Then
    MyEmail.Send
End If

Next i

End Sub
```

答:
Because you are re-using the same object just attach the logo once at the start.

Option Explicit

Sub SendMyMail()

    Const LOGO = "C:\Users\Users1\Desktop\Signature\userSignature.png"
    Const DAYS = 3
    Const SCHEMA = "http://schemas.microsoft.com/cdo/configuration/"

    ' configure email
    Dim MyEmail As Object
    Set MyEmail = CreateObject("CDO.Message")
    With MyEmail
        With .Configuration.Fields
            .Item(SCHEMA & "sendusing") = 2
            .Item(SCHEMA & "smtpserver") = "smtp.#.com"
            .Item(SCHEMA & "smtpserverport") = 465
            .Item(SCHEMA & "smtpauthenticate") = 1
            .Item(SCHEMA & "sendusername") = "#@#"
            .Item(SCHEMA & "sendpassword") = "#"
            .Item(SCHEMA & "smtpusessl") = 1
            .Update
        End With
        ' add logo
        .AddAttachment LOGO
    End With

    Dim sh As Worksheet, sh2 As Worksheet
    Dim serialno As String, n As Long, i As Long, last_row As Long
    Set sh = ThisWorkbook.Sheets("Sheet1")
    Set sh2 = ThisWorkbook.Sheets("Sheet2")

    With sh
        last_row = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    For i = 2 To last_row
        If sh.Range("C" & i).Value <= Now - DAYS Then
            serialno = sh.Range("A" & i).Value
            With MyEmail
                .Subject = "Hello there (HTTPS) Serial: " & serialno
                .From = "redacted"
                .To = sh.Range("B" & i).Value
                .HTMLBody = Replace(sh2.Range("D2"), "replace_serial_here", serialno)

                ' send
                On Error Resume Next
                .Send
                If Err.Number = 0 Then
                    n = n + 1
                Else
                    MsgBox Err.Description, vbExclamation, "Error Row " & i
                End If
                On Error GoTo 0

            End With
        Else
            'Debug.Print "Skipped row " & i & " = " & sh.Range("C" & i)
        End If
    Next

    MsgBox n & " emails sent", vbInformation

End Sub
```


问:
Why can't I get two lists from one list comprehension?
So I have an array of the following form:

```<code>[(1, u'first_type', u'data_gid_1'),
 (2, u'first_type', u'data_gid_2'),
 (3, u'first_type', u'data_gid_3'),
 (4, u'first_type', u'data_gid_4')]
</code>```

Now I want to extract the first and the last element of each inside list into separate lists. So if I do:

```<code>>>> ids = [dat[0] for dat in all_data]
>>> gds = [dat[2] for dat in all_data]
</code>```

This works as I expect it to. However I was trying to merge these two into one call, something like:

```<code> (ids, gds) = [(dat[0], dat[2]) for dat in all_data]
</code>```

This however fails with an:
     ValueError: too many values to unpack

So could anyone explain why this is happening and if what I am trying to do is even possible.

Regards,
Bogdan

答:
[(dat[0], dat[2]) for dat in all_data] means that you're creating a list of tuples (dat[0],dat[2]). It does not mean you have two lists, one of d[0] and the other of d[2].

You could simply use zip, but that will result in tuples. If you want lists, you'll have to apply list to the result:

```<code>(ids, gds) = map(list,zip(*[(dat[0], dat[2]) for dat in a]))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I have an array of the following form:

[(1, u'first_type', u'data_gid_1'),
 (2, u'first_type', u'data_gid_2'),
 (3, u'first_type', u'data_gid_3'),
 (4, u'first_type', u'data_gid_4')]

Now I want to extract the first and the last element of each inside list into separate lists. So if I do:

>>> ids = [dat[0] for dat in all_data]
>>> gds = [dat[2] for dat in all_data]

This works as I expect it to. However I was trying to merge these two into one call, something like:

 (ids, gds) = [(dat[0], dat[2]) for dat in all_data]

This however fails with an:
     ValueError: too many values to unpack

So could anyone explain why this is happening and if what I am trying to do is even possible.

Regards,
Bogdan

Body:
[(dat[0], dat[2]) for dat in all_data] means that you're creating a list of tuples (dat[0],dat[2]). It does not mean you have two lists, one of d[0] and the other of d[2].

You could simply use zip, but that will result in tuples. If you want lists, you'll have to apply list to the result:

(ids, gds) = map(list,zip(*[(dat[0], dat[2]) for dat in a]))


问:
Create specific bean dependant on property
Lets say i have two beans:

class MyBean implements BeanInterface(){}

class MyBean2 implements BeanInterface(){}

And if specific property exists, i want to create MyBean, otherwise I want to create MyBean2(). How can i do this?

```<code>@Bean
@ConditionalOnProperty(name = "property.validation")
public BeanInterface beanInterface() {
    return new MyBean();
}
</code>```

works if I want to create MyBean if property exists, but how do I create MyBean2 if it doesn't?

```<code>@Bean
@ConditionalOnMissingBean(MyBean.class)
public BeanInterface beanInterface() {
    return new MyBean2();
}
</code>```

complains that method with same name exists, and if i understand it correctly, the methods name need to be camelCase name of the bean.

How do i do this?

Thanks

//edit i tried:

```<code>@Bean
@ConditionalOnProperty(name = "property.validation")
@Order(1)
public BeanInterface beanInterface() {
    return new MyBean();
}

@Bean("beanInterface")
@ConditionalOnMissingBean(MyBean.class)
@Order(2)
public BeanInterface beanInterface() {
    return new MyBean2();
}
</code>```

but it didnt work, second bean is not getting created when property is missing.

答: You can specify bean name @Bean("beanInterface") then method name can be anything.

Body:
Lets say i have two beans:

class MyBean implements BeanInterface(){}

class MyBean2 implements BeanInterface(){}

And if specific property exists, i want to create MyBean, otherwise I want to create MyBean2(). How can i do this?

@Bean
@ConditionalOnProperty(name = "property.validation")
public BeanInterface beanInterface() {
    return new MyBean();
}

works if I want to create MyBean if property exists, but how do I create MyBean2 if it doesn't?

@Bean
@ConditionalOnMissingBean(MyBean.class)
public BeanInterface beanInterface() {
    return new MyBean2();
}

complains that method with same name exists, and if i understand it correctly, the methods name need to be camelCase name of the bean.

How do i do this?

Thanks

//edit i tried:

@Bean
@ConditionalOnProperty(name = "property.validation")
@Order(1)
public BeanInterface beanInterface() {
    return new MyBean();
}

@Bean("beanInterface")
@ConditionalOnMissingBean(MyBean.class)
@Order(2)
public BeanInterface beanInterface() {
    return new MyBean2();
}

but it didnt work, second bean is not getting created when property is missing.


问:
How to access the value of constant in settings.py
I'd like ask about how to access the value of a constant declared in setting.py the following way:

```<code>PAYMENT_VARIANTS = {
'redsys': ('payments_redsys.RedsysProvider', {
    'merchant_code': '123456789',
    'terminal': '1',
    'shared_secret': 'aaaaaaaaaaaaaaaaaaaaaaaaaa',
    'currency': '978',
})
</code>```

}

I can import:

```<code>from django.conf import settings
</code>```

But, how I can access the value of field 'currency' or other at this level.

Thanks, regards,

答:
You can do for example:

```<code>from django.conf import settings

if settings.DEBUG:
    # Do something
</code>```

In your case would be something like:

```<code>settings.PAYMENT_VARIANTS['redsys']
</code>```

Body:
I'd like ask about how to access the value of a constant declared in setting.py the following way:

PAYMENT_VARIANTS = {
'redsys': ('payments_redsys.RedsysProvider', {
    'merchant_code': '123456789',
    'terminal': '1',
    'shared_secret': 'aaaaaaaaaaaaaaaaaaaaaaaaaa',
    'currency': '978',
})

}

I can import:

from django.conf import settings

But, how I can access the value of field 'currency' or other at this level.

Thanks, regards,

Body:
You can do for example:

from django.conf import settings

if settings.DEBUG:
    # Do something

In your case would be something like:

settings.PAYMENT_VARIANTS['redsys']


问:
Disable local authentication methods for Cosmos DB database accounts using Azure CLI
I am trying to create a cosmos DB account using Azure CLI.
One of required policies I have to comply with is "Cosmos DB database accounts should have local authentication methods disabled". In the following document I see how to set it using Azure Resource Manager templates . See below

```<code>"resources": [
    {
        "type": " Microsoft.DocumentDB/databaseAccounts",
        "properties": {
            "disableLocalAuth": true,
            // ...
        },
        // ...
    },
    // ...
 ]
</code>```

Now my question is how to do the same using AZ CLI?

The command I am using is => az cosmosdb create ...

I don't see any flag that will allow the similar setting in AZ CLI.

答:
You can always use Azure REST API invocation to apply any change in the CosmosDB account, see here

https://learn.microsoft.com/en-us/rest/api/cosmos-db-resource-provider/2021-10-15/database-accounts/create-or-update

I've used Postman for that, btw I post a CURL example here by which I was able to modify a couple of properties (you need to get an oauth2 token before):

```<code>curl --location --request PUT 'https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<database-account-name>?api-version=2021-10-15' \
--header 'Authorization: Bearer <oauth2-token>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "location": "North Europe",
    "properties": {
        "databaseAccountOfferType": "Standard",
        "disableLocalAuth": true,
        "disableKeyBasedMetadataWriteAccess":true,
        "locations": [
            {
                "isVirtualNetworkFilterEnabled": false,
                "locationName": "North Europe",
                "failoverPriority": 0,
                "isZoneRedundant": false
            }
        ]
    }
}'
</code>```

Body:
I am trying to create a cosmos DB account using Azure CLI.
One of required policies I have to comply with is "Cosmos DB database accounts should have local authentication methods disabled". In the following document I see how to set it using Azure Resource Manager templates . See below

"resources": [
    {
        "type": " Microsoft.DocumentDB/databaseAccounts",
        "properties": {
            "disableLocalAuth": true,
            // ...
        },
        // ...
    },
    // ...
 ]

Now my question is how to do the same using AZ CLI?

The command I am using is => az cosmosdb create ...

I don't see any flag that will allow the similar setting in AZ CLI.

Body:
You can always use Azure REST API invocation to apply any change in the CosmosDB account, see here

https://learn.microsoft.com/en-us/rest/api/cosmos-db-resource-provider/2021-10-15/database-accounts/create-or-update

I've used Postman for that, btw I post a CURL example here by which I was able to modify a couple of properties (you need to get an oauth2 token before):

curl --location --request PUT 'https://management.azure.com/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<database-account-name>?api-version=2021-10-15' \
--header 'Authorization: Bearer <oauth2-token>' \
--header 'Content-Type: application/json' \
--data-raw '{
    "location": "North Europe",
    "properties": {
        "databaseAccountOfferType": "Standard",
        "disableLocalAuth": true,
        "disableKeyBasedMetadataWriteAccess":true,
        "locations": [
            {
                "isVirtualNetworkFilterEnabled": false,
                "locationName": "North Europe",
                "failoverPriority": 0,
                "isZoneRedundant": false
            }
        ]
    }
}'


问:
Use derived class to add properties and maintain compatibility with existing classes
I'm writing a Qt 6.2.0 application running in Ubuntu 20.04.
My goal is to add a property to the existing class QtOpcUaNode.
So I wrote:

```<code>class MyOpcUaNode : public QOpcUaNode
{
    Q_OBJECT

public:
    explicit MyOpcUaNode(QOpcUaNode *parent = nullptr) : QOpcUaNode(parent) { }
    bool updated;
};
</code>```

But here the first error:

```<code>error: no matching function for call to ‘QOpcUaNode::QOpcUaNode(QOpcUaNode*&)’
In file included from ../MyProject/myproject.cpp:1:
../MyProject/myproject.h: In constructor ‘MyOpcUaNode::MyOpcUaNode(QOpcUaNode*)’:
../MyProject/myproject.h:16:73: error: no matching function for call to ‘QOpcUaNode::QOpcUaNode(QOpcUaNode*&)’
   16 |     explicit MyOpcUaNode(QOpcUaNode *parent = nullptr) : QOpcUaNode(parent) { }
      |                                                                         ^
</code>```

I want to use my class in this way:

```<code>QList<MyOpcUaNode *> _listOpcNodes;

_listOpcNodes.append(MyOpcUaNode(_opcUaClient->node("ns=4;s=MEM_RUN_LINE")));
...
_listOpcNodes[x]->updated = true;
</code>```

Is it correct my approach?

I tried without the copy-constructor but I was not sure how to convert a QOpcUaNode * to MyOpcUaNode *. Trying with:

```<code>MyOpcUaNode *node = qobject_cast<MyOpcUaNode *>(_opcUaClient->node("ns=4;s=MEM_RUN_LINE"));
</code>```

lead node to be a null pointer (even if the _opcUaClient->node was correct).

答: If you want to add property to class which inherits from QObject, you can do it with setProperty() https://doc.qt.io/qt-5/qobject.html#setProperty. Well, it is not type-safe but it is very simple. Sometimes pragmatism beats purism.

Body:
I'm writing a Qt 6.2.0 application running in Ubuntu 20.04.
My goal is to add a property to the existing class QtOpcUaNode.
So I wrote:

class MyOpcUaNode : public QOpcUaNode
{
    Q_OBJECT

public:
    explicit MyOpcUaNode(QOpcUaNode *parent = nullptr) : QOpcUaNode(parent) { }
    bool updated;
};

But here the first error:

error: no matching function for call to ‘QOpcUaNode::QOpcUaNode(QOpcUaNode*&)’
In file included from ../MyProject/myproject.cpp:1:
../MyProject/myproject.h: In constructor ‘MyOpcUaNode::MyOpcUaNode(QOpcUaNode*)’:
../MyProject/myproject.h:16:73: error: no matching function for call to ‘QOpcUaNode::QOpcUaNode(QOpcUaNode*&)’
   16 |     explicit MyOpcUaNode(QOpcUaNode *parent = nullptr) : QOpcUaNode(parent) { }
      |                                                                         ^

I want to use my class in this way:

QList<MyOpcUaNode *> _listOpcNodes;

_listOpcNodes.append(MyOpcUaNode(_opcUaClient->node("ns=4;s=MEM_RUN_LINE")));
...
_listOpcNodes[x]->updated = true;

Is it correct my approach?

I tried without the copy-constructor but I was not sure how to convert a QOpcUaNode * to MyOpcUaNode *. Trying with:

MyOpcUaNode *node = qobject_cast<MyOpcUaNode *>(_opcUaClient->node("ns=4;s=MEM_RUN_LINE"));

lead node to be a null pointer (even if the _opcUaClient->node was correct).


问:
How to list all the log group in Cloudwatch using boto3
How to I list all the log groups in Cloudwatch using Boto3. When I try the below syntax. I get error.

```<code>client = boto3.client('logs')

response = client.describe_log_groups(limit=51)
</code>```

validation error detected: Value '51' at 'limit' failed to satisfy
constraint: Member must have value less than or equal to 50

Based on documentation we could go above 50

limit (integer) -- The maximum number of items returned. If you don't
specify a value, the default is up to 50 items.

答:
When in doubt, always go to the API documentation, which says the following:

Valid Range: Minimum value of 1. Maximum value of 50.

To solve your problem, you need to use a paginator:

```<code>paginator = logs_client.get_paginator('describe_log_groups')
for page in paginator.paginate():
    for group in page['logGroups']:
        print(group)
</code>```

Body:
How to I list all the log groups in Cloudwatch using Boto3. When I try the below syntax. I get error.

client = boto3.client('logs')

response = client.describe_log_groups(limit=51)

validation error detected: Value '51' at 'limit' failed to satisfy
constraint: Member must have value less than or equal to 50

Based on documentation we could go above 50

limit (integer) -- The maximum number of items returned. If you don't
specify a value, the default is up to 50 items.

Body:
When in doubt, always go to the API documentation, which says the following:

Valid Range: Minimum value of 1. Maximum value of 50.

To solve your problem, you need to use a paginator:

paginator = logs_client.get_paginator('describe_log_groups')
for page in paginator.paginate():
    for group in page['logGroups']:
        print(group)


问:
Youtube Music API for Uploaded music
Problem:
Youtube Music sucks for playing back music you have uploaded for years. The app sucks, and the Android Auto app sucks. I've contacted the YT Music team many times, but they don't seem to listen to music ever so they don't even understand the problem(s).

Solution:
Create my own app to play back my own music that lives in Google/Youtube Music. I'm an Android app developer so might as well fix this my own way.

Are there APIs for Youtube Music? I know there's an unofficial Youtube Music API, but that's phython, it doesn't build at the moment (Feb 2022), and it seems to focus on paid music, not my own uploaded library.

Would Google drive APIs do this? If so, is there documentation on how to use it? I can figure out the OAuth part, but I don't know where to get the data for the parameters in this sample api

Is there a better way for this? I just need to download the music files, and then create a player around them.

Thank you!

答:
I was looking for something similar but the closest I got was ytmusicapi in python. It works for me and I installed it via pip install ytmusicapi. Its source is hosted on https://github.com/sigma67/ytmusicapi there, perhaps, you can see the YTM protocol. Authentication works by simply copying cookies from your browser after authenticating with YTM manually. That worked for me as well.

Another option is Kodi and a plugin they have: https://forum.kodi.tv/showthread.php?tid=360827 (but that did not seem to work for me after 3 minutes I spent on it).

If you are serious about it and you can't get YTM protocol via the source of ytmusicapi, then you can perhaps reverse-engineer the protocol using your browser. Firefox's Tools->Browser Tools->Web Developer Tools is your best friend. After you authenticate to YTM, open the "tools", click on "Library" on YTM webpage, then in "tools" tab, go to Network and look for a POST similar to https://music.youtube.com/youtubei/v1/browse?key=... right click on it and Copy->Copy as Curl. You will be able to see what auth-headers it sends and also what's the protocol for showing up your YTM Library.

Title: Youtube Music API for Uploaded music


问:
How to destroy the kafka message listener container rather than stopping it
I am trying to dynamically add/ remove listeners in run time using the KafkaListenerEndpointRegistry. This class provides option to register new listener in run time, but does not have option to destroy/unregister an already running listener. We have a stop API to stop a particular container, but we have to destroy the container with a particular id and want to re-register it with same id but different set of topics.
Could anyone please let us know if we have a feasible solution to do it.</p>

答:
The registry has no API to completely remove containers.

Don't use the endpoint registry to create these containers, just use the container factory yourself (see the code in the registry), and keep track of them; then you can stop() and destroy() them as needed.


问:
How can I change active Bootstrap tab style to underline?
Bootstrap nav tab how to change active tab to underline?
This is my code.

// Bootstrap Handles The Javascript```
<pre class="snippet-code-css lang-css prettyprint-override"><code>// Add css to underline the active tab</code>```

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

      <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Home</button>
      <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button" role="tab" aria-controls="nav-profile" aria-selected="false">Profile</button>
      <button class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" data-bs-target="#nav-contact" type="button" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</button>

Home

Profile

Contact

```

Thanks in advance!

答:
You can do it this way:

// Tabs
var triggerTabList = [].slice.call(
    document.querySelectorAll(".nav-tabs>button")
);
triggerTabList.forEach(function (triggerEl) {
    var tabTrigger = new bootstrap.Tab(triggerEl);

    triggerEl.addEventListener("click", function (event) {
        document.querySelectorAll(".nav-tabs>button").forEach(
            (button) =>
                (button.style.cssText = `
            background-color: #fff;
            color: rgb(245, 158 ,11);
            transition: background-color .5s;
            `)
        );

        document.querySelectorAll(".nav-tabs>button.active").forEach(
            (button) =>
                (button.style.cssText = `
          cursor: default;
          background-color: #fff;
          font-weight: bold;
          border: none;
          border-bottom: 3px solid rgb(245, 158 ,11);
          color: rgb(245, 158 ,11);
          transition: all .5s;`)
        );
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nav-tabs>button.active,
.nav-tabs>button.active:hover,
.nav-tabs>button.active:focus {
  color: #555;
  cursor: default;
  background-color: #fff;
  font-weight: bold;
  border: none;
  border-bottom: 3px solid #1976d2;
}

.nav-tabs>button {
  transition: none;
  border-bottom: 1px solid #dee2e6;
}

.nav-tabs>button:hover {
  border: none;
  border-bottom: 1px solid #dee2e6;
  margin-bottom: 0px;
  /* font-size: initial; */
}</code>```

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

      <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Home</button>
      <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button" role="tab" aria-controls="nav-profile" aria-selected="false">Profile</button>
      <button class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" data-bs-target="#nav-contact" type="button" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</button>

Home

Profile

Contact

```

Body:
Bootstrap nav tab how to change active tab to underline?
This is my code.

// Bootstrap Handles The Javascript

// Add css to underline the active tab

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

      <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Home</button>
      <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button" role="tab" aria-controls="nav-profile" aria-selected="false">Profile</button>
      <button class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" data-bs-target="#nav-contact" type="button" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</button>

Home

Profile

Contact

Thanks in advance!

Body:
You can do it this way:

// Tabs
var triggerTabList = [].slice.call(
    document.querySelectorAll(".nav-tabs>button")
);
triggerTabList.forEach(function (triggerEl) {
    var tabTrigger = new bootstrap.Tab(triggerEl);

    triggerEl.addEventListener("click", function (event) {
        document.querySelectorAll(".nav-tabs>button").forEach(
            (button) =>
                (button.style.cssText = `
            background-color: #fff;
            color: rgb(245, 158 ,11);
            transition: background-color .5s;
            `)
        );

        document.querySelectorAll(".nav-tabs>button.active").forEach(
            (button) =>
                (button.style.cssText = `
          cursor: default;
          background-color: #fff;
          font-weight: bold;
          border: none;
          border-bottom: 3px solid rgb(245, 158 ,11);
          color: rgb(245, 158 ,11);
          transition: all .5s;`)
        );
    });
});

.nav-tabs>button.active,
.nav-tabs>button.active:hover,
.nav-tabs>button.active:focus {
  color: #555;
  cursor: default;
  background-color: #fff;
  font-weight: bold;
  border: none;
  border-bottom: 3px solid #1976d2;
}

.nav-tabs>button {
  transition: none;
  border-bottom: 1px solid #dee2e6;
}

.nav-tabs>button:hover {
  border: none;
  border-bottom: 1px solid #dee2e6;
  margin-bottom: 0px;
  /* font-size: initial; */
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<div class="container">
  <nav>
    <div class="nav nav-tabs" id="nav-tab" role="tablist">
      <button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Home</button>
      <button class="nav-link" id="nav-profile-tab" data-bs-toggle="tab" data-bs-target="#nav-profile" type="button" role="tab" aria-controls="nav-profile" aria-selected="false">Profile</button>
      <button class="nav-link" id="nav-contact-tab" data-bs-toggle="tab" data-bs-target="#nav-contact" type="button" role="tab" aria-controls="nav-contact" aria-selected="false">Contact</button>
    </div>
  </nav>
  <div class="tab-content" id="nav-tabContent">
    <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">Home</div>
    <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">Profile</div>
    <div class="tab-pane fade" id="nav-contact" role="tabpanel" aria-labelledby="nav-contact-tab">Contact</div>
  </div>
</div>


问:
cannot enable cors in nestJs
I'm trying to connect react and NestJS but got cors error
my request from the browser (google chrome) is blocked by cors.
I cannot even log the incoming request!!!!!!
in the browser network tab I see CORS error from xhr
and in the console tab I see

```<code>Access to XMLHttpRequest at 'localhost:3500/api/v1/users/login' from origin
'http://localhost:3001' has been blocked by CORS policy: Cross origin requests are only supported
for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
Axios Error: Network Error
    at createError (createError.js:16:1)
    at XMLHttpRequest.handleError (xhr.js:84:1)
xhr.js:177 POST localhost:3500/api/v1/users/login net::ERR_FAILED
</code>```

I've tried { cors: true } and app.enableCors(); and

```<code>app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
</code>```

and

```<code>const corsOptions: CorsOptions = {
    allowedHeaders: ['origin', 'x-requested-with', 'content-type', 'accept', 'authorization'],
    credentials: true,
    origin: ['http://localhost:3001', 'http://localhost:3000'],
  }
  app.enableCors(corsOptions);
</code>```

答:
Looks like you're making a request to localhost:3500/api/v1/users/login, which has no scheme.

Use http://localhost:3500/api/v1/users/login instead

Title: cannot enable cors in nestJs

Body:
I'm trying to connect react and NestJS but got cors error
my request from the browser (google chrome) is blocked by cors.
I cannot even log the incoming request!!!!!!
in the browser network tab I see CORS error from xhr
and in the console tab I see

Access to XMLHttpRequest at 'localhost:3500/api/v1/users/login' from origin
'http://localhost:3001' has been blocked by CORS policy: Cross origin requests are only supported
for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.
Axios Error: Network Error
    at createError (createError.js:16:1)
    at XMLHttpRequest.handleError (xhr.js:84:1)
xhr.js:177 POST localhost:3500/api/v1/users/login net::ERR_FAILED

I've tried { cors: true } and app.enableCors(); and

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });

and

const corsOptions: CorsOptions = {
    allowedHeaders: ['origin', 'x-requested-with', 'content-type', 'accept', 'authorization'],
    credentials: true,
    origin: ['http://localhost:3001', 'http://localhost:3000'],
  }
  app.enableCors(corsOptions);


问:
How to create forms using VUE?
It is my first day learning VUE, and I'm following a tutorial by freeCodeCamp.org on YTB.

When it comes to the concept of component, the lecturer showed how to create a login form project by using components.
I followed exactly what she typed, but the code just didn't run. I'm confused why that happened.

Here is the ytb address: https://www.youtube.com/watch?v=FXpIoQ_rT_c&t=2224s , and the component section started from 00:29:20.

Here are the codes. Can anyone tell the reason plz? thx ahead!

```<code><!DOCTYPE html>
<html>
<head>
<title>vueComponents</title>
<style type="text/css">
    [v-cloak]{
        display: none;
    }
    input {
        margin: 10px;
        display: block;
    }
</style>
</head>
<body>
<div id="app" v-cloak>
    <login-form />
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
    let app=Vue.createApp({
        data():{
            return{
                greeting : 'hello VUE',
            }
        }
    })
    app.component ('login-form',{
        template: ‘
            <form @submit="handleSubmit">
                <h1> {{ title }} </h1>
                <input type="email" />
                <input type="password" />
                <button>Log In</button>
            </form>
            ’,
        data(){
            return{
                title:'Login Form'
            }
        },
        methods:{
            handleSubmit(){
                console.log('submitted')
            }
        }

    })
    app.mount('#app')
</script>
</body>
</html>
</code>```

答:
Looks like there is an issue with quotes in the template.

Working Demo :

let app = Vue.createApp({
  data() {
    return {
        greeting : 'hello VUE',
        }
  }
})
app.component ('login-form',{
  template: `<form @submit="handleSubmit">

 {{ title }}

               <input type="email" />
               <input type="password" />
               <button>Log In</button>
               </form>`,
  data() {
    return {
        title:'Login Form'
    }
    },
  methods:{
    handleSubmit(){
      console.log('submitted')
    }
  }
})
app.mount('#app')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/vue@next"></script>

<div id="app" v-cloak>
    <login-form />
</div></code>```

Title: How to create forms using VUE?

Body:
It is my first day learning VUE, and I'm following a tutorial by freeCodeCamp.org on YTB.

When it comes to the concept of component, the lecturer showed how to create a login form project by using components.
I followed exactly what she typed, but the code just didn't run. I'm confused why that happened.

Here is the ytb address: https://www.youtube.com/watch?v=FXpIoQ_rT_c&t=2224s , and the component section started from 00:29:20.

Here are the codes. Can anyone tell the reason plz? thx ahead!

<!DOCTYPE html>

<title>vueComponents</title>

    <login-form />

Body:
Looks like there is an issue with quotes in the template.

Working Demo :

let app = Vue.createApp({
  data() {
    return {
        greeting : 'hello VUE',
        }
  }
})
app.component ('login-form',{
  template: `<form @submit="handleSubmit">
  <h1> {{ title }} </h1>
               <input type="email" />
               <input type="password" />
               <button>Log In</button>
               </form>`,
  data() {
    return {
        title:'Login Form'
    }
    },
  methods:{
    handleSubmit(){
      console.log('submitted')
    }
  }
})
app.mount('#app')

<script src="https://unpkg.com/vue@next"></script>

<div id="app" v-cloak>
    <login-form />
</div>


问:
print char pointer value in c
-: was trying to learn pointers in c :-

I couldn't print the value at the character pointer, rest of the program works fine.
It just prints a blank space, didn't get any error though.

```<code>#include<stdio.h>

void main() {
    int num, *num_ptr;
    char ch, *ch_ptr;

    printf("Enter a number and a single character : ");
    scanf("%d%c",&num,&ch);

    num_ptr = #
    ch_ptr = &ch;

    //printf("\ncontent at num_ptr = %p \n",num_ptr);
    //printf("content at ch_ptr = %p\n",ch_ptr);
    //printf("value of the content at num_ptr = %d\n",*num_ptr);

    /* error part */
        printf("value of the content at ch_ptr = %c\n",*ch_ptr);
    /* error part */

    //printf("\n");
    //printf("num_ptr + 2 = %p\n",num_ptr+2);
    //printf("ch_ptr + 2 = %p\n",ch_ptr+2);
    //printf("\n");
    //printf("num_ptr + 1 = %p\n",++num_ptr);
    //printf("num_ptr - 1 = %p\n",--num_ptr);
    //printf("ch_ptr + 1 = %p\n",++ch_ptr);
    //printf("ch_ptr - 1 = %p\n",--ch_ptr);
    //printf("\n");
    //printf("num_ptr + 5 = %p\n",num_ptr+5);
    //printf("ch_ptr - 5 = %p\n\n",--ch_ptr-5);
}
</code>```

答: Your input is 21 t, which means that scanf will read 21 into num, and the in-between whitespace into ch, which is what you specify in the first argument to scanf. You either separate the format specifiers by a blank space, i.e. %d %c, or enter the input without the whitespace, hence 21t.

Title: print char pointer value in c

Body:
-: was trying to learn pointers in c :-

I couldn't print the value at the character pointer, rest of the program works fine.
It just prints a blank space, didn't get any error though.

#include<stdio.h>

void main() {
    int num, *num_ptr;
    char ch, *ch_ptr;

    printf("Enter a number and a single character : ");
    scanf("%d%c",&num,&ch);

    num_ptr = #
    ch_ptr = &ch;

    //printf("\ncontent at num_ptr = %p \n",num_ptr);
    //printf("content at ch_ptr = %p\n",ch_ptr);
    //printf("value of the content at num_ptr = %d\n",*num_ptr);

    /* error part */
        printf("value of the content at ch_ptr = %c\n",*ch_ptr);
    /* error part */

    //printf("\n");
    //printf("num_ptr + 2 = %p\n",num_ptr+2);
    //printf("ch_ptr + 2 = %p\n",ch_ptr+2);
    //printf("\n");
    //printf("num_ptr + 1 = %p\n",++num_ptr);
    //printf("num_ptr - 1 = %p\n",--num_ptr);
    //printf("ch_ptr + 1 = %p\n",++ch_ptr);
    //printf("ch_ptr - 1 = %p\n",--ch_ptr);
    //printf("\n");
    //printf("num_ptr + 5 = %p\n",num_ptr+5);
    //printf("ch_ptr - 5 = %p\n\n",--ch_ptr-5);
}


问:
Aggregate payload of 3 different calls into 1 file | Mule 3
I try to aggregate the payload of three http request call into 1 file. I use the scatter gather for that. One of http requests call is using the output response of one http request and the other is alone. The issue is that I can not combine al three payload into one file. Does anyone have experience with this.

Below I have added the code and picture to make it clear.

This is my desire output in the file;

```<code>{
  "@odata.context": "https://servicenow.com/repo/odata/$metadata#Changes",
  "value": [
    {
       "id": "gggggg-210c-49d7-aa25-ddfdfdfdfd",
      "changenr": "1111111111111111",
      "Description": "xxxxxxxxxxxxx",
    },
    {
      "id": "fffffff-210c-49d7-aa25-ddfdfdfdfd",
      "changenr": "1111111111111111",
      "Description": "xxxxxxxxxxxxx",

    },
    {
      "id": "3k3k3k3-210c-3234-aa25-ddfdfdfdfd",
      "changenr": "1111111111111111",
      "Description": "xxxxxxxxxxxxx",
    }
  ],
  "@odata.context": "https://servicenow.com/repo/odata/$metadata#Details", #### USE THE ID of CHANGEs to call DETAILS
  "value": [
    {
      "id": "7005fc43-9c9d-43f5-abc1-656565cbdd63",
      "detailDesc": "No number present",
      "Date": "2022-01-24T18:59:58Z",
      "status": false,
    },
    {
      "id": "7005fc43-9c9d-43f5-abc1-656565cbdd63",
      "detailDesc": "No number present",
      "Date": "2022-01-24T18:59:58Z",
      "status": true,
    }
    ],
  "@odata.context": "https://servicenow.com/repo/odata/$metadata#Problems", ## SECOND CALL in the scatter
  "value": [
    {
      "id": "9001fc4a-8c8d-43f5-abc7-146945cbdd63",
      "problemnr": "problem with tank",
      "briefDescription": "H1",
      "reporterName": "unknow,",

    },
    {
    "id": "9001fc4a-8c8d-43f5-abc7-146945cbdd63",
      "problemnr": "problem with tank",
      "briefDescription": "H1 and h2",
      "reporterName": "unknow,",
    },
    {
     "id": "9001fc4a-8c8d-43f5-abc7-146945cbdd63",
      "problemnr": "problem with tank",
      "briefDescription": "H1 and h2 & H3",
      "reporterName": "unknow,",
    }
  ]
}
</code>```

Thanks guys.

```<code><?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:validation="http://www.mulesoft.org/schema/mule/validation" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/validation http://www.mulesoft.org/schema/mule/validation/current/mule-validation.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd">
    <http:request-config name="HTTP_Request_Configuration" protocol="HTTPS" host="servicenow.net" port="443" basePath="servicenow/Details?$filter=id eq #[flowVars.arrayCreate]" doc:name="HTTP Request Configuration">
        <http:basic-authentication username="xxxxxxxxxxxxxxx" password="xxxxxxxxxxxxxxxxxxxxx" preemptive="true"/>
    </http:request-config>
    <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
    <http:request-config name="HTTP_Request_Configuration1" protocol="HTTPS" host="lol.servicenow.net" port="443" basePath="/services/changes?$filter=Date gt 2021-12-01T10:00:00Z and Date lt 2021-12-01T11:00:00Z" doc:name="HTTP Request Configuration">
        <http:basic-authentication username="xxxxxxxxx" password="xxxxxxxxxxxxxxxxxxxx" preemptive="true"/>
    </http:request-config>
    <http:request-config name="HTTP_Request_Configuration2" protocol="HTTPS" host="servicenow.net" port="443" doc:name="HTTP Request Configuration">
        <http:basic-authentication username="xxxxxxxxxxx" password="xxxxxxxxxxxxxxxx" preemptive="true"/>
    </http:request-config>
    <file:connector name="File" autoDelete="true" outputAppend="true" streaming="true" validateConnections="true" doc:name="File"/>
    <file:connector name="File3" writeToDirectory="D:\servicenow" workFileNamePattern="second-of-three-#[function:datestamp:ddMMyyyy-HHmmss].json" autoDelete="true" outputAppend="true" streaming="true" validateConnections="true" doc:name="File"/>
    <file:connector name="File2222" writeToDirectory="D:\servicenow"  autoDelete="true" streaming="true" validateConnections="true" doc:name="File" outputAppend="true"/>
    <flow name="test-filtersFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
        <scatter-gather doc:name="Scatter-Gather">
            <processor-chain>
                <http:request config-ref="HTTP_Request_Configuration1" path="" method="GET" doc:name="HTTP"/>
                <dw:transform-message doc:name="Transform Message">
                    <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
                    <dw:set-variable variableName="arrayCreate"><![CDATA[%dw 1.0
%output application/java
---
(payload.value.id) joinBy " or id eq "]]></dw:set-variable>
                    <dw:set-variable variableName="incPayload"><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-variable>
                </dw:transform-message>
                <http:request config-ref="HTTP_Request_Configuration" path="" method="GET" doc:name="HTTP"/>
                <dw:transform-message doc:name="Transform Message">
                    <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload ++ flowVars.incPayload]]></dw:set-payload>
                </dw:transform-message>

            </processor-chain>
            <processor-chain>
                <http:request config-ref="HTTP_Request_Configuration2" path="servicenow/problems" method="GET" doc:name="HTTP"/>
                <dw:transform-message doc:name="Transform Message">
                    <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
                    <dw:set-variable variableName="catPayload"><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-variable>
                </dw:transform-message>
            </processor-chain>
        </scatter-gather>
        <file:outbound-endpoint path="D:\fileshare-service" outputPattern="second-of-three-#[function:datestamp:ddMMyyyy-HHmmss].json" responseTimeout="10000" doc:name="File" connector-ref="File2222"/>
        <dw:transform-message doc:name="Transform Message">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
        </dw:transform-message>
    </flow>
</mule>
</code>```

答:
Scatter-Gather collects the responses from all the concurrent routes, and aggregates them into a single message. In your case there is only TWO concurrent routes because one is sequential routes in which one http request is dependent on the other one. so you will not have three response array from Scatter-Gather. You need to provide what is the desired output you want so that we can help you.

The Structure of the Scatter-Gather will look like below which is array of JAVA .

{
"0": {
"attributes": "....",
"payload": ""
},
"1": {
"attributes": "....",
"payload": ""
}
}

Body:
I try to aggregate the payload of three http request call into 1 file. I use the scatter gather for that. One of http requests call is using the output response of one http request and the other is alone. The issue is that I can not combine al three payload into one file. Does anyone have experience with this.

Below I have added the code and picture to make it clear.

This is my desire output in the file;

{
  "@odata.context": "https://servicenow.com/repo/odata/$metadata#Changes",
  "value": [
    {
       "id": "gggggg-210c-49d7-aa25-ddfdfdfdfd",
      "changenr": "1111111111111111",
      "Description": "xxxxxxxxxxxxx",
    },
    {
      "id": "fffffff-210c-49d7-aa25-ddfdfdfdfd",
      "changenr": "1111111111111111",
      "Description": "xxxxxxxxxxxxx",

    },
    {
      "id": "3k3k3k3-210c-3234-aa25-ddfdfdfdfd",
      "changenr": "1111111111111111",
      "Description": "xxxxxxxxxxxxx",
    }
  ],
  "@odata.context": "https://servicenow.com/repo/odata/$metadata#Details", #### USE THE ID of CHANGEs to call DETAILS
  "value": [
    {
      "id": "7005fc43-9c9d-43f5-abc1-656565cbdd63",
      "detailDesc": "No number present",
      "Date": "2022-01-24T18:59:58Z",
      "status": false,
    },
    {
      "id": "7005fc43-9c9d-43f5-abc1-656565cbdd63",
      "detailDesc": "No number present",
      "Date": "2022-01-24T18:59:58Z",
      "status": true,
    }
    ],
  "@odata.context": "https://servicenow.com/repo/odata/$metadata#Problems", ## SECOND CALL in the scatter
  "value": [
    {
      "id": "9001fc4a-8c8d-43f5-abc7-146945cbdd63",
      "problemnr": "problem with tank",
      "briefDescription": "H1",
      "reporterName": "unknow,",

    },
    {
    "id": "9001fc4a-8c8d-43f5-abc7-146945cbdd63",
      "problemnr": "problem with tank",
      "briefDescription": "H1 and h2",
      "reporterName": "unknow,",
    },
    {
     "id": "9001fc4a-8c8d-43f5-abc7-146945cbdd63",
      "problemnr": "problem with tank",
      "briefDescription": "H1 and h2 & H3",
      "reporterName": "unknow,",
    }
  ]
}

Thanks guys.

<?xml version="1.0" encoding="UTF-8"?>

<mule xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:metadata="http://www.mulesoft.org/schema/mule/metadata" xmlns:validation="http://www.mulesoft.org/schema/mule/validation" xmlns:dw="http://www.mulesoft.org/schema/mule/ee/dw" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/dw http://www.mulesoft.org/schema/mule/ee/dw/current/dw.xsd
http://www.mulesoft.org/schema/mule/validation http://www.mulesoft.org/schema/mule/validation/current/mule-validation.xsd
http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd">
    <http:request-config name="HTTP_Request_Configuration" protocol="HTTPS" host="servicenow.net" port="443" basePath="servicenow/Details?$filter=id eq #[flowVars.arrayCreate]" doc:name="HTTP Request Configuration">
        <http:basic-authentication username="xxxxxxxxxxxxxxx" password="xxxxxxxxxxxxxxxxxxxxx" preemptive="true"/>
    </http:request-config>
    <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>
    <http:request-config name="HTTP_Request_Configuration1" protocol="HTTPS" host="lol.servicenow.net" port="443" basePath="/services/changes?$filter=Date gt 2021-12-01T10:00:00Z and Date lt 2021-12-01T11:00:00Z" doc:name="HTTP Request Configuration">
        <http:basic-authentication username="xxxxxxxxx" password="xxxxxxxxxxxxxxxxxxxx" preemptive="true"/>
    </http:request-config>
    <http:request-config name="HTTP_Request_Configuration2" protocol="HTTPS" host="servicenow.net" port="443" doc:name="HTTP Request Configuration">
        <http:basic-authentication username="xxxxxxxxxxx" password="xxxxxxxxxxxxxxxx" preemptive="true"/>
    </http:request-config>
    <file:connector name="File" autoDelete="true" outputAppend="true" streaming="true" validateConnections="true" doc:name="File"/>
    <file:connector name="File3" writeToDirectory="D:\servicenow" workFileNamePattern="second-of-three-#[function:datestamp:ddMMyyyy-HHmmss].json" autoDelete="true" outputAppend="true" streaming="true" validateConnections="true" doc:name="File"/>
    <file:connector name="File2222" writeToDirectory="D:\servicenow"  autoDelete="true" streaming="true" validateConnections="true" doc:name="File" outputAppend="true"/>
    <flow name="test-filtersFlow">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
        <scatter-gather doc:name="Scatter-Gather">
            <processor-chain>
                <http:request config-ref="HTTP_Request_Configuration1" path="" method="GET" doc:name="HTTP"/>
                <dw:transform-message doc:name="Transform Message">
                    <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
                    <dw:set-variable variableName="arrayCreate"><![CDATA[%dw 1.0
%output application/java
---
(payload.value.id) joinBy " or id eq "]]></dw:set-variable>
                    <dw:set-variable variableName="incPayload"><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-variable>
                </dw:transform-message>
                <http:request config-ref="HTTP_Request_Configuration" path="" method="GET" doc:name="HTTP"/>
                <dw:transform-message doc:name="Transform Message">
                    <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload ++ flowVars.incPayload]]></dw:set-payload>
                </dw:transform-message>

            </processor-chain>
            <processor-chain>
                <http:request config-ref="HTTP_Request_Configuration2" path="servicenow/problems" method="GET" doc:name="HTTP"/>
                <dw:transform-message doc:name="Transform Message">
                    <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
                    <dw:set-variable variableName="catPayload"><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-variable>
                </dw:transform-message>
            </processor-chain>
        </scatter-gather>
        <file:outbound-endpoint path="D:\fileshare-service" outputPattern="second-of-three-#[function:datestamp:ddMMyyyy-HHmmss].json" responseTimeout="10000" doc:name="File" connector-ref="File2222"/>
        <dw:transform-message doc:name="Transform Message">
            <dw:set-payload><![CDATA[%dw 1.0
%output application/json
---
payload]]></dw:set-payload>
        </dw:transform-message>
    </flow>
</mule>


问:
How to find similarity between two strings with function using python
These are two strings

```<code>string1 = 'SUTURE SILK 30 INCHES(75CM) 3-0 BLK'
string2 = 'SUTURE NON-ABSORBABLE PERMA-HAND SIZE 3-0 L'
</code>```

I want output like

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

how I can do this by using function

答:
Considering that you want to get the Levenshtein Distance, without any aditional dependency you can do something like this:

```<code>def levenshteinDistance(s1, s2):
if len(s1) > len(s2):
    s1, s2 = s2, s1

distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
    dist = [i2+1]
    for i1, c1 in enumerate(s1):
        if c1 == c2:
            dist.append(distances[i1])
        else:
            dist.append(1 + min((distances[i1], distances[i1 + 1], dist[-1])))
    distances = dist
return distances[-1]
</code>```

You can get more informations about this distance on wikipedia.

Body:
These are two strings

string1 = 'SUTURE SILK 30 INCHES(75CM) 3-0 BLK'
string2 = 'SUTURE NON-ABSORBABLE PERMA-HAND SIZE 3-0 L'

I want output like

0.801452

how I can do this by using function

Body:
Considering that you want to get the Levenshtein Distance, without any aditional dependency you can do something like this:

def levenshteinDistance(s1, s2):
if len(s1) > len(s2):
    s1, s2 = s2, s1

distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
    dist = [i2+1]
    for i1, c1 in enumerate(s1):
        if c1 == c2:
            dist.append(distances[i1])
        else:
            dist.append(1 + min((distances[i1], distances[i1 + 1], dist[-1])))
    distances = dist
return distances[-1]

You can get more informations about this distance on wikipedia.


问:
how to unit test file upload in django
In my django app, I have a view which accomplishes file upload.The  core snippet is like this

```<code>...
if  (request.method == 'POST'):
    if request.FILES.has_key('file'):
        file = request.FILES['file']
        with open(settings.destfolder+'/%s' % file.name, 'wb+') as dest:
            for chunk in file.chunks():
                dest.write(chunk)
</code>```

I would like to unit test the view.I am planning to test the happy path as well as the fail path..ie,the case where the request.FILES has no key 'file'  , case where request.FILES['file'] has None..

How do I set up the post data for the happy path?Can somebody tell me?

答:
Very handy solution with mock</p>
```<code>from django.test import TestCase, override_settings
#use your own client request factory
from my_framework.test import APIClient

from django.core.files import File
import tempfile
from pathlib import Path
import mock

image_mock = mock.MagicMock(spec=File)
image_mock.name = 'image.png' # or smt else

class MyTest(TestCase):

    # I assume we want to put this file in storage
    # so to avoid putting garbage in our MEDIA_ROOT
    # we're using temporary storage for test purposes
    @override_settings(MEDIA_ROOT=Path(tempfile.gettempdir()))
    def test_send_file(self):
        client = APIClient()
        client.post(
            '/endpoint/'
            {'file':image_mock},
            format="multipart"
        )
</code>```

Title: how to unit test file upload in django

Body:
In my django app, I have a view which accomplishes file upload.The  core snippet is like this

...
if  (request.method == 'POST'):
    if request.FILES.has_key('file'):
        file = request.FILES['file']
        with open(settings.destfolder+'/%s' % file.name, 'wb+') as dest:
            for chunk in file.chunks():
                dest.write(chunk)

I would like to unit test the view.I am planning to test the happy path as well as the fail path..ie,the case where the request.FILES has no key 'file'  , case where request.FILES['file'] has None..

How do I set up the post data for the happy path?Can somebody tell me?

Body:
Very handy solution with mock

from django.test import TestCase, override_settings
#use your own client request factory
from my_framework.test import APIClient

from django.core.files import File
import tempfile
from pathlib import Path
import mock

image_mock = mock.MagicMock(spec=File)
image_mock.name = 'image.png' # or smt else

class MyTest(TestCase):

    # I assume we want to put this file in storage
    # so to avoid putting garbage in our MEDIA_ROOT
    # we're using temporary storage for test purposes
    @override_settings(MEDIA_ROOT=Path(tempfile.gettempdir()))
    def test_send_file(self):
        client = APIClient()
        client.post(
            '/endpoint/'
            {'file':image_mock},
            format="multipart"
        )


答:
You can access the PAYMENT_VARIANTS dictionary using settings.PAYMENT_VARIANTS and can access the key currency like this

```<code>settings.PAYMENT_VARIANTS['redsys'][1]['currency]
</code>```

Title: How to access the value of constant in settings.py

Body:
I'd like ask about how to access the value of a constant declared in setting.py the following way:

PAYMENT_VARIANTS = {
'redsys': ('payments_redsys.RedsysProvider', {
    'merchant_code': '123456789',
    'terminal': '1',
    'shared_secret': 'aaaaaaaaaaaaaaaaaaaaaaaaaa',
    'currency': '978',
})

}

I can import:

from django.conf import settings

But, how I can access the value of field 'currency' or other at this level.

Thanks, regards,

Body:
You can access the PAYMENT_VARIANTS dictionary using settings.PAYMENT_VARIANTS and can access the key currency like this

settings.PAYMENT_VARIANTS['redsys'][1]['currency]


问:
How to return values from C/++ functions correctly?
I have made some app and the method im using is this:

```<code>INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}
</code>```

and I call it like:

```<code>char returned[255];
name(first,second,returned);
printf/cout;
</code>```

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.

答:
Well, in this case returned is allocated on the stack, so surely you can't just free it (I don't know if you can delete it in C++). Just re-use it.

Maybe in this case, returning a pointer to the array would be better.

Body:
I have made some app and the method im using is this:

INT name(char *one,char *two,char buffer[]){
memcpy(buffer,"omg",4);//or using std::string::copy ... that's how I actually return value
...}

and I call it like:

char returned[255];
name(first,second,returned);
printf/cout;

Everything is fine. Now my question is, is this method terrible or a disaster? Also, what is going on with allocated memory for 255 chars, I mean is there a way to re-allocate it somehow to save memory a little?

This is so called pass-by-reference, in either case I have to return multiple values (from 2 to 10). If I would need only 1 I would use return buffer with static type I guess.

Thanks. Write your favourite methods please while I read similar questions to this one hehe.


问:
Invoke a lambda from VSCode python
could not find any answer on this.

All the tutorials mention how to use AWS toolkit or how to locally develop and test your lambda on VSCode. That's not what I would like, I already have a lambda, and I would just like to invoke it.

To call a s3 or Dynamo DB, I can just run

```<code>dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)
scan_kwargs = {
    'FilterExpression': Key(my_key).eq(key_equal)
}
response = table.scan(**scan_kwargs)
data = response['Items']
</code>```

What is the equivalent for invoking the lambda?

答:
Try:

lambda_client = boto3.client('lambda', region_name='')

lambda_client.invoke(FunctionName='', InvocationType='', Payload='')
```

Where the empty strings can be replaced with your information.

See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#client

Title: Invoke a lambda from VSCode python

Body:
could not find any answer on this.

All the tutorials mention how to use AWS toolkit or how to locally develop and test your lambda on VSCode. That's not what I would like, I already have a lambda, and I would just like to invoke it.

To call a s3 or Dynamo DB, I can just run

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(table_name)
scan_kwargs = {
    'FilterExpression': Key(my_key).eq(key_equal)
}
response = table.scan(**scan_kwargs)
data = response['Items']

What is the equivalent for invoking the lambda?

Body:
Try:

lambda_client = boto3.client('lambda', region_name='')

lambda_client.invoke(FunctionName='', InvocationType='', Payload='')

Where the empty strings can be replaced with your information.

See: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lambda.html#client


问:
align different image ridimension and delete margin
I should like know how I can fix different image alignment and remove margin.  I want to align items in the center but there is a part of iamge that I think is margin that I can't remove. The part I want remove is the orange zone

.content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px;
  width: 100%;
}

.content__row {
  display: flex;
  width: 100%;
  margin: 5px 0;
}

.content__img {
  display: flex;
  width: 80%;
  height: 90%;
  padding: 0%;
}

.content__a {
  text-decoration: none;
  align-items: center;
}

.content__p {
  align-items: center;
  text-align: center;
  width: 80%;
  font-size: 35px;
  font-weight: 900;
  font-family: 'Ubuntu', sans-serif;
  color: rgb(39, 39, 255);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
  <div class="content__row">

      <img class="content__img" src="https://via.placeholder.com/300x600" alt="">
      <p class="content__p">COMPILARE
        <br>
        <span class="content__span">730?</span>
      </p>

      <img class="content__img" src="https://via.placeholder.com/300x600" alt="">
      <p class="content__p">CALCOLARE
        <br>
        <span class="content__span">L'ISEE?</span>
      </p>

      <img class="content__img" src="https://via.placeholder.com/300x600" alt="">
      <p class="content__p">CALCOLARE
        <br>
        <span class="content__span">L'ISEE?</span>
      </p>

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

答:
Couple is css issue exist.

Remove width: 80%; from .content__p. Because this will restrict the width of the p tage.

For .content__img remove width: 80%; if you need full width image. If you are using width: 80%;, then add margin: 0 auto; to the same, this will add equal space at left and right of the image.

.content__img I have removed height: 90%;. It looks odd with restricted height (Not mandatory, add if needed).

From .content remove padding: 20px;. This will creeate unwanted horizontal scroll in the page.

For .content_a, add display: flex; flex-direction: column; flex: 1; to avod the unwanted blank space in the right side of 3 elements.

Working Fiddle

.content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  /* Removiung padding, its creating unwanted scroll */
  /* padding: 20px; */
  width: 100%;
}

.content__row {
  display: flex;
  width: 100%;
  margin: 5px 0;
}

.content__img {
  display: flex;
  /* Donot restrict height */
  /* height: 90%; */
  padding: 0%;
  /* Restrict width only if needed or else comment the below one */
  width: 80%;
  /* If you are having a width value, set margin to 0 auto to align image at center */
  margin: 0 auto;
}

.content__a {
  text-decoration: none;
  align-items: center;
  /* Adding this because there is some blank space after 3 elements */
  display: flex;
  flex-direction: column;
  flex: 1;
}

.content__p {
  align-items: center;
  text-align: center;
  /* Donot restrict width */
  /* width: 80%; */
  font-size: 35px;
  font-weight: 900;
  font-family: 'Ubuntu', sans-serif;
  color: rgb(39, 39, 255);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="content">
<div class="content__row">

    <img class="content__img" src="https://via.placeholder.com/400" alt="">
    <p class="content__p">
      COMPILARE
      <br>
      <span class="content__span">730?</span>
    </p>

    <img class="content__img" src="https://via.placeholder.com/400" alt="">
    <p class="content__p">
      CALCOLARE
      <br>
      <span class="content__span">L'ISEE?</span>
    </p>

    <img class="content__img" src="https://via.placeholder.com/400" alt="">
    <p class="content__p">
      CALCOLARE
      <br>
      <span class="content__span">L'ISEE?</span>
    </p>

</div></code>```

Body:
I should like know how I can fix different image alignment and remove margin.  I want to align items in the center but there is a part of iamge that I think is margin that I can't remove. The part I want remove is the orange zone

.content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20px;
  width: 100%;
}

.content__row {
  display: flex;
  width: 100%;
  margin: 5px 0;
}

.content__img {
  display: flex;
  width: 80%;
  height: 90%;
  padding: 0%;
}

.content__a {
  text-decoration: none;
  align-items: center;
}

.content__p {
  align-items: center;
  text-align: center;
  width: 80%;
  font-size: 35px;
  font-weight: 900;
  font-family: 'Ubuntu', sans-serif;
  color: rgb(39, 39, 255);
}

COMPILARE

        730?

CALCOLARE

        L'ISEE?

CALCOLARE

        L'ISEE?

Body:
Couple is css issue exist.

Remove width: 80%; from .content__p. Because this will restrict the width of the p tage.

For .content__img remove width: 80%; if you need full width image. If you are using width: 80%;, then add margin: 0 auto; to the same, this will add equal space at left and right of the image.

.content__img I have removed height: 90%;. It looks odd with restricted height (Not mandatory, add if needed).

From .content remove padding: 20px;. This will creeate unwanted horizontal scroll in the page.

For .content_a, add display: flex; flex-direction: column; flex: 1; to avod the unwanted blank space in the right side of 3 elements.

Working Fiddle

.content {
  display: flex;
  justify-content: space-around;
  align-items: center;
  /* Removiung padding, its creating unwanted scroll */
  /* padding: 20px; */
  width: 100%;
}

.content__row {
  display: flex;
  width: 100%;
  margin: 5px 0;
}

.content__img {
  display: flex;
  /* Donot restrict height */
  /* height: 90%; */
  padding: 0%;
  /* Restrict width only if needed or else comment the below one */
  width: 80%;
  /* If you are having a width value, set margin to 0 auto to align image at center */
  margin: 0 auto;
}

.content__a {
  text-decoration: none;
  align-items: center;
  /* Adding this because there is some blank space after 3 elements */
  display: flex;
  flex-direction: column;
  flex: 1;
}

.content__p {
  align-items: center;
  text-align: center;
  /* Donot restrict width */
  /* width: 80%; */
  font-size: 35px;
  font-weight: 900;
  font-family: 'Ubuntu', sans-serif;
  color: rgb(39, 39, 255);
}

<div class="content">
<div class="content__row">
  <a class="content__a" href="#">
    <img class="content__img" src="https://via.placeholder.com/400" alt="">
    <p class="content__p">
      COMPILARE
      <br>
      <span class="content__span">730?</span>
    </p>
  </a>
  <a class="content__a" href="#">
    <img class="content__img" src="https://via.placeholder.com/400" alt="">
    <p class="content__p">
      CALCOLARE
      <br>
      <span class="content__span">L'ISEE?</span>
    </p>
  </a>
  <a class="content__a" href="#">
    <img class="content__img" src="https://via.placeholder.com/400" alt="">
    <p class="content__p">
      CALCOLARE
      <br>
      <span class="content__span">L'ISEE?</span>
    </p>
  </a>
</div>


问:
Implement @emotion/babel-plugin with jest
In our project we got the @emotion/babel-plugin working, but we just can't get it to work with jest, our jest-preprocess file looks like the following:

```<code>const babelJest = require('babel-jest');

const babelOptions = {
  presets: ['babel-preset-gatsby'],
  plugins: ['@emotion'],
};

module.exports = babelJest.default.createTransformer(babelOptions);
</code>```

When we run the tests we just get:

```<code>Component selectors can only be used in conjunction with @emotion/babel-plugin.
</code>```

答:
Have you tried using:</p>
```<code>// jest-preprocess.js
const babelJest = require('babel-jest').default;

const babelOptions = {
  presets: [
    "babel-preset-gatsby",
    "@emotion/babel-preset-css-prop",
  ],
  plugins: ["emotion"],
}
module.exports = babelJest.createTransformer(babelOptions)
</code>```

Body:
In our project we got the @emotion/babel-plugin working, but we just can't get it to work with jest, our jest-preprocess file looks like the following:

const babelJest = require('babel-jest');

const babelOptions = {
  presets: ['babel-preset-gatsby'],
  plugins: ['@emotion'],
};

module.exports = babelJest.default.createTransformer(babelOptions);

When we run the tests we just get:

Component selectors can only be used in conjunction with @emotion/babel-plugin.

Body:
Have you tried using:

// jest-preprocess.js
const babelJest = require('babel-jest').default;

const babelOptions = {
  presets: [
    "babel-preset-gatsby",
    "@emotion/babel-preset-css-prop",
  ],
  plugins: ["emotion"],
}
module.exports = babelJest.createTransformer(babelOptions)


问:
The code I wrote on Flutter was working yesterday, but today it just gives a black screen
The code I wrote on Flutter was working yesterday, but today it just gives a black screen. I don't understand. I am learning and it's very annoying to do this without any errors. 199 / 5,000

These parts were entered because more details were requested about the post. It's still waiting for me to explain this issue further. I'm getting a black screen, I don't understand how to explain.

    import 'package:flutter/cupertino.dart';
    import 'package:flutter/material.dart';

    bool _valuehidra = true;
    bool _valuelight = true;
    bool _valuewebasto = true;
    bool _valueusb = true;
    bool _valuealter = true;

    void main() {
      runApp(const MaterialApp(
      ));
    }

    class MyApp extends StatefulWidget {
      const MyApp({Key? key}) : super(key: key);

      @override
      _State createState() => _State();
    }

    class _State extends State<MyApp> {
      bool isSwitched = false;

      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
        body: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
            Container(
              margin: const EdgeInsets.fromLTRB(10, 30, 0, 0),
              child: Image.asset('assets/images/logoisim.png', height: 125.0, fit: BoxFit.cover,),
            ),
            ],
          ),
          Container(

            decoration: BoxDecoration(
              color: Colors.indigoAccent,
                borderRadius: BorderRadius.circular(30.0),
            ),
            width: 350,
            height: 70,
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(top: 20),
            child: Row(
              children: <Widget>[
                SizedBox(width: 200,
                  child: Container(
                    margin: const EdgeInsets.only(left: 30),
                    alignment: Alignment.centerLeft,
                    child: const Text('AYDINLATMA', style: TextStyle(color: Colors.white, fontSize: 25,fontFamily: 'YesevaOne' )),
                  ),
                ),
                Transform.scale( scale: 1.3,
                  child: Container(
                    margin: const EdgeInsets.only(left:50),
                    child: CupertinoSwitch(
                      value: _valuelight,
                      onChanged: (value) {
                        setState(() {
                          _valuelight = value;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.indigo,
              borderRadius: BorderRadius.circular(30.0),
            ),
            width: 350,
            height: 70,
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(top: 10),
            child: Row(
              children: <Widget>[
                SizedBox(width: 200,
                  child: Container(
                    margin: const EdgeInsets.only(left: 30),
                    alignment: Alignment.centerLeft,
                    child: const Text('WEBASTO', style: TextStyle(color: Colors.white, fontSize: 25,fontFamily: 'YesevaOne' )),
                  ),
                ),
                Transform.scale( scale: 1.3,
                  child: Container(
                    margin: const EdgeInsets.only(left:50),
                    child: CupertinoSwitch(
                      value: _valuewebasto,
                      onChanged: (value) {
                        setState(() {
                          _valuewebasto = value;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.indigoAccent,
              borderRadius: BorderRadius.circular(30.0),
            ),
            width: 350,
            height: 70,
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(top: 10),
            child: Row(
              children: <Widget>[
                SizedBox(width: 200,
                  child: Container(
                    margin: const EdgeInsets.only(left: 30),
                    alignment: Alignment.centerLeft,
                    child: const Text('HİDRAFOR', style: TextStyle(color: Colors.white, fontSize: 25,fontFamily: 'YesevaOne' )),
                  ),
                ),
                Transform.scale( scale: 1.3,
                  child: Container(
                    margin: const EdgeInsets.only(left:50),
                    child: CupertinoSwitch(
                      value: _valuehidra,
                      onChanged: (value) {
                        setState(() {
                          _valuehidra = value;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.indigo,
              borderRadius: BorderRadius.circular(30.0),
            ),
            width: 350,
            height: 70,
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(top: 10),
            child: Row(
              children: <Widget>[
                SizedBox(width: 200,
                  child: Container(
                    margin: const EdgeInsets.only(left: 30),
                    alignment: Alignment.centerLeft,
                    child: const Text('ALTERNATÖR', style: TextStyle(color: Colors.white, fontSize: 25,fontFamily: 'YesevaOne' )),
                  ),
                ),
                Transform.scale( scale: 1.3,
                  child: Container(
                    margin: const EdgeInsets.only(left:50),
                    child: CupertinoSwitch(
                      value: _valuealter,
                      onChanged: (value) {
                        setState(() {
                          _valuealter = value;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.indigoAccent,
              borderRadius: BorderRadius.circular(30.0),
            ),
            width: 350,
            height: 70,
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(top: 10),
            child: Row(
              children: <Widget>[
                SizedBox(width: 200,
                  child: Container(
                    margin: const EdgeInsets.only(left: 30),
                    alignment: Alignment.centerLeft,
                    child: const Text('USB (12V)', style: TextStyle(color: Colors.white, fontSize: 25,fontFamily: 'YesevaOne' )),
                  ),
                ),
                Transform.scale( scale: 1.3,
                  child: Container(
                    margin: const EdgeInsets.only(left:50),
                    child: CupertinoSwitch(
                      value: _valueusb,
                      onChanged: (value) {
                        setState(() {
                          _valueusb = value;
                        });
                      },
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.indigo,
              borderRadius: BorderRadius.circular(30.0),
            ),
            width: 350,
            height: 90,
            alignment: Alignment.bottomCenter,
            margin: const EdgeInsets.only(top: 10),
            child: Row(
              children: <Widget>[
                Container(
                  margin: const EdgeInsets.only(left: 30),
                  child: Image.asset('assets/images/caravan.png', height: 40.0, fit: BoxFit.cover,),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 10),
                  alignment: Alignment.center,
                  child: const Text('KARAVANIM', style: TextStyle(color: Colors.white, fontSize: 31,fontFamily: 'YesevaOne' )),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 10),
                  child: Image.asset('assets/images/caravan2.png', height: 40.0, fit: BoxFit.cover,),
                ),
              ],
            ),
          ),

        ],
        ),
      ),
    );
  }
}

```

答:
change void main to these</p>
```<code>void main(){
  runApp(MyApp())
}
</code>```

Body:
change void main to these

void main(){
  runApp(MyApp())
}


问:
Why does flutter doctor gives android tollchain error
when i type flutter doctor i recieve this one

Android toolchain - develop for Android devices
X Unable to locate Android SDK.
Install Android Studio from: https://developer.android.com/studio/index.html
On first launch it will assist you in installing the Android SDK components.
(or visit https://flutter.dev/docs/get-started/install/windows#android-setup for detailed instructions).
If the Android SDK has been installed to a custom location, please use
flutter config --android-sdk to update to that location.

For any help - thanks =)

答: you may need to add ANDROID_HOME to your system variables and the value would be your sdk path</p>


问:
How to import other modules defined in the same Android app project inside Kotlin code?
I was trying to understand how to create multiple independent modules inside a project and use them in the main app module. I am using android studio Arctic Fox 2020.3.1. I have difficulty in importing the module into Kotlin code. Here is the step I followed.

I have created a 'basic activity' project named MyAppProj. It created a project with module app inside it. (build+run works fine)

Next I added a new module to the project MyAppProj. Since I needed to call C++, I created a 'Android native library' module. As per the suggestion from Android Studio, I used MyAppProj:nativelib as the module name. I didn't know what that ":" was for. (build+run works fine)

Now I have the following structure:

█ Question: What should I do to use the NativeLib class (defined inside MyAppProj:nativelib module) inside the app module's MainActivity.kt file?

All the paths that I tried so far have failed, such as:

```<code>import com.myhomeorg.myappproj.nativelib
import nativelib
</code>```

Note: I am a beginner in Android development. Your help will be greatly appreciated!

答:
In order to import it you should add to build.gradle:

```<code>dependencies {
    implementation project(":MyAppProj")
}
</code>```

and this also to settings.gradle:

```<code>include ':MyAppProj'
</code>```

And then on Kotlin you can import the classes you need like any other.

Body:
I was trying to understand how to create multiple independent modules inside a project and use them in the main app module. I am using android studio Arctic Fox 2020.3.1. I have difficulty in importing the module into Kotlin code. Here is the step I followed.

I have created a 'basic activity' project named MyAppProj. It created a project with module app inside it. (build+run works fine)

Next I added a new module to the project MyAppProj. Since I needed to call C++, I created a 'Android native library' module. As per the suggestion from Android Studio, I used MyAppProj:nativelib as the module name. I didn't know what that ":" was for. (build+run works fine)

Now I have the following structure:

█ Question: What should I do to use the NativeLib class (defined inside MyAppProj:nativelib module) inside the app module's MainActivity.kt file?

All the paths that I tried so far have failed, such as:

import com.myhomeorg.myappproj.nativelib
import nativelib

Note: I am a beginner in Android development. Your help will be greatly appreciated!

Body:
In order to import it you should add to build.gradle:

dependencies {
    implementation project(":MyAppProj")
}

and this also to settings.gradle:

include ':MyAppProj'

And then on Kotlin you can import the classes you need like any other.