问:
Hyperledger Fabric Raft Orderer Setup Failed with authentication handshake failure on channel create
I am creating a HLF network with raft as orderering service.

```<code> peer channel create -o ProdOrderer1_ProdOrdr_com:7050 -c masterchannel -f ./configtx/masterchannel.tx --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/msp/tlscacerts/tlsca.ProdOrdr_com-cert.pem
</code>```

But it returns the following error in peer cli.

```<code> 2020-02-14 06:00:09.733 UTC [grpc] watcher -> DEBU 039 ccResolverWrapper: sending new addresses to cc: [{ProdOrderer1_ProdOrdr_com:7050 0  <nil>}]
 2020-02-14 06:00:09.733 UTC [grpc] switchBalancer -> DEBU 03a ClientConn switching balancer to "pick_first"
 2020-02-14 06:00:09.733 UTC [grpc] HandleSubConnStateChange -> DEBU 03b pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, CONNECTING
 2020-02-14 06:00:09.736 UTC [grpc] createTransport -> DEBU 03c grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.ProdOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...
 2020-02-14 06:00:09.736 UTC [grpc] HandleSubConnStateChange -> DEBU 03d pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, TRANSIENT_FAILURE
 2020-02-14 06:00:10.734 UTC [grpc] HandleSubConnStateChange -> DEBU 03e pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, CONNECTING
 2020-02-14 06:00:10.738 UTC [grpc] createTransport -> DEBU 03f grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.StancOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...
 2020-02-14 06:00:10.738 UTC [grpc] HandleSubConnStateChange -> DEBU 040 pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, TRANSIENT_FAILURE
 2020-02-14 06:00:12.121 UTC [grpc] HandleSubConnStateChange -> DEBU 041 pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, CONNECTING
 2020-02-14 06:00:12.124 UTC [grpc] createTransport -> DEBU 042 grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.ProdOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...
 2020-02-14 06:00:12.124 UTC [grpc] HandleSubConnStateChange -> DEBU 043 pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, TRANSIENT_FAILURE
 Error: failed to create deliver client: orderer client failed to connect to ProdOrderer1_ProdOrdr_com:7050: failed to create new connection: context deadline exceeded
</code>```

I have checked to logs of peer & orderer containers.The logs of the orderer container reports the tls bad certificate error.

```<code>2020-02-14 06:22:33.504 UTC [core.comm] ServerHandshake -> ERRO 2849 TLS handshake failed with error remote error: tls: bad certificate server=Orderer remoteaddress=10.0.23.4:18725

2020-02-14 06:22:35.859 UTC [orderer.common.cluster.puller] probeEndpoint -> WARN 2853 Failed connecting to {ProdOrderer4_ProdOrdr_com:7050 [-----BEGIN CERTIFICATE-----
2020-02-14 06:22:35.859 UTC [orderer.common.cluster.puller] func1 -> WARN 2854 Received error of type 'failed to create new connection: context deadline exceeded' from {ProdOrderer4_ProdOrdr_com:7050 [-----BEGIN CERTIFICATE-----
</code>```

I am attaching crypto-config.yaml,configtx.yaml,docker-compose.yaml for the reference.

crypto-config.yaml

```<code>            OrdererOrgs:
              - Name: ProdOrderer
                Domain: ProdOrdr_com
                Specs:
                 - Hostname: ProdOrderer1
                   SANS:
                     - "localhost"
                     - "127.0.0.1"
                - Hostname: ProdOrderer2
                   SANS:
                     - "localhost"
                     - "127.0.0.1"
                - Hostname: ProdOrderer3
                   SANS:
                     - "localhost"
                     - "127.0.0.1"

             PeerOrgs:
                 - Name: ProdOrg

                 - Name: ProdOrgA
</code>```

configtx.yaml

```<code>Organizations:
  - &OrdererOrg
      Name: ProdOrderer
      ID: ProdOrdererMSP
      MSPDir: crypto-config/ordererOrganizations/ProdOrdr_com/msp
      Policies:
         Readers:
            Type: Signature
            Rule: "OR('ProdOrdererMSP.member')"
         Writers:
            Type: Signature
            Rule: "OR('ProdOrdererMSP.member')"
         Admins:
            Type: Signature
            Rule:  "OR('ProdOrdererMSP.admin')"
    - &ProdOrg
        Name: ProdOrg
        ID: ProdOrgMSP
        MSPDir: crypto-config/peerOrganizations/peerProd_com/msp
        Policies:
             Readers:
                    Type: Signature
                    Rule: "OR('ProdOrgMSP.admin','ProdOrgMSP.peer', 'ProdOrgMSP.client')"
             Writers:
                    Type: Signature
                    Rule: "OR('ProdOrgMSP.admin', 'ProdOrgMSP.client')"
             Admins:
                    Type: Signature
                    Rule: "OR('ProdOrgMSP.admin')"
             AnchorPeers:
                  - Host: HOSTA_peerProd_com
                    Port: 7051
       - &ProdOrgA
              Name: ProdOrgA
              ID: ProdOrgAMSP
              MSPDir: crypto-config/peerOrganizations/peerProdA_com/msp
              Policies:
                Readers:
                    Type: Signature
                    Rule: "OR('ProdOrgAMSP.admin','ProdOrgAMSP.peer', 'ProdOrgAMSP.client')"
                    Writers:
                       Type: Signature
                       Rule: "OR('ProdOrgAMSP.admin', 'ProdOrgAMSP.client')"
                    Admins:
                       Type: Signature
                       Rule: "OR('ProdOrgAMSP.admin')"
                    AnchorPeers:
                       - Host: HOSTA_peerProdA_com
                         Port: 7051

        Capabilities:
                     Channel: &ChannelCapabilities
                        V1_4_3: true
                        V1_3: false
                        V1_1: false
                    Orderer: &OrdererCapabilities
                        V1_4_2: true
                        V1_1: false
                   Application: &ApplicationCapabilities
                        V1_4_2: true
                        V1_3: false
                        V1_2: false
                        V1_1: false
        Application: &ApplicationDefaults

                  Organizations:
                  Policies:
                      Readers:
                        Type: ImplicitMeta
                        Rule: "ANY Readers"
                      Writers:
                        Type: ImplicitMeta
                        Rule: "ANY Writers"
                      Admins:
                        Type: ImplicitMeta
                        Rule: "MAJORITY Admins"

                 Capabilities:
                      <<: *ApplicationCapabilities

       Orderer: &OrdererDefaults

                 OrdererType: solo
                 Addresses:
                    - ProdOrderer1_ProdOrdr_com:7050
                 BatchTimeout: 2s
                 BatchSize:
                 MaxMessageCount: 10
                 AbsoluteMaxBytes: 99 MB
                 PreferredMaxBytes: 512 KB
                 Kafka:
                   Brokers:
                     - 127.0.0.1:9092

                 EtcdRaft:
                    Consenters:
                      - Host:  ProdOrderer1_ProdOrdr_com
                        Port: 7050
                        ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                       ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                      - Host: ProdOrderer2_ProdOrdr_com
                        Port: 7050
                        ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                        ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                      - Host: ProdOrderer3_ProdOrdr_com
                        Port: 7050
                        ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt
                        ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt

                 Organizations:
                        Policies:
                              Readers:
                                   Type: ImplicitMeta
                                   Rule: "ANY Readers"
                              Writers:
                                  Type: ImplicitMeta
                                  Rule: "ANY Writers"
                              Admins:
                                  Type: ImplicitMeta
                                  Rule: "MAJORITY Admins"
                         BlockValidation:
                             Type: ImplicitMeta
                             Rule: "ANY Writers"

                   Channel: &ChannelDefaults
                      Policies:
                         Readers:
                            Type: ImplicitMeta
                            Rule: "ANY Readers"
                         Writers:
                            Type: ImplicitMeta
                            Rule: "ANY Writers"
                         Admins:
                            Type: ImplicitMeta
                            Rule: "MAJORITY Admins"
                     Capabilities:
                          <<: *ChannelCapabilities

           Profiles:

                     OrdererGenesis:
                          <<: *ChannelDefaults
                         Orderer:
                              <<: *OrdererDefaults
                         Organizations:
                          - *OrdererOrg
                         Capabilities:
                              <<: *OrdererCapabilities
                         Consortiums:
                              SampleConsortium:
                                 Organizations:
                                     - *ProdOrg
                                     - *ProdOrgA

                          OrgChannel:
                             Consortium: SampleConsortium
                             Application:
                                 <<: *ApplicationDefaults
                             Organizations:
                               - *ProdOrg
                               - *ProdOrgA
                               Capabilities:
                                   <<: *ApplicationCapabilities

                         SampleDevModeKafka:
                               <<: *ChannelDefaults
                               Capabilities:
                                    <<: *ChannelCapabilities
                               Orderer:
                                    <<: *OrdererDefaults
                               OrdererType: kafka
                               Kafka:
                                     Brokers:
                                        - kafka.example.com:9092

                               Organizations:
                                    - *OrdererOrg
                                Capabilities:
                                 <<: *OrdererCapabilities
                                Application:
                                   <<: *ApplicationDefaults
                                Organizations:
                                   - <<: *OrdererOrg
                                Consortiums:
                                    SampleConsortium:
                                Organizations:
                                 - *ProdOrg
                                 - *ProdOrgA

                       SampleMultiNodeEtcdRaft:
                             <<: *ChannelDefaults
                             Capabilities:
                                 <<: *ChannelCapabilities
                             Orderer:
                                 <<: *OrdererDefaults
                                 OrdererType: etcdraft
                                 EtcdRaft:
                                       Consenters:
                                             - Host:  ProdOrderer1_ProdOrdr_com
                                               Port: 7050
                                               ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                                               ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                                            - Host:  ProdOrderer2_ProdOrdr_com
                                              Port: 7050
                                              ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                                              ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                                            - Host:  ProdOrderer3_ProdOrdr_com
                                                 Port: 7050
                                                 ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt
                                                 ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt

                             Addresses:
                              -  ProdOrderer1_ProdOrdr_com:7050
                              -  ProdOrderer2_ProdOrdr_com:7050
                              -  ProdOrderer3_ProdOrdr_com:7050

                      Organizations:
                             - *OrdererOrg
                             Capabilities:
                                   <<: *OrdererCapabilities
                             Application:
                                    <<: *ApplicationDefaults
                            Organizations:
                                   - <<: *OrdererOrg
                            Consortiums:
                                SampleConsortium:
                                   Organizations:
                                        - *ProdOrg
                                        - *ProdOrgA
</code>```

