问:
Get Cost Information of EC2 instance type - AWS GO SDK
Is there a way to get instance type cost information using AWS GO SDK?

so far I have seen cost and usage endpoint to get an existing instance total incurred cost
but I just want to know how much an instance type would cost me per hour

答:
From Using the AWS Price List API - AWS Billing and Cost Management:

The Price List Service API (AKA the Query API) and AWS Price List API (AKA the Bulk API) enable you to query for the prices of AWS services using either JSON (with the Price List Service API) or HTML (with the AWS Price List API).

Be warned, however... There are many dimensions to an instance, such as:

Instance Type

Location (region)

Pricing model (On-Demand, Reserved Instance and Duration, Savings Plan)

Operating System

Tenancy

As an example, here is an AWS CLI command using the Price List Query API to retrieve pricing details about a t3.micro Linux instance in us-east-1 with no pre-installed software:

```<code>aws pricing get-products --region us-east-1 --service-code AmazonEC2 --filters Type=TERM_MATCH,Field=instanceType,Value=t3.micro Type=TERM_MATCH,Field=location,Value="US East (N. Virginia)" Type=TERM_MATCH,Field=usagetype,Value=BoxUsage:t3.micro Type=TERM_MATCH,Field=operatingSystem,Value=Linux Type=TERM_MATCH,Field=preInstalledSw,Value=NA --max-results 30 --output text

{
    "product": {
        "productFamily": "Compute Instance",
        "attributes": {
            "enhancedNetworkingSupported": "No",
            "intelTurboAvailable": "No",
            "memory": "1 GiB",
            "dedicatedEbsThroughput": "Up to 1536 Mbps",
            "vcpu": "2",
            "capacitystatus": "Used",
            "locationType": "AWS Region",
            "storage": "EBS only",
            "instanceFamily": "General purpose",
            "operatingSystem": "Linux",
            "intelAvx2Available": "No",
            "physicalProcessor": "Intel Skylake E5 2686 v5",
            "clockSpeed": "2.5 GHz",
            "ecu": "Variable",
            "networkPerformance": "Low to Moderate",
            "servicename": "Amazon Elastic Compute Cloud",
            "instanceType": "t3.micro",
            "tenancy": "Shared",
            "usagetype": "BoxUsage:t3.micro",
            "normalizationSizeFactor": "0.5",
            "intelAvxAvailable": "No",
            "servicecode": "AmazonEC2",
            "licenseModel": "No License required",
            "currentGeneration": "Yes",
            "preInstalledSw": "NA",
            "location": "US East (N. Virginia)",
            "processorArchitecture": "64-bit",
            "operation": "RunInstances"
        },
        "sku": "CRAJUW7BTXFMT2UJ"
    },
    "serviceCode": "AmazonEC2",
    "terms": {
        "OnDemand": {
            "CRAJUW7BTXFMT2UJ.JRTCKXETXF": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.JRTCKXETXF.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "$0.0104 per On Demand Linux t3.micro Instance Hour",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.JRTCKXETXF.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0104000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-05-01T00:00:00Z",
                "offerTermCode": "JRTCKXETXF",
                "termAttributes": {}
            }
        },
        "Reserved": {
            "CRAJUW7BTXFMT2UJ.MZU6U2429S": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.MZU6U2429S.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.MZU6U2429S.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "123"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.MZU6U2429S.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.MZU6U2429S.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "MZU6U2429S",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "63"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0024000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "R5XV2EPZQZ",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "Partial Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.38NPMPTW36": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.38NPMPTW36.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.38NPMPTW36.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "55"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.38NPMPTW36.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.38NPMPTW36.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0021000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "38NPMPTW36",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "Partial Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.Z2E3P23VKM": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.Z2E3P23VKM.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.Z2E3P23VKM.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0052000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "Z2E3P23VKM",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.VJWZNREJX2": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.VJWZNREJX2.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.VJWZNREJX2.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "61"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.VJWZNREJX2.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.VJWZNREJX2.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "VJWZNREJX2",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "103"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "NQ3QZPMQV9",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.BPH4J8HBKS": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.BPH4J8HBKS.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.BPH4J8HBKS.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0045000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "BPH4J8HBKS",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.CUZHX8X6JH": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0036000000"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "31"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "CUZHX8X6JH",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "Partial Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.7NE97W5U4E": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.7NE97W5U4E.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.7NE97W5U4E.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0075000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "7NE97W5U4E",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.6QCMYABX3D": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.6QCMYABX3D.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.6QCMYABX3D.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.6QCMYABX3D.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.6QCMYABX3D.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "53"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "6QCMYABX3D",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.4NA7Y494T4": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.4NA7Y494T4.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.4NA7Y494T4.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0065000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "4NA7Y494T4",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.HU7G6KETJZ": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0031000000"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "27"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "HU7G6KETJZ",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "Partial Upfront"
                }
            }
        }
    },
    "version": "20200519173025",
    "publicationDate": "2020-05-19T17:30:25Z"
}
</code>```

Body:
From Using the AWS Price List API - AWS Billing and Cost Management:

The Price List Service API (AKA the Query API) and AWS Price List API (AKA the Bulk API) enable you to query for the prices of AWS services using either JSON (with the Price List Service API) or HTML (with the AWS Price List API).

Be warned, however... There are many dimensions to an instance, such as:

Instance Type

Location (region)

Pricing model (On-Demand, Reserved Instance and Duration, Savings Plan)

Operating System

Tenancy

As an example, here is an AWS CLI command using the Price List Query API to retrieve pricing details about a t3.micro Linux instance in us-east-1 with no pre-installed software:

aws pricing get-products --region us-east-1 --service-code AmazonEC2 --filters Type=TERM_MATCH,Field=instanceType,Value=t3.micro Type=TERM_MATCH,Field=location,Value="US East (N. Virginia)" Type=TERM_MATCH,Field=usagetype,Value=BoxUsage:t3.micro Type=TERM_MATCH,Field=operatingSystem,Value=Linux Type=TERM_MATCH,Field=preInstalledSw,Value=NA --max-results 30 --output text

