问:
Encodable: Flattening structures
Let's say I have some type that has a JSON representation as such:

```<code>{
  "count": 3,
  "name": "Pianos",
  "type": "instrument",
  "id": 1,
}
</code>```

Let's say that I want to represent this as a Swift object that looks like this:

```<code>struct SomeObject: Codable { // this is the object I'd like to represent
  let id: Int
  let details: SomeDetails
}

struct SomeDetails: Codable {
  let count: Int
  let name: String
  let type: String
}
</code>```

Decoding this object is a no-brainer. But how would encoding work in this instance such that I can encode into a flat structure -- the same structure that I used to create this object and have shared in the JSON example above?

答:
An improvement for the previous answers. There is no need to manually encode or decode the other objects you can just forward the initialisers.

struct SomeDetails: Codable {
  let count: Int
  let name: String
  let type: String
}

struct SomeObject: Codable {
  enum CodingKeys: String, CodingKey {
    case id
  }

  let id: Int
  let details: SomeDetails

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    id = try container.decode(Int.self, forKey: .id)
    details = try SomeDetails(from: decoder)
  }

  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(id, forKey: .id)
    try details.encode(to: encoder)
  }
}
```

<p>And for some added sugar you can use Swift 5s dynamic member lookup so that you can access those members nicely <code>object.name</code>.</p>

<pre class="lang-swift prettyprint-override"><code>@dynamicMemberLookup
struct SomeObject {
  ...

  subscript<T>(dynamicMember member: KeyPath<SomeDetails, T>) -> T {
    details[keyPath: member]
  }
}
</code>```

Title: Encodable: Flattening structures

Body:
Let's say I have some type that has a JSON representation as such:

{
  "count": 3,
  "name": "Pianos",
  "type": "instrument",
  "id": 1,
}

Let's say that I want to represent this as a Swift object that looks like this:

struct SomeObject: Codable { // this is the object I'd like to represent
  let id: Int
  let details: SomeDetails
}

struct SomeDetails: Codable {
  let count: Int
  let name: String
  let type: String
}

Decoding this object is a no-brainer. But how would encoding work in this instance such that I can encode into a flat structure -- the same structure that I used to create this object and have shared in the JSON example above?

Body:
An improvement for the previous answers. There is no need to manually encode or decode the other objects you can just forward the initialisers.

struct SomeDetails: Codable {
  let count: Int
  let name: String
  let type: String
}

struct SomeObject: Codable {
  enum CodingKeys: String, CodingKey {
    case id
  }

  let id: Int
  let details: SomeDetails

  init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    id = try container.decode(Int.self, forKey: .id)
    details = try SomeDetails(from: decoder)
  }

  func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    try container.encode(id, forKey: .id)
    try details.encode(to: encoder)
  }
}

And for some added sugar you can use Swift 5s dynamic member lookup so that you can access those members nicely object.name.

@dynamicMemberLookup
struct SomeObject {
  ...

  subscript<T>(dynamicMember member: KeyPath<SomeDetails, T>) -> T {
    details[keyPath: member]
  }
}


来源: stackexchange

问:
cassandra.cluster with pyinstaller not working
I am trying to create executable using pyinstaller on my Mac for a simple python file TestAudit.py, which contains

from cassandra.cluster import Cluster

And getting below error when I run my executable:

```<code>TestAudit.py:7: DeprecationWarning: Using or importing the ABCs from
'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
Traceback (most recent call last):
  File "TestAudit.py", line 7, in <module>
  File "cassandra/cluster.py", line 23, in init cassandra.cluster
ModuleNotFoundError: No module named 'concurrent'
[46470] Failed to execute script TestAudit
</code>```

My Python version is Python 3.7.3
Mac: MacOS High Sierra, Version 10.13.6

Please help if anybody knows how to fix this, Or else how can we package TestAudit.py along with dependencies ?

TestAudit.py file:

```<code>"""Program to initialze Cassandra driver"""
from cassandra.cluster import Cluster
from datetime import datetime
print("now =", datetime.now())
</code>```

答:
What worked for me was to add every missing module to the hiddenimports of pyinstaller and run the executable again until no more missing modules were found.

After compiling an executable with pyInstaller, you will notice a *.spec file inside your directory. There, you can add the modules to the hiddenimports list and run pyInstaller <yourModule>.spec to build the executable again.

Here's the list of missing modules that I found for my case:

```<code>hiddenimports=['concurrent', 'concurrent.futures', 'json', 'cassandra.connection', 'cassandra.marshal', 'cassandra.protocol', 'cassandra.type_codes', 'geomet.wkt', 'cassandra.compat', 'cassandra.cython_deps', 'cassandra.pool', 'cassandra.policies', 'cassandra.timestamps', 'cassandra.datastax', 'cassandra.datastax.insights', 'cassandra.datastax.insights.reporter', 'cassandra.datastax.cloud', 'cassandra.io', 'cassandra.io.asyncorereactor']
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create executable using pyinstaller on my Mac for a simple python file TestAudit.py, which contains

from cassandra.cluster import Cluster

And getting below error when I run my executable:

TestAudit.py:7: DeprecationWarning: Using or importing the ABCs from
'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
Traceback (most recent call last):
  File "TestAudit.py", line 7, in <module>
  File "cassandra/cluster.py", line 23, in init cassandra.cluster
ModuleNotFoundError: No module named 'concurrent'
[46470] Failed to execute script TestAudit

My Python version is Python 3.7.3
Mac: MacOS High Sierra, Version 10.13.6

Please help if anybody knows how to fix this, Or else how can we package TestAudit.py along with dependencies ?

TestAudit.py file:

"""Program to initialze Cassandra driver"""
from cassandra.cluster import Cluster
from datetime import datetime
print("now =", datetime.now())

Body:
What worked for me was to add every missing module to the hiddenimports of pyinstaller and run the executable again until no more missing modules were found.

After compiling an executable with pyInstaller, you will notice a *.spec file inside your directory. There, you can add the modules to the hiddenimports list and run pyInstaller <yourModule>.spec to build the executable again.

Here's the list of missing modules that I found for my case:

hiddenimports=['concurrent', 'concurrent.futures', 'json', 'cassandra.connection', 'cassandra.marshal', 'cassandra.protocol', 'cassandra.type_codes', 'geomet.wkt', 'cassandra.compat', 'cassandra.cython_deps', 'cassandra.pool', 'cassandra.policies', 'cassandra.timestamps', 'cassandra.datastax', 'cassandra.datastax.insights', 'cassandra.datastax.insights.reporter', 'cassandra.datastax.cloud', 'cassandra.io', 'cassandra.io.asyncorereactor']


问:
How to convert below api response which is in xml format to c# class?
I had posted a question regarding how to call api which is in xml format.

Calling api in xml format in c# - Getting error "Remote certificate is invalid according to the validation procedure"

Now I am getting a response from the api.  But now I want to convert the response  to c# object. The attributes of xml changes in case of success and failure.

Below response if everything is success..

```<code><FIXML xsi:schemaLocation="http://www.finacle.com/fixml BalInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Header> <ResponseHeader> <RequestMessageKey> <RequestUUID>Req_1560515797477</RequestUUID> <ServiceRequestId>BalInq</ServiceRequestId> <ServiceRequestVersion>10.2</ServiceRequestVersion> <ChannelId>COR</ChannelId> </RequestMessageKey> <ResponseMessageInfo> <BankId>01</BankId> <TimeZone>GMT+05:30</TimeZone> <MessageDateTime>2020-05-29T12:39:13.379</MessageDateTime> </ResponseMessageInfo><UBUSTransaction> <Id/> <Status/> </UBUSTransaction> <HostTransaction> <Id/> <Status>SUCCESS</Status> </HostTransaction> <HostParentTransaction> <Id/> <Status/> </HostParentTransaction> <CustomInfo/> </ResponseHeader> </Header> <Body> <BalInqResponse> <BalInqRs> <AcctId> <AcctId>4362500100484501</AcctId> <AcctType> <SchmCode></SchmCode> <SchmType></SchmType> </AcctType> <AcctCurr>INR</AcctCurr> <BankInfo> <BankId></BankId> <Name></Name> <BranchId>436</BranchId> <BranchName></BranchName> <PostAddr> <Addr1></Addr1> <Addr2></Addr2> <Addr3></Addr3> <City></City> <StateProv></StateProv> <PostalCode></PostalCode> <Country></Country> <AddrType></AddrType> </PostAddr> </BankInfo> </AcctId> <AcctBal> <BalType>CLRBAL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SANLIM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UTLAMT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DRWPWR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>ADHOC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SINTRN</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNADH</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DACC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>LIEN</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SYSRES</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>OVDFUT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DAFALM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FUTBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FLOAT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>AVAIL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FFDAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EFFAVL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EFUAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode></currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EMRADV</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNEMR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNSTR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SYSGENLM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UNCLRBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>POOLAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>HOMAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FUTCR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UTILFUTBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>USEDOC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DAFAWITHDRAWL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode></currencyCode> </BalAmt> </AcctBal> </BalInqRs><BalInq_CustomData/> </BalInqResponse></Body></FIXML>
</code>```

Below response in case of failure

```<code><FIXML xsi:schemaLocation="http://www.finacle.com/fixml BalInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Header>
<ResponseHeader>
<RequestMessageKey>
<RequestUUID>Req_1560515797477</RequestUUID>
<ServiceRequestId>BalInq</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>COR</ChannelId>
</RequestMessageKey>
<ResponseMessageInfo>
<BankId>01</BankId>
<TimeZone></TimeZone>
<MessageDateTime>2020-05-29T07:28:59.421</MessageDateTime>
</ResponseMessageInfo>
<UBUSTransaction>
<Id>null</Id>
<Status>FAILED</Status>
</UBUSTransaction>
<HostTransaction>
<Id>0000</Id>
<Status>FAILURE</Status>
</HostTransaction>
<HostParentTransaction>
<Id>null</Id>
<Status>null</Status>
</HostParentTransaction>
<CustomInfo/>
</ResponseHeader>
</Header>
<Body>
<Error>
<FIBusinessException>
<ErrorDetail><ErrorCode>162</ErrorCode><ErrorDesc>Account does not exist</ErrorDesc><ErrorSource>acct.foracid</ErrorSource><ErrorType>BE</ErrorType></ErrorDetail>
</FIBusinessException>
</Error></Body>
</FIXML>
</code>```

How do I convert it c# objects?.  Because attribute changes.

答:
Create two classes, one for Success and one for Failed message. Depending on Status Code parse the response to corresponding class.
If you're thinking to create a dynamical class(es), well you could try using dynamic keyword, but C# is strong type language.
Also, there is a small tool who can help you create the class from the response, give it a try, here is  the link.

So the glue between your statuses is the header part, so I have separated it in one class.

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
   public class HeaderDto
   {

       [XmlRoot(ElementName = "RequestMessageKey", Namespace = "http://www.finacle.com/fixml")]
       public class RequestMessageKey
       {
           [XmlElement(ElementName = "RequestUUID", Namespace = "http://www.finacle.com/fixml")]
           public string RequestUUID { get; set; }
           [XmlElement(ElementName = "ServiceRequestId", Namespace = "http://www.finacle.com/fixml")]
           public string ServiceRequestId { get; set; }
           [XmlElement(ElementName = "ServiceRequestVersion", Namespace = "http://www.finacle.com/fixml")]
           public string ServiceRequestVersion { get; set; }
           [XmlElement(ElementName = "ChannelId", Namespace = "http://www.finacle.com/fixml")]
           public string ChannelId { get; set; }
       }

       [XmlRoot(ElementName = "ResponseMessageInfo", Namespace = "http://www.finacle.com/fixml")]
       public class ResponseMessageInfo
       {
           [XmlElement(ElementName = "BankId", Namespace = "http://www.finacle.com/fixml")]
           public string BankId { get; set; }
           [XmlElement(ElementName = "TimeZone", Namespace = "http://www.finacle.com/fixml")]
           public string TimeZone { get; set; }
           [XmlElement(ElementName = "MessageDateTime", Namespace = "http://www.finacle.com/fixml")]
           public string MessageDateTime { get; set; }
       }

       [XmlRoot(ElementName = "UBUSTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class UBUSTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "HostTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class HostTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "HostParentTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class HostParentTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "ResponseHeader", Namespace = "http://www.finacle.com/fixml")]
       public class ResponseHeader
       {
           [XmlElement(ElementName = "RequestMessageKey", Namespace = "http://www.finacle.com/fixml")]
           public RequestMessageKey RequestMessageKey { get; set; }
           [XmlElement(ElementName = "ResponseMessageInfo", Namespace = "http://www.finacle.com/fixml")]
           public ResponseMessageInfo ResponseMessageInfo { get; set; }
           [XmlElement(ElementName = "UBUSTransaction", Namespace = "http://www.finacle.com/fixml")]
           public UBUSTransaction UBUSTransaction { get; set; }
           [XmlElement(ElementName = "HostTransaction", Namespace = "http://www.finacle.com/fixml")]
           public HostTransaction HostTransaction { get; set; }
           [XmlElement(ElementName = "HostParentTransaction", Namespace = "http://www.finacle.com/fixml")]
           public HostParentTransaction HostParentTransaction { get; set; }
           [XmlElement(ElementName = "CustomInfo", Namespace = "http://www.finacle.com/fixml")]
           public string CustomInfo { get; set; }
       }

       [XmlRoot(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
       public class Header
       {
           [XmlElement(ElementName = "ResponseHeader", Namespace = "http://www.finacle.com/fixml")]
           public ResponseHeader ResponseHeader { get; set; }
       }
   }
}
```