Docker-compose.yaml file

I have created the network using docker-swarm.

```<code>                    version: "3.4"
                    networks:
                       dev:
                       attachable: true

                    services:
                       ProdOrderer1_ProdOrdr_com:
                       container_name: ProdOrderer1_ProdOrdr_com
                       image: hyperledger/fabric-orderer:1.4.4
                       environment:
                          - ORDERER_GENERAL_LOGLEVEL=info
                          - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
                          - ORDERER_GENERAL_GENESISMETHOD=file
                          - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
                          - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/orderer1/msp
                          # enabled TLS
                          - ORDERER_GENERAL_TLS_ENABLED=true
                          - ORDERER_GENERAL_TLS_PRIVATEKEY=/etc/hyperledger/orderer1/tls/server.key
                          - ORDERER_GENERAL_TLS_CERTIFICATE=/etc/hyperledger/orderer1/tls/server.crt
                          - ORDERER_GENERAL_TLS_ROOTCAS=[/etc/hyperledger/orderer1/tls/ca.crt]
                          - ORDERER_GENERAL_LOCALMSPID=ProdOrdererMSP
                          - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1
                          - ORDERER_KAFKA_VERBOSE=true
                          - ORDERER_GENERAL_CLUSTER_CLIENTCERTIFICATE=/etc/hyperledger/orderer1/tls/server.crt
                          - ORDERER_GENERAL_CLUSTER_CLIENTPRIVATEKEY=/etc/hyperledger/orderer1/tls/server.key
                          - ORDERER_GENERAL_CLUSTER_ROOTCAS=[/etc/hyperledger/orderer1/tls/ca.crt]
                         - FABRIC_LOGGING_SPEC=DEBUG
                         volumes:
                           - /opt/ProdNode/config/:/etc/hyperledger/configtx
                           - /opt/ProdNode/crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com:/etc/hyperledger/orderer1
                           - /opt/ProdNode/hyp-data/orderer1:/var/hyperledger/production/orderer1
                 working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
                 command: orderer
                 ports:
                    - 7050:7050
                deploy:
                   replicas: 1
                placement:
                   constraints:
                     - node.id == wohcakp6rt413tvqtnsd77o81
                depends_on:
                restart: always
                networks:
                    - dev

         ProdOrderer2_ProdOrdr_com:
               container_name: ProdOrderer2_ProdOrdr_com
               image: hyperledger/fabric-orderer:1.4.4
               environment:
                   - ORDERER_GENERAL_LOGLEVEL=info
                   - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
                   - ORDERER_GENERAL_GENESISMETHOD=file
                   - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
                   - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/orderer2/msp
                  # enabled TLS
                  - ORDERER_GENERAL_TLS_ENABLED=true
                  - ORDERER_GENERAL_TLS_PRIVATEKEY=/etc/hyperledger/orderer2/tls/server.key
                  - ORDERER_GENERAL_TLS_CERTIFICATE=/etc/hyperledger/orderer2/tls/server.crt
                  - ORDERER_GENERAL_TLS_ROOTCAS=[/etc/hyperledger/orderer2/tls/ca.crt]
                  - ORDERER_GENERAL_LOCALMSPID=ProdOrdererMSP
                  - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1
                  - ORDERER_KAFKA_VERBOSE=true
                  - ORDERER_GENERAL_CLUSTER_CLIENTCERTIFICATE=/etc/hyperledger/orderer2/tls/server.crt
                  - ORDERER_GENERAL_CLUSTER_CLIENTPRIVATEKEY=/etc/hyperledger/orderer2/tls/server.key
                  - ORDERER_GENERAL_CLUSTER_ROOTCAS=[/etc/hyperledger/orderer2/tls/ca.crt]
                  - FABRIC_LOGGING_SPEC=DEBUG
            volumes:
                - /opt/ProdNode/config/:/etc/hyperledger/configtx
                - /opt/ProdNode/crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com:/etc/hyperledger/orderer2
                - /opt/ProdNode/hyp-data/orderer2:/var/hyperledger/production/orderer2
            working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
            command: orderer
            ports:
                - 8050:7050
            deploy:
               replicas: 1
            placement:
            constraints:
               - node.id == wohcakp6rt413tvqtnsd77o81
           depends_on:
           restart: always
           networks:
              - dev

         ProdOrderer3_ProdOrdr_com:
         container_name: ProdOrderer3_ProdOrdr_com

        ca_ProdOrg:
           image: hyperledger/fabric-ca:1.4.4
           environment:
                 - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
                 - FABRIC_CA_SERVER_CA_NAME=ca_ProdOrg
                 - FABRIC_CA_SERVER_TLS_ENABLED=true
                 - FABRIC_CA_SERVER_TLS_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.peerProd_com-cert.pem
                 - FABRIC_CA_SERVER_TLS_KEYFILE=/etc/hyperledger/fabric-ca-server-config/21a106a45dfc8c3d350d16832bd6923fbc037b278ba94c4084f2a698548cf311_sk
           ports:
             - "7054:7054"
           command: sh -c 'fabric-ca-server start --ca.certfile /etc/hyperledger/fabric-ca-server-config/ca.peerProd_com-cert.pem --ca.keyfile /etc/hyperledger/fabric-ca-server-config/21a106a45dfc8c3d350d16832bd6923fbc037b278ba94c4084f2a698548cf311_sk -b admina:adminpw -d'
           volumes:
                - /opt/ProdNode/crypto-config/peerOrganizations/peerProd_com/ca/:/etc/hyperledger/fabric-ca-server-config
          container_name: ca_ProdOrg
          networks:
                - dev
          deploy:
              replicas: 1
         placement:
             constraints:
                - node.id == wohcakp6rt413tvqtnsd77o81
         restart: always
         depends_on:
                - ProdOrderer1_ProdOrdr_com
                - ProdOrderer2_ProdOrdr_com
                - ProdOrderer1_ProdOrdr_com
       HOSTA_peerProd_com:
             container_name: HOSTA_peerProd_com
             image: hyperledger/fabric-peer:1.4.4
             environment:
                 - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
                 - CORE_PEER_ID=HOSTA_peerProd_com
                 - CORE_PEER_LOCALMSPID=ProdOrgMSP
                 - CORE_PEER_ADDRESS=HOSTA_peerProd_com:7051
                 - CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb_HOSTA_peerProd_com:5984
                 - CORE_PEER_GOSSIP_BOOTSTRAP=HOSTA_peerProd_com:7051
                 - CORE_PEER_GOSSIP_EXTERNALENDPOINT=HOSTA_peerProd_com:7051
                 - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:7052
                 - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=swarm_dev
                 - CORE_LOGGING_PEER=INFO
                 - CORE_CHAINCODE_LOGGING_LEVEL=DEBUG
                 - CORE_PEER_GOSSIP_USELEADERELECTION=true
                 - CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/peer/msp
                 - CORE_PEER_GOSSIP_ORGLEADER=false
                 - CORE_PEER_PROFILE_ENABLED=true
                 #TLS Settings
                 - CORE_PEER_TLS_ENABLED=true
                 - CORE_PEER_TLS_CERT_FILE=/etc/hyperledger/peer/tls/server.crt
                 - CORE_PEER_TLS_KEY_FILE=/etc/hyperledger/peer/tls/server.key
                 - CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/peer/tls/ca.crt
                 #Couch DB config
                - CORE_LEDGER_STATE_STATEDATABASE=CouchDB
                - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=admin
                - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=P@ss123
           volumes:
              - /var/run/:/host/var/run/
              - /opt/ProdNode/config/:/etc/hyperledger/configtx
              - /opt/ProdNode/crypto-config/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com:/etc/hyperledger/peer
              - /opt/ProdNode/crypto-config/peerOrganizations/peerProd_com/users:/etc/hyperledger/users
              - /opt/ProdNode/hyp-data/peer-1_1/:/var/hyperledger/production
           working_dir: /opt/gopath/src/github.com/hyperledger/peer
           command: peer node start
           deploy:
             replicas: 1
             placement:
                 constraints:
                   - node.id == wohcakp6rt413tvqtnsd77o81
           restart: always
           ports:
                 - 7051:7051
                 - 7053:7053
          depends_on:
                - ProdOrderer1_ProdOrdr_com
                - ProdOrderer2_ProdOrdr_com
                - ProdOrderer1_ProdOrdr_com
                - couchdb_HOSTA_peerProd_com
                - ca_ProdOrg
         networks:
               - dev

        couchdb_HOSTA_peerProd_com:
            container_name: couchdb_HOSTA_peerProd_com

          ca_ProdOrgA:
             image: hyperledger/fabric-ca:1.4.4

            HOSTA_peerProdA_com:
             container_name: HOSTA_peerProdA_com
             image: hyperledger/fabric-peer:1.4.4

          couchdb_HOSTA_peerProdA_com:
             container_name: couchdb_HOSTA_peerProdA_com

        cli:
          container_name: cli
          image: hyperledger/fabric-tools:1.4.4
          tty: true
          environment:
              - GOPATH=/opt/gopath
              - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
              - FABRIC_LOGGING_SPEC=DEBUG
              - CORE_PEER_ID=cli
              - CORE_PEER_ADDRESS=HOSTA_peerProd_com:7051
              - CORE_PEER_LOCALMSPID=ProdOrgMSP
              - CORE_PEER_TLS_ENABLED=true #Should be kept to true if not running event listenr
              - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com/tls/server.crt
              - CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com/tls/server.key
             - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com/tls/ca.crt
             - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/users/Admin@peerProd_com/msp
           - CORE_CHAINCODE_KEEPALIVE=10
        working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
        command: /bin/bash
        deploy:
           replicas: 1
           placement:
               constraints:
                   - node.id == wohcakp6rt413tvqtnsd77o81
        volumes:
             - /var/run/:/host/var/run/
             - ./../chaincode/:/opt/gopath/src/github.com/chaincode/
             - ./crypto-config/:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
             - ./config:/opt/gopath/src/github.com/hyperledger/fabric/peer/configtx
             - ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/
       networks:
           - dev
       depends_on:
          - ProdOrderer1_ProdOrdr_com
          - ProdOrderer2_ProdOrdr_com
          - ProdOrderer3_ProdOrdr_com
          - HOSTA_peerProd_com
          - HOSTA_peerProdA_com
</code>```