{
    "product": {
        "productFamily": "Compute Instance",
        "attributes": {
            "enhancedNetworkingSupported": "No",
            "intelTurboAvailable": "No",
            "memory": "1 GiB",
            "dedicatedEbsThroughput": "Up to 1536 Mbps",
            "vcpu": "2",
            "capacitystatus": "Used",
            "locationType": "AWS Region",
            "storage": "EBS only",
            "instanceFamily": "General purpose",
            "operatingSystem": "Linux",
            "intelAvx2Available": "No",
            "physicalProcessor": "Intel Skylake E5 2686 v5",
            "clockSpeed": "2.5 GHz",
            "ecu": "Variable",
            "networkPerformance": "Low to Moderate",
            "servicename": "Amazon Elastic Compute Cloud",
            "instanceType": "t3.micro",
            "tenancy": "Shared",
            "usagetype": "BoxUsage:t3.micro",
            "normalizationSizeFactor": "0.5",
            "intelAvxAvailable": "No",
            "servicecode": "AmazonEC2",
            "licenseModel": "No License required",
            "currentGeneration": "Yes",
            "preInstalledSw": "NA",
            "location": "US East (N. Virginia)",
            "processorArchitecture": "64-bit",
            "operation": "RunInstances"
        },
        "sku": "CRAJUW7BTXFMT2UJ"
    },
    "serviceCode": "AmazonEC2",
    "terms": {
        "OnDemand": {
            "CRAJUW7BTXFMT2UJ.JRTCKXETXF": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.JRTCKXETXF.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "$0.0104 per On Demand Linux t3.micro Instance Hour",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.JRTCKXETXF.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0104000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-05-01T00:00:00Z",
                "offerTermCode": "JRTCKXETXF",
                "termAttributes": {}
            }
        },
        "Reserved": {
            "CRAJUW7BTXFMT2UJ.MZU6U2429S": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.MZU6U2429S.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.MZU6U2429S.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "123"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.MZU6U2429S.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.MZU6U2429S.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "MZU6U2429S",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "63"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.R5XV2EPZQZ.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0024000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "R5XV2EPZQZ",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "Partial Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.38NPMPTW36": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.38NPMPTW36.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.38NPMPTW36.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "55"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.38NPMPTW36.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.38NPMPTW36.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0021000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "38NPMPTW36",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "Partial Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.Z2E3P23VKM": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.Z2E3P23VKM.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.Z2E3P23VKM.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0052000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "Z2E3P23VKM",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.VJWZNREJX2": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.VJWZNREJX2.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.VJWZNREJX2.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "61"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.VJWZNREJX2.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.VJWZNREJX2.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "VJWZNREJX2",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "103"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.NQ3QZPMQV9.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "NQ3QZPMQV9",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.BPH4J8HBKS": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.BPH4J8HBKS.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.BPH4J8HBKS.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0045000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "BPH4J8HBKS",
                "termAttributes": {
                    "LeaseContractLength": "3yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.CUZHX8X6JH": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0036000000"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.CUZHX8X6JH.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "31"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "CUZHX8X6JH",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "Partial Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.7NE97W5U4E": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.7NE97W5U4E.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.7NE97W5U4E.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0075000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2018-08-03T20:10:30Z",
                "offerTermCode": "7NE97W5U4E",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "convertible",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.6QCMYABX3D": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.6QCMYABX3D.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "USD 0.0 per Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.6QCMYABX3D.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0000000000"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.6QCMYABX3D.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.6QCMYABX3D.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "53"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "6QCMYABX3D",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "All Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.4NA7Y494T4": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.4NA7Y494T4.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.4NA7Y494T4.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0065000000"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "4NA7Y494T4",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "No Upfront"
                }
            },
            "CRAJUW7BTXFMT2UJ.HU7G6KETJZ": {
                "priceDimensions": {
                    "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.6YS6EN2CT7": {
                        "unit": "Hrs",
                        "endRange": "Inf",
                        "description": "Linux/UNIX (Amazon VPC), t3.micro reserved instance applied",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.6YS6EN2CT7",
                        "beginRange": "0",
                        "pricePerUnit": {
                            "USD": "0.0031000000"
                        }
                    },
                    "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.2TG2D8R56U": {
                        "unit": "Quantity",
                        "description": "Upfront Fee",
                        "appliesTo": [],
                        "rateCode": "CRAJUW7BTXFMT2UJ.HU7G6KETJZ.2TG2D8R56U",
                        "pricePerUnit": {
                            "USD": "27"
                        }
                    }
                },
                "sku": "CRAJUW7BTXFMT2UJ",
                "effectiveDate": "2020-04-01T00:00:00Z",
                "offerTermCode": "HU7G6KETJZ",
                "termAttributes": {
                    "LeaseContractLength": "1yr",
                    "OfferingClass": "standard",
                    "PurchaseOption": "Partial Upfront"
                }
            }
        }
    },
    "version": "20200519173025",
    "publicationDate": "2020-05-19T17:30:25Z"
}


来源: stackexchange

问:
How can we do pagination in datagridview in winform
I want to show 10 records per page in a datagridview on a window form and user must click next button to show next 10 records. Is it there some property in DataGridview or do i need to create a custom control.

What i need to do to achieve this.

答:
My answer is 10years late and I can't begin to explain why. But I think what is important is that I have something to offer. :D

I love to solve problems in the simplest way possible and by far this is the simplest way I use. If there are any issues with it, am glad to fix it.

```<code>using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        SqlDataAdapter pagingAdapter;
        DataSet pagingDS;
        int scrollVal; // This defines how many more data sets there are to load
        int rowsPerPage = 10; // This defines the total number of rows to show

        public Form1()
        {
            InitializeComponent();
            scrollVal = 0;
        }

        private void BtnShowresults_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
            string sql = "SELECT * FROM Authors";
            SqlConnection connection = new SqlConnection(connectionString);
            pagingAdapter = new SqlDataAdapter(sql, connection);
            pagingDS = new DataSet();
            connection.Open();

            //This part will get the total number of records from the query
            pagingAdapter.Fill(dataSetProjects);
            DataTable dataTable = pagingDS.Tables[0];
            int rowCount = Convert.ToInt32(dataTable.Rows.Count);
            this.btnShowresults.Tag = rowCount; // We set it to the button tag

            pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "Authors_table");
            connection.Close();
            dataGridView1.DataSource = pagingDS;
            dataGridView1.DataMember = "Authors_table";
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (scrollVal < = 0)
            {
                scrollVal = 0;
            } else
            {
                scrollVal -= rowsPerPage;
            }
            pagingDS.Clear();
            pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
        }

        private void BtnNext_Click(object sender, EventArgs e)
        {
            Button btnShowresults = (Button)pnSearch.Controls["btnShowresults"];
            int resCount = Convert.ToInt32(btnShowresults.Tag);
            if (scrollVal <= resCount)
            {
                scrollVal = rowsPerPage;
            } else
            {
                scrollVal = rowsPerPage;
            }
            pagingDS.Clear();
            pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
        }
    }
}
</code>```

This code is found on http://csharp.net-informations.com/datagridview/csharp-datagridview-paging.htm. It had a few bugs I needed to fix. Consider this a cleaned up version.

ContentLicense: CC BY-SA 3.0

Body:
My answer is 10years late and I can't begin to explain why. But I think what is important is that I have something to offer. :D

I love to solve problems in the simplest way possible and by far this is the simplest way I use. If there are any issues with it, am glad to fix it.

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Drawing;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        SqlDataAdapter pagingAdapter;
        DataSet pagingDS;
        int scrollVal; // This defines how many more data sets there are to load
        int rowsPerPage = 10; // This defines the total number of rows to show

        public Form1()
        {
            InitializeComponent();
            scrollVal = 0;
        }

        private void BtnShowresults_Click(object sender, EventArgs e)
        {
            string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
            string sql = "SELECT * FROM Authors";
            SqlConnection connection = new SqlConnection(connectionString);
            pagingAdapter = new SqlDataAdapter(sql, connection);
            pagingDS = new DataSet();
            connection.Open();

            //This part will get the total number of records from the query
            pagingAdapter.Fill(dataSetProjects);
            DataTable dataTable = pagingDS.Tables[0];
            int rowCount = Convert.ToInt32(dataTable.Rows.Count);
            this.btnShowresults.Tag = rowCount; // We set it to the button tag

            pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "Authors_table");
            connection.Close();
            dataGridView1.DataSource = pagingDS;
            dataGridView1.DataMember = "Authors_table";
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (scrollVal < = 0)
            {
                scrollVal = 0;
            } else
            {
                scrollVal -= rowsPerPage;
            }
            pagingDS.Clear();
            pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
        }

        private void BtnNext_Click(object sender, EventArgs e)
        {
            Button btnShowresults = (Button)pnSearch.Controls["btnShowresults"];
            int resCount = Convert.ToInt32(btnShowresults.Tag);
            if (scrollVal <= resCount)
            {
                scrollVal = rowsPerPage;
            } else
            {
                scrollVal = rowsPerPage;
            }
            pagingDS.Clear();
            pagingAdapter.Fill(pagingDS, scrollVal, rowsPerPage, "authors_table");
        }
    }
}

This code is found on http://csharp.net-informations.com/datagridview/csharp-datagridview-paging.htm. It had a few bugs I needed to fix. Consider this a cleaned up version.

ContentLicense: CC BY-SA 4.0


问:
How to make a Subtraction with those values using alias
I have this code:

```<code>SELECT
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'EE' Then M.VALOR End), 0) AS VALOR_EST_EMPENHO  ,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'LI' Then M.VALOR End), 0) AS VALOR_LIQ_BRUTO,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'EL' Then M.VALOR End), 0) AS VALOR_EST_LIQUIDACAO,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO In ('PG', 'RT') Then M.VALOR End), 0) AS VALOR_PAG_BRUTO,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'EP' Then M.VALOR End), 0) AS VALOR_EST_PAGAMENTO,
    EMP_COD
FROM
    CTP_DESPESA_EMPENHADA_MOVIMENTACAO_VI M
GROUP BY
    M.EMP_COD
</code>```

What I'm trying to do is to subtract them and getting the value, but they are using alias so when I do VALOR_EST_EMPENHO - VALOR_LIQ_BRUTO it gets me the following error:

Msg 207, Level 16, State 1, Line 23

  Invalid column name 'VALOR_EST_EMPENHO'

How am I supposed to do this?

答:
Couple of things:

The CASE WHEN statement has an ELSE path. It is better to set that to 0 to avoid the COALESCE.

As suggested by others, you can repeat the COALESCE(SUM()) instructions to get the desired results. However for readability, I see where your are coming from.

```<code>SELECT Sum(CALCULATED.VALOR_EST_EMPENHO) AS VALOR_EST_EMPENHO
 , Sum(CALCULATED.VALOR_LIQ_BRUTO) AS VALOR_LIQ_BRUTO
 , Sum(CALCULATED.VALOR_EST_LIQUIDACAO) AS VALOR_EST_LIQUIDACAO
 , Sum(CALCULATED.VALOR_PAG_BRUTO) AS VALOR_PAG_BRUTO
 , Sum(CALCULATED.VALOR_EST_PAGAMENTO) AS VALOR_EST_PAGAMENTO
 , Sum(CALCULATED.VALOR_EST_EMPENHO - CALCULATED.VALOR_LIQ_BRUTO) AS VALOR_X
 , M.EMP_COD
FROM   CTP_DESPESA_EMPENHADA_MOVIMENTACAO_VI M
CROSS APPLY(
  SELECT Case When M.TIPO_MOVIMENTO = 'EE' Then M.VALOR ELSE 0 End AS VALOR_EST_EMPENHO
       , Case When M.TIPO_MOVIMENTO = 'LI' Then M.VALOR ELSE 0 End AS VALOR_LIQ_BRUTO
       , Case When M.TIPO_MOVIMENTO = 'EL' Then M.VALOR ELSE 0 End AS VALOR_EST_LIQUIDACAO
       , Case When M.TIPO_MOVIMENTO In ('PG', 'RT') Then M.VALOR ELSE 0 End AS VALOR_PAG_BRUTO
       , Case When M.TIPO_MOVIMENTO = 'EP' Then M.VALOR ELSE 0 End AS VALOR_EST_PAGAMENTO
  ) CALCULATED
GROUP BY
  M.EMP_COD
</code>```

The inline table that results from the CROSS APPLY statement is calculated for each of the rows. In execution time, the query will expand the columns used from the inline table, so effectively, this will result in a query with more CASE WHEN statements.

I hope this helps.

Body:
I have this code:

SELECT
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'EE' Then M.VALOR End), 0) AS VALOR_EST_EMPENHO  ,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'LI' Then M.VALOR End), 0) AS VALOR_LIQ_BRUTO,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'EL' Then M.VALOR End), 0) AS VALOR_EST_LIQUIDACAO,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO In ('PG', 'RT') Then M.VALOR End), 0) AS VALOR_PAG_BRUTO,
    Coalesce(Sum(Case When M.TIPO_MOVIMENTO = 'EP' Then M.VALOR End), 0) AS VALOR_EST_PAGAMENTO,
    EMP_COD
FROM
    CTP_DESPESA_EMPENHADA_MOVIMENTACAO_VI M
GROUP BY
    M.EMP_COD

What I'm trying to do is to subtract them and getting the value, but they are using alias so when I do VALOR_EST_EMPENHO - VALOR_LIQ_BRUTO it gets me the following error:

Msg 207, Level 16, State 1, Line 23

  Invalid column name 'VALOR_EST_EMPENHO'

How am I supposed to do this?

Body:
Couple of things:

The CASE WHEN statement has an ELSE path. It is better to set that to 0 to avoid the COALESCE.

As suggested by others, you can repeat the COALESCE(SUM()) instructions to get the desired results. However for readability, I see where your are coming from.

SELECT Sum(CALCULATED.VALOR_EST_EMPENHO) AS VALOR_EST_EMPENHO
 , Sum(CALCULATED.VALOR_LIQ_BRUTO) AS VALOR_LIQ_BRUTO
 , Sum(CALCULATED.VALOR_EST_LIQUIDACAO) AS VALOR_EST_LIQUIDACAO
 , Sum(CALCULATED.VALOR_PAG_BRUTO) AS VALOR_PAG_BRUTO
 , Sum(CALCULATED.VALOR_EST_PAGAMENTO) AS VALOR_EST_PAGAMENTO
 , Sum(CALCULATED.VALOR_EST_EMPENHO - CALCULATED.VALOR_LIQ_BRUTO) AS VALOR_X
 , M.EMP_COD
FROM   CTP_DESPESA_EMPENHADA_MOVIMENTACAO_VI M
CROSS APPLY(
  SELECT Case When M.TIPO_MOVIMENTO = 'EE' Then M.VALOR ELSE 0 End AS VALOR_EST_EMPENHO
       , Case When M.TIPO_MOVIMENTO = 'LI' Then M.VALOR ELSE 0 End AS VALOR_LIQ_BRUTO
       , Case When M.TIPO_MOVIMENTO = 'EL' Then M.VALOR ELSE 0 End AS VALOR_EST_LIQUIDACAO
       , Case When M.TIPO_MOVIMENTO In ('PG', 'RT') Then M.VALOR ELSE 0 End AS VALOR_PAG_BRUTO
       , Case When M.TIPO_MOVIMENTO = 'EP' Then M.VALOR ELSE 0 End AS VALOR_EST_PAGAMENTO
  ) CALCULATED
GROUP BY
  M.EMP_COD

The inline table that results from the CROSS APPLY statement is calculated for each of the rows. In execution time, the query will expand the columns used from the inline table, so effectively, this will result in a query with more CASE WHEN statements.

I hope this helps.


问:
Creating columns based on individual values in rows pandas
Looking to simplify a huge dataset via pandas which has four columns,

```<code>        Time        A   B     C
    27/5/2020 1:30 -90 -12  0 2 3 5 6
    27/5/2020 1:35 -90 -11  0 2 3 4 6 7 8
    27/5/2020 1:40 -80 -12  2 4 5 6 9 12 15
</code>```

I want to create a new dataframe which can give me all the existing columns and create new columns with value 1 based on the current numbers positions in columns C for each row.

Like;

```<code>Time             A   B      C             Col1 Col2 Col3 Col4 Col5 Col6 Col7
27/5/2020 1:30 -90 -12  0 2 3 5 6          1   0    1    1    0     1   1
</code>```

and so on..
any help will be much appreciated. I am working through some for loops at the moment

答:
Let us try get_dummies

```<code>df=df.join(df.C.str.get_dummies(' ').add_prefix('col'))
</code>```

Body:
Looking to simplify a huge dataset via pandas which has four columns,

        Time        A   B     C
    27/5/2020 1:30 -90 -12  0 2 3 5 6
    27/5/2020 1:35 -90 -11  0 2 3 4 6 7 8
    27/5/2020 1:40 -80 -12  2 4 5 6 9 12 15

I want to create a new dataframe which can give me all the existing columns and create new columns with value 1 based on the current numbers positions in columns C for each row.

Like;

Time             A   B      C             Col1 Col2 Col3 Col4 Col5 Col6 Col7
27/5/2020 1:30 -90 -12  0 2 3 5 6          1   0    1    1    0     1   1

and so on..
any help will be much appreciated. I am working through some for loops at the moment

Body:
Let us try get_dummies