<p>The Success response class would look something like this...</p>

<pre class="lang-cs prettyprint-override"><code>/*
 Licensed under the Apache License, Version 2.0

 http://www.apache.org/licenses/LICENSE-2.0
 */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using static Xml2CSharp.HeaderDto;

namespace Xml2CSharp
{
    public class SuccessDto
    {
        public RequestMessageKey RequestMessageKey { get; set; }
        public ResponseMessageInfo ResponseMessageInfo { get; set; }
        public UBUSTransaction UBUSTransaction { get; set; }
        public HostTransaction HostTransaction { get; set; }
        public HostParentTransaction HostParentTransaction { get; set; }
        public ResponseHeader ResponseHeader { get; set; }
        public Header Header { get; set; }

        [XmlRoot(ElementName = "AcctType", Namespace = "http://www.finacle.com/fixml")]
        public class AcctType
        {
            [XmlElement(ElementName = "SchmCode", Namespace = "http://www.finacle.com/fixml")]
            public string SchmCode { get; set; }
            [XmlElement(ElementName = "SchmType", Namespace = "http://www.finacle.com/fixml")]
            public string SchmType { get; set; }
        }

        [XmlRoot(ElementName = "PostAddr", Namespace = "http://www.finacle.com/fixml")]
        public class PostAddr
        {
            [XmlElement(ElementName = "Addr1", Namespace = "http://www.finacle.com/fixml")]
            public string Addr1 { get; set; }
            [XmlElement(ElementName = "Addr2", Namespace = "http://www.finacle.com/fixml")]
            public string Addr2 { get; set; }
            [XmlElement(ElementName = "Addr3", Namespace = "http://www.finacle.com/fixml")]
            public string Addr3 { get; set; }
            [XmlElement(ElementName = "City", Namespace = "http://www.finacle.com/fixml")]
            public string City { get; set; }
            [XmlElement(ElementName = "StateProv", Namespace = "http://www.finacle.com/fixml")]
            public string StateProv { get; set; }
            [XmlElement(ElementName = "PostalCode", Namespace = "http://www.finacle.com/fixml")]
            public string PostalCode { get; set; }
            [XmlElement(ElementName = "Country", Namespace = "http://www.finacle.com/fixml")]
            public string Country { get; set; }
            [XmlElement(ElementName = "AddrType", Namespace = "http://www.finacle.com/fixml")]
            public string AddrType { get; set; }
        }

        [XmlRoot(ElementName = "BankInfo", Namespace = "http://www.finacle.com/fixml")]
        public class BankInfo
        {
            [XmlElement(ElementName = "BankId", Namespace = "http://www.finacle.com/fixml")]
            public string BankId { get; set; }
            [XmlElement(ElementName = "Name", Namespace = "http://www.finacle.com/fixml")]
            public string Name { get; set; }
            [XmlElement(ElementName = "BranchId", Namespace = "http://www.finacle.com/fixml")]
            public string BranchId { get; set; }
            [XmlElement(ElementName = "BranchName", Namespace = "http://www.finacle.com/fixml")]
            public string BranchName { get; set; }
            [XmlElement(ElementName = "PostAddr", Namespace = "http://www.finacle.com/fixml")]
            public PostAddr PostAddr { get; set; }
        }