Could anyone help me to resolve the error I am facing?

答:
The following error message says it all:

```<code>2020-02-14 06:00:12.124 UTC [grpc] createTransport -> DEBU 042 grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.ProdOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...
</code>```

The hostname you are using to connect - ProdOrderer1_ProdOrdr_com - does not match the valid names in the TLS certificate.  The way cryptogen works is that it automatically adds a CommonName using the format '{{.Hostname}}.{{.Domain}}', hence ProdOrderer1.ProdOrdr_com. I assume you are using a different naming convention due to naming rules for Docker Swarm, so if you really need to use ProdOrderer1_ProdOrdr_com then you will need to modify your crypto-config.yaml to override the template used to generate the CommonName used in each certificate:

```<code>OrdererOrgs:
  - Name: ProdOrderer
    Domain: ProdOrdr_com
    Specs:
      - Hostname: ProdOrderer1
        CommonName: '{{.Hostname}}_{{.Domain}}'
        SANS:
          - localhost
          - 127.0.0.1
      - Hostname: ProdOrderer2
        CommonName: '{{.Hostname}}_{{.Domain}}'
        SANS:
          - localhost
          - 127.0.0.1
      - Hostname: ProdOrderer3
        CommonName: '{{.Hostname}}_{{.Domain}}'
        SANS:
          - localhost
          - 127.0.0.1
</code>```

Body:
I am creating a HLF network with raft as orderering service.

 peer channel create -o ProdOrderer1_ProdOrdr_com:7050 -c masterchannel -f ./configtx/masterchannel.tx --tls true --cafile /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/msp/tlscacerts/tlsca.ProdOrdr_com-cert.pem

But it returns the following error in peer cli.

 2020-02-14 06:00:09.733 UTC [grpc] watcher -> DEBU 039 ccResolverWrapper: sending new addresses to cc: [{ProdOrderer1_ProdOrdr_com:7050 0  <nil>}]
 2020-02-14 06:00:09.733 UTC [grpc] switchBalancer -> DEBU 03a ClientConn switching balancer to "pick_first"
 2020-02-14 06:00:09.733 UTC [grpc] HandleSubConnStateChange -> DEBU 03b pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, CONNECTING
 2020-02-14 06:00:09.736 UTC [grpc] createTransport -> DEBU 03c grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.ProdOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...
 2020-02-14 06:00:09.736 UTC [grpc] HandleSubConnStateChange -> DEBU 03d pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, TRANSIENT_FAILURE
 2020-02-14 06:00:10.734 UTC [grpc] HandleSubConnStateChange -> DEBU 03e pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, CONNECTING
 2020-02-14 06:00:10.738 UTC [grpc] createTransport -> DEBU 03f grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.StancOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...
 2020-02-14 06:00:10.738 UTC [grpc] HandleSubConnStateChange -> DEBU 040 pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, TRANSIENT_FAILURE
 2020-02-14 06:00:12.121 UTC [grpc] HandleSubConnStateChange -> DEBU 041 pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, CONNECTING
 2020-02-14 06:00:12.124 UTC [grpc] createTransport -> DEBU 042 grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.ProdOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...
 2020-02-14 06:00:12.124 UTC [grpc] HandleSubConnStateChange -> DEBU 043 pickfirstBalancer: HandleSubConnStateChange: 0xc0002d9e80, TRANSIENT_FAILURE
 Error: failed to create deliver client: orderer client failed to connect to ProdOrderer1_ProdOrdr_com:7050: failed to create new connection: context deadline exceeded

I have checked to logs of peer & orderer containers.The logs of the orderer container reports the tls bad certificate error.

2020-02-14 06:22:33.504 UTC [core.comm] ServerHandshake -> ERRO 2849 TLS handshake failed with error remote error: tls: bad certificate server=Orderer remoteaddress=10.0.23.4:18725