df=df.join(df.C.str.get_dummies(' ').add_prefix('col'))


问:
best way to find substring using regex in python 3
I was trying to find out the best way to find the specific substring in key value pair using re for the following:

```<code>some_string-variable_length/some_no_variable_digit/some_no1_variable_digit/some_string1/some_string2
eg: aba/101/11111/cde/xyz or aaa/111/1119/cde/xzx or ada/21111/5/cxe/yyz
</code>```

here everything is variable and what I was looking for is something like below in key value pair:

```<code>`cde: 2` as there are two entries for cde

cxe: 1 as there is only one cxe
</code>```

Note: everything is variable here except /. ie cde or cxe or some string will be there exactly after two / in each case

```<code>input:aba/101/11111/cde/xyz/blabla
output: cde:xyz/blabla
input: aaa/111/1119/cde/xzx/blabla
output: cde:xzx/blabla
input: aahjdsga/11231/1119/gfts/sjhgdshg/blabla
output: gfts:sjhgdshg/blabla
</code>```

If you notice here, my key is always the first string after 3rd / and value is always the substring after key

Body:
I was trying to find out the best way to find the specific substring in key value pair using re for the following:

some_string-variable_length/some_no_variable_digit/some_no1_variable_digit/some_string1/some_string2
eg: aba/101/11111/cde/xyz or aaa/111/1119/cde/xzx or ada/21111/5/cxe/yyz

here everything is variable and what I was looking for is something like below in key value pair:

`cde: 2` as there are two entries for cde

cxe: 1 as there is only one cxe

Note: everything is variable here except /. ie cde or cxe or some string will be there exactly after two / in each case

input:aba/101/11111/cde/xyz/blabla
output: cde:xyz/blabla
input: aaa/111/1119/cde/xzx/blabla
output: cde:xzx/blabla
input: aahjdsga/11231/1119/gfts/sjhgdshg/blabla
output: gfts:sjhgdshg/blabla

If you notice here, my key is always the first string after 3rd / and value is always the substring after key

Body:
Try (?<!\S)[^\s/]*(?:/[^\s/]*){2}/([^\s/]*)

demo

Try new per commnt

(?<!\S)[^\s/]*(?:/[^\s/]*){2}/([^\s/]*)(?:/(\S*))?

demo2


问:
Can terraform run "apply" for multiple infrastructure/workspace in parallel?
We have one terraform instance and script which could create infra in azure. We would like to use same scripts to create/update/destroy isolated infra for each one of our customers on azure . We have achieved this by assigning one workspace for each client,different var files and using backend remote state files on azure.

Our intend is to create a wrapper python program that could create multiple threads and trigger terraform apply in parallel for all workspaces. This seems to be not working as terraform runs for one workspace at a time.
Any suggestions/advice on how we can achieve parallel execution of terraform apply for different workspaces?

答:
It's safe to run multiple Terraform processes concurrently as long as:

They all have totally distinct backend configurations, both in terms of state storage and in terms of lock configuration. (If they have overlapping lock configuration then they'll mutex each other, effectively serializing the operations in spite of you running multiple copies.)

They work with an entirely disjoint set of remote objects, including those represented by both managed resources (resource blocks) and data resources (data blocks).

Most remote APIs do not support any sort of transaction or mutex concept directly themselves, so Terraform cannot generally offer fine-grained mutual exclusion for individual objects. However, multiple runs that work with entirely separate remote objects will not interact with one another.

Removing a workspace (using terraform workspace delete) concurrently with an operation against that workspace will cause undefined behavior, because it is likely to delete the very objects Terraform is using to track the operation.

There is no built-in Terraform command for running multiple operations concurrently, so to do so will require custom automation that wraps Terraform.


问:
Is it possible to create Noobaa bucket without creating ObjectBucketClaim(OBC)?
I am able to create noobaa bucket by creating OBC as shown below:

```<code>apiVersion: objectbucket.io/v1alpha1
kind: ObjectBucketClaim
metadata:
  name: my-obc1
spec:
  storageClassName: noobaa-test.noobaa.io
  bucketName: my-bucket
  additionalConfig: {}
</code>```

Above OBC will create a noobaa bucket my-bucket.
But is there any way we can create noobaa bucket directly without having to create OBC?

答:
There are several ways to create buckets in noobaa other than OBC:

You can use the UI - open with noobaa ui.

You can use the simple command - noobaa bucket create <name>.

You can use the internal API - noobaa api bucket create_bucket '{ "name": "<name>" ... }' (see here the json schema of this api params)

You can use S3 - take the endpoint and credentials from noobaa status.

Thanks! Guy

Body:
I am able to create noobaa bucket by creating OBC as shown below:

apiVersion: objectbucket.io/v1alpha1
kind: ObjectBucketClaim
metadata:
  name: my-obc1
spec:
  storageClassName: noobaa-test.noobaa.io
  bucketName: my-bucket
  additionalConfig: {}

Above OBC will create a noobaa bucket my-bucket.
But is there any way we can create noobaa bucket directly without having to create OBC?


问:
unexpected back slash added to char variables with read_xlsx
So I had this peculiar problem after importing an excel sheet with 'datetime' column as character (eg. "2018/1/5 17:12:26")

using read_xlsx('filepath'). It works well with numeric values in the first two columns, but adds some additional characters to the column 3

variable (eg."\"2018/1/5 17:12:26\"" ). I am running a R 3.6.3 on Mac.

Does anyone know what's happening here? I didn't specified any other args though.

Any suggestions would be very appreciated. Thanks.

答:
After reading the dataset, we can convert the 'datetime' to Datetime class with lubridate

```<code>library(dplyr)
library(lubridate)
licks <- licks %>%
             mutate(datetime = ymd_hms(datetime))
</code>```

It seems that there are some double quotes, which would be automatically removed with ymd_hms

```<code>ymd_hms('"2018/1/5 17:25:36"')
#[1] "2018-01-05 17:25:36 UTC"
</code>```

Body:
After reading the dataset, we can convert the 'datetime' to Datetime class with lubridate

library(dplyr)
library(lubridate)
licks <- licks %>%
             mutate(datetime = ymd_hms(datetime))

It seems that there are some double quotes, which would be automatically removed with ymd_hms

ymd_hms('"2018/1/5 17:25:36"')
#[1] "2018-01-05 17:25:36 UTC"


问:
Database Mirroring / Postgres Streaming Replication
I am not a DBA; I'm the primary developer of an enterprise database based application.

I'm currently specing out some new machines to upgrade our existing enterprise database. Currently we're running Postgres 8.4 with a database at our DR site that receives updates at intervals via some custom rsync work a former employee performed.

One of the major issues we're trying to tackle is latency between two global offices. We have staff in NY and staff in London. Currently, the London staffers suffer the fate of our VPN pipe. I'm not really in a position to change that infrastructure.

What I'd like to do is move to Postgres 9 and setup streaming replication. The slave would be in the London office, which would alleviate read problems for users. The problem I foresee is writes to the slave (not sure how PG handles this, my understanding is the slave is in read-only mode). Ideally, writes would be sent to the master in NY (writes are very infrequent from London, but necessary) by the database itself. Furthermore, I can setup fallover to have it act as a hot swappable backup (replacing the DR). Again, all contained within Postgres configuration with no additional code.

That's my idealized solution. How far off am I? Is this at all possible?

I'm a little overwhelmed by the breadth of this topic and Google is not really helping me. I would appreciate any advice from some experienced DBAs, with anecdotes, relevant documentation or examples.

Currently we're using SQLAlchemy as the primary interface to the database, if that's relevant. It does mean we're not tied to Postgres.

Thanks everyone.

答:
pgpool-II can handle this for your:

Check this example.


问:
Combining two columns to create a datetime object
I would need to create a datetime by combining two columns in a dataframe.
My original dataset has these columns:

```<code>Date                Time
05/29/2020         00:12
05/29/2020         00:32
05/28/2020         00.59
</code>```

I would like to create a new column which combines Date + Time, i.e. which creates a datetime object:

```<code>Date_time
05/22/2020 00:12
05/22/2020 00:32
05/28/2020 00:59
</code>```

I used

```<code>df['Time'] = df['Time'].astype('datetime64[ns]')
</code>```

but the output gave me today's date plus values from column Time 2020-05-29 00:22:00.
How could I get the right date by using the columns Date and Time above?

答:
You can try </p>

```<code>df['Date_time']=pd.to_datetime(df.Date+ ' '+df.Time, format='%m/%d/%Y %H:%M:%S')
</code>```

Body:
I would need to create a datetime by combining two columns in a dataframe.
My original dataset has these columns:

Date                Time
05/29/2020         00:12
05/29/2020         00:32
05/28/2020         00.59

I would like to create a new column which combines Date + Time, i.e. which creates a datetime object:

Date_time
05/22/2020 00:12
05/22/2020 00:32
05/28/2020 00:59

I used

df['Time'] = df['Time'].astype('datetime64[ns]')

but the output gave me today's date plus values from column Time 2020-05-29 00:22:00.
How could I get the right date by using the columns Date and Time above?

Body:
You can try

df['Date_time']=pd.to_datetime(df.Date+ ' '+df.Time, format='%m/%d/%Y %H:%M:%S')


问:
Can I get the path of the currently running java executable?
Suppose I want to run a java program from the command line and I use this command:

```<code>myExes\java\java.exe AJavaProgram
</code>```

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.

答:
How about this way?

You can get a java home dir.

String path = System.getProperty("java.home");
```

Body:
Suppose I want to run a java program from the command line and I use this command:

myExes\java\java.exe AJavaProgram

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.


问:
Selenium with Angular - XPath how to get to elements when $index present?
Using Python 3.7 with Selenium on pages that include Angular, please advise how to best locate an element such as this:

```<code><input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style="">
</code>```

or this

```<code><button type="button" uib-tooltip="Edit" tooltip-placement="right" class="btn btn-primary" ng-click="section3.data.editContainer($index);" ng-disabled="editingDrilling1 || submissionTypeSR">
</code>```

when it exists in blocks such as the following. What's tripping me up is the $index... The page has multiple fieldset tags and that number is DYNAMIC... For example, a user can add more of one type of the fieldset while editing the page- but only this one type.

```<code><div ng-if="section3.data.generalSection3.srvyTyId != null && section3.data.generalSection3.srvyTyId != ''" class="ng-scope" style="">
    <!-- ngRepeat: wellFeature in section3.data.generalSection3.container track by $index -->
    <div ng-repeat="wellFeature in section3.data.generalSection3.container track by $index" class="ng-scope">
        <!-- ngIf: section3.data.generalSection3.container[$index].deleteSegmentLocation == null -->
        <fieldset class="legend-border ng-scope" ng-if="section3.data.generalSection3.container[$index].deleteSegmentLocation == null">
            <legend/>
            <div class="col-lg-12 panel panel-default">
                <div class="row panel-heading ng-binding">
                            SHL <br>
                        <!-- ngIf: section3.data.generalSection3.container[$index].legBHLAttr == 'PPP' -->
                        <!-- ngIf: section3.data.generalSection3.container[$index].legBHLAttr != 'PPP' && section3.data.generalSection3.container[$index].legBHLAttr != 'SHL' -->
                        <!-- ngIf: section3.data.generalSection3.container[$index].legBHLAttr == 'SHL' -->
                        <div ng-if="section3.data.generalSection3.container[$index].legBHLAttr == 'SHL'" class="ng-scope"/>
                        <!-- end ngIf: section3.data.generalSection3.container[$index].legBHLAttr == 'SHL' -->
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-11">
                        <!-- ngIf: section3.data.generalSection3.srvyTyId=='1'|| section3.data.generalSection3.srvyTyId=='3' || section3.data.generalSection3.srvyTyId=='2' || section3.data.generalSection3.srvyTyId=='4' -->
                        <div ng-if="section3.data.generalSection3.srvyTyId=='1'|| section3.data.generalSection3.srvyTyId=='3' || section3.data.generalSection3.srvyTyId=='2' || section3.data.generalSection3.srvyTyId=='4'" style="padding-left: 15px; padding-right: 15px;" class="ng-scope">
                            <div class="row">
                                <div class="col-lg-6">
                                    <div class="form-group">
                                        <label class="required-field">Lease Type</label>
                                        <br>
                                            <div ng-class="classes('lseCatTy'+','+$index.toString(), [])">
                                                <label class="radio-inline">
                                                    <input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style=""> Federal
                                                    </label>
                                                    <label class="radio-inline">

</code>```

What I have working is:

```<code>self.wait.until(EC.presence_of_element_located((By.XPATH, "//button[@ng-click='section3.data.editContainer($index);']"))).click()
</code>```

And this gets the first instance of that button (in the top fieldset), but I don't know how to get an arbitrary instance of it.

Body:
Using Python 3.7 with Selenium on pages that include Angular, please advise how to best locate an element such as this:

<input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style="">

or this

<button type="button" uib-tooltip="Edit" tooltip-placement="right" class="btn btn-primary" ng-click="section3.data.editContainer($index);" ng-disabled="editingDrilling1 || submissionTypeSR">

when it exists in blocks such as the following. What's tripping me up is the $index... The page has multiple fieldset tags and that number is DYNAMIC... For example, a user can add more of one type of the fieldset while editing the page- but only this one type.

        <fieldset class="legend-border ng-scope" ng-if="section3.data.generalSection3.container[$index].deleteSegmentLocation == null">
            <legend/>

                            SHL

                                        Lease Type

                                                    <input type="radio" ng-model="section3.data.generalSection3.container[$index].lseCatTy" value="FEDERAL" ng-disabled="!section3.data.generalSection3.container[$index].editable" ng-class="classes('lseCatTy')" ng-change="section3.updateLseCatTy($index, section3.data.generalSection3.container[$index].lseCatTy)" class="ng-valid ng-not-empty ng-dirty ng-touched ng-valid-parse" name="759" style=""> Federal

What I have working is:

self.wait.until(EC.presence_of_element_located((By.XPATH, "//button[@ng-click='section3.data.editContainer($index);']"))).click()

And this gets the first instance of that button (in the top fieldset), but I don't know how to get an arbitrary instance of it.

Body: driver.find_elements_by_css_selector('[ng-model*="$index"],[ng-click*="$index"]')


问:
Avoiding Side Effects in List Comprehension
What is the most Pythonic and efficient way of processing a list of dictionaries and avoiding side effects (what are side effects)?

More specifically: Why does the following code produce a generator object, while just about any other similar code produces the desired output?

```<code>print(sum(dictionary[site] for site in dictionary) for dictionary in listofdictionaries)
</code>```

Some background

I started by fiddling with **kwargs and produced what I would consider pretty awful code.

```<code>def testing(**kwargs):
    mysum = 0
    for kw in kwargs:
        mysum += kwargs[kw]
    print(mysum)

listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]

for dictionary in listofdictionaries:
    testing(**dictionary)
</code>```

I reviewed the Data Structures Document including List Comprehension and found a better way to achieve the same output:

```<code>listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]
for dictionary in listofdictionaries:
    mysum = 0
    for value in dictionary:
        mysum += dictionary[value]
    print(mysum)
</code>```

And then got a little clever and shortened it a bit more:

```<code>for dictionary in listofdictionaries:
    print(sum(dictionary[value] for value in dictionary))
</code>```

I really have no interest in making this a one-liner for the sake of making it a one-liner, but after reading countless list comprehension posts on Stack Overflow talking about avoiding "side effects", I feel like there may be an additional step to take this. Perhaps I'm not understanding what side effects are.

Regardless, each of these should result in the output:

```<code>6
15
</code>```

答:
You can get pretty close by adding a function to calculate the sum of one dictionary, and use a list comprehension like this:

```<code>def dict_sum(dictionary):
    mysum = 0
    for value in dictionary:
        mysum += dictionary[value]
    return mysum