        [XmlRoot(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
        public class AcctId
        {
            [XmlElement(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
            public string AcctId { get; set; }
            [XmlElement(ElementName = "AcctType", Namespace = "http://www.finacle.com/fixml")]
            public AcctType AcctType { get; set; }
            [XmlElement(ElementName = "AcctCurr", Namespace = "http://www.finacle.com/fixml")]
            public string AcctCurr { get; set; }
            [XmlElement(ElementName = "BankInfo", Namespace = "http://www.finacle.com/fixml")]
            public BankInfo BankInfo { get; set; }
        }

        [XmlRoot(ElementName = "BalAmt", Namespace = "http://www.finacle.com/fixml")]
        public class BalAmt
        {
            [XmlElement(ElementName = "amountValue", Namespace = "http://www.finacle.com/fixml")]
            public string AmountValue { get; set; }
            [XmlElement(ElementName = "currencyCode", Namespace = "http://www.finacle.com/fixml")]
            public string CurrencyCode { get; set; }
        }

        [XmlRoot(ElementName = "AcctBal", Namespace = "http://www.finacle.com/fixml")]
        public class AcctBal
        {
            [XmlElement(ElementName = "BalType", Namespace = "http://www.finacle.com/fixml")]
            public string BalType { get; set; }
            [XmlElement(ElementName = "BalAmt", Namespace = "http://www.finacle.com/fixml")]
            public BalAmt BalAmt { get; set; }
        }

        [XmlRoot(ElementName = "BalInqRs", Namespace = "http://www.finacle.com/fixml")]
        public class BalInqRs
        {
            [XmlElement(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
            public AcctId AcctId { get; set; }
            [XmlElement(ElementName = "AcctBal", Namespace = "http://www.finacle.com/fixml")]
            public List<AcctBal> AcctBal { get; set; }
        }

        [XmlRoot(ElementName = "BalInqResponse", Namespace = "http://www.finacle.com/fixml")]
        public class BalInqResponse
        {
            [XmlElement(ElementName = "BalInqRs", Namespace = "http://www.finacle.com/fixml")]
            public BalInqRs BalInqRs { get; set; }
            [XmlElement(ElementName = "BalInq_CustomData", Namespace = "http://www.finacle.com/fixml")]
            public string BalInq_CustomData { get; set; }
        }

        [XmlRoot(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
        public class Body
        {
            [XmlElement(ElementName = "BalInqResponse", Namespace = "http://www.finacle.com/fixml")]
            public BalInqResponse BalInqResponse { get; set; }
        }

        [XmlRoot(ElementName = "FIXML", Namespace = "http://www.finacle.com/fixml")]
        public class FIXML
        {
            [XmlElement(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
            public Header Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
            public string SchemaLocation { get; set; }
            [XmlAttribute(AttributeName = "xmlns")]
            public string Xmlns { get; set; }
            [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Xsi { get; set; }
        }
    }

}
</code>```

And Failed class would be like this

/*
 Licensed under the Apache License, Version 2.0

 http://www.apache.org/licenses/LICENSE-2.0
 */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using static Xml2CSharp.HeaderDto;

namespace Xml2CSharp
{
    public class FailedDto
    {
        public RequestMessageKey RequestMessageKey { get; set; }
        public ResponseMessageInfo ResponseMessageInfo { get; set; }
        public UBUSTransaction UBUSTransaction { get; set; }
        public HostTransaction HostTransaction { get; set; }
        public HostParentTransaction HostParentTransaction { get; set; }
        public ResponseHeader ResponseHeader { get; set; }
        public Header Header { get; set; }

        [XmlRoot(ElementName = "ErrorDetail", Namespace = "http://www.finacle.com/fixml")]
        public class ErrorDetail
        {
            [XmlElement(ElementName = "ErrorCode", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorCode { get; set; }
            [XmlElement(ElementName = "ErrorDesc", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorDesc { get; set; }
            [XmlElement(ElementName = "ErrorSource", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorSource { get; set; }
            [XmlElement(ElementName = "ErrorType", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorType { get; set; }
        }

        [XmlRoot(ElementName = "FIBusinessException", Namespace = "http://www.finacle.com/fixml")]
        public class FIBusinessException
        {
            [XmlElement(ElementName = "ErrorDetail", Namespace = "http://www.finacle.com/fixml")]
            public ErrorDetail ErrorDetail { get; set; }
        }

        [XmlRoot(ElementName = "Error", Namespace = "http://www.finacle.com/fixml")]
        public class Error
        {
            [XmlElement(ElementName = "FIBusinessException", Namespace = "http://www.finacle.com/fixml")]
            public FIBusinessException FIBusinessException { get; set; }
        }

        [XmlRoot(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
        public class Body
        {
            [XmlElement(ElementName = "Error", Namespace = "http://www.finacle.com/fixml")]
            public Error Error { get; set; }
        }

        [XmlRoot(ElementName = "FIXML", Namespace = "http://www.finacle.com/fixml")]
        public class FIXML
        {
            [XmlElement(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
            public Header Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
            public string SchemaLocation { get; set; }
            [XmlAttribute(AttributeName = "xmlns")]
            public string Xmlns { get; set; }
            [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Xsi { get; set; }
        }
    }
}
```

Please consider this as pseudo code, since it's not tested.
So when you get the response, parse the header, and read the node you need to validate if its Success or Failed message, then just parse it as that object.

Body:
I had posted a question regarding how to call api which is in xml format.

Calling api in xml format in c# - Getting error "Remote certificate is invalid according to the validation procedure"

Now I am getting a response from the api.  But now I want to convert the response  to c# object. The attributes of xml changes in case of success and failure.

Below response if everything is success..

<FIXML xsi:schemaLocation="http://www.finacle.com/fixml BalInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  <ResponseHeader> <RequestMessageKey> <RequestUUID>Req_1560515797477</RequestUUID> <ServiceRequestId>BalInq</ServiceRequestId> <ServiceRequestVersion>10.2</ServiceRequestVersion> <ChannelId>COR</ChannelId> </RequestMessageKey> <ResponseMessageInfo> <BankId>01</BankId> <TimeZone>GMT+05:30</TimeZone> <MessageDateTime>2020-05-29T12:39:13.379</MessageDateTime> </ResponseMessageInfo><UBUSTransaction> <Id/> <Status/> </UBUSTransaction> <HostTransaction> <Id/> <Status>SUCCESS</Status> </HostTransaction> <HostParentTransaction> <Id/> <Status/> </HostParentTransaction> <CustomInfo/> </ResponseHeader>   <BalInqResponse> <BalInqRs> <AcctId> <AcctId>4362500100484501</AcctId> <AcctType> <SchmCode></SchmCode> <SchmType></SchmType> </AcctType> <AcctCurr>INR</AcctCurr> <BankInfo> <BankId></BankId> <Name></Name> <BranchId>436</BranchId> <BranchName></BranchName> <PostAddr> <Addr1></Addr1> <Addr2></Addr2> <Addr3></Addr3> <City></City> <StateProv></StateProv> <PostalCode></PostalCode> <Country></Country> <AddrType></AddrType> </PostAddr> </BankInfo> </AcctId> <AcctBal> <BalType>CLRBAL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SANLIM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UTLAMT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DRWPWR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>ADHOC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SINTRN</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNADH</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DACC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>LIEN</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SYSRES</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>OVDFUT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DAFALM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FUTBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FLOAT</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>AVAIL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FFDAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EFFAVL</BalType> <BalAmt> <amountValue>2.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EFUAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode></currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>EMRADV</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNEMR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>CLNSTR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>SYSGENLM</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UNCLRBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>POOLAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>HOMAVL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>FUTCR</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>UTILFUTBAL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>USEDOC</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode>INR</currencyCode> </BalAmt> </AcctBal> <AcctBal> <BalType>DAFAWITHDRAWL</BalType> <BalAmt> <amountValue>0.00</amountValue> <currencyCode></currencyCode> </BalAmt> </AcctBal> </BalInqRs><BalInq_CustomData/> </BalInqResponse></FIXML>

Below response in case of failure

<FIXML xsi:schemaLocation="http://www.finacle.com/fixml BalInq.xsd" xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<ResponseHeader>
<RequestMessageKey>
<RequestUUID>Req_1560515797477</RequestUUID>
<ServiceRequestId>BalInq</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>COR</ChannelId>
</RequestMessageKey>
<ResponseMessageInfo>
<BankId>01</BankId>
<TimeZone></TimeZone>
<MessageDateTime>2020-05-29T07:28:59.421</MessageDateTime>
</ResponseMessageInfo>
<UBUSTransaction>
<Id>null</Id>
<Status>FAILED</Status>
</UBUSTransaction>
<HostTransaction>
<Id>0000</Id>
<Status>FAILURE</Status>
</HostTransaction>
<HostParentTransaction>
<Id>null</Id>
<Status>null</Status>
</HostParentTransaction>
<CustomInfo/>
</ResponseHeader>

<Error>
<FIBusinessException>
<ErrorDetail><ErrorCode>162</ErrorCode><ErrorDesc>Account does not exist</ErrorDesc><ErrorSource>acct.foracid</ErrorSource><ErrorType>BE</ErrorType></ErrorDetail>
</FIBusinessException>
</Error>
</FIXML>

How do I convert it c# objects?.  Because attribute changes.

Body:
Create two classes, one for Success and one for Failed message. Depending on Status Code parse the response to corresponding class.
If you're thinking to create a dynamical class(es), well you could try using dynamic keyword, but C# is strong type language.
Also, there is a small tool who can help you create the class from the response, give it a try, here is  the link.

So the glue between your statuses is the header part, so I have separated it in one class.

using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
   public class HeaderDto
   {

       [XmlRoot(ElementName = "RequestMessageKey", Namespace = "http://www.finacle.com/fixml")]
       public class RequestMessageKey
       {
           [XmlElement(ElementName = "RequestUUID", Namespace = "http://www.finacle.com/fixml")]
           public string RequestUUID { get; set; }
           [XmlElement(ElementName = "ServiceRequestId", Namespace = "http://www.finacle.com/fixml")]
           public string ServiceRequestId { get; set; }
           [XmlElement(ElementName = "ServiceRequestVersion", Namespace = "http://www.finacle.com/fixml")]
           public string ServiceRequestVersion { get; set; }
           [XmlElement(ElementName = "ChannelId", Namespace = "http://www.finacle.com/fixml")]
           public string ChannelId { get; set; }
       }

       [XmlRoot(ElementName = "ResponseMessageInfo", Namespace = "http://www.finacle.com/fixml")]
       public class ResponseMessageInfo
       {
           [XmlElement(ElementName = "BankId", Namespace = "http://www.finacle.com/fixml")]
           public string BankId { get; set; }
           [XmlElement(ElementName = "TimeZone", Namespace = "http://www.finacle.com/fixml")]
           public string TimeZone { get; set; }
           [XmlElement(ElementName = "MessageDateTime", Namespace = "http://www.finacle.com/fixml")]
           public string MessageDateTime { get; set; }
       }

       [XmlRoot(ElementName = "UBUSTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class UBUSTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "HostTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class HostTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "HostParentTransaction", Namespace = "http://www.finacle.com/fixml")]
       public class HostParentTransaction
       {
           [XmlElement(ElementName = "Id", Namespace = "http://www.finacle.com/fixml")]
           public string Id { get; set; }
           [XmlElement(ElementName = "Status", Namespace = "http://www.finacle.com/fixml")]
           public string Status { get; set; }
       }

       [XmlRoot(ElementName = "ResponseHeader", Namespace = "http://www.finacle.com/fixml")]
       public class ResponseHeader
       {
           [XmlElement(ElementName = "RequestMessageKey", Namespace = "http://www.finacle.com/fixml")]
           public RequestMessageKey RequestMessageKey { get; set; }
           [XmlElement(ElementName = "ResponseMessageInfo", Namespace = "http://www.finacle.com/fixml")]
           public ResponseMessageInfo ResponseMessageInfo { get; set; }
           [XmlElement(ElementName = "UBUSTransaction", Namespace = "http://www.finacle.com/fixml")]
           public UBUSTransaction UBUSTransaction { get; set; }
           [XmlElement(ElementName = "HostTransaction", Namespace = "http://www.finacle.com/fixml")]
           public HostTransaction HostTransaction { get; set; }
           [XmlElement(ElementName = "HostParentTransaction", Namespace = "http://www.finacle.com/fixml")]
           public HostParentTransaction HostParentTransaction { get; set; }
           [XmlElement(ElementName = "CustomInfo", Namespace = "http://www.finacle.com/fixml")]
           public string CustomInfo { get; set; }
       }

       [XmlRoot(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
       public class Header
       {
           [XmlElement(ElementName = "ResponseHeader", Namespace = "http://www.finacle.com/fixml")]
           public ResponseHeader ResponseHeader { get; set; }
       }
   }
}

The Success response class would look something like this...

/*
 Licensed under the Apache License, Version 2.0

 http://www.apache.org/licenses/LICENSE-2.0
 */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using static Xml2CSharp.HeaderDto;

namespace Xml2CSharp
{
    public class SuccessDto
    {
        public RequestMessageKey RequestMessageKey { get; set; }
        public ResponseMessageInfo ResponseMessageInfo { get; set; }
        public UBUSTransaction UBUSTransaction { get; set; }
        public HostTransaction HostTransaction { get; set; }
        public HostParentTransaction HostParentTransaction { get; set; }
        public ResponseHeader ResponseHeader { get; set; }
        public Header Header { get; set; }

        [XmlRoot(ElementName = "AcctType", Namespace = "http://www.finacle.com/fixml")]
        public class AcctType
        {
            [XmlElement(ElementName = "SchmCode", Namespace = "http://www.finacle.com/fixml")]
            public string SchmCode { get; set; }
            [XmlElement(ElementName = "SchmType", Namespace = "http://www.finacle.com/fixml")]
            public string SchmType { get; set; }
        }

        [XmlRoot(ElementName = "PostAddr", Namespace = "http://www.finacle.com/fixml")]
        public class PostAddr
        {
            [XmlElement(ElementName = "Addr1", Namespace = "http://www.finacle.com/fixml")]
            public string Addr1 { get; set; }
            [XmlElement(ElementName = "Addr2", Namespace = "http://www.finacle.com/fixml")]
            public string Addr2 { get; set; }
            [XmlElement(ElementName = "Addr3", Namespace = "http://www.finacle.com/fixml")]
            public string Addr3 { get; set; }
            [XmlElement(ElementName = "City", Namespace = "http://www.finacle.com/fixml")]
            public string City { get; set; }
            [XmlElement(ElementName = "StateProv", Namespace = "http://www.finacle.com/fixml")]
            public string StateProv { get; set; }
            [XmlElement(ElementName = "PostalCode", Namespace = "http://www.finacle.com/fixml")]
            public string PostalCode { get; set; }
            [XmlElement(ElementName = "Country", Namespace = "http://www.finacle.com/fixml")]
            public string Country { get; set; }
            [XmlElement(ElementName = "AddrType", Namespace = "http://www.finacle.com/fixml")]
            public string AddrType { get; set; }
        }

        [XmlRoot(ElementName = "BankInfo", Namespace = "http://www.finacle.com/fixml")]
        public class BankInfo
        {
            [XmlElement(ElementName = "BankId", Namespace = "http://www.finacle.com/fixml")]
            public string BankId { get; set; }
            [XmlElement(ElementName = "Name", Namespace = "http://www.finacle.com/fixml")]
            public string Name { get; set; }
            [XmlElement(ElementName = "BranchId", Namespace = "http://www.finacle.com/fixml")]
            public string BranchId { get; set; }
            [XmlElement(ElementName = "BranchName", Namespace = "http://www.finacle.com/fixml")]
            public string BranchName { get; set; }
            [XmlElement(ElementName = "PostAddr", Namespace = "http://www.finacle.com/fixml")]
            public PostAddr PostAddr { get; set; }
        }

        [XmlRoot(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
        public class AcctId
        {
            [XmlElement(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
            public string AcctId { get; set; }
            [XmlElement(ElementName = "AcctType", Namespace = "http://www.finacle.com/fixml")]
            public AcctType AcctType { get; set; }
            [XmlElement(ElementName = "AcctCurr", Namespace = "http://www.finacle.com/fixml")]
            public string AcctCurr { get; set; }
            [XmlElement(ElementName = "BankInfo", Namespace = "http://www.finacle.com/fixml")]
            public BankInfo BankInfo { get; set; }
        }

        [XmlRoot(ElementName = "BalAmt", Namespace = "http://www.finacle.com/fixml")]
        public class BalAmt
        {
            [XmlElement(ElementName = "amountValue", Namespace = "http://www.finacle.com/fixml")]
            public string AmountValue { get; set; }
            [XmlElement(ElementName = "currencyCode", Namespace = "http://www.finacle.com/fixml")]
            public string CurrencyCode { get; set; }
        }

        [XmlRoot(ElementName = "AcctBal", Namespace = "http://www.finacle.com/fixml")]
        public class AcctBal
        {
            [XmlElement(ElementName = "BalType", Namespace = "http://www.finacle.com/fixml")]
            public string BalType { get; set; }
            [XmlElement(ElementName = "BalAmt", Namespace = "http://www.finacle.com/fixml")]
            public BalAmt BalAmt { get; set; }
        }

        [XmlRoot(ElementName = "BalInqRs", Namespace = "http://www.finacle.com/fixml")]
        public class BalInqRs
        {
            [XmlElement(ElementName = "AcctId", Namespace = "http://www.finacle.com/fixml")]
            public AcctId AcctId { get; set; }
            [XmlElement(ElementName = "AcctBal", Namespace = "http://www.finacle.com/fixml")]
            public List<AcctBal> AcctBal { get; set; }
        }

        [XmlRoot(ElementName = "BalInqResponse", Namespace = "http://www.finacle.com/fixml")]
        public class BalInqResponse
        {
            [XmlElement(ElementName = "BalInqRs", Namespace = "http://www.finacle.com/fixml")]
            public BalInqRs BalInqRs { get; set; }
            [XmlElement(ElementName = "BalInq_CustomData", Namespace = "http://www.finacle.com/fixml")]
            public string BalInq_CustomData { get; set; }
        }

        [XmlRoot(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
        public class Body
        {
            [XmlElement(ElementName = "BalInqResponse", Namespace = "http://www.finacle.com/fixml")]
            public BalInqResponse BalInqResponse { get; set; }
        }

        [XmlRoot(ElementName = "FIXML", Namespace = "http://www.finacle.com/fixml")]
        public class FIXML
        {
            [XmlElement(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
            public Header Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
            public string SchemaLocation { get; set; }
            [XmlAttribute(AttributeName = "xmlns")]
            public string Xmlns { get; set; }
            [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Xsi { get; set; }
        }
    }

}

And Failed class would be like this

/*
 Licensed under the Apache License, Version 2.0

 http://www.apache.org/licenses/LICENSE-2.0
 */
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
using static Xml2CSharp.HeaderDto;

namespace Xml2CSharp
{
    public class FailedDto
    {
        public RequestMessageKey RequestMessageKey { get; set; }
        public ResponseMessageInfo ResponseMessageInfo { get; set; }
        public UBUSTransaction UBUSTransaction { get; set; }
        public HostTransaction HostTransaction { get; set; }
        public HostParentTransaction HostParentTransaction { get; set; }
        public ResponseHeader ResponseHeader { get; set; }
        public Header Header { get; set; }

        [XmlRoot(ElementName = "ErrorDetail", Namespace = "http://www.finacle.com/fixml")]
        public class ErrorDetail
        {
            [XmlElement(ElementName = "ErrorCode", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorCode { get; set; }
            [XmlElement(ElementName = "ErrorDesc", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorDesc { get; set; }
            [XmlElement(ElementName = "ErrorSource", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorSource { get; set; }
            [XmlElement(ElementName = "ErrorType", Namespace = "http://www.finacle.com/fixml")]
            public string ErrorType { get; set; }
        }

        [XmlRoot(ElementName = "FIBusinessException", Namespace = "http://www.finacle.com/fixml")]
        public class FIBusinessException
        {
            [XmlElement(ElementName = "ErrorDetail", Namespace = "http://www.finacle.com/fixml")]
            public ErrorDetail ErrorDetail { get; set; }
        }

        [XmlRoot(ElementName = "Error", Namespace = "http://www.finacle.com/fixml")]
        public class Error
        {
            [XmlElement(ElementName = "FIBusinessException", Namespace = "http://www.finacle.com/fixml")]
            public FIBusinessException FIBusinessException { get; set; }
        }

        [XmlRoot(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
        public class Body
        {
            [XmlElement(ElementName = "Error", Namespace = "http://www.finacle.com/fixml")]
            public Error Error { get; set; }
        }

        [XmlRoot(ElementName = "FIXML", Namespace = "http://www.finacle.com/fixml")]
        public class FIXML
        {
            [XmlElement(ElementName = "Header", Namespace = "http://www.finacle.com/fixml")]
            public Header Header { get; set; }
            [XmlElement(ElementName = "Body", Namespace = "http://www.finacle.com/fixml")]
            public Body Body { get; set; }
            [XmlAttribute(AttributeName = "schemaLocation", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
            public string SchemaLocation { get; set; }
            [XmlAttribute(AttributeName = "xmlns")]
            public string Xmlns { get; set; }
            [XmlAttribute(AttributeName = "xsi", Namespace = "http://www.w3.org/2000/xmlns/")]
            public string Xsi { get; set; }
        }
    }
}

Please consider this as pseudo code, since it's not tested.
So when you get the response, parse the header, and read the node you need to validate if its Success or Failed message, then just parse it as that object.


问:
docker-compose - COMPOSE_PROJECT_NAME, DockerHub and "service name". How to use it?
I'm using docker-compose to built customised nginx and php images and then I'd like to push it to DockeHub.

I'm using COMPOSE_PROJECT_NAME in an .env file to set a prefix image name:

```<code>COMPOSE_PROJECT_NAME=myapp
</code>```

and docker-compose.yml is something like:

```<code>version: '3'
services:
  php-fpm:
    build:
      context: ./php-fpm
      args:
         .....
      volumes:
         .....
      expose:
         .....

  nginx:
    build:
      context: ./nginx
      args:
         .....
      volumes:
         .....
      port:
         .....
</code>```

Running docker-compose up -d the images name are:

```<code>myapp_nginx
myapp_php-fpm
</code>```

the container name are:

```<code>myapp_nginx_1
myapp_php-fpm_1
</code>```

Now, to push these images to DocekeHub I need to change image name adding the DockerHub "account" suffix:

```<code>myaccount/myapp_nginx
myaccount/myapp_php-fpm
</code>```

to solve this problem, I added the "image" option to docker-compose.yml:

```<code>version: '3'
services:
  php-fpm:
    build:
      context: ./php-fpm
      args:
         .....
      volumes:
         .....
      expose:
         .....
      image: myaccount/${COMPOSE_PROJECT_NAME}_php-fpm

  nginx:
    build:
      context: ./nginx
      args:
         .....
      volumes:
         .....
      port:
         .....
      image: myaccount/${COMPOSE_PROJECT_NAME}_nginx
</code>```

now, running docker-compose push the images are pushed to DockerHub.

Ok, my question are:

1) is there a way to insert DockerHub account name myaccout into COMPOSE_PROJECT_NAME variable? Something like: COMPOSE_PROJECT_NAME=myaccount/myapp to create automatically the image name like: myaccount/myapp_nginx and myaccount/myapp_php-fpm?

2) is there a variable to get "service name" the retrieve the name nginx or php-fpm?
For example, into the docker-compose.yml file, I could set: image: myaccount/${COMPOSE_PROJECT_NAME}_<service_name> then If I change the "service name" from nginx to nginx2 automatically the image will be myaccount/myapp_nginx2

3) is there a way to rename the images produced with docker-compose only to permit the push?

Thank you

答:
You'd typically use fixed image names in this context.  A published image name shouldn't be dependent on details of the specific Compose file that launched it.

version: '3'
services:
  nginx:
    build: ./nginx
    image: myaccount/nginx # no project name
```

<p>Imagine you're planning to run this same setup on a different system.  It has Docker and Compose installed, but none of your application source code.  You should be able to copy the <code>docker-compose.yml</code> file there, delete the <code>build:</code> line, and run the same thing.  It doesn't matter if the directory is named <code>project</code> or <code>other</code>, and it doesn't matter if the Compose setup actually names the service <code>proxy</code> instead of <code>nginx</code>; you'd use the same <code>image:</code> to refer to it.</p>

<pre class="lang-yaml prettyprint-override"><code># COMPOSE_PROJECT_NAME=other
version: '3'
services:
  proxy:
    image: myaccount/nginx # same image as above
</code>```

If you're unhappy with the names Compose produces, you can manually docker tag and docker push the images outside of Compose.  You'll also need to do this if you want an image to have multiple tags (both a date stamp and latest for example) or if for whatever reason you need to push it to multiple repositories (both Docker Hub and Amazon ECR).

Body:
I'm using docker-compose to built customised nginx and php images and then I'd like to push it to DockeHub.

I'm using COMPOSE_PROJECT_NAME in an .env file to set a prefix image name:

COMPOSE_PROJECT_NAME=myapp

and docker-compose.yml is something like:

version: '3'
services:
  php-fpm:
    build:
      context: ./php-fpm
      args:
         .....
      volumes:
         .....
      expose:
         .....

  nginx:
    build:
      context: ./nginx
      args:
         .....
      volumes:
         .....
      port:
         .....

Running docker-compose up -d the images name are:

myapp_nginx
myapp_php-fpm

the container name are:

myapp_nginx_1
myapp_php-fpm_1

Now, to push these images to DocekeHub I need to change image name adding the DockerHub "account" suffix:

myaccount/myapp_nginx
myaccount/myapp_php-fpm

to solve this problem, I added the "image" option to docker-compose.yml:

version: '3'
services:
  php-fpm:
    build:
      context: ./php-fpm
      args:
         .....
      volumes:
         .....
      expose:
         .....
      image: myaccount/${COMPOSE_PROJECT_NAME}_php-fpm

  nginx:
    build:
      context: ./nginx
      args:
         .....
      volumes:
         .....
      port:
         .....
      image: myaccount/${COMPOSE_PROJECT_NAME}_nginx

now, running docker-compose push the images are pushed to DockerHub.

Ok, my question are:

1) is there a way to insert DockerHub account name myaccout into COMPOSE_PROJECT_NAME variable? Something like: COMPOSE_PROJECT_NAME=myaccount/myapp to create automatically the image name like: myaccount/myapp_nginx and myaccount/myapp_php-fpm?

2) is there a variable to get "service name" the retrieve the name nginx or php-fpm?
For example, into the docker-compose.yml file, I could set: image: myaccount/${COMPOSE_PROJECT_NAME}_<service_name> then If I change the "service name" from nginx to nginx2 automatically the image will be myaccount/myapp_nginx2

3) is there a way to rename the images produced with docker-compose only to permit the push?

Thank you

Body:
You'd typically use fixed image names in this context.  A published image name shouldn't be dependent on details of the specific Compose file that launched it.

version: '3'
services:
  nginx:
    build: ./nginx
    image: myaccount/nginx # no project name

Imagine you're planning to run this same setup on a different system.  It has Docker and Compose installed, but none of your application source code.  You should be able to copy the docker-compose.yml file there, delete the build: line, and run the same thing.  It doesn't matter if the directory is named project or other, and it doesn't matter if the Compose setup actually names the service proxy instead of nginx; you'd use the same image: to refer to it.

# COMPOSE_PROJECT_NAME=other
version: '3'
services:
  proxy:
    image: myaccount/nginx # same image as above

If you're unhappy with the names Compose produces, you can manually docker tag and docker push the images outside of Compose.  You'll also need to do this if you want an image to have multiple tags (both a date stamp and latest for example) or if for whatever reason you need to push it to multiple repositories (both Docker Hub and Amazon ECR).


问:
UML help C# Design Principles
I have a problem understanding an UML below:

Specifically, what is the relationship between PersistentSet and ThirdPartyPersistentSet?
What is the relationship between PersistentObject and ThirdPartyPersistentSet?

Please note that the UML is from Agile Principles, Patterns, and Practices in C#
By Martin C. Robert, Martin Micah 2006. Chapter 10

Thanks in advance!

答:
The black diamond represents composition, containment (as in having a field of the type pointed by the arrow):
PersistentSet entities contain ThirdPartyPersistentSet entities
When PersistenSet is destroyed, all ThirdPartyPersistenSet objects contained will also be destroyed.

The dashed line represents dependency, as in makes a function call that has a parameter of the type pointed by the arrow):
ThirdPartyPersistentSet depends on PersistentObject

Look at the Wikipedia entry for more details

ContentLicense: CC BY-SA 3.0

Title: UML help C# Design Principles


问:
List combination challenge in Python 3
I am just facing one tricky challenge to make a list combination in python 3.

I have one list that needs to used for combination. (given list)

```<code>['01101001', '01110110', '01100101', '01101011']
</code>```

I want to get the list combined with each value like below. (result list)

```<code>['00001111', '11110100', '10010110', '01011011']
</code>```

The first item in the result list is made by the combination of the first 4 strings and the second 4 strings of each item in turn in the given list.
So 0000 are the first 4 strings of each item and 1111 are the second 4 strings of each item in the given list.
Thus the first item of the result list is 00001111.

What is the optimized code written by Python 3?
Thank you in advance!

答:
Here is the solution.

```<code>givenList = ['01101001', '01110110', '01100101', '01101011']
unitList = list()
result = list()

for i in range(8):
  for j in givenList:
    unitList.append(j[i])
  if i % 2 == 1:
    result.append(''.join(unitList))
    unitList = []

print(result)
</code>```

This would be working for only the given list contains static 8 digits.
You can update the 8 with len(givenList[0]).

Title: List combination challenge in Python 3

Body:
I am just facing one tricky challenge to make a list combination in python 3.

I have one list that needs to used for combination. (given list)

['01101001', '01110110', '01100101', '01101011']

I want to get the list combined with each value like below. (result list)

['00001111', '11110100', '10010110', '01011011']

The first item in the result list is made by the combination of the first 4 strings and the second 4 strings of each item in turn in the given list.
So 0000 are the first 4 strings of each item and 1111 are the second 4 strings of each item in the given list.
Thus the first item of the result list is 00001111.

What is the optimized code written by Python 3?
Thank you in advance!

Body:
Here is the solution.

givenList = ['01101001', '01110110', '01100101', '01101011']
unitList = list()
result = list()

for i in range(8):
  for j in givenList:
    unitList.append(j[i])
  if i % 2 == 1:
    result.append(''.join(unitList))
    unitList = []

print(result)

This would be working for only the given list contains static 8 digits.
You can update the 8 with len(givenList[0]).


问:
add subtitles for rows of a plot
For a plot like this:

```<code>import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True)
ax1.plot(x, y)
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')
</code>```

how can I add subtitles for a row?. It should look like this:

I made "Title1" and "Title2" with photoshop, how can I add them to the plot in python?

答:
You can do it by adding 3 lines of code as below:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

```<code>f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True)
plt.subplots_adjust(wspace=0.2, hspace=0.5)
ax1.plot(x, y)
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')

ax1.text(6.1, 1.36, 'Title1', color='r',fontsize=20)
ax3.text(6.1, 1.36, 'Title2', color='b',fontsize=20)
</code>```

Title: add subtitles for rows of a plot

Body:
For a plot like this:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True)
ax1.plot(x, y)
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')

how can I add subtitles for a row?. It should look like this:

I made "Title1" and "Title2" with photoshop, how can I add them to the plot in python?

Body:
You can do it by adding 3 lines of code as below:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharey=True)
plt.subplots_adjust(wspace=0.2, hspace=0.5)
ax1.plot(x, y)
ax2.scatter(x, y)
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
ax4.plot(x, 2 * y ** 2 - 1, color='r')

ax1.text(6.1, 1.36, 'Title1', color='r',fontsize=20)
ax3.text(6.1, 1.36, 'Title2', color='b',fontsize=20)


问:
How to add Array value to JSON Key in Swift
How to add request.httpBody = getPostData(params: ["contactsList": ["1212121212, "5555555544"]]) in place of
let parameters = getPostString(params:   ["contactsList":[phNumArray]])

below is working code but how to add phNumArray in palce of individual of individual numberes to contactsList

Postman output for API:

working code: anyone can copy paste to see output

```<code>import UIKit
class TestViewController: UIViewController {
    var phNumArray = ["1111111111", "5555555544"]
    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostString(params: [String: Any]) -> String {
        var data = [String]()
        for (key, value) in params {
            data.append(key + "=\(value)")
        }
        print(data.map { String($0) }.joined(separator: "&"))
        return data.map { String($0) }.joined(separator: "&")
    }

    func callPostApi() {
        let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
        guard let requestUrl = url else { fatalError() }
        var request = URLRequest(url: requestUrl)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        let parameters = getPostString(params: ["contactsList": ["5555555544", "11111111111"]])

        print("json parameter phone numbers \(parameters)")

        request.httpBody = parameters.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            let httpResponse = response as? HTTPURLResponse
            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString)")

                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                    print("fetching json \(json)")
                    let fetchStatus = json["userName"] as? String
                    print("fetching json userName \(String(describing: fetchStatus))")

                    let user = json["5555555544"] as? [String: Any]
                    let name = user?["userName"] as? String
                    print("first username \(name)")
                } catch {}
            }
        }
        task.resume()
    }
}
</code>```

please help me to solve the issue with contactsList value.

答:
Update: All this time you were sending the request as JSON encoded instead of as form-data. I'm adding the code for that below, try it out:

class ViewController: UIViewController {

    var phNumArray  = ["1111111111", "5555555544"]

    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostData(params: [String:Any]) -> Data? {
        return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    }

    func callPostApi() {

        let url            = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        try? request.setMultipartFormData(["contactsList": "\(phNumArray)"], encoding: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

                let user = json["5555555544"] as? [String: Any]
                let name = user?["userName"] as? String
                print("first username \(name)")
            }
        }.resume()
    }
}

extension URLRequest {

    public mutating func setMultipartFormData(_ parameters: [String: String], encoding: String.Encoding) throws {

        let makeRandom = { UInt32.random(in: (.min)...(.max)) }
        let boundary = String(format: "------------------------%08X%08X", makeRandom(), makeRandom())

        let contentType: String = try {
            guard let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding.rawValue)) else {
                throw MultipartFormDataEncodingError.characterSetName
            }
            return "multipart/form-data; charset=\(charset); boundary=\(boundary)"
        }()
        addValue(contentType, forHTTPHeaderField: "Content-Type")

        httpBody = try {
            var body = Data()

            for (rawName, rawValue) in parameters {
                if !body.isEmpty {
                    body.append("\r\n".data(using: .utf8)!)
                }

                body.append("--\(boundary)\r\n".data(using: .utf8)!)

                guard
                    rawName.canBeConverted(to: encoding),
                    let disposition = "Content-Disposition: form-data; name=\"\(rawName)\"\r\n".data(using: encoding) else {
                    throw MultipartFormDataEncodingError.name(rawName)
                }
                body.append(disposition)

                body.append("\r\n".data(using: .utf8)!)

                guard let value = rawValue.data(using: encoding) else {
                    throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
                }

                body.append(value)
            }

            body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

            return body
        }()
    }
}

public enum MultipartFormDataEncodingError: Error {
    case characterSetName
    case name(String)
    case value(String, name: String)
}
```

<p>Instead of converting to JSON <code>String</code> and then converting it to <code>Data</code>, use <code>JSONSerialization</code>, here's an example:</p>

<pre class="lang-swift prettyprint-override"><code>func getPostData(params:[String:Any]) -> Data? {
    return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
}
</code>```

And then assign it directly to URLRequest's httpBody, like this:

let arrayOfNumbers = [String]()
arrayOfNumbers.append("5555555544")
arrayOfNumbers.append("11111111111")
request.httpBody = getPostData(params: ["contactsList": arrayOfNumbers])
```

Also, go through the Apple Documentation, you'll find valuable information there. If don't understand concepts there google more about JSONSerializing and POST request httpBody.

Body:
How to add request.httpBody = getPostData(params: ["contactsList": ["1212121212, "5555555544"]]) in place of
let parameters = getPostString(params:   ["contactsList":[phNumArray]])

below is working code but how to add phNumArray in palce of individual of individual numberes to contactsList

Postman output for API:

working code: anyone can copy paste to see output

import UIKit
class TestViewController: UIViewController {
    var phNumArray = ["1111111111", "5555555544"]
    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostString(params: [String: Any]) -> String {
        var data = [String]()
        for (key, value) in params {
            data.append(key + "=\(value)")
        }
        print(data.map { String($0) }.joined(separator: "&"))
        return data.map { String($0) }.joined(separator: "&")
    }

    func callPostApi() {
        let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
        guard let requestUrl = url else { fatalError() }
        var request = URLRequest(url: requestUrl)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        let parameters = getPostString(params: ["contactsList": ["5555555544", "11111111111"]])

        print("json parameter phone numbers \(parameters)")

        request.httpBody = parameters.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            let httpResponse = response as? HTTPURLResponse
            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString)")

                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                    print("fetching json \(json)")
                    let fetchStatus = json["userName"] as? String
                    print("fetching json userName \(String(describing: fetchStatus))")

                    let user = json["5555555544"] as? [String: Any]
                    let name = user?["userName"] as? String
                    print("first username \(name)")
                } catch {}
            }
        }
        task.resume()
    }
}

please help me to solve the issue with contactsList value.

Body:
Update: All this time you were sending the request as JSON encoded instead of as form-data. I'm adding the code for that below, try it out:

class ViewController: UIViewController {

    var phNumArray  = ["1111111111", "5555555544"]

    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostData(params: [String:Any]) -> Data? {
        return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    }

    func callPostApi() {

        let url            = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        try? request.setMultipartFormData(["contactsList": "\(phNumArray)"], encoding: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

                let user = json["5555555544"] as? [String: Any]
                let name = user?["userName"] as? String
                print("first username \(name)")
            }
        }.resume()
    }
}

extension URLRequest {

    public mutating func setMultipartFormData(_ parameters: [String: String], encoding: String.Encoding) throws {

        let makeRandom = { UInt32.random(in: (.min)...(.max)) }
        let boundary = String(format: "------------------------%08X%08X", makeRandom(), makeRandom())

        let contentType: String = try {
            guard let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding.rawValue)) else {
                throw MultipartFormDataEncodingError.characterSetName
            }
            return "multipart/form-data; charset=\(charset); boundary=\(boundary)"
        }()
        addValue(contentType, forHTTPHeaderField: "Content-Type")

        httpBody = try {
            var body = Data()

            for (rawName, rawValue) in parameters {
                if !body.isEmpty {
                    body.append("\r\n".data(using: .utf8)!)
                }

                body.append("--\(boundary)\r\n".data(using: .utf8)!)

                guard
                    rawName.canBeConverted(to: encoding),
                    let disposition = "Content-Disposition: form-data; name=\"\(rawName)\"\r\n".data(using: encoding) else {
                    throw MultipartFormDataEncodingError.name(rawName)
                }
                body.append(disposition)

                body.append("\r\n".data(using: .utf8)!)

                guard let value = rawValue.data(using: encoding) else {
                    throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
                }

                body.append(value)
            }

            body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

            return body
        }()
    }
}

public enum MultipartFormDataEncodingError: Error {
    case characterSetName
    case name(String)
    case value(String, name: String)
}

Instead of converting to JSON String and then converting it to Data, use JSONSerialization, here's an example:

func getPostData(params:[String:Any]) -> Data? {
    return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
}

And then assign it directly to URLRequest's httpBody, like this:

let arrayOfNumbers = [String]()
arrayOfNumbers.append("5555555544")
arrayOfNumbers.append("11111111111")
request.httpBody = getPostData(params: ["contactsList": arrayOfNumbers])

Also, go through the Apple Documentation, you'll find valuable information there. If don't understand concepts there google more about JSONSerializing and POST request httpBody.


问:
Remove validator after submitting
I created two textboxes one for the title and another for the name.

I am using validations if the textboxes are not filled, so the information is only submitted if both are filled.

My problem is that after submitting I try to clear the values of the variables and when clearing that value the validation messages appear.

Is there a way to successfully submit and clear the value of variables, the validator does not appear?

DEMO

html

```<code><div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="title..." [showClearButton]="true" [(ngModel)]="title">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Title">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>
<div style="margin-top:16px;width:50%">
    <dx-text-box placeholder="name..." [showClearButton]="true" [(ngModel)]="name">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Name">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>
</div>

<dx-button text="Submit" [useSubmitBehavior]="true" (onClick)="Save()"></dx-button>
</code>```

.ts

```<code>title: string;
name: string;

Save(){
  if(this.title == "" || this.title == undefined || this.name == "" || this.name == undefined){
  }
  else{
    alert("Sucess !!");
    this.title = "";
    this.name = "";
  }
}
</code>```

Problem

Here, I filled in the textboxes and submitted successfully. I cleared the value of the variables, but when doing this, the validator is activated, when in fact everything was supposed to be in the initial state :(

答:
As a quick workaround, you can wrap the template in a form, then use that to check if it's pristine, in order to know whether or not to show the validator message. Then instead of assigning an empty string to your properties, you can reset the form (after importing it in the component through ViewChild()).

That does feel like a hack though, because the toolkit you're using should automatically know this. If it doesn't, then why bother use it.

Also, I suggest you also start reading on Angular Reactive Forms.

Anyways, I attached my suggested changes in a Stackblitz.

Good luck with your project!

Title: Remove validator after submitting

Body:
I created two textboxes one for the title and another for the name.

I am using validations if the textboxes are not filled, so the information is only submitted if both are filled.

My problem is that after submitting I try to clear the values of the variables and when clearing that value the validation messages appear.

Is there a way to successfully submit and clear the value of variables, the validator does not appear?

DEMO

html

    <dx-text-box placeholder="title..." [showClearButton]="true" [(ngModel)]="title">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Title">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>

    <dx-text-box placeholder="name..." [showClearButton]="true" [(ngModel)]="name">
        <dx-validator>
            <dxi-validation-rule type="required" message="Insert Name">
            </dxi-validation-rule>
        </dx-validator>
    </dx-text-box>

<dx-button text="Submit" [useSubmitBehavior]="true" (onClick)="Save()"></dx-button>

.ts

title: string;
name: string;

Save(){
  if(this.title == "" || this.title == undefined || this.name == "" || this.name == undefined){
  }
  else{
    alert("Sucess !!");
    this.title = "";
    this.name = "";
  }
}

Problem

Here, I filled in the textboxes and submitted successfully. I cleared the value of the variables, but when doing this, the validator is activated, when in fact everything was supposed to be in the initial state :(


问:
sendgrid error "Access forbidden" when trying to GET user profile API
The following API request:

```<code>curl --request GET \
     --url https://api.sendgrid.com/v3/user/profile \
     --header 'Authorization: Bearer API KEY'\
     --header 'Content-Type: application/json'
</code>```

From the docs: https://sendgrid.com/docs/API_Reference/Web_API_v3/user.html

Results in a HTTP 403 response with the following body:

```<code>{"errors":[{"field":null,"message":"access forbidden"}]}
</code>```

I went to Settings -> API Keys and clicked on 'Edit details' to view the permissions granted to my API key and, as far as I can tell, there isn't any permission that I can grant (or revoke) that seems related to 'user profile'.

Just to be on the safe side, I have configured every single permission to 'Full Access' (when available) or to 'Read Access' if 'full access' is not available but I am still getting this HTTP 403 error.

What is the permission I need to grant to my API key in order to be able to retrieve my user profile?

答:
I just meet this issue, and I here is my solution: You need to create the Auth Sender: https://app.sendgrid.com/settings/sender_auth
For testing, just create a simple Single Sender Verification, for productions, you should create a account base on your domain.
I use free version and I can send my email after fix this. Notice that, email can go to Spam inbox.

Body:
The following API request:

curl --request GET \
     --url https://api.sendgrid.com/v3/user/profile \
     --header 'Authorization: Bearer API KEY'\
     --header 'Content-Type: application/json'

From the docs: https://sendgrid.com/docs/API_Reference/Web_API_v3/user.html

Results in a HTTP 403 response with the following body:

{"errors":[{"field":null,"message":"access forbidden"}]}

I went to Settings -> API Keys and clicked on 'Edit details' to view the permissions granted to my API key and, as far as I can tell, there isn't any permission that I can grant (or revoke) that seems related to 'user profile'.

Just to be on the safe side, I have configured every single permission to 'Full Access' (when available) or to 'Read Access' if 'full access' is not available but I am still getting this HTTP 403 error.

What is the permission I need to grant to my API key in order to be able to retrieve my user profile?


问:
JavaScript output of a string instead of undefined?
I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?</p>

```<code>var greet = function(name) {
   let  first = String(name. charAt(0). toUpperCase());
    let second = String(name.slice(1));

    console.log('Hello ' + first + second + '!');
    }
</code>```

答:
Your function is working fine - you just need to invoke it and feed its argument with a name...

[for the result look in the console]

var greet = function(name) {
  let first = String(name.charAt(0).toUpperCase());
  let second = String(name.slice(1));

  console.log('Hello ' + first + second + '!');
}
;
greet("henky");```

Body:
I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?

var greet = function(name) {
   let  first = String(name. charAt(0). toUpperCase());
    let second = String(name.slice(1));

    console.log('Hello ' + first + second + '!');
    }


问:
Python requiring an attribute be converted to a string
```<code>from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()
</code>```

Trace back i get in terminal is:

```<code>    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string
</code>```

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

答:
To return the value of a named attribute of an object you must supply a string of the name of the attribute.

```<code>room = getattr(self, 'next')
</code>```

From the python docs:
getattr(object, name[, default])

Return the value of the named attribute of object.name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

Body:
from sys import exit
from random import randint

class Map(object):

 def death():
    print quips[randint (0, len(quips)-1)]
    exit(1)

 def princess_lives_here():
    print "You see a beautiful Princess with a shiny crown."
    print "She offers you some cake."

    eat_it = raw_input(">")

    if eat_it == "eat it":
        print "You explode like a pinata full of frogs."
        print "The Princess cackles and eats the frogs. Yum!"
        return 'death'

    elif eat_it == "do not eat it":
        print "She throws the cake at you and it cuts off your head."
        print "The last thing you see is her munching on your face. Yum!"
        return 'death'

    elif eat_it == "make her eat it":
        print "The Princess screams as you cram the cake in her mouth."
        print "Then she smiles and cries and thank you for saving her."
        print "She points to a tiny door and says, 'The Koi needs cake too.'"
        print "She gives you the very last bit of cake and shoves you in."
        return 'gold_koi_pond'

    else:
        print "The Princess looks at you confused and just points at the cake."
        return 'princess_lives_here'

class Engine(object):

 def __init__(self, start, quips):
    self.quips = [
        "You died. You suck at this.",
        "Your mom would be proud, if she were smarter",
        "Such a luser.",
        "I have a small puppy that's better at this."
    ]
    self.start = start

 def play(self):
    next = self.start

    while True:
        print "\n-----"
        room = getattr(self, next)
        next = room()

m = Map()
e = Engine(m, "princess_lives_here")

e.play()

Trace back i get in terminal is:

    Traceback (most recent call last):
  File "ec42.py", line 162, in <module>
    e.play()
  File "ec42.py", line 156, in play
    room = getattr(self, next)
TypeError: getattr(): attribute name must be string

I have been working on this far too long, and just cannot nail it down. The main issue is getting the map class to run inside the engine class as an object. thanks in advance for the help.

Body:
To return the value of a named attribute of an object you must supply a string of the name of the attribute.

room = getattr(self, 'next')

From the python docs:
getattr(object, name[, default])

Return the value of the named attribute of object.name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.


问:
How can query string parameters be forwarded through a proxy_pass with nginx?
```<code>upstream apache {
   server 127.0.0.1:8080;
}
server{
   location ~* ^/service/(.*)$ {
      proxy_pass http://apache/$1;
      proxy_redirect off;
   }
 }
</code>```

The above snippet will redirect requests where the url includes the string "service" to another server, but it does not include query parameters.

答:
worked with adding $request_uri:

proxy_pass http://apache/$request_uri;

Body:
upstream apache {
   server 127.0.0.1:8080;
}
server{
   location ~* ^/service/(.*)$ {
      proxy_pass http://apache/$1;
      proxy_redirect off;
   }
 }

The above snippet will redirect requests where the url includes the string "service" to another server, but it does not include query parameters.


问:
Is there any way to parameterise the table name provided in a SQL query in mule 4
I have tried the following queries -
INSERT INTO (:tableName) (ENTITY_NAME,PAYLOAD_BLOB,PAYLOAD_JSON) VALUES (:entityName,:payload_blob,:payload_json);

INSERT INTO #vars.tableName (ENTITY_NAME,PAYLOAD_BLOB,PAYLOAD_JSON) VALUES (:entityName,:payload_blob,:payload_json);

INSERT INTO $(vars.tableName) (ENTITY_NAME,PAYLOAD_BLOB,PAYLOAD_JSON) VALUES (:entityName,:payload_blob,:payload_json);

But all the 3 queries resulted in an Bad Synatx error.

答:
Create variable with SQL statement

```<code>INSERT INTO ${vars.tableName} (ENTITY_NAME,PAYLOAD_BLOB,PAYLOAD_JSON) VALUES (:entityName,:payload_blob,:payload_json)
</code>```

then use it in the Insert Component. Keep in mind - you still have to provide these internal values :entityName,:payload_blob,:payload_json in this Insert Component.

Body:
Create variable with SQL statement

INSERT INTO ${vars.tableName} (ENTITY_NAME,PAYLOAD_BLOB,PAYLOAD_JSON) VALUES (:entityName,:payload_blob,:payload_json)

then use it in the Insert Component. Keep in mind - you still have to provide these internal values :entityName,:payload_blob,:payload_json in this Insert Component.


问:
How to count years in the text in R?
I want to count years found between the opening and closing brackets in the following text named txt.

```<code>library(stringr)
txt <- "Text Mining exercise (2020) Mining, p. 628508; Computer Science text analysis (1998) Computer Science, p.345-355; Introduction to data mining (2015) J. Data Science, pp. 31-33"
</code>```

lengths(strsplit(txt,"\\(\\d{4}\\)")) gives me 4 which is wrong. Any help, please?

答:
You can use str_extract_all with positive lookahead and lookbehind regex.

```<code>stringr::str_extract_all(txt, '(?<=\\()\\d+(?=\\))')[[1]]
#[1] "2020" "1998" "2015"
</code>```

If you want to count how many are present use length over it.

```<code>length(stringr::str_extract_all(txt, '(?<=\\()\\d+(?=\\))')[[1]])
#[1] 3
</code>```

Probably, using str_match_all is easier

```<code>stringr::str_match_all(txt, '\\((\\d+)\\)')[[1]][, 2]
#[1] "2020" "1998" "2015"
</code>```

Title: How to count years in the text in R?

Body:
I want to count years found between the opening and closing brackets in the following text named txt.

library(stringr)
txt <- "Text Mining exercise (2020) Mining, p. 628508; Computer Science text analysis (1998) Computer Science, p.345-355; Introduction to data mining (2015) J. Data Science, pp. 31-33"

lengths(strsplit(txt,"\\(\\d{4}\\)")) gives me 4 which is wrong. Any help, please?

Body:
You can use str_extract_all with positive lookahead and lookbehind regex.

stringr::str_extract_all(txt, '(?<=\\()\\d+(?=\\))')[[1]]
#[1] "2020" "1998" "2015"

If you want to count how many are present use length over it.

length(stringr::str_extract_all(txt, '(?<=\\()\\d+(?=\\))')[[1]])
#[1] 3

Probably, using str_match_all is easier

stringr::str_match_all(txt, '\\((\\d+)\\)')[[1]][, 2]
#[1] "2020" "1998" "2015"


问:
Multiply chunked dask xarray by mask
I have a large (>100 GB) xarray Dataset holding weather forecast data (dimensions time, forecast step, latitude, longitude, with dask chunks over the time, latitude and longitude dimensions) and want to work out the average weather (for each time point) over an irregularly shaped region (defined by a binary mask array with dimensions latitude and longitude).
The naive way of doing this is:

```<code>average_weather = weather.where(mask).mean(dim=('latitude', 'longitude'))
</code>```

However, for most of the (latitude, longitude) chunks, the mask values in that region are all zero, so there is no need to load that chunk. So far as I can tell by briefly looking at the xarray and dask source, there is no optimization that checks if all the mask values for a chunk are zero before loading the chunk, so the naive command will use a great deal of unnecessary data transfer and CPU.

I did see that it is possible to use drop=True in the where command to limit the computation to the bounding box of the mask, but is it possible to do better than this?

答:
By default when using where, the values where the mask is False are replaced by NaN. If you use the drop=True keyword, they will be dropped completely. Note that this can change the shape of your data, or lead to unexpected NaN values sometimes.

e.g.
average_weather = weather.where(mask, drop=True).mean(dim=('latitude', 'longitude'))

Title: Multiply chunked dask xarray by mask

Body:
I have a large (>100 GB) xarray Dataset holding weather forecast data (dimensions time, forecast step, latitude, longitude, with dask chunks over the time, latitude and longitude dimensions) and want to work out the average weather (for each time point) over an irregularly shaped region (defined by a binary mask array with dimensions latitude and longitude).
The naive way of doing this is:

average_weather = weather.where(mask).mean(dim=('latitude', 'longitude'))

However, for most of the (latitude, longitude) chunks, the mask values in that region are all zero, so there is no need to load that chunk. So far as I can tell by briefly looking at the xarray and dask source, there is no optimization that checks if all the mask values for a chunk are zero before loading the chunk, so the naive command will use a great deal of unnecessary data transfer and CPU.

I did see that it is possible to use drop=True in the where command to limit the computation to the bounding box of the mask, but is it possible to do better than this?


问:
Is C# a high level language?
Is C# a high level language? I see it as more like medium level, but I am still unsure about this. Would you consider it as high level as some of the popular scripting languages?

Or does it accommodate more than one level?

答: C# allows use of pointers, is compiled just in time but sometimes ahead of time. Compared to a lot of other languages I use even though it allows very rapid software development it is slightly lower and closer to the hardware which comes to great advantage.</p>

OwnerDisplayName: Joan Venge

ContentLicense: CC BY-SA 2.5

Title: Is C# a high level language?

OwnerDisplayName: Ctrl Alt D-1337


问:
export table using ssh
I want to export a table of mysql database using ssh so how can I take this one.</p>

答:
If the dump is going to be very large, you'll probably want to run it in the background, to assure you losing connection to SSH doesn't cause a problem.

Also, you could use nice if it is a live server and don't want to effect its performance too much

```<code>nohup nice mysqldump -uuser -ppassword [other flags] database tablename > dumpfile.sql
</code>```

You can then use SSH File Transfer to download it to your computer, or use scp to send it to another server:

```<code>nohup nice scp dumpfile.sql user@IP:/path/ &
</code>```

Then you can load it in to mysql

```<code>nohup nice mysql -uuser -ppassword database < dumpfile.sql &
</code>```

**Use nohup if its going to take a long time and losing connection could be a problem.  nohup causes to run in background

**Use nice to lower the priority of the process, ie. in case is live server and performance is important.  You should know nice doesn't stop your mysql from being slowed down by a query that takes a long time to finish, so beware.

Title: export table using ssh

Body:
If the dump is going to be very large, you'll probably want to run it in the background, to assure you losing connection to SSH doesn't cause a problem.

Also, you could use nice if it is a live server and don't want to effect its performance too much

nohup nice mysqldump -uuser -ppassword [other flags] database tablename > dumpfile.sql

You can then use SSH File Transfer to download it to your computer, or use scp to send it to another server:

nohup nice scp dumpfile.sql user@IP:/path/ &

Then you can load it in to mysql

nohup nice mysql -uuser -ppassword database < dumpfile.sql &

**Use nohup if its going to take a long time and losing connection could be a problem.  nohup causes to run in background

**Use nice to lower the priority of the process, ie. in case is live server and performance is important.  You should know nice doesn't stop your mysql from being slowed down by a query that takes a long time to finish, so beware.


问:
Delete postman cache
I use Postman extension to check out my RESTful APIs

I am trying to make a request to my "localhost", but it seems to have cached one of the query parameters.

I tried clearing cache of my chrome browser but this does not seem to work. I went to the extent of even changing the API resource name.

Has anyone come across such an issue?

答:
I tried the solution above and it didn't work for me. What worked was restart the application. I'm using eclipse and running a spring boot application. </p>

<p>In case someone is using the same environment and facing the same problem it may help. </p>

Title: Delete postman cache

Body:
I tried the solution above and it didn't work for me. What worked was restart the application. I'm using eclipse and running a spring boot application.

In case someone is using the same environment and facing the same problem it may help.