2020-02-14 06:22:35.859 UTC [orderer.common.cluster.puller] probeEndpoint -> WARN 2853 Failed connecting to {ProdOrderer4_ProdOrdr_com:7050 [-----BEGIN CERTIFICATE-----
2020-02-14 06:22:35.859 UTC [orderer.common.cluster.puller] func1 -> WARN 2854 Received error of type 'failed to create new connection: context deadline exceeded' from {ProdOrderer4_ProdOrdr_com:7050 [-----BEGIN CERTIFICATE-----

I am attaching crypto-config.yaml,configtx.yaml,docker-compose.yaml for the reference.

crypto-config.yaml

            OrdererOrgs:
              - Name: ProdOrderer
                Domain: ProdOrdr_com
                Specs:
                 - Hostname: ProdOrderer1
                   SANS:
                     - "localhost"
                     - "127.0.0.1"
                - Hostname: ProdOrderer2
                   SANS:
                     - "localhost"
                     - "127.0.0.1"
                - Hostname: ProdOrderer3
                   SANS:
                     - "localhost"
                     - "127.0.0.1"

             PeerOrgs:
                 - Name: ProdOrg

                 - Name: ProdOrgA

configtx.yaml

Organizations:
  - &OrdererOrg
      Name: ProdOrderer
      ID: ProdOrdererMSP
      MSPDir: crypto-config/ordererOrganizations/ProdOrdr_com/msp
      Policies:
         Readers:
            Type: Signature
            Rule: "OR('ProdOrdererMSP.member')"
         Writers:
            Type: Signature
            Rule: "OR('ProdOrdererMSP.member')"
         Admins:
            Type: Signature
            Rule:  "OR('ProdOrdererMSP.admin')"
    - &ProdOrg
        Name: ProdOrg
        ID: ProdOrgMSP
        MSPDir: crypto-config/peerOrganizations/peerProd_com/msp
        Policies:
             Readers:
                    Type: Signature
                    Rule: "OR('ProdOrgMSP.admin','ProdOrgMSP.peer', 'ProdOrgMSP.client')"
             Writers:
                    Type: Signature
                    Rule: "OR('ProdOrgMSP.admin', 'ProdOrgMSP.client')"
             Admins:
                    Type: Signature
                    Rule: "OR('ProdOrgMSP.admin')"
             AnchorPeers:
                  - Host: HOSTA_peerProd_com
                    Port: 7051
       - &ProdOrgA
              Name: ProdOrgA
              ID: ProdOrgAMSP
              MSPDir: crypto-config/peerOrganizations/peerProdA_com/msp
              Policies:
                Readers:
                    Type: Signature
                    Rule: "OR('ProdOrgAMSP.admin','ProdOrgAMSP.peer', 'ProdOrgAMSP.client')"
                    Writers:
                       Type: Signature
                       Rule: "OR('ProdOrgAMSP.admin', 'ProdOrgAMSP.client')"
                    Admins:
                       Type: Signature
                       Rule: "OR('ProdOrgAMSP.admin')"
                    AnchorPeers:
                       - Host: HOSTA_peerProdA_com
                         Port: 7051

        Capabilities:
                     Channel: &ChannelCapabilities
                        V1_4_3: true
                        V1_3: false
                        V1_1: false
                    Orderer: &OrdererCapabilities
                        V1_4_2: true
                        V1_1: false
                   Application: &ApplicationCapabilities
                        V1_4_2: true
                        V1_3: false
                        V1_2: false
                        V1_1: false
        Application: &ApplicationDefaults

                  Organizations:
                  Policies:
                      Readers:
                        Type: ImplicitMeta
                        Rule: "ANY Readers"
                      Writers:
                        Type: ImplicitMeta
                        Rule: "ANY Writers"
                      Admins:
                        Type: ImplicitMeta
                        Rule: "MAJORITY Admins"

                 Capabilities:
                      <<: *ApplicationCapabilities

       Orderer: &OrdererDefaults

                 OrdererType: solo
                 Addresses:
                    - ProdOrderer1_ProdOrdr_com:7050
                 BatchTimeout: 2s
                 BatchSize:
                 MaxMessageCount: 10
                 AbsoluteMaxBytes: 99 MB
                 PreferredMaxBytes: 512 KB
                 Kafka:
                   Brokers:
                     - 127.0.0.1:9092

                 EtcdRaft:
                    Consenters:
                      - Host:  ProdOrderer1_ProdOrdr_com
                        Port: 7050
                        ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                       ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                      - Host: ProdOrderer2_ProdOrdr_com
                        Port: 7050
                        ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                        ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                      - Host: ProdOrderer3_ProdOrdr_com
                        Port: 7050
                        ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt
                        ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt

                 Organizations:
                        Policies:
                              Readers:
                                   Type: ImplicitMeta
                                   Rule: "ANY Readers"
                              Writers:
                                  Type: ImplicitMeta
                                  Rule: "ANY Writers"
                              Admins:
                                  Type: ImplicitMeta
                                  Rule: "MAJORITY Admins"
                         BlockValidation:
                             Type: ImplicitMeta
                             Rule: "ANY Writers"

                   Channel: &ChannelDefaults
                      Policies:
                         Readers:
                            Type: ImplicitMeta
                            Rule: "ANY Readers"
                         Writers:
                            Type: ImplicitMeta
                            Rule: "ANY Writers"
                         Admins:
                            Type: ImplicitMeta
                            Rule: "MAJORITY Admins"
                     Capabilities:
                          <<: *ChannelCapabilities

           Profiles:

                     OrdererGenesis:
                          <<: *ChannelDefaults
                         Orderer:
                              <<: *OrdererDefaults
                         Organizations:
                          - *OrdererOrg
                         Capabilities:
                              <<: *OrdererCapabilities
                         Consortiums:
                              SampleConsortium:
                                 Organizations:
                                     - *ProdOrg
                                     - *ProdOrgA

                          OrgChannel:
                             Consortium: SampleConsortium
                             Application:
                                 <<: *ApplicationDefaults
                             Organizations:
                               - *ProdOrg
                               - *ProdOrgA
                               Capabilities:
                                   <<: *ApplicationCapabilities

                         SampleDevModeKafka:
                               <<: *ChannelDefaults
                               Capabilities:
                                    <<: *ChannelCapabilities
                               Orderer:
                                    <<: *OrdererDefaults
                               OrdererType: kafka
                               Kafka:
                                     Brokers:
                                        - kafka.example.com:9092

                               Organizations:
                                    - *OrdererOrg
                                Capabilities:
                                 <<: *OrdererCapabilities
                                Application:
                                   <<: *ApplicationDefaults
                                Organizations:
                                   - <<: *OrdererOrg
                                Consortiums:
                                    SampleConsortium:
                                Organizations:
                                 - *ProdOrg
                                 - *ProdOrgA

                       SampleMultiNodeEtcdRaft:
                             <<: *ChannelDefaults
                             Capabilities:
                                 <<: *ChannelCapabilities
                             Orderer:
                                 <<: *OrdererDefaults
                                 OrdererType: etcdraft
                                 EtcdRaft:
                                       Consenters:
                                             - Host:  ProdOrderer1_ProdOrdr_com
                                               Port: 7050
                                               ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                                               ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com/tls/server.crt
                                            - Host:  ProdOrderer2_ProdOrdr_com
                                              Port: 7050
                                              ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                                              ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com/tls/server.crt
                                            - Host:  ProdOrderer3_ProdOrdr_com
                                                 Port: 7050
                                                 ClientTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt
                                                 ServerTLSCert: crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer3.ProdOrdr_com/tls/server.crt

                             Addresses:
                              -  ProdOrderer1_ProdOrdr_com:7050
                              -  ProdOrderer2_ProdOrdr_com:7050
                              -  ProdOrderer3_ProdOrdr_com:7050

                      Organizations:
                             - *OrdererOrg
                             Capabilities:
                                   <<: *OrdererCapabilities
                             Application:
                                    <<: *ApplicationDefaults
                            Organizations:
                                   - <<: *OrdererOrg
                            Consortiums:
                                SampleConsortium:
                                   Organizations:
                                        - *ProdOrg
                                        - *ProdOrgA

Docker-compose.yaml file

I have created the network using docker-swarm.

                    version: "3.4"
                    networks:
                       dev:
                       attachable: true

                    services:
                       ProdOrderer1_ProdOrdr_com:
                       container_name: ProdOrderer1_ProdOrdr_com
                       image: hyperledger/fabric-orderer:1.4.4
                       environment:
                          - ORDERER_GENERAL_LOGLEVEL=info
                          - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
                          - ORDERER_GENERAL_GENESISMETHOD=file
                          - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
                          - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/orderer1/msp
                          # enabled TLS
                          - ORDERER_GENERAL_TLS_ENABLED=true
                          - ORDERER_GENERAL_TLS_PRIVATEKEY=/etc/hyperledger/orderer1/tls/server.key
                          - ORDERER_GENERAL_TLS_CERTIFICATE=/etc/hyperledger/orderer1/tls/server.crt
                          - ORDERER_GENERAL_TLS_ROOTCAS=[/etc/hyperledger/orderer1/tls/ca.crt]
                          - ORDERER_GENERAL_LOCALMSPID=ProdOrdererMSP
                          - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1
                          - ORDERER_KAFKA_VERBOSE=true
                          - ORDERER_GENERAL_CLUSTER_CLIENTCERTIFICATE=/etc/hyperledger/orderer1/tls/server.crt
                          - ORDERER_GENERAL_CLUSTER_CLIENTPRIVATEKEY=/etc/hyperledger/orderer1/tls/server.key
                          - ORDERER_GENERAL_CLUSTER_ROOTCAS=[/etc/hyperledger/orderer1/tls/ca.crt]
                         - FABRIC_LOGGING_SPEC=DEBUG
                         volumes:
                           - /opt/ProdNode/config/:/etc/hyperledger/configtx
                           - /opt/ProdNode/crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer1.ProdOrdr_com:/etc/hyperledger/orderer1
                           - /opt/ProdNode/hyp-data/orderer1:/var/hyperledger/production/orderer1
                 working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
                 command: orderer
                 ports:
                    - 7050:7050
                deploy:
                   replicas: 1
                placement:
                   constraints:
                     - node.id == wohcakp6rt413tvqtnsd77o81
                depends_on:
                restart: always
                networks:
                    - dev

         ProdOrderer2_ProdOrdr_com:
               container_name: ProdOrderer2_ProdOrdr_com
               image: hyperledger/fabric-orderer:1.4.4
               environment:
                   - ORDERER_GENERAL_LOGLEVEL=info
                   - ORDERER_GENERAL_LISTENADDRESS=0.0.0.0
                   - ORDERER_GENERAL_GENESISMETHOD=file
                   - ORDERER_GENERAL_GENESISFILE=/etc/hyperledger/configtx/genesis.block
                   - ORDERER_GENERAL_LOCALMSPDIR=/etc/hyperledger/orderer2/msp
                  # enabled TLS
                  - ORDERER_GENERAL_TLS_ENABLED=true
                  - ORDERER_GENERAL_TLS_PRIVATEKEY=/etc/hyperledger/orderer2/tls/server.key
                  - ORDERER_GENERAL_TLS_CERTIFICATE=/etc/hyperledger/orderer2/tls/server.crt
                  - ORDERER_GENERAL_TLS_ROOTCAS=[/etc/hyperledger/orderer2/tls/ca.crt]
                  - ORDERER_GENERAL_LOCALMSPID=ProdOrdererMSP
                  - ORDERER_KAFKA_TOPIC_REPLICATIONFACTOR=1
                  - ORDERER_KAFKA_VERBOSE=true
                  - ORDERER_GENERAL_CLUSTER_CLIENTCERTIFICATE=/etc/hyperledger/orderer2/tls/server.crt
                  - ORDERER_GENERAL_CLUSTER_CLIENTPRIVATEKEY=/etc/hyperledger/orderer2/tls/server.key
                  - ORDERER_GENERAL_CLUSTER_ROOTCAS=[/etc/hyperledger/orderer2/tls/ca.crt]
                  - FABRIC_LOGGING_SPEC=DEBUG
            volumes:
                - /opt/ProdNode/config/:/etc/hyperledger/configtx
                - /opt/ProdNode/crypto-config/ordererOrganizations/ProdOrdr_com/orderers/ProdOrderer2.ProdOrdr_com:/etc/hyperledger/orderer2
                - /opt/ProdNode/hyp-data/orderer2:/var/hyperledger/production/orderer2
            working_dir: /opt/gopath/src/github.com/hyperledger/fabric/orderer
            command: orderer
            ports:
                - 8050:7050
            deploy:
               replicas: 1
            placement:
            constraints:
               - node.id == wohcakp6rt413tvqtnsd77o81
           depends_on:
           restart: always
           networks:
              - dev

         ProdOrderer3_ProdOrdr_com:
         container_name: ProdOrderer3_ProdOrdr_com

        ca_ProdOrg:
           image: hyperledger/fabric-ca:1.4.4
           environment:
                 - FABRIC_CA_HOME=/etc/hyperledger/fabric-ca-server
                 - FABRIC_CA_SERVER_CA_NAME=ca_ProdOrg
                 - FABRIC_CA_SERVER_TLS_ENABLED=true
                 - FABRIC_CA_SERVER_TLS_CERTFILE=/etc/hyperledger/fabric-ca-server-config/ca.peerProd_com-cert.pem
                 - FABRIC_CA_SERVER_TLS_KEYFILE=/etc/hyperledger/fabric-ca-server-config/21a106a45dfc8c3d350d16832bd6923fbc037b278ba94c4084f2a698548cf311_sk
           ports:
             - "7054:7054"
           command: sh -c 'fabric-ca-server start --ca.certfile /etc/hyperledger/fabric-ca-server-config/ca.peerProd_com-cert.pem --ca.keyfile /etc/hyperledger/fabric-ca-server-config/21a106a45dfc8c3d350d16832bd6923fbc037b278ba94c4084f2a698548cf311_sk -b admina:adminpw -d'
           volumes:
                - /opt/ProdNode/crypto-config/peerOrganizations/peerProd_com/ca/:/etc/hyperledger/fabric-ca-server-config
          container_name: ca_ProdOrg
          networks:
                - dev
          deploy:
              replicas: 1
         placement:
             constraints:
                - node.id == wohcakp6rt413tvqtnsd77o81
         restart: always
         depends_on:
                - ProdOrderer1_ProdOrdr_com
                - ProdOrderer2_ProdOrdr_com
                - ProdOrderer1_ProdOrdr_com
       HOSTA_peerProd_com:
             container_name: HOSTA_peerProd_com
             image: hyperledger/fabric-peer:1.4.4
             environment:
                 - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
                 - CORE_PEER_ID=HOSTA_peerProd_com
                 - CORE_PEER_LOCALMSPID=ProdOrgMSP
                 - CORE_PEER_ADDRESS=HOSTA_peerProd_com:7051
                 - CORE_LEDGER_STATE_COUCHDBCONFIG_COUCHDBADDRESS=couchdb_HOSTA_peerProd_com:5984
                 - CORE_PEER_GOSSIP_BOOTSTRAP=HOSTA_peerProd_com:7051
                 - CORE_PEER_GOSSIP_EXTERNALENDPOINT=HOSTA_peerProd_com:7051
                 - CORE_PEER_CHAINCODELISTENADDRESS=0.0.0.0:7052
                 - CORE_VM_DOCKER_HOSTCONFIG_NETWORKMODE=swarm_dev
                 - CORE_LOGGING_PEER=INFO
                 - CORE_CHAINCODE_LOGGING_LEVEL=DEBUG
                 - CORE_PEER_GOSSIP_USELEADERELECTION=true
                 - CORE_PEER_MSPCONFIGPATH=/etc/hyperledger/peer/msp
                 - CORE_PEER_GOSSIP_ORGLEADER=false
                 - CORE_PEER_PROFILE_ENABLED=true
                 #TLS Settings
                 - CORE_PEER_TLS_ENABLED=true
                 - CORE_PEER_TLS_CERT_FILE=/etc/hyperledger/peer/tls/server.crt
                 - CORE_PEER_TLS_KEY_FILE=/etc/hyperledger/peer/tls/server.key
                 - CORE_PEER_TLS_ROOTCERT_FILE=/etc/hyperledger/peer/tls/ca.crt
                 #Couch DB config
                - CORE_LEDGER_STATE_STATEDATABASE=CouchDB
                - CORE_LEDGER_STATE_COUCHDBCONFIG_USERNAME=admin
                - CORE_LEDGER_STATE_COUCHDBCONFIG_PASSWORD=P@ss123
           volumes:
              - /var/run/:/host/var/run/
              - /opt/ProdNode/config/:/etc/hyperledger/configtx
              - /opt/ProdNode/crypto-config/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com:/etc/hyperledger/peer
              - /opt/ProdNode/crypto-config/peerOrganizations/peerProd_com/users:/etc/hyperledger/users
              - /opt/ProdNode/hyp-data/peer-1_1/:/var/hyperledger/production
           working_dir: /opt/gopath/src/github.com/hyperledger/peer
           command: peer node start
           deploy:
             replicas: 1
             placement:
                 constraints:
                   - node.id == wohcakp6rt413tvqtnsd77o81
           restart: always
           ports:
                 - 7051:7051
                 - 7053:7053
          depends_on:
                - ProdOrderer1_ProdOrdr_com
                - ProdOrderer2_ProdOrdr_com
                - ProdOrderer1_ProdOrdr_com
                - couchdb_HOSTA_peerProd_com
                - ca_ProdOrg
         networks:
               - dev

        couchdb_HOSTA_peerProd_com:
            container_name: couchdb_HOSTA_peerProd_com

          ca_ProdOrgA:
             image: hyperledger/fabric-ca:1.4.4

            HOSTA_peerProdA_com:
             container_name: HOSTA_peerProdA_com
             image: hyperledger/fabric-peer:1.4.4

          couchdb_HOSTA_peerProdA_com:
             container_name: couchdb_HOSTA_peerProdA_com

        cli:
          container_name: cli
          image: hyperledger/fabric-tools:1.4.4
          tty: true
          environment:
              - GOPATH=/opt/gopath
              - CORE_VM_ENDPOINT=unix:///host/var/run/docker.sock
              - FABRIC_LOGGING_SPEC=DEBUG
              - CORE_PEER_ID=cli
              - CORE_PEER_ADDRESS=HOSTA_peerProd_com:7051
              - CORE_PEER_LOCALMSPID=ProdOrgMSP
              - CORE_PEER_TLS_ENABLED=true #Should be kept to true if not running event listenr
              - CORE_PEER_TLS_CERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com/tls/server.crt
              - CORE_PEER_TLS_KEY_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com/tls/server.key
             - CORE_PEER_TLS_ROOTCERT_FILE=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/peers/HOSTA.peerProd_com/tls/ca.crt
             - CORE_PEER_MSPCONFIGPATH=/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/peerOrganizations/peerProd_com/users/Admin@peerProd_com/msp
           - CORE_CHAINCODE_KEEPALIVE=10
        working_dir: /opt/gopath/src/github.com/hyperledger/fabric/peer
        command: /bin/bash
        deploy:
           replicas: 1
           placement:
               constraints:
                   - node.id == wohcakp6rt413tvqtnsd77o81
        volumes:
             - /var/run/:/host/var/run/
             - ./../chaincode/:/opt/gopath/src/github.com/chaincode/
             - ./crypto-config/:/opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/
             - ./config:/opt/gopath/src/github.com/hyperledger/fabric/peer/configtx
             - ./scripts:/opt/gopath/src/github.com/hyperledger/fabric/peer/scripts/
       networks:
           - dev
       depends_on:
          - ProdOrderer1_ProdOrdr_com
          - ProdOrderer2_ProdOrdr_com
          - ProdOrderer3_ProdOrdr_com
          - HOSTA_peerProd_com
          - HOSTA_peerProdA_com

Could anyone help me to resolve the error I am facing?

Body:
The following error message says it all:

2020-02-14 06:00:12.124 UTC [grpc] createTransport -> DEBU 042 grpc: addrConn.createTransport failed to connect to {ProdOrderer1_ProdOrdr_com:7050 0  <nil>}. Err :connection error: desc = "transport: authentication handshake failed: x509: certificate is valid for ProdOrderer1.ProdOrdr_com, ProdOrderer1, localhost, not ProdOrderer1_ProdOrdr_com". Reconnecting...

The hostname you are using to connect - ProdOrderer1_ProdOrdr_com - does not match the valid names in the TLS certificate.  The way cryptogen works is that it automatically adds a CommonName using the format '{{.Hostname}}.{{.Domain}}', hence ProdOrderer1.ProdOrdr_com. I assume you are using a different naming convention due to naming rules for Docker Swarm, so if you really need to use ProdOrderer1_ProdOrdr_com then you will need to modify your crypto-config.yaml to override the template used to generate the CommonName used in each certificate:

OrdererOrgs:
  - Name: ProdOrderer
    Domain: ProdOrdr_com
    Specs:
      - Hostname: ProdOrderer1
        CommonName: '{{.Hostname}}_{{.Domain}}'
        SANS:
          - localhost
          - 127.0.0.1
      - Hostname: ProdOrderer2
        CommonName: '{{.Hostname}}_{{.Domain}}'
        SANS:
          - localhost
          - 127.0.0.1
      - Hostname: ProdOrderer3
        CommonName: '{{.Hostname}}_{{.Domain}}'
        SANS:
          - localhost
          - 127.0.0.1


来源: stackexchange

问:
Spring boot MVC : Whitelabel Error Page
Getting the following Whitelabel Error Page while
I am running Spring Boot MVC app.

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Apr 13 15:45:59 IST 2016
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [home]: would dispatch back to the current handler URL [/rewards/web/home] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

application.properties

```<code>server.contextPath=/rewards/web
</code>```

rewardsweb-servlet.xml:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.rewards.web" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <mvc:annotation-driven />

</beans>
</code>```

web.xml

```<code><web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <display-name>rewards-web</display-name>
    <welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
        <servlet-name>rewardsweb</servlet-name>
        <servlet-class>
                    org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>rewardsweb</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>
</code>```

Spring Boot files

```<code>package com.rewards.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

package com.rewards.web;

import io.undertow.Undertow.Builder;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.undertow.UndertowBuilderCustomizer;
import org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
public class ApplicationConfiguration {
    @Bean
    public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
        UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
        factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {

            public void customize(Builder builder) {
                builder.addHttpListener(9090, "0.0.0.0");
            }

        });
        return factory;
    }
}
</code>```

Controller:

```<code>package com.rewards.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Controller
public class HomeController {

    @RequestMapping("/home")
    public String getHome(){
        System.out.println("-------this is home----------");
        return "home";
    }
}
</code>```

JSP

```<code>home.jsp is in this path : /src/main/webapp/WEB-INF/views/jsp/home.jsp
</code>```

when i hit : http://localhost:9090/rewards/web/home
i am getting Whitelabel Error

And also i have tried following solution,  added the following code in controller class. but no help.

```<code>package com.rewards.web.controller;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController implements ErrorController{

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error() {
        return "Error handling";
    }

    public String getErrorPath() {
        return PATH;
    }

    @RequestMapping("/home")
    public String getHome(){
        System.out.println("-------this is home----------");
        return "home";
    }
}
</code>```

Can you please help me out.

Thanks.

答:
You have to follow below thing steps before rendering a JSP page in spring boot application.

1.application.properties

spring.mvc.view.prefix = /*
spring.mvc.view.suffix = .jsp

2.POM.XML

```<code><dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
</code>```

3.Place JSPs in proper path. I prefer below folder structure -> src\main\webapp\view\

If you follow above points,JSP will happily integrated with springboot

ContentLicense: CC BY-SA 3.0

Title: Spring boot MVC : Whitelabel Error Page

Body:
Getting the following Whitelabel Error Page while
I am running Spring Boot MVC app.

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Apr 13 15:45:59 IST 2016
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [home]: would dispatch back to the current handler URL [/rewards/web/home] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)

application.properties

server.contextPath=/rewards/web

rewardsweb-servlet.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:component-scan base-package="com.rewards.web" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <mvc:resources mapping="/resources/**" location="/resources/" />

    <mvc:annotation-driven />

</beans>

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <display-name>rewards-web</display-name>
    <welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
        <servlet-name>rewardsweb</servlet-name>
        <servlet-class>
                    org.springframework.web.servlet.DispatcherServlet
                </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>rewardsweb</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Spring Boot files

package com.rewards.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

package com.rewards.web;

import io.undertow.Undertow.Builder;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.undertow.UndertowBuilderCustomizer;
import org.springframework.boot.context.embedded.undertow.UndertowEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
public class ApplicationConfiguration {
    @Bean
    public UndertowEmbeddedServletContainerFactory embeddedServletContainerFactory() {
        UndertowEmbeddedServletContainerFactory factory = new UndertowEmbeddedServletContainerFactory();
        factory.addBuilderCustomizers(new UndertowBuilderCustomizer() {

            public void customize(Builder builder) {
                builder.addHttpListener(9090, "0.0.0.0");
            }

        });
        return factory;
    }
}

Controller:

package com.rewards.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Controller
public class HomeController {

    @RequestMapping("/home")
    public String getHome(){
        System.out.println("-------this is home----------");
        return "home";
    }
}

JSP

home.jsp is in this path : /src/main/webapp/WEB-INF/views/jsp/home.jsp

when i hit : http://localhost:9090/rewards/web/home
i am getting Whitelabel Error

And also i have tried following solution,  added the following code in controller class. but no help.

package com.rewards.web.controller;

import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HomeController implements ErrorController{

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public String error() {
        return "Error handling";
    }

    public String getErrorPath() {
        return PATH;
    }

    @RequestMapping("/home")
    public String getHome(){
        System.out.println("-------this is home----------");
        return "home";
    }
}

Can you please help me out.

Thanks.

Body:
You have to follow below thing steps before rendering a JSP page in spring boot application.

1.application.properties

spring.mvc.view.prefix = /*
spring.mvc.view.suffix = .jsp

2.POM.XML

<dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
</dependency>
<dependency>
   <groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>

3.Place JSPs in proper path. I prefer below folder structure -> src\main\webapp\view\

If you follow above points,JSP will happily integrated with springboot

ContentLicense: CC BY-SA 4.0


问:
How to combine two values into a single key for a dictionary in python?
So, I have a dictionary in the following format. The key is a concatenated string and the value is a list of tuples.

```<code>dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)],..........}
</code>```

Now, I want to change the key from 'ABC|1' to 'ABC' and combining the two values of 'ABC|1' and 'ABC|2' into a single value for the key 'ABC'. Thus, the final_dict should look like this:

```<code>final_dict = {'ABC':[(1,10),(5,16),(15,30),(9,18),(78,10),(5,10)],
              'XYZ':[(45,56),(72,79),(81,98),(100,120),(11,26),(78,99),(105,119),(150,178)],....}