print([dict_sum(dictionary) for dictionary in listofdictionaries])
>> [6, 15]
</code>```

But, your two-liner shouldn't have any side-effects. I don't know what posts you are referring to, but if you aren't modifying the lists then you should be fine and they should be unchanged at the end.

Body:
What is the most Pythonic and efficient way of processing a list of dictionaries and avoiding side effects (what are side effects)?

More specifically: Why does the following code produce a generator object, while just about any other similar code produces the desired output?

print(sum(dictionary[site] for site in dictionary) for dictionary in listofdictionaries)

Some background

I started by fiddling with **kwargs and produced what I would consider pretty awful code.

def testing(**kwargs):
    mysum = 0
    for kw in kwargs:
        mysum += kwargs[kw]
    print(mysum)

listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]

for dictionary in listofdictionaries:
    testing(**dictionary)

I reviewed the Data Structures Document including List Comprehension and found a better way to achieve the same output:

listofdictionaries = [{"site1": 1, "room1": 2, "day1": 3}, {"site2": 4, "room2": 5, "day2": 6}]
for dictionary in listofdictionaries:
    mysum = 0
    for value in dictionary:
        mysum += dictionary[value]
    print(mysum)

And then got a little clever and shortened it a bit more:

for dictionary in listofdictionaries:
    print(sum(dictionary[value] for value in dictionary))

I really have no interest in making this a one-liner for the sake of making it a one-liner, but after reading countless list comprehension posts on Stack Overflow talking about avoiding "side effects", I feel like there may be an additional step to take this. Perhaps I'm not understanding what side effects are.

Regardless, each of these should result in the output:

6
15

Body:
You can get pretty close by adding a function to calculate the sum of one dictionary, and use a list comprehension like this:

def dict_sum(dictionary):
    mysum = 0
    for value in dictionary:
        mysum += dictionary[value]
    return mysum

print([dict_sum(dictionary) for dictionary in listofdictionaries])
>> [6, 15]

But, your two-liner shouldn't have any side-effects. I don't know what posts you are referring to, but if you aren't modifying the lists then you should be fine and they should be unchanged at the end.


问:
Loading Pixi spritesheets from TexturePacker manually and not through Pixi.Loader?
I have been using TexturePacker and Pixi for animations, but now the exported TexturePacker files (multipacked) are stored in a CMS system. The CMS prepends the file names with unpredictable letters and numbers, which makes PIXI unable to link the json and spritesheets together, and also the "related_multi_packs" value in json are now incorrect.

Is there a way to tell PIXI to use these files in a "manual" way? After I load the json files with standard ajax, could I i.e. inject the correct spritesheet url in the json files, and then give it to PIXI somehow?

答:
I ended up parsing it manually as I could find no other way. It was easier than expected.

Loaded json files with axios.

Looped through the multipack files and made sure the correct json
and spritesheet was grouped together in an array.

Loaded the spritesheet images with Pixi loader.

Parsed the json and built sprites on the baseTexture with correct frame/trim/orig/rotation.

Work like a charm.


问:
Float distance for 80 bit long double
For float, double, and __float128, we have the following code which computes the number of representables between them:

int32_t float_distance(float x, float y) {
    static_assert(sizeof(float) == sizeof(int32_t), "float is incorrect size.");
    int32_t xi = *reinterpret_cast<int32_t*>(&x);
    int32_t yi = *reinterpret_cast<int32_t*>(&y);
    return yi - xi;
}

int64_t float_distance(double x, double y) {
    static_assert(sizeof(double) == sizeof(int64_t), "double is incorrect size.");
    int64_t xi = *reinterpret_cast<int64_t*>(&x);
    int64_t yi = *reinterpret_cast<int64_t*>(&y);
    return yi - xi;
}

__int128_t float_distance(__float128 x, __float128 y) {
    static_assert(sizeof(__float128) == sizeof(__int128_t), "quad is incorrect size.");
    __int128_t xi = *reinterpret_cast<__int128_t*>(&x);
    __int128_t yi = *reinterpret_cast<__int128_t*>(&y);
    return yi - xi;
}
```