</code>```

The approach I am trying is as follows:

```<code>final_dict = dict()
for key in dictionary.keys():
  new_key = key.split('|')[0]
  if new_key not in final_dict:
    value = list()
  if new_key in key:
    value.append(dictionary[key])
</code>```

However, this is not working. Can anybody provide me a suggestion to do this? Without using pandas.

Body:
So, I have a dictionary in the following format. The key is a concatenated string and the value is a list of tuples.

dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)],..........}

Now, I want to change the key from 'ABC|1' to 'ABC' and combining the two values of 'ABC|1' and 'ABC|2' into a single value for the key 'ABC'. Thus, the final_dict should look like this:

final_dict = {'ABC':[(1,10),(5,16),(15,30),(9,18),(78,10),(5,10)],
              'XYZ':[(45,56),(72,79),(81,98),(100,120),(11,26),(78,99),(105,119),(150,178)],....}

The approach I am trying is as follows:

final_dict = dict()
for key in dictionary.keys():
  new_key = key.split('|')[0]
  if new_key not in final_dict:
    value = list()
  if new_key in key:
    value.append(dictionary[key])

However, this is not working. Can anybody provide me a suggestion to do this? Without using pandas.

Body:
Just some variation in your code:

dictionary = {'ABC|1':[(1,10),(5,16),(15,30)],
              'ABC|2':[(9,18),(78,10),(5,10)],
              'XYZ|1':[(45,56),(72,79),(81,98),(100,120)],
              'XYZ|2':[(11,26),(78,99),(105,119),(150,178)]}

final_dict = {}
for key in dictionary.keys():
    new_key = key.split('|')[0]
    if new_key not in final_dict:
        final_dict[new_key] = dictionary[key]
    else:
        final_dict[new_key].extend(dictionary[key])

I tried the above code and gives this output:

{'XYZ': [(45, 56), (72, 79), (81, 98), (100, 120), (11, 26), (78, 99), (105, 119), (150, 178)], 'ABC': [(1, 10), (5, 16), (15,
 30), (9, 18), (78, 10), (5, 10)]}


问:
Matrix elements addition with this way
I wrote this code to add elements with this way my problem is that i want to apply it with larger matrix

```<code>zz=[[1,2],[3,4]]
for i in range(len(zz[0])):
    x=zz[0][i]
    for i in range(len(zz[1])):
        xx=x+zz[1][i]
        print(xx)