(This code works for x,y > 0, for legibility we aren't dealing with the general case.)

There is no int80_t, so what is the analogous code for long double? Out of desperation, I tried both __int128_t and __int64_t return types, but no joy.

Edit: It seems like this is not a well-known property of IEEE-754 floating point numbers. Here's a good read for those who are wondering why this works.

答:
You can do it using the properties of the floating-point representation provided in the numeric_limits template of the <numeric> header and routines in <cmath>. No examination of the bits representing the values is required. Here is sample code in C++.

```<code>#include <cmath>
#include <cstdint>

#include <numeric>

/*  Return the signed distance from 0 to x, measuring distance as one unit per
    number representable in FPType.  x must be a finite number.
*/
template<typename FPType> intmax_t ToOrdinal(FPType x)
{
    static const int
        Radix             = std::numeric_limits<FPType>::radix,
        SignificandDigits = std::numeric_limits<FPType>::digits,
        MinimumExponent   = std::numeric_limits<FPType>::min_exponent;

    //  Number of normal representable numbers for each exponent.
    static const intmax_t
        NumbersPerExponent = scalbn(Radix-1, SignificandDigits-1);

    static_assert(std::numeric_limits<FPType>::has_denorm == std::denorm_present,
        "This code presumes floating-point type has subnormal numbers.");

    if (x == 0)
        return 0;

    //  Separate the sign.
    int sign = std::signbit(x) ? -1 : +1;
    x = std::fabs(x);

    //  Separate the significand and exponent.
    int exponent = std::ilogb(x)+1;
    FPType fraction = std::scalbn(x, -exponent);

    if (exponent < MinimumExponent)
    {
        //  For subnormal x, adjust to its subnormal representation.
        fraction = std::scalbn(fraction, exponent - MinimumExponent);
        exponent = MinimumExponent;
    }

    /*  Start with the number of representable numbers in preceding normal
        exponent ranges.
    */
    intmax_t count = (exponent - MinimumExponent) * NumbersPerExponent;

    /*  For subnormal numbers, fraction * radix ** SignificandDigits is the
        number of representable numbers from 0 to x.  For normal numbers,
        (fraction-1) * radix ** SignificandDigits is the number of
        representable numbers from the start of x's exponent range to x, and
        1 * radix ** SignificandDigits is the number of representable subnormal
        numbers (which we have not added into count yet).  So, in either case,
        adding fraction * radix ** SignificandDigits is the desired amount to
        add to count.
    */
    count += (intmax_t) std::scalbn(fraction, SignificandDigits);

    return sign * count;
}

/*  Return the number of representable numbers from x to y, including one
    endpoint.
*/
template<typename FPType> intmax_t Distance(FPType y, FPType x)
{
    return ToOrdinal(y) - ToOrdinal(x);
}

#include <iomanip>
#include <iostream>

template<typename FPType> static void Try(FPType x)
{
    std::cout << x << " -> " << ToOrdinal(x) << ".\n";
}

int main(void)
{
    Try(0.f);
    Try(0x1p-149f);
    Try(0x1p-127f);
    Try(0x1p-126f);
    Try(0x1p-126f + 0x1p-149f);
    Try(1.f);
    Try(1.5f);
    Try(0.l);
    Try(1.l);
    Try(1.5l);

    //  Test from 3 steps below 4 to 5 steps above 4.
    float x = 4, y = x;
    for (int i = 0; i < 3; ++i)
        x = std::nexttowardf(x, 0);
    for (int i = 0; i < 5; ++i)
        y = std::nexttowardf(y, INFINITY);
    std::cout << "There are " << Distance(y, x) << std::setprecision(8)
        << " representable numbers from " << x << " to " << y << ".\n";

}
</code>```

Title: Float distance for 80 bit long double

Body:
For float, double, and __float128, we have the following code which computes the number of representables between them:

int32_t float_distance(float x, float y) {
    static_assert(sizeof(float) == sizeof(int32_t), "float is incorrect size.");
    int32_t xi = *reinterpret_cast<int32_t*>(&x);
    int32_t yi = *reinterpret_cast<int32_t*>(&y);
    return yi - xi;
}

int64_t float_distance(double x, double y) {
    static_assert(sizeof(double) == sizeof(int64_t), "double is incorrect size.");
    int64_t xi = *reinterpret_cast<int64_t*>(&x);
    int64_t yi = *reinterpret_cast<int64_t*>(&y);
    return yi - xi;
}

__int128_t float_distance(__float128 x, __float128 y) {
    static_assert(sizeof(__float128) == sizeof(__int128_t), "quad is incorrect size.");
    __int128_t xi = *reinterpret_cast<__int128_t*>(&x);
    __int128_t yi = *reinterpret_cast<__int128_t*>(&y);
    return yi - xi;
}

(This code works for x,y > 0, for legibility we aren't dealing with the general case.)

There is no int80_t, so what is the analogous code for long double? Out of desperation, I tried both __int128_t and __int64_t return types, but no joy.

Edit: It seems like this is not a well-known property of IEEE-754 floating point numbers. Here's a good read for those who are wondering why this works.

Body:
You can do it using the properties of the floating-point representation provided in the numeric_limits template of the <numeric> header and routines in <cmath>. No examination of the bits representing the values is required. Here is sample code in C++.

#include <cmath>
#include <cstdint>

#include <numeric>

/*  Return the signed distance from 0 to x, measuring distance as one unit per
    number representable in FPType.  x must be a finite number.
*/
template<typename FPType> intmax_t ToOrdinal(FPType x)
{
    static const int
        Radix             = std::numeric_limits<FPType>::radix,
        SignificandDigits = std::numeric_limits<FPType>::digits,
        MinimumExponent   = std::numeric_limits<FPType>::min_exponent;

    //  Number of normal representable numbers for each exponent.
    static const intmax_t
        NumbersPerExponent = scalbn(Radix-1, SignificandDigits-1);

    static_assert(std::numeric_limits<FPType>::has_denorm == std::denorm_present,
        "This code presumes floating-point type has subnormal numbers.");

    if (x == 0)
        return 0;

    //  Separate the sign.
    int sign = std::signbit(x) ? -1 : +1;
    x = std::fabs(x);

    //  Separate the significand and exponent.
    int exponent = std::ilogb(x)+1;
    FPType fraction = std::scalbn(x, -exponent);

    if (exponent < MinimumExponent)
    {
        //  For subnormal x, adjust to its subnormal representation.
        fraction = std::scalbn(fraction, exponent - MinimumExponent);
        exponent = MinimumExponent;
    }

    /*  Start with the number of representable numbers in preceding normal
        exponent ranges.
    */
    intmax_t count = (exponent - MinimumExponent) * NumbersPerExponent;

    /*  For subnormal numbers, fraction * radix ** SignificandDigits is the
        number of representable numbers from 0 to x.  For normal numbers,
        (fraction-1) * radix ** SignificandDigits is the number of
        representable numbers from the start of x's exponent range to x, and
        1 * radix ** SignificandDigits is the number of representable subnormal
        numbers (which we have not added into count yet).  So, in either case,
        adding fraction * radix ** SignificandDigits is the desired amount to
        add to count.
    */
    count += (intmax_t) std::scalbn(fraction, SignificandDigits);

    return sign * count;
}

/*  Return the number of representable numbers from x to y, including one
    endpoint.
*/
template<typename FPType> intmax_t Distance(FPType y, FPType x)
{
    return ToOrdinal(y) - ToOrdinal(x);
}

#include <iomanip>
#include <iostream>

template<typename FPType> static void Try(FPType x)
{
    std::cout << x << " -> " << ToOrdinal(x) << ".\n";
}

int main(void)
{
    Try(0.f);
    Try(0x1p-149f);
    Try(0x1p-127f);
    Try(0x1p-126f);
    Try(0x1p-126f + 0x1p-149f);
    Try(1.f);
    Try(1.5f);
    Try(0.l);
    Try(1.l);
    Try(1.5l);

    //  Test from 3 steps below 4 to 5 steps above 4.
    float x = 4, y = x;
    for (int i = 0; i < 3; ++i)
        x = std::nexttowardf(x, 0);
    for (int i = 0; i < 5; ++i)
        y = std::nexttowardf(y, INFINITY);
    std::cout << "There are " << Distance(y, x) << std::setprecision(8)
        << " representable numbers from " << x << " to " << y << ".\n";

}


问:
Xcode: project settings vs. target settings
I'm creating a static lib on Mac OS X for one of our customers, as well as a small cmd line app to test the static lib. The cmd line project has 2 extra library search paths, which meant I was linking to the Debug version in Release mode and just about went crazy, so I tried to get rid of these two paths, but I couldn't find where they were specified. I was looking in the project info, but it turns out they were specified in the target info.

I don't understand the distinction?! Why there are 2 sets of settings, which are essentially the same?! Can someone please enlighten me?

答:
Preface: you ship targets. Your end products are targets. Not projects. Think of a project as the umbrella above multiple targets.

For a more realistic example assume both Uber and Lyft were being developed by the your (umbrella) company.

The company has the following three environments:

Debug

QA

Release

The Debug and Release configs come out of the box with every new project you create. You can create as many additional configs as you want

This would require 3 configurations. To add a QA configuration follow the tutorial here

Did I apply this to the target or project?

I applied it to the project.

Ok so configs are only for projects and not for targets. Right?

Incorrect! It's confusing I know. You have to think of the project as a big container where you create your configs in there.

Then for each target (not project), for following tabs:

General, Resource Tags, Build rules, Info:

There is no difference between different configs

Signing and Capabilities tab:

You can switch between teams and sign it with a different team. This is useful if you want to sign your beta builds with your enterprise certificate but sign your Appstore build with app store certificate.

Build Settings tab:

For almost every variable in this section you can give a different value based on the config. Common Build Settings to customize are:

Architectures - 'Build Active Architecture only'

Build Options 'Debug Information Format'

Packaging

Set the plist you want per configuration.

Change the bundle identifier (Packaging >> Product Bundle Identifier). If you switch values for a field then in the plist you'll see as:

Signing

Code Signing identity

Code Signing Style (Manual or Automatic)

Development team

Provisioning Profile

Apple Clang - Optimization Level

If the values are different then the row's value would be

```<code><Multiple values>
</code>```

and you basically have to expand that value to see what value is given for debug and what value is given for Release or QA config.

If all the values are the same then you'll just see the value that is given to all of them. By default the values are the same.

Build Phases:
There's no out GUI way of switching based on configuration. However you can still do run certain commands based on the configuration. Example:

```<code>if [ "${CONFIGURATION}" = "Debug" ]; then
"${PODS_ROOT}/SwiftLint/swiftlint" autocorrect
"${PODS_ROOT}/SwiftLint/swiftlint"
fi
</code>```

Summary

Long story short, this allows you to have 2 different apps (targets) with the same code (project), in 3 different environments (dev, QA, release). You create the different environments using configurations.

To learn more on this I highly recommend you to read more about this in depth and understand what configuration files (xcconfig) is. It's much more simpler than you think. It's mainly a key value pair:

AppCoda - Using Xcode Configuration (.xcconfig) to Manage Different Build Settings

NSHipster - Xcode Build Configuration Files

Body:
Preface: you ship targets. Your end products are targets. Not projects. Think of a project as the umbrella above multiple targets.

For a more realistic example assume both Uber and Lyft were being developed by the your (umbrella) company.

The company has the following three environments:

Debug

QA

Release

The Debug and Release configs come out of the box with every new project you create. You can create as many additional configs as you want

This would require 3 configurations. To add a QA configuration follow the tutorial here

Did I apply this to the target or project?

I applied it to the project.

Ok so configs are only for projects and not for targets. Right?

Incorrect! It's confusing I know. You have to think of the project as a big container where you create your configs in there.

Then for each target (not project), for following tabs:

General, Resource Tags, Build rules, Info:

There is no difference between different configs

Signing and Capabilities tab:

You can switch between teams and sign it with a different team. This is useful if you want to sign your beta builds with your enterprise certificate but sign your Appstore build with app store certificate.

Build Settings tab:

For almost every variable in this section you can give a different value based on the config. Common Build Settings to customize are:

Architectures - 'Build Active Architecture only'

Build Options 'Debug Information Format'

Packaging

Set the plist you want per configuration.

Change the bundle identifier (Packaging >> Product Bundle Identifier). If you switch values for a field then in the plist you'll see as:

Signing

Code Signing identity

Code Signing Style (Manual or Automatic)

Development team

Provisioning Profile

Apple Clang - Optimization Level

If the values are different then the row's value would be

<Multiple values>

and you basically have to expand that value to see what value is given for debug and what value is given for Release or QA config.

If all the values are the same then you'll just see the value that is given to all of them. By default the values are the same.

Build Phases:
There's no out GUI way of switching based on configuration. However you can still do run certain commands based on the configuration. Example:

if [ "${CONFIGURATION}" = "Debug" ]; then
"${PODS_ROOT}/SwiftLint/swiftlint" autocorrect
"${PODS_ROOT}/SwiftLint/swiftlint"
fi

Summary

Long story short, this allows you to have 2 different apps (targets) with the same code (project), in 3 different environments (dev, QA, release). You create the different environments using configurations.

To learn more on this I highly recommend you to read more about this in depth and understand what configuration files (xcconfig) is. It's much more simpler than you think. It's mainly a key value pair:

AppCoda - Using Xcode Configuration (.xcconfig) to Manage Different Build Settings

NSHipster - Xcode Build Configuration Files


问:
Altair heatmap independent color map calculation per row
I am trying to plot a heatmap using altair. The idea is that the color mapping is applied independently to each of the rows and not across all the observations. Unfortunately, this is what I get so far.

As you can see on the graph, you can only see changes in one row, because this is the one with more cases. However, the idea is to apply the mapping for each row and not all together.

This is the code that I have so far:

data = pd.read_csv(
    "https://raw.githubusercontent.com/jlcoto/covid-peru-data/master"
    "/data/limpia/data_limpia_datos_siscovid_2020_05_26.csv",
    parse_dates=["fecha_resultado"],
    dtype={"ubigeo": "string"},
)

evol_departamento = (
    data.groupby(
        ["departamento", pd.Grouper(key="fecha_resultado", freq="D")]
    )[["uuid"]]
    .count()
    .rename(columns={"uuid": "num_casos"})
    .reset_index()
)

alt.Chart(evol_departamento).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    y="departamento:O",
    color=alt.Color("num_casos:Q"),
).resolve_scale(color="independent",)
```

I saw this reply about using resolve_scale, however it does not seem to do the trick.

答:
I was thinking of using row faceting with opacity for the cases and color for the departments. Although opacity lacks a bit of the contrast.

chart2 = alt.Chart(evol_departamento).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    color=alt.Color("departamento:N", legend=None),
    opacity = alt.Opacity("num_casos:Q", legend=None)
).properties(
    width=800, height=12
).facet(row='departamento:N'
).configure_facet(
    spacing= 0
).configure_view(
    stroke=None
).resolve_scale(
    opacity='independent'
)

chart2
```

I did not immediately found out how to rotate the labels with labelAngle.

chart

Body:
I am trying to plot a heatmap using altair. The idea is that the color mapping is applied independently to each of the rows and not across all the observations. Unfortunately, this is what I get so far.

As you can see on the graph, you can only see changes in one row, because this is the one with more cases. However, the idea is to apply the mapping for each row and not all together.

This is the code that I have so far:

data = pd.read_csv(
    "https://raw.githubusercontent.com/jlcoto/covid-peru-data/master"
    "/data/limpia/data_limpia_datos_siscovid_2020_05_26.csv",
    parse_dates=["fecha_resultado"],
    dtype={"ubigeo": "string"},
)

evol_departamento = (
    data.groupby(
        ["departamento", pd.Grouper(key="fecha_resultado", freq="D")]
    )[["uuid"]]
    .count()
    .rename(columns={"uuid": "num_casos"})
    .reset_index()
)

alt.Chart(evol_departamento).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    y="departamento:O",
    color=alt.Color("num_casos:Q"),
).resolve_scale(color="independent",)