</code>```

The output will be:

```<code>z[0][0]+z[1][0]
z[0][0]+z[1][1]
z[0][1]+z[1][0]
z[0][0]+z[1][1]
</code>```

答:
You could use recursion for this:

```<code>def sum_combinations(matrix):
    head, *tail = matrix
    if not tail:  # we reached the last row
        yield from head
        return
    for number in head:
        for other in sum_combinations(tail):
            yield number + other
</code>```

This should work for any size of matrix.

Usage:

```<code>for sum_ in sum_combinations(zz):
    print(sum_)
</code>```

Title: Matrix elements addition with this way

Body:
I wrote this code to add elements with this way my problem is that i want to apply it with larger matrix

zz=[[1,2],[3,4]]
for i in range(len(zz[0])):
    x=zz[0][i]
    for i in range(len(zz[1])):
        xx=x+zz[1][i]
        print(xx)

The output will be:

z[0][0]+z[1][0]
z[0][0]+z[1][1]
z[0][1]+z[1][0]
z[0][0]+z[1][1]

Body:
You could use recursion for this:

def sum_combinations(matrix):
    head, *tail = matrix
    if not tail:  # we reached the last row
        yield from head
        return
    for number in head:
        for other in sum_combinations(tail):
            yield number + other

This should work for any size of matrix.

Usage:

for sum_ in sum_combinations(zz):
    print(sum_)


问:
React - Substitute for `setState` Callback in Functional Components?
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

```<code>const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}
</code>```

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

答:
I wonder if useEffect is the best solution. Specially when calling setTimeout within useEffect is going to cause an infinite loop since every time we call setOpenDoor, the app renders and then useEffect is called calling again a setTimeOut that will call a setOpenDoor function... Graphically:

```<code>setTimeout -> setOpenDoor -> useEffect -> setTimeout -> ... hell
</code>```

Of course you could use an if statement wihin useEffect the same way that @ksav suggested but that does not accomplish one requirement of @Kayote:

I dont know the current value of state (it may be true/false)

Here is a solution that works without useEffect and accomplish the requirement stated above:

Code working in codesandbox

There, see the importance of this piece of code:

```<code>const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  setTimeout(() => setOpenDoor(openDoor => !openDoor), 500);
};
</code>```

Since we are using setTimeout, we need to pass callback to setOpenDoor instead of the updated state. This is because we want to send the 'current' state. If we sent the new state instead, by the time that setTimeOut processes that state, it will have changed (because we did it before setTimeOut executes its callback with setOpenDoor(!openDoor);)  and no changes will be made.

Body:
We have migrated to 'React Functional Components' instead of 'Class based Component'. I cannot find the substitute logic for setState callback function. I.e, I have a functional component with state, and I want to create an event handler function that mutates the state multiple times in sequence, the caveat being that I dont know the current value of state (it may be true/false). The following example may make more sense.

const Example = () => {
  const [ openDoor, setOpenDoor ] = useState(false);
  // the following handler should swich 'openDoor' state to inverse of
  // current state value. Then after setTimeout duration, inverse it again
  const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  // within setTimeout below, '!openDoor' does not work because it still
  // receives the same value as above because of async nature of
  // state updates
  setTimeout(() => setOpenDoor(!openDoor), 500)
  }
  return(...);
}

In class based components, we had callback argument which would update state after previous update. How do I achieve the same in the above functional component using state hook?

Body:
I wonder if useEffect is the best solution. Specially when calling setTimeout within useEffect is going to cause an infinite loop since every time we call setOpenDoor, the app renders and then useEffect is called calling again a setTimeOut that will call a setOpenDoor function... Graphically:

setTimeout -> setOpenDoor -> useEffect -> setTimeout -> ... hell

Of course you could use an if statement wihin useEffect the same way that @ksav suggested but that does not accomplish one requirement of @Kayote:

I dont know the current value of state (it may be true/false)

Here is a solution that works without useEffect and accomplish the requirement stated above:

Code working in codesandbox

There, see the importance of this piece of code:

const toggleOpenDoor = () => {
  setOpenDoor(!openDoor);
  setTimeout(() => setOpenDoor(openDoor => !openDoor), 500);
};

Since we are using setTimeout, we need to pass callback to setOpenDoor instead of the updated state. This is because we want to send the 'current' state. If we sent the new state instead, by the time that setTimeOut processes that state, it will have changed (because we did it before setTimeOut executes its callback with setOpenDoor(!openDoor);)  and no changes will be made.


问:
Form loads with the minimal size (which displays only the title bar) rather than the size corresponding to the value set to its properties
I have a form which contains a Menu Strip docked to the top, a Status Strip docked to the bottom, and a Panel docked to fill the entire space between the aforementioned controls. I have set the attributes to the following values for the form:

During the design phase:

```<code>AutoScaleMode: Dpi
AutoSize: false
AutoSizeMode: GrowOnly
DoubleBuffered: true
SizeGripStyle: Show
</code>```

During runtime (in the form's constructor):

```<code>// Calculate the default size of the window on the basis of the ratio of the dimensions of the window to the dimension of the screen resolution of the machine used in development as the default dimensions of the window is aligned to that of the machine used to design it
this.Size = new Size(Screen.GetWorkingArea(this.Location).Size.Width * (widthOfWindowInDesignPhase /horizontalResolutionOfTheDisplayInDesignPhase), Screen.GetWorkingArea(this.Location).Size.Height * (heightOfWindowInDesignPhase / verticalResolutionOfTheDisplayInDesignPhase));
this.MinimumSize = new Size(this.Size.Width, this.Size.Height);
</code>```

My first attempt to resolve this issue was to tinker around with the AutoSize and AutoSizeMode properties, but I require this to be set to the aforestated values as changing them would not allow the user to resize the form. The other approach I tried, which also failed, was by setting the AutoSize properties of the aforementioned controls to false as to force the child containers of the form to not resize.

Thanks in advance.

PS Screenshot of the concerned form:

答:
A (blunder) numeric error occurs when calculating the size of the form as the statements (widthOfWindowInDesignPhase /horizontalResolutionOfTheDisplayInDesignPhase) and (heightOfWindowInDesignPhase / verticalResolutionOfTheDisplayInDesignPhase) return a floating point value that cannot be stored as an integer.

The appropriate statement is as follows:

this.Size = new Size(Convert.ToInt32(Screen.GetWorkingArea(this.Location).Size.Width * (Convert.ToDouble(widthOfWindowInDesignPhase) / Convert.ToDouble(horizontalResolutionOfTheDisplayInDesignPhase))), Convert.ToInt32(Screen.GetWorkingArea(this.Location).Size.Height * (Convert.ToDouble(heightOfWindowInDesignPhase) / Convert.ToDouble(verticalResolutionOfTheDisplayInDesignPhase))));

Body:
I have a form which contains a Menu Strip docked to the top, a Status Strip docked to the bottom, and a Panel docked to fill the entire space between the aforementioned controls. I have set the attributes to the following values for the form:

During the design phase:

AutoScaleMode: Dpi
AutoSize: false
AutoSizeMode: GrowOnly
DoubleBuffered: true
SizeGripStyle: Show

During runtime (in the form's constructor):

// Calculate the default size of the window on the basis of the ratio of the dimensions of the window to the dimension of the screen resolution of the machine used in development as the default dimensions of the window is aligned to that of the machine used to design it
this.Size = new Size(Screen.GetWorkingArea(this.Location).Size.Width * (widthOfWindowInDesignPhase /horizontalResolutionOfTheDisplayInDesignPhase), Screen.GetWorkingArea(this.Location).Size.Height * (heightOfWindowInDesignPhase / verticalResolutionOfTheDisplayInDesignPhase));
this.MinimumSize = new Size(this.Size.Width, this.Size.Height);

My first attempt to resolve this issue was to tinker around with the AutoSize and AutoSizeMode properties, but I require this to be set to the aforestated values as changing them would not allow the user to resize the form. The other approach I tried, which also failed, was by setting the AutoSize properties of the aforementioned controls to false as to force the child containers of the form to not resize.

Thanks in advance.

PS Screenshot of the concerned form:


问:
Upload JSON file to WebAPI
I'm trying to upload a JSON file to a .Net Core 3 WebApp using Powershell Core, but can't get it to work. The 'file' is always null.

Below the code from the WebApp:

```<code>[HttpPost]
public async Task<ActionResult> UploadFile(IFormFile file)
{
    if (!ModelState.IsValid)
        return BadRequest();

        var path = Path.GetTempFileName();
        var stream = new FileStream(path, FileMode.Create);
        await file.CopyToAsync(stream);
        string FileName = file.FileName;

        // .. parsing the file

        return Ok();
}
</code>```

And the actual request from Powershell:

```<code>$file = '/fileToUpload.json'
Invoke-RestMethod -Uri 'https://localhost:5001/uploadfile' -Method Post -InFile $file -ContentType 'application/json'
</code>```

But this request always returns the following error:

```<code>Invoke-RestMethod : System.NullReferenceException: Object reference not set to an instance of an object.
</code>```

And when setting a breakpoint in the method, I can see that the 'file' is always null.

Initially I started with a method that accepts JSON data in the body, but there seems to be some sort of limitation in the body of a Post request when using Invoke-RestMethod, so I had to come up with another solution to work around this 'limit'.
I am not running into a limit issue when using Postman though, so I guess it's related to a Powershell. In case anyone knows how to solve this 'body limit' issue, that would be even greater as I prefer posting the JSON data in the body instead of posting a file.

Hope someone can help me out.
Thanks in advance.

答:
Okay I managed to solve my initial issue: the apparent payload limit of the body in a POST request when using the Invoke-RestMethod cmd-let. I switched using curl and now everything works as expected, so I don't have to post a file instead of the JSON data (which also seems to work fine now btw).

Here's the curl command I used for all that might run into the same issue:

```<code>curl --url 'https://localhost:5001/postJSON' --insecure -H 'Content-Type: application/json' --request POST --data @fileToUpload.json
</code>```

Title: Upload JSON file to WebAPI

Body:
I'm trying to upload a JSON file to a .Net Core 3 WebApp using Powershell Core, but can't get it to work. The 'file' is always null.

Below the code from the WebApp:

[HttpPost]
public async Task<ActionResult> UploadFile(IFormFile file)
{
    if (!ModelState.IsValid)
        return BadRequest();

        var path = Path.GetTempFileName();
        var stream = new FileStream(path, FileMode.Create);
        await file.CopyToAsync(stream);
        string FileName = file.FileName;

        // .. parsing the file

        return Ok();
}

And the actual request from Powershell:

$file = '/fileToUpload.json'
Invoke-RestMethod -Uri 'https://localhost:5001/uploadfile' -Method Post -InFile $file -ContentType 'application/json'

But this request always returns the following error:

Invoke-RestMethod : System.NullReferenceException: Object reference not set to an instance of an object.

And when setting a breakpoint in the method, I can see that the 'file' is always null.

Initially I started with a method that accepts JSON data in the body, but there seems to be some sort of limitation in the body of a Post request when using Invoke-RestMethod, so I had to come up with another solution to work around this 'limit'.
I am not running into a limit issue when using Postman though, so I guess it's related to a Powershell. In case anyone knows how to solve this 'body limit' issue, that would be even greater as I prefer posting the JSON data in the body instead of posting a file.

Hope someone can help me out.
Thanks in advance.

Body:
Okay I managed to solve my initial issue: the apparent payload limit of the body in a POST request when using the Invoke-RestMethod cmd-let. I switched using curl and now everything works as expected, so I don't have to post a file instead of the JSON data (which also seems to work fine now btw).

Here's the curl command I used for all that might run into the same issue:

curl --url 'https://localhost:5001/postJSON' --insecure -H 'Content-Type: application/json' --request POST --data @fileToUpload.json


问:
How to securely create PHP variables with extract
In my previous post i ask how to create variables from an array ( PHP Variables made with foreach ) i got several answers and i was testing extract() but i have seen several against it for security reasons.

Now my question here is how can i use extract in a secure way from a $_POST that has an array that was made using jquery serialized.

With secure i mean that if a user inputs the wrong data, the secure way can take care of that with no problems.

THe PHP Site has a small warning in the extract command the says the following:

Do not use extract() on untrusted
  data, like user input (i.e. $_GET,
  $_FILES, etc.). If you do, for example
  if you want to run old code that
  relies on register_globals
  temporarily, make sure you use one of
  the non-overwriting extract_type
  values such as EXTR_SKIP and be aware
  that you should extract in the same
  order that's defined in
  variables_order within the php.ini.

It warns about the use but does not provide an example at least of how to solve the user of extract in a secure way.

答:
The best option is to not use extract() at all. It's a bad design decision from the days when PHP was the equivalent of wet toilet paper for writing secure code.

It may be painful, but it is far better to write out a long sequence of:

```<code>$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
etc...
</code>```

or simply use $_POST['var1'] and company everywhere in your code.

As soon as you start using extract, you're giving malicious users a potential way into your code, no matter how much time/effort you put into it. You don't drill a hole through a bank vault door because it's too annoying to have to open the door each time to let some money out. Once there's a hole, it will be exploited.

Body:
The best option is to not use extract() at all. It's a bad design decision from the days when PHP was the equivalent of wet toilet paper for writing secure code.

It may be painful, but it is far better to write out a long sequence of:

$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
etc...

or simply use $_POST['var1'] and company everywhere in your code.

As soon as you start using extract, you're giving malicious users a potential way into your code, no matter how much time/effort you put into it. You don't drill a hole through a bank vault door because it's too annoying to have to open the door each time to let some money out. Once there's a hole, it will be exploited.


问:
In drupal 8, how do i access the markup of a media entity?
I am in mymodule_node_view_alter because i want to conditionally unset one of the fields of a node.
I kint($build).
The field i am interested in is a media entity (media image).
How'd I get to the markup of a media entity?
I brows through output of kint() but never see anything like a link or a uri for that media file?</p>

答: You will get the media target id from the $build then you have to load Media by target_id and then you will get the uri & URL of the media file.</p>


问:
How to generate three unequal numbers?
Here the number generation :

```<code>for( int i=0; i<3; i++) {
    int randomNumbers = random.nextInt(10) + 1;
}
</code>```

And here I can receive the same digits.

For example: 5,7,5;

But I need to receive only different numbers: 5,1,9.

Is it possible maybe with some little piece of code or I should write some method for it?

答:
Here's a way that avoids rejection sampling: generate one number up to 10, one up to 9, and up to 8. Avoid repeats by incrementing. This guarantees a uniform distribution.

int a = random.nextInt(10) + 1;
int b = random.nextInt(9) + 1;
if(b >= a) { b++; }
int c = random.nextInt(8) + 1;
if(c >= (a > b ? b : a)) { c++; }
if(c >= (a > b ? a : b)) { c++; }
```

Title: How to generate three unequal numbers?

Body:
Here the number generation :

for( int i=0; i<3; i++) {
    int randomNumbers = random.nextInt(10) + 1;
}

And here I can receive the same digits.

For example: 5,7,5;

But I need to receive only different numbers: 5,1,9.

Is it possible maybe with some little piece of code or I should write some method for it?


问:
Stream analytics - How to handle json in reference input
I have an Azure Stream Analytics (ASA) job which processes device telemetry data from event hub. The stream should be joined with reference data from a sql table, to enhance each message with additional device meta data. The merged entry should be stored in CosmosDb.

The sql database to serve the device metadata:

```<code>CREATE TABLE [dbo].[MyTable]
(
  [DeviceId] NVARCHAR(20) NOT NULL PRIMARY KEY,
  [MetaData] NVARCHAR(MAX) NULL   /* this stores json, which can vary per record */
)
</code>```

In ASA I have configured the reference data input with a simple query:

```<code>SELECT DeviceId, JSON_QUERY(MetaData) FROM [dbo].[MyTable]
</code>```

And I have the main ASA query that performs the join:

```<code>WITH temptable AS (
SELECT * FROM [telemetry-input] TD PARTITION BY PartitionId
LEFT OUTER JOIN [metadata-input] MD
ON TD.DeviceId = MD.DeviceId
)

SELECT TD.*, MD.MetaData
INTO [cosmos-db-output]
FROM temptable PARTITION BY PartitionId
</code>```