I saw this reply about using resolve_scale, however it does not seem to do the trick.

Body:
I was thinking of using row faceting with opacity for the cases and color for the departments. Although opacity lacks a bit of the contrast.

chart2 = alt.Chart(evol_departamento).mark_rect().encode(
    x="monthdate(fecha_resultado)",
    color=alt.Color("departamento:N", legend=None),
    opacity = alt.Opacity("num_casos:Q", legend=None)
).properties(
    width=800, height=12
).facet(row='departamento:N'
).configure_facet(
    spacing= 0
).configure_view(
    stroke=None
).resolve_scale(
    opacity='independent'
)

chart2

I did not immediately found out how to rotate the labels with labelAngle.

chart


问:
Why in this example uploaded_by which is (uploaded_by_id) gets passed to DB as NULL?
why uploade_by_id is not set to user ID? want to map uploaded files to the user which uploads.

models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Profile(models.Model):
    CUSTOMER_TYPE = (
        ('Business', 'Business'),
        ('Personal', 'Personal'),
        )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    customer_type = models.CharField(max_length=10,choices=CUSTOMER_TYPE)
    phone = models.CharField(max_length=10, blank=True)

    def __str__(self):
        return self.user.username

class Document(models.Model):
    uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE)
    document_name = models.FileField()
    date_created = models.DateTimeField(auto_now_add=True)
</code>```

答:
You set the user of the object in the view. Models are request-unaware. So you should rewrite the view to:

```<code>@login_required
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            <b>form.instance.uploaded_by = request.user</b>
            form.save()
            messages.success(request, 'File successfully uploaded')
            return redirect('profile')
    else:
        form = UploadFileForm()
    context = {'form': form}
    return render(request, 'users/upload.html', context)</code>```

In the form you exclude the uploaded_by field:

```<code>class UploadFileFOrm(forms.ModelForm):
    class Meta:
        model = Document
        exclude = ['uploaded_by']</code>```

Body:
why uploade_by_id is not set to user ID? want to map uploaded files to the user which uploads.

models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class Profile(models.Model):
    CUSTOMER_TYPE = (
        ('Business', 'Business'),
        ('Personal', 'Personal'),
        )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    customer_type = models.CharField(max_length=10,choices=CUSTOMER_TYPE)
    phone = models.CharField(max_length=10, blank=True)

    def __str__(self):
        return self.user.username

class Document(models.Model):
    uploaded_by = models.ForeignKey(User, on_delete=models.CASCADE)
    document_name = models.FileField()
    date_created = models.DateTimeField(auto_now_add=True)

Body:
You set the user of the object in the view. Models are request-unaware. So you should rewrite the view to:

@login_required
def upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.uploaded_by = request.user
            form.save()
            messages.success(request, 'File successfully uploaded')
            return redirect('profile')
    else:
        form = UploadFileForm()
    context = {'form': form}
    return render(request, 'users/upload.html', context)

In the form you exclude the uploaded_by field:

class UploadFileFOrm(forms.ModelForm):
    class Meta:
        model = Document
        exclude = ['uploaded_by']