It all works and merged data gets stored in CosmosDb. However, the value of the Metadata column from sql is treated as string, and stored in comos with quotes and escape chars. Example:

```<code>{ "DeviceId" : "abc1234", … , "MetaData" : "{ \"TestKey\": \"test value\" }" };
</code>```

Is there a way to handle & store the json from Metadata as a proper Json object i.e.

```<code>{ "DeviceId" : "abc1234", … , "MetaData" : { "TestKey": "test value" } };
</code>```

答:
I found the way to achieve it in ASA - you need to create javascript user function:

```<code>function parseJson(strjson){
          return JSON.parse(strjson);
}
</code>```

And call it in your query:

```<code>...
SELECT TD.*, udf.parseJson(MD.MetaData)
...
</code>```

Body:
I have an Azure Stream Analytics (ASA) job which processes device telemetry data from event hub. The stream should be joined with reference data from a sql table, to enhance each message with additional device meta data. The merged entry should be stored in CosmosDb.

The sql database to serve the device metadata:

CREATE TABLE [dbo].[MyTable]
(
  [DeviceId] NVARCHAR(20) NOT NULL PRIMARY KEY,
  [MetaData] NVARCHAR(MAX) NULL   /* this stores json, which can vary per record */
)

In ASA I have configured the reference data input with a simple query:

SELECT DeviceId, JSON_QUERY(MetaData) FROM [dbo].[MyTable]

And I have the main ASA query that performs the join:

WITH temptable AS (
SELECT * FROM [telemetry-input] TD PARTITION BY PartitionId
LEFT OUTER JOIN [metadata-input] MD
ON TD.DeviceId = MD.DeviceId
)

SELECT TD.*, MD.MetaData
INTO [cosmos-db-output]
FROM temptable PARTITION BY PartitionId

It all works and merged data gets stored in CosmosDb. However, the value of the Metadata column from sql is treated as string, and stored in comos with quotes and escape chars. Example:

{ "DeviceId" : "abc1234", … , "MetaData" : "{ \"TestKey\": \"test value\" }" };

Is there a way to handle & store the json from Metadata as a proper Json object i.e.

{ "DeviceId" : "abc1234", … , "MetaData" : { "TestKey": "test value" } };

Body:
I found the way to achieve it in ASA - you need to create javascript user function:

function parseJson(strjson){
          return JSON.parse(strjson);
}

And call it in your query:

...
SELECT TD.*, udf.parseJson(MD.MetaData)
...


问:
django S3 - trim imagefield filename but not the url path
this is a followup to my question here: ImageField / FileField Django form Currently unable to trim the path to filename

In my Django app, there is an imagefield uploaded to S3
After trim the imagefile path name, the image is not accessible because the url is trimmed. How can I trim the display but don't trim the path?

I manage to trim the display showing the filename like this

```<code>class CustomClearableFileInput(ClearableFileInput):

    def get_context(self, name, value, attrs):
        logging.debug("%s",name)
        logging.debug("%s",value)
        value.name = path.basename(value.name)
        context = super().get_context(name, value, attrs)
        return context

    class CompanySettingEdit(forms.ModelForm):
       company_logo = forms.ImageField(widget=CustomClearableFileInput)
</code>```

this is the output:

```<code>https://imgur.com/a/M42Mz <-- display correct
https://bucketname.s3.amazonaws.com/media/certiport_logo.png <-- invalid url
</code>```

If I dont trim it:

```<code>class CustomClearableFileInput(ClearableFileInput):

    def get_context(self, name, value, attrs):
        logging.debug("%s",name)
        logging.debug("%s",value)
        # value.name = path.basename(value.name) <-- remove this
        context = super().get_context(name, value, attrs)
        return context

    class CompanySettingEdit(forms.ModelForm):
       company_logo = forms.ImageField(widget=CustomClearableFileInput)
</code>```

this is the output:

```<code>https://imgur.com/a/rGi8f <-- display incorrect
https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png <--valid url
</code>```

my goal is to:

```<code>display: certiport_logo.png
url: https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png
</code>```

How can I achieve this ?

答:
If you are doing this for the purpose of Django admin then it might help you.
You can save anything in the name of the Image field as it just a name that is used to build the URL for the image.

Now when you open Django admin with an Image field in it, the form will call the Storage class defined as DEFAULT_FILE_STORAGE in settings.py.

```<code>DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'
</code>```

Now this FileSystemStorage class is responsible to create the URL for the image which will open when you click on the Image name in the admin.

Now come to your need. As you require image name to be just certiport_logo.png, you can save this name to your image field and override FileSystemStorage class' url function to create the URL. Here is the example

```<code>from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):
    """
    Override django default storage class to build urls
    """
    def url(self, name):
        return "https://bucketname.s3.amazonaws.com/media/company_logo/15/{}".format(name)

</code>```

Override the url function as per your need for different Django models and you will be able to show just image name even with the correct image URL.
Make sure to set new class path to settings.py

```<code>DEFAULT_FILE_STORAGE = 'apps.commons.custom_storage.CustomStorage'
</code>```

Body:
this is a followup to my question here: ImageField / FileField Django form Currently unable to trim the path to filename

In my Django app, there is an imagefield uploaded to S3
After trim the imagefile path name, the image is not accessible because the url is trimmed. How can I trim the display but don't trim the path?

I manage to trim the display showing the filename like this

class CustomClearableFileInput(ClearableFileInput):

    def get_context(self, name, value, attrs):
        logging.debug("%s",name)
        logging.debug("%s",value)
        value.name = path.basename(value.name)
        context = super().get_context(name, value, attrs)
        return context

    class CompanySettingEdit(forms.ModelForm):
       company_logo = forms.ImageField(widget=CustomClearableFileInput)

this is the output:

https://imgur.com/a/M42Mz <-- display correct
https://bucketname.s3.amazonaws.com/media/certiport_logo.png <-- invalid url

If I dont trim it:

class CustomClearableFileInput(ClearableFileInput):

    def get_context(self, name, value, attrs):
        logging.debug("%s",name)
        logging.debug("%s",value)
        # value.name = path.basename(value.name) <-- remove this
        context = super().get_context(name, value, attrs)
        return context

    class CompanySettingEdit(forms.ModelForm):
       company_logo = forms.ImageField(widget=CustomClearableFileInput)

this is the output:

https://imgur.com/a/rGi8f <-- display incorrect
https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png <--valid url

my goal is to:

display: certiport_logo.png
url: https://bucketname.s3.amazonaws.com/media/company_logo/15/certiport_logo.png

How can I achieve this ?

Body:
If you are doing this for the purpose of Django admin then it might help you.
You can save anything in the name of the Image field as it just a name that is used to build the URL for the image.

Now when you open Django admin with an Image field in it, the form will call the Storage class defined as DEFAULT_FILE_STORAGE in settings.py.

DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'

Now this FileSystemStorage class is responsible to create the URL for the image which will open when you click on the Image name in the admin.

Now come to your need. As you require image name to be just certiport_logo.png, you can save this name to your image field and override FileSystemStorage class' url function to create the URL. Here is the example

from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):
    """
    Override django default storage class to build urls
    """
    def url(self, name):
        return "https://bucketname.s3.amazonaws.com/media/company_logo/15/{}".format(name)

Override the url function as per your need for different Django models and you will be able to show just image name even with the correct image URL.
Make sure to set new class path to settings.py

DEFAULT_FILE_STORAGE = 'apps.commons.custom_storage.CustomStorage'


问:
Bootstrap seems to apply a smaller size to checkboxes in wordpress plugin
I am creating a wordpress plugin. When I import bootstrap from //stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css
there is a couple of checkboxes which shrink down to 8x8.
I have used the devtools to work out that in scaffolding.less there is html font-size being set to 10px which is under 'Inherited from html.wp-toolbar.
If I turn this off in the devtools (even though its crossed out) the the checkbox returns to its normal size. Is it possible to override this in css or even the html directly somehow?</p>

答:
There are few things you can try to override the CSS.

Place the required CSS rule after bootstrap css

Use !important to override

Use inline styles in html file