问:
Not able to perform Deep Insert operation for API_PRODUCT_SRV Standard WhiteListed API using S/4 Hana Cloud SDK
I have completed read and update operations on API_PRODUCT_SRV Service.

Now while doing deep insert on API_PRODUCT_SRV (Product Entity-which has many associations) I am getting the following error.

```<code>“errordetails”: [

{
“code”: “API_PRD_MSG/004”,
“message”: “Provide atleast one description for the product.”,
“propertyref”: “”,
“severity”: “error”,
“target”: “”
}
]
</code>```

I found this deep dive blog

https://blogs.sap.com/2017/12/07/step-20-with-s4hana-cloud-sdk-create-and-deep-insert-with-the-virtual-data-model-for-odata/comment-page-1/#comment-453020

which explains the deep insert using servlets.(i.e Using HttpServletReq) which provides the rest service.

But I am using the CreateRequest class from SAP Cloud Application Programming Model which generates odata service, so that I cannot use the similar code which is presented in the blog.

I have added the code and the payload for your perusal.

Create Operation code

```<code>@Create(serviceName = "ProductService", entity = "Products")
    public CreateResponse create(CreateRequest req) throws ODataException {
        Product toCreate = new ModelMapper().map(req.getMapData(), Product.class);
        Product created = new DefaultProductMasterService().createProduct(toCreate)
                .execute(new ErpConfigContext("K4XS4SDKDest"));
        return CreateResponse.setSuccess().setData(created).response();
    }
</code>```

Payload being used:

```<code>{
  "Product" : "BALL",
    "ProductType" : "ZHLB",
    "CrossPlantStatus" : "",
    "CrossPlantStatusValidityDate" : null,
    "CreationDate" : "\/Date(1499731200000)\/",
    "CreatedByUser" : "11279380",
    "LastChangeDate" : "\/Date(1550448000000)\/",
    "LastChangedByUser" : "HWV87616",
    "IsMarkedForDeletion" : false,
    "ProductOldID" : "",
    "GrossWeight" : "0.000",
    "PurchaseOrderQuantityUnit" : "",
    "SourceOfSupply" : "",
    "WeightUnit" : "KG",
    "NetWeight" : "0.000",
    "CountryOfOrigin" : "",
    "CompetitorID" : "",
    "ProductGroup" : "01",
    "BaseUnit" : "EA",
    "ItemCategoryGroup" : "",
    "ProductHierarchy" : "",
    "Division" : "",
    "VarblPurOrdUnitIsActive" : "",
    "VolumeUnit" : "",
    "MaterialVolume" : "0.000",
    "ANPCode" : "0",
    "Brand" : "",
    "ProcurementRule" : "",
    "ValidityStartDate" : null,
    "LowLevelCode" : "",
    "ProdNoInGenProdInPrepackProd" : "",
    "SerialIdentifierAssgmtProfile" : "",
    "SizeOrDimensionText" : "",
    "IndustryStandardName" : "",
    "ProductStandardID" : "",
    "InternationalArticleNumberCat" : "",
    "ProductIsConfigurable" : false,
    "IsBatchManagementRequired" : false,
    "ExternalProductGroup" : "",
    "CrossPlantConfigurableProduct" : "",
    "SerialNoExplicitnessLevel" : "",
    "ManufacturerPartProfile" : "",
    "ChangeNumber" : "",
    "MaterialRevisionLevel" : "",
    "HandlingIndicator" : "",
    "WarehouseProductGroup" : "",
    "WarehouseStorageCondition" : "",
    "StandardHandlingUnitType" : "",
    "SerialNumberProfile" : "",
    "AdjustmentProfile" : "",
    "PreferredUnitOfMeasure" : "",
    "IsPilferable" : false,
    "IsRelevantForHzdsSubstances" : false,
    "QuarantinePeriod" : "0",
    "TimeUnitForQuarantinePeriod" : "",
    "QualityInspectionGroup" : "",
    "AuthorizationGroup" : "",
    "HandlingUnitType" : "",
    "HasVariableTareWeight" : false,
    "MaximumPackagingLength" : "0.000",
    "MaximumPackagingWidth" : "0.000",
    "MaximumPackagingHeight" : "0.000",
  "to_Description": {
    "results": [
     {
        "Product" : "BALL",
        "Language" : "EN",
        "ProductDescription" : "Pipes for machines"
      }
    ]
  }
}
</code>```

Can u please help me how shall I modify my code to make deep insert with SAP S/4HANA Cloud SDK work while using SAP Cloud Application Programming Model (CreateRequest class)?

Log file:

```<code>Product(super=VdmObject(customFields={}, changedOriginalFields={LowLevelCode=null, ProductGroup=null, SizeOrDimensionText=null, CreatedByUser=null, CountryOfOrigin=null, Product=null, ProductStandardID=null, IsPilferable=null, VolumeUnit=null, WarehouseProductGroup=null, WarehouseStorageCondition=null, MaterialVolume=null, ManufacturerPartProfile=null, CrossPlantStatus=null, TimeUnitForQuarantinePeriod=null, GrossWeight=null, InternationalArticleNumberCat=null, SourceOfSupply=null, ProductType=null, ItemCategoryGroup=null, ProcurementRule=null, BaseUnit=null, ProductOldID=null, VarblPurOrdUnitIsActive=null, LastChangedByUser=null, Brand=null, MaximumPackagingWidth=null, QuarantinePeriod=null, PurchaseOrderQuantityUnit=null, ProductHierarchy=null, AuthorizationGroup=null, StandardHandlingUnitType=null, MaterialRevisionLevel=null, ExternalProductGroup=null, CrossPlantConfigurableProduct=null, MaximumPackagingLength=null, HasVariableTareWeight=null, ANPCode=null, ProdNoInGenProdInPrepackProd=null, WeightUnit=null, IsMarkedForDeletion=null, CompetitorID=null, QualityInspectionGroup=null, IsBatchManagementRequired=null, IsRelevantForHzdsSubstances=null, Division=null, SerialIdentifierAssgmtProfile=null, AdjustmentProfile=null, PreferredUnitOfMeasure=null, SerialNoExplicitnessLevel=null, HandlingIndicator=null, HandlingUnitType=null, NetWeight=null, ProductIsConfigurable=null, IndustryStandardName=null, SerialNumberProfile=null, ChangeNumber=null, MaximumPackagingHeight=null}), product=BELL, productType=ZHLB, crossPlantStatus=, crossPlantStatusValidityDate=null, creationDate=null, createdByUser=11279380, lastChangeDate=null, lastChangedByUser=HWV87616, lastChangeDateTime=null, isMarkedForDeletion=false, productOldID=, grossWeight=0.000, purchaseOrderQuantityUnit=, sourceOfSupply=, weightUnit=KG, netWeight=0.000, countryOfOrigin=, competitorID=, productGroup=01, baseUnit=EA, itemCategoryGroup=, productHierarchy=, division=, varblPurOrdUnitIsActive=, volumeUnit=, materialVolume=0.000, aNPCode=0, brand=, procurementRule=, validityStartDate=null, lowLevelCode=, prodNoInGenProdInPrepackProd=, serialIdentifierAssgmtProfile=, sizeOrDimensionText=, industryStandardName=, productStandardID=, internationalArticleNumberCat=, productIsConfigurable=false, isBatchManagementRequired=false, externalProductGroup=, crossPlantConfigurableProduct=, serialNoExplicitnessLevel=, productManufacturerNumber=null, manufacturerNumber=null, manufacturerPartProfile=, changeNumber=, materialRevisionLevel=, handlingIndicator=, warehouseProductGroup=, warehouseStorageCondition=, standardHandlingUnitType=, serialNumberProfile=, adjustmentProfile=, preferredUnitOfMeasure=, isPilferable=false, isRelevantForHzdsSubstances=false, quarantinePeriod=0, timeUnitForQuarantinePeriod=, qualityInspectionGroup=, authorizationGroup=, handlingUnitType=, hasVariableTareWeight=false, maximumPackagingLength=0.000, maximumPackagingWidth=0.000, maximumPackagingHeight=0.000, erpConfigContext=null, toDescription=null, toPlant=null, toProductBasicText=null, toProductInspectionText=null, toProductProcurement=null, toProductPurchaseText=null, toProductQualityMgmt=null, toProductSales=null, toProductSalesTax=null, toProductStorage=null, toProductUnitsOfMeasure=null, toSalesDelivery=null)
{ "written_at":"2019-03-11T03:56:27.923Z","written_ts":918343802814688,"component_id":"e8c99eff-1a4e-4266-ba2a-fc099399100c","component_name":"FNpy7mXtvln0dnT1-FinalTestApp-srv","DCComponent":"","organization_name":"-","component_type":"application","space_name":"dev","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"a78252bf-72bf-479c-b761-8260de0c776e","Application":"FNpy7mXtvln0dnT1-FinalTestApp-srv","container_id":"10.0.138.113","type":"log","logger":"com.sap.cloud.sdk.service.prov.api.util.ProcessorHelper","thread":"http-nio-0.0.0.0-3000-exec-7","level":"ERROR","categories":[],"msg":"The endpoint responded with HTTP error code 400.\nProvide atleast one description for the product.\nFull error message: \n{\n  \"error\": {\n    \"code\": \"API_PRD_MSG/004\",\n    \"message\": {\n      \"lang\": \"en\",\n      \"value\": \"Provide atleast one description for the product.\"\n    },\n    \"innererror\": {\n      \"application\": {\n        \"component_id\": \"LO-MD-MM\",\n        \"service_namespace\": \"/SAP/\",\n        \"service_id\": \"API_PRODUCT_SRV\",\n        \"service_version\": \"0001\"\n      },\n      \"transactionid\": \"C16DD240C7520010E005C7E648BC12F5\",\n      \"timestamp\": \"20190311035627.5989630\",\n      \"Error_Resolution\": {\n        \"SAP_Transaction\": \"For backend administrators: run transaction /IWFND/ERROR_LOG on SAP Gateway hub system and search for entries with the timestamp above for more details\",\n        \"SAP_Note\": \"See SAP Note 1797736 for error analysis (https://service.sap.com/sap/support/notes/1797736)\"\n      },\n      \"errordetails\": [\n        {\n          \"code\": \"API_PRD_MSG/004\",\n          \"message\": \"Provide atleast one description for the product.\",\n          \"propertyref\": \"\",\n          \"severity\": \"error\",\n          \"target\": \"\"\n        }\n      ]\n    }\n  }\n}","stacktrace":["java.lang.reflect.InvocationTargetException","\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)","\tat
</code>```

my-service.cds

```<code>    using API_PRODUCT_SRV  from '../srv/external/csn/API_PRODUCT_SRV.json';
    service ProductService {

      entity Products as Projection on API_PRODUCT_SRV.A_ProductType {
       key Product,
       ProductType,
       CreationDate,
       CrossPlantStatus,
       CrossPlantStatusValidityDate,
        CreatedByUser,
        LastChangeDate,
        LastChangedByUser,
        IsMarkedForDeletion,
        ProductOldID,
        GrossWeight,
        PurchaseOrderQuantityUnit,
        SourceOfSupply,
        WeightUnit,
        NetWeight,
        CountryOfOrigin,
        CompetitorID,
        ProductGroup,
        BaseUnit,
        ItemCategoryGroup,
        ProductHierarchy,
        Division,
        VarblPurOrdUnitIsActive,
        VolumeUnit,
        MaterialVolume,
        ANPCode,
        Brand,
        ProcurementRule,
        ValidityStartDate,
        LowLevelCode,
        ProdNoInGenProdInPrepackProd,
        SerialIdentifierAssgmtProfile,
        SizeOrDimensionText,
        IndustryStandardName,
        ProductStandardID,
        InternationalArticleNumberCat,
        ProductIsConfigurable,
        IsBatchManagementRequired,
        ExternalProductGroup,
        CrossPlantConfigurableProduct,
        SerialNoExplicitnessLevel,
        ProductManufacturerNumber,
        ManufacturerPartProfile,
        ChangeNumber,
        MaterialRevisionLevel,
        HandlingIndicator,
        WarehouseProductGroup,
        WarehouseStorageCondition,
        StandardHandlingUnitType,
        SerialNumberProfile,
        AdjustmentProfile,
        PreferredUnitOfMeasure,
       IsPilferable,
        IsRelevantForHzdsSubstances,
        QuarantinePeriod,
        TimeUnitForQuarantinePeriod,
        QualityInspectionGroup,
        AuthorizationGroup,
        HandlingUnitType,
        HasVariableTareWeight,
        MaximumPackagingLength,
        MaximumPackagingWidth,
        MaximumPackagingHeight,
      to_Description
      }
 entity A_ProductDescriptionType as Projection on API_PRODUCT_SRV.A_ProductDescriptionType
  {
              key  Product,
             key   Language,
                ProductDescription
}
}
</code>```

Can u please tell how to add associations in it?
my-service.cds

```<code>using API_BUSINESS_PARTNER as bp from './external/csn/API_BUSINESS_PARTNER';

service CrudService{

 @cds.persistence.skip
 Entity BusinessPartner as projection on bp.A_BusinessPartnerType{
   BusinessPartner,
   LastName,
   FirstName,
   BusinessPartnerCategory
  };
}
</code>```

Warm regards,

Meenakshi

答:
The problem is your JSON request payload:

```<code>{
  "Product" : "BALL",
  ...
  "to_Description": {
    "results": [
     {
        "Product" : "BALL",
        "Language" : "EN",
        "ProductDescription" : "Pipes for machines"
      }
    ]
  }
}
</code>```

to_Description is not expected to be an object. Instead it should be an array:

```<code>{
  "Product" : "BALL",
  ...
  "to_Description": [
     {
        "Product" : "BALL",
        "Language" : "EN",
        "ProductDescription" : "Pipes for machines"
     }
  ]
}
</code>```

Body:
I have completed read and update operations on API_PRODUCT_SRV Service.

Now while doing deep insert on API_PRODUCT_SRV (Product Entity-which has many associations) I am getting the following error.

“errordetails”: [

{
“code”: “API_PRD_MSG/004”,
“message”: “Provide atleast one description for the product.”,
“propertyref”: “”,
“severity”: “error”,
“target”: “”
}
]

I found this deep dive blog

https://blogs.sap.com/2017/12/07/step-20-with-s4hana-cloud-sdk-create-and-deep-insert-with-the-virtual-data-model-for-odata/comment-page-1/#comment-453020

which explains the deep insert using servlets.(i.e Using HttpServletReq) which provides the rest service.

But I am using the CreateRequest class from SAP Cloud Application Programming Model which generates odata service, so that I cannot use the similar code which is presented in the blog.

I have added the code and the payload for your perusal.

Create Operation code

@Create(serviceName = "ProductService", entity = "Products")
    public CreateResponse create(CreateRequest req) throws ODataException {
        Product toCreate = new ModelMapper().map(req.getMapData(), Product.class);
        Product created = new DefaultProductMasterService().createProduct(toCreate)
                .execute(new ErpConfigContext("K4XS4SDKDest"));
        return CreateResponse.setSuccess().setData(created).response();
    }

Payload being used:

{
  "Product" : "BALL",
    "ProductType" : "ZHLB",
    "CrossPlantStatus" : "",
    "CrossPlantStatusValidityDate" : null,
    "CreationDate" : "\/Date(1499731200000)\/",
    "CreatedByUser" : "11279380",
    "LastChangeDate" : "\/Date(1550448000000)\/",
    "LastChangedByUser" : "HWV87616",
    "IsMarkedForDeletion" : false,
    "ProductOldID" : "",
    "GrossWeight" : "0.000",
    "PurchaseOrderQuantityUnit" : "",
    "SourceOfSupply" : "",
    "WeightUnit" : "KG",
    "NetWeight" : "0.000",
    "CountryOfOrigin" : "",
    "CompetitorID" : "",
    "ProductGroup" : "01",
    "BaseUnit" : "EA",
    "ItemCategoryGroup" : "",
    "ProductHierarchy" : "",
    "Division" : "",
    "VarblPurOrdUnitIsActive" : "",
    "VolumeUnit" : "",
    "MaterialVolume" : "0.000",
    "ANPCode" : "0",
    "Brand" : "",
    "ProcurementRule" : "",
    "ValidityStartDate" : null,
    "LowLevelCode" : "",
    "ProdNoInGenProdInPrepackProd" : "",
    "SerialIdentifierAssgmtProfile" : "",
    "SizeOrDimensionText" : "",
    "IndustryStandardName" : "",
    "ProductStandardID" : "",
    "InternationalArticleNumberCat" : "",
    "ProductIsConfigurable" : false,
    "IsBatchManagementRequired" : false,
    "ExternalProductGroup" : "",
    "CrossPlantConfigurableProduct" : "",
    "SerialNoExplicitnessLevel" : "",
    "ManufacturerPartProfile" : "",
    "ChangeNumber" : "",
    "MaterialRevisionLevel" : "",
    "HandlingIndicator" : "",
    "WarehouseProductGroup" : "",
    "WarehouseStorageCondition" : "",
    "StandardHandlingUnitType" : "",
    "SerialNumberProfile" : "",
    "AdjustmentProfile" : "",
    "PreferredUnitOfMeasure" : "",
    "IsPilferable" : false,
    "IsRelevantForHzdsSubstances" : false,
    "QuarantinePeriod" : "0",
    "TimeUnitForQuarantinePeriod" : "",
    "QualityInspectionGroup" : "",
    "AuthorizationGroup" : "",
    "HandlingUnitType" : "",
    "HasVariableTareWeight" : false,
    "MaximumPackagingLength" : "0.000",
    "MaximumPackagingWidth" : "0.000",
    "MaximumPackagingHeight" : "0.000",
  "to_Description": {
    "results": [
     {
        "Product" : "BALL",
        "Language" : "EN",
        "ProductDescription" : "Pipes for machines"
      }
    ]
  }
}

Can u please help me how shall I modify my code to make deep insert with SAP S/4HANA Cloud SDK work while using SAP Cloud Application Programming Model (CreateRequest class)?

Log file:

Product(super=VdmObject(customFields={}, changedOriginalFields={LowLevelCode=null, ProductGroup=null, SizeOrDimensionText=null, CreatedByUser=null, CountryOfOrigin=null, Product=null, ProductStandardID=null, IsPilferable=null, VolumeUnit=null, WarehouseProductGroup=null, WarehouseStorageCondition=null, MaterialVolume=null, ManufacturerPartProfile=null, CrossPlantStatus=null, TimeUnitForQuarantinePeriod=null, GrossWeight=null, InternationalArticleNumberCat=null, SourceOfSupply=null, ProductType=null, ItemCategoryGroup=null, ProcurementRule=null, BaseUnit=null, ProductOldID=null, VarblPurOrdUnitIsActive=null, LastChangedByUser=null, Brand=null, MaximumPackagingWidth=null, QuarantinePeriod=null, PurchaseOrderQuantityUnit=null, ProductHierarchy=null, AuthorizationGroup=null, StandardHandlingUnitType=null, MaterialRevisionLevel=null, ExternalProductGroup=null, CrossPlantConfigurableProduct=null, MaximumPackagingLength=null, HasVariableTareWeight=null, ANPCode=null, ProdNoInGenProdInPrepackProd=null, WeightUnit=null, IsMarkedForDeletion=null, CompetitorID=null, QualityInspectionGroup=null, IsBatchManagementRequired=null, IsRelevantForHzdsSubstances=null, Division=null, SerialIdentifierAssgmtProfile=null, AdjustmentProfile=null, PreferredUnitOfMeasure=null, SerialNoExplicitnessLevel=null, HandlingIndicator=null, HandlingUnitType=null, NetWeight=null, ProductIsConfigurable=null, IndustryStandardName=null, SerialNumberProfile=null, ChangeNumber=null, MaximumPackagingHeight=null}), product=BELL, productType=ZHLB, crossPlantStatus=, crossPlantStatusValidityDate=null, creationDate=null, createdByUser=11279380, lastChangeDate=null, lastChangedByUser=HWV87616, lastChangeDateTime=null, isMarkedForDeletion=false, productOldID=, grossWeight=0.000, purchaseOrderQuantityUnit=, sourceOfSupply=, weightUnit=KG, netWeight=0.000, countryOfOrigin=, competitorID=, productGroup=01, baseUnit=EA, itemCategoryGroup=, productHierarchy=, division=, varblPurOrdUnitIsActive=, volumeUnit=, materialVolume=0.000, aNPCode=0, brand=, procurementRule=, validityStartDate=null, lowLevelCode=, prodNoInGenProdInPrepackProd=, serialIdentifierAssgmtProfile=, sizeOrDimensionText=, industryStandardName=, productStandardID=, internationalArticleNumberCat=, productIsConfigurable=false, isBatchManagementRequired=false, externalProductGroup=, crossPlantConfigurableProduct=, serialNoExplicitnessLevel=, productManufacturerNumber=null, manufacturerNumber=null, manufacturerPartProfile=, changeNumber=, materialRevisionLevel=, handlingIndicator=, warehouseProductGroup=, warehouseStorageCondition=, standardHandlingUnitType=, serialNumberProfile=, adjustmentProfile=, preferredUnitOfMeasure=, isPilferable=false, isRelevantForHzdsSubstances=false, quarantinePeriod=0, timeUnitForQuarantinePeriod=, qualityInspectionGroup=, authorizationGroup=, handlingUnitType=, hasVariableTareWeight=false, maximumPackagingLength=0.000, maximumPackagingWidth=0.000, maximumPackagingHeight=0.000, erpConfigContext=null, toDescription=null, toPlant=null, toProductBasicText=null, toProductInspectionText=null, toProductProcurement=null, toProductPurchaseText=null, toProductQualityMgmt=null, toProductSales=null, toProductSalesTax=null, toProductStorage=null, toProductUnitsOfMeasure=null, toSalesDelivery=null)
{ "written_at":"2019-03-11T03:56:27.923Z","written_ts":918343802814688,"component_id":"e8c99eff-1a4e-4266-ba2a-fc099399100c","component_name":"FNpy7mXtvln0dnT1-FinalTestApp-srv","DCComponent":"","organization_name":"-","component_type":"application","space_name":"dev","component_instance":"0","organization_id":"-","correlation_id":"-","CSNComponent":"","space_id":"a78252bf-72bf-479c-b761-8260de0c776e","Application":"FNpy7mXtvln0dnT1-FinalTestApp-srv","container_id":"10.0.138.113","type":"log","logger":"com.sap.cloud.sdk.service.prov.api.util.ProcessorHelper","thread":"http-nio-0.0.0.0-3000-exec-7","level":"ERROR","categories":[],"msg":"The endpoint responded with HTTP error code 400.\nProvide atleast one description for the product.\nFull error message: \n{\n  \"error\": {\n    \"code\": \"API_PRD_MSG/004\",\n    \"message\": {\n      \"lang\": \"en\",\n      \"value\": \"Provide atleast one description for the product.\"\n    },\n    \"innererror\": {\n      \"application\": {\n        \"component_id\": \"LO-MD-MM\",\n        \"service_namespace\": \"/SAP/\",\n        \"service_id\": \"API_PRODUCT_SRV\",\n        \"service_version\": \"0001\"\n      },\n      \"transactionid\": \"C16DD240C7520010E005C7E648BC12F5\",\n      \"timestamp\": \"20190311035627.5989630\",\n      \"Error_Resolution\": {\n        \"SAP_Transaction\": \"For backend administrators: run transaction /IWFND/ERROR_LOG on SAP Gateway hub system and search for entries with the timestamp above for more details\",\n        \"SAP_Note\": \"See SAP Note 1797736 for error analysis (https://service.sap.com/sap/support/notes/1797736)\"\n      },\n      \"errordetails\": [\n        {\n          \"code\": \"API_PRD_MSG/004\",\n          \"message\": \"Provide atleast one description for the product.\",\n          \"propertyref\": \"\",\n          \"severity\": \"error\",\n          \"target\": \"\"\n        }\n      ]\n    }\n  }\n}","stacktrace":["java.lang.reflect.InvocationTargetException","\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)","\tat

my-service.cds

    using API_PRODUCT_SRV  from '../srv/external/csn/API_PRODUCT_SRV.json';
    service ProductService {

      entity Products as Projection on API_PRODUCT_SRV.A_ProductType {
       key Product,
       ProductType,
       CreationDate,
       CrossPlantStatus,
       CrossPlantStatusValidityDate,
        CreatedByUser,
        LastChangeDate,
        LastChangedByUser,
        IsMarkedForDeletion,
        ProductOldID,
        GrossWeight,
        PurchaseOrderQuantityUnit,
        SourceOfSupply,
        WeightUnit,
        NetWeight,
        CountryOfOrigin,
        CompetitorID,
        ProductGroup,
        BaseUnit,
        ItemCategoryGroup,
        ProductHierarchy,
        Division,
        VarblPurOrdUnitIsActive,
        VolumeUnit,
        MaterialVolume,
        ANPCode,
        Brand,
        ProcurementRule,
        ValidityStartDate,
        LowLevelCode,
        ProdNoInGenProdInPrepackProd,
        SerialIdentifierAssgmtProfile,
        SizeOrDimensionText,
        IndustryStandardName,
        ProductStandardID,
        InternationalArticleNumberCat,
        ProductIsConfigurable,
        IsBatchManagementRequired,
        ExternalProductGroup,
        CrossPlantConfigurableProduct,
        SerialNoExplicitnessLevel,
        ProductManufacturerNumber,
        ManufacturerPartProfile,
        ChangeNumber,
        MaterialRevisionLevel,
        HandlingIndicator,
        WarehouseProductGroup,
        WarehouseStorageCondition,
        StandardHandlingUnitType,
        SerialNumberProfile,
        AdjustmentProfile,
        PreferredUnitOfMeasure,
       IsPilferable,
        IsRelevantForHzdsSubstances,
        QuarantinePeriod,
        TimeUnitForQuarantinePeriod,
        QualityInspectionGroup,
        AuthorizationGroup,
        HandlingUnitType,
        HasVariableTareWeight,
        MaximumPackagingLength,
        MaximumPackagingWidth,
        MaximumPackagingHeight,
      to_Description
      }
 entity A_ProductDescriptionType as Projection on API_PRODUCT_SRV.A_ProductDescriptionType
  {
              key  Product,
             key   Language,
                ProductDescription
}
}

Can u please tell how to add associations in it?
my-service.cds

using API_BUSINESS_PARTNER as bp from './external/csn/API_BUSINESS_PARTNER';

service CrudService{

 @cds.persistence.skip
 Entity BusinessPartner as projection on bp.A_BusinessPartnerType{
   BusinessPartner,
   LastName,
   FirstName,
   BusinessPartnerCategory
  };
}

Warm regards,

Meenakshi

Body:
The problem is your JSON request payload:

{
  "Product" : "BALL",
  ...
  "to_Description": {
    "results": [
     {
        "Product" : "BALL",
        "Language" : "EN",
        "ProductDescription" : "Pipes for machines"
      }
    ]
  }
}

to_Description is not expected to be an object. Instead it should be an array:

{
  "Product" : "BALL",
  ...
  "to_Description": [
     {
        "Product" : "BALL",
        "Language" : "EN",
        "ProductDescription" : "Pipes for machines"
     }
  ]
}


来源: stackexchange

问:
How to initialize HashSet values by construction?
I need to create a Set with initial values.

```<code>Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
</code>```

Is there a way to do this in one line of code? For instance, it's useful for a final static field.

答:
Combining answer by Michael Berdyshev with Generics and using constructor with initialCapacity, comparing with Arrays.asList variant:

```<code>  import java.util.Collections;
  import java.util.HashSet;
  import java.util.Set;

  @SafeVarargs
  public static <T> Set<T> buildSetModif(final T... values) {
    final Set<T> modifiableSet = new HashSet<T>(values.length);
    Collections.addAll(modifiableSet, values);
    return modifiableSet;
  }

  @SafeVarargs
  public static <T> Set<T> buildSetModifTypeSafe(final T... values) {
    return new HashSet<T>(Arrays.asList(values));
  }

  @SafeVarargs
  public static <T> Set<T> buildeSetUnmodif(final T... values) {
    return Collections.unmodifiableSet(buildSetModifTypeSafe(values));
    // Or use Set.of("a", "b", "c") if you use Java 9
  }
</code>```

This is good if you pass a few values for init, for anything large
use other methods

If you accidentally mix types with buildSetModif the resulting T will
be ? extends Object, which is probably not what you want, this cannot happen with the buildSetModifTypeSafe variant, meaning that  buildSetModifTypeSafe(1, 2, "a"); will not compile

ContentLicense: CC BY-SA 4.0

Body:
I need to create a Set with initial values.

Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");

Is there a way to do this in one line of code? For instance, it's useful for a final static field.

Body:
Combining answer by Michael Berdyshev with Generics and using constructor with initialCapacity, comparing with Arrays.asList variant:

  import java.util.Collections;
  import java.util.HashSet;
  import java.util.Set;

  @SafeVarargs
  public static <T> Set<T> buildSetModif(final T... values) {
    final Set<T> modifiableSet = new HashSet<T>(values.length);
    Collections.addAll(modifiableSet, values);
    return modifiableSet;
  }

  @SafeVarargs
  public static <T> Set<T> buildSetModifTypeSafe(final T... values) {
    return new HashSet<T>(Arrays.asList(values));
  }

  @SafeVarargs
  public static <T> Set<T> buildeSetUnmodif(final T... values) {
    return Collections.unmodifiableSet(buildSetModifTypeSafe(values));
    // Or use Set.of("a", "b", "c") if you use Java 9
  }

This is good if you pass a few values for init, for anything large
use other methods

If you accidentally mix types with buildSetModif the resulting T will
be ? extends Object, which is probably not what you want, this cannot happen with the buildSetModifTypeSafe variant, meaning that  buildSetModifTypeSafe(1, 2, "a"); will not compile


问:
How to call Java Executable file with arguments in windows service using c#
I have java executable file that has to be started automatically on system reboot with out login, we are planing to call that java excutable file with some arguments from windows service.

Can some one suggest me about the how can we achieve it.

Earlier i have used bat file to start executable file, batch file has to start manually(to avoid this we are going for winservice option).

java -jar -Djdbc.driver="<>" -DDB_URL="<>"

Thanks in advance.

答:
You can try Process.Start()

See Microsoft-docs


问:
Generating i18n translation file for multicomponent Angular application
I have an application developed with several components (.ts and .html). When I try to generate Xlif translation file with ng xi18n, only one component seems to be scanned, and translation sources for all other components are not in the xlif generated file.

Any idea or suggestions? Or is this a limitation of Angular CLI?

Many thanks

答: Answering my own question:  I used a script to insert i18n in other files but there was a typo (i18 only). Once corrected, translation sources were generated for all components of the project.</p>


问:
Unable to load Action class while deploying struts2.5 war file on weblogic 10.3.6
Unable to load Action error while deploying struts2 war file on weblogic 10.3.6

The above question is very similar to the issue I'm facing but there is no solution provided.
I have an application in struts2.5 which I have exported to a *.war file and trying to deploy it to weblogic 10.3.6(running on java7).
During deployment I get an error that the Action class is not found (when I can see it present in the war file's WEB-INF/classes).

As mentioned by user3898783 in above link- "What weblogic does during
WAR deployment(obviously it internally explodes) it puts all the files reside in web-inf/classes folder into jar called _wl_cls_gen.jar file and copies into web-inf/lib directory under domain stage folder." - similar is my problem.
I am currently using the wls:prefer-web-inf-classes"true" /wls:prefer-web-inf-classes configuration in my weblogic.xml file which hasn't really solved my problem.

Weblogic.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
     <wls:container-descriptor>
        <wls:prefer-web-inf-classes>true</wls:prefer-web-inf-classes>
     </wls:container-descriptor>

    <wls:session-descriptor>
        <wls:cookies-enabled>true</wls:cookies-enabled>
     </wls:session-descriptor>

</wls:weblogic-web-app>

<May 23, 2019 1:00:02 AM CDT> <Error> <HTTP> <BEA-101165> <Could not load user defined filter in web.xml: org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.
Unable to load configuration. - action - zip:/apps/bea/wls103/user_projects/domains/mydomain/servers/mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/lib/_wl_cls_gen.jar!/struts.xml:16:97
        at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:509)
        at org.apache.struts2.dispatcher.InitOperations.initDispatcher(InitOperations.java:73)
        at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:61)
        at weblogic.servlet.internal.FilterManager$FilterInitAction.run(FilterManager.java:343)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        Truncated. see log file for complete stacktrace
Caused By: Unable to load configuration. - action - zip:/apps/bea/wls103/user_projects/domains/mydomain/servers/mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/lib/_wl_cls_gen.jar!/struts.xml:16:97
        at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69)
        at org.apache.struts2.dispatcher.Dispatcher.getContainer(Dispatcher.java:957)
        at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:463)
        at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:496)
        at org.apache.struts2.dispatcher.InitOperations.initDispatcher(InitOperations.java:73)
        Truncated. see log file for complete stacktrace
Caused By: Action class [com.myapp.struts.actions.LoginAction] not found - action - zip:/apps/bea/wls103/user_projects/domains/mydomain/servers/mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/lib/_wl_cls_gen.jar!/struts.xml:16:97
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:508)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:457)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:572)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:326)
        at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:108)
        Truncated. see log file for complete stacktrace
>
</code>```

I checked my struts.xml(struts.xml:16:97) - and it is pointing to the LoginAction action class mapping, which obviously its not able to find under the weblogic "../domains/../mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/classes"

Thanking you in anticipation

答:
Finally I was able to figure this out. The culprit has been the compiler compliance level in my eclipse project.  Although I was using jdk1.7 in my project buildpath, I should have also checked for the projects compiler compliance version in Eclipse which was 1.8 (proj right click> JavaCompiler> I set it to 1.7).
Also, I was using javax.servlet-api-3.0.1.jar - I switched to servlet2.5 as I read somewhere that weblogic10.3.x is only compliant upto servlet2.5. </p>

<p>I hope this helps someone looking for a solution to similar problem. </p>

Body:
Unable to load Action error while deploying struts2 war file on weblogic 10.3.6

The above question is very similar to the issue I'm facing but there is no solution provided.
I have an application in struts2.5 which I have exported to a *.war file and trying to deploy it to weblogic 10.3.6(running on java7).
During deployment I get an error that the Action class is not found (when I can see it present in the war file's WEB-INF/classes).

As mentioned by user3898783 in above link- "What weblogic does during
WAR deployment(obviously it internally explodes) it puts all the files reside in web-inf/classes folder into jar called _wl_cls_gen.jar file and copies into web-inf/lib directory under domain stage folder." - similar is my problem.
I am currently using the wls:prefer-web-inf-classes"true" /wls:prefer-web-inf-classes configuration in my weblogic.xml file which hasn't really solved my problem.

Weblogic.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.4/weblogic-web-app.xsd">
     <wls:container-descriptor>
        <wls:prefer-web-inf-classes>true</wls:prefer-web-inf-classes>
     </wls:container-descriptor>

    <wls:session-descriptor>
        <wls:cookies-enabled>true</wls:cookies-enabled>
     </wls:session-descriptor>

</wls:weblogic-web-app>

<May 23, 2019 1:00:02 AM CDT> <Error> <HTTP> <BEA-101165> <Could not load user defined filter in web.xml: org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.
Unable to load configuration. - action - zip:/apps/bea/wls103/user_projects/domains/mydomain/servers/mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/lib/_wl_cls_gen.jar!/struts.xml:16:97
        at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:509)
        at org.apache.struts2.dispatcher.InitOperations.initDispatcher(InitOperations.java:73)
        at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:61)
        at weblogic.servlet.internal.FilterManager$FilterInitAction.run(FilterManager.java:343)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        Truncated. see log file for complete stacktrace
Caused By: Unable to load configuration. - action - zip:/apps/bea/wls103/user_projects/domains/mydomain/servers/mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/lib/_wl_cls_gen.jar!/struts.xml:16:97
        at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:69)
        at org.apache.struts2.dispatcher.Dispatcher.getContainer(Dispatcher.java:957)
        at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:463)
        at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:496)
        at org.apache.struts2.dispatcher.InitOperations.initDispatcher(InitOperations.java:73)
        Truncated. see log file for complete stacktrace
Caused By: Action class [com.myapp.struts.actions.LoginAction] not found - action - zip:/apps/bea/wls103/user_projects/domains/mydomain/servers/mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/lib/_wl_cls_gen.jar!/struts.xml:16:97
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:508)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addAction(XmlConfigurationProvider.java:457)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:572)
        at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:326)
        at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:108)
        Truncated. see log file for complete stacktrace
>

I checked my struts.xml(struts.xml:16:97) - and it is pointing to the LoginAction action class mapping, which obviously its not able to find under the weblogic "../domains/../mymanagedserver/tmp/_WL_user/myapp/4bdx7o/war/WEB-INF/classes"

Thanking you in anticipation

Body:
Finally I was able to figure this out. The culprit has been the compiler compliance level in my eclipse project.  Although I was using jdk1.7 in my project buildpath, I should have also checked for the projects compiler compliance version in Eclipse which was 1.8 (proj right click> JavaCompiler> I set it to 1.7).
Also, I was using javax.servlet-api-3.0.1.jar - I switched to servlet2.5 as I read somewhere that weblogic10.3.x is only compliant upto servlet2.5.

I hope this helps someone looking for a solution to similar problem.


问:
the most-positive-fixnum in emacs
Upon checking the variable in 'most-positive-fixnum' in emacs, it output:

```<code>most-positive-fixnum is a variable defined in ‘data.c’.
Its value is 2305843009213693951
Documentation:
The largest value that is representable in a Lisp integer.
</code>```

It's log2 value:

```<code>In [8]: math.log2(2305843009213693951)
Out[8]: 61.0
</code>```

why set is as 2 **61 rather than 2**62,  or 2**63?

答:
Because there are tag bits: when encountering an object a dynamically-typed language needs to know what type it is.  To do this there must be some 'tag' information which tells it that.  A naive approach would be to represent all objects by at least two machine words: a word of tag information and at least one word for the object itself.  This is a disaster for objects like integers, as it means you need two machine words for even small integers which you would expect to fit in one.  This in turn means that, for instance, (+ 1 2) needs to allocate storage, which you would like it not to do.

To get around this you reduce the maximum size of small integers (fixums) and use some of the spare bits in the word as the tag that says 'this is a fixnum'.  There is a very clever trick you can do here called 'low tags': if you reserve, for instance, two tag bits at the low end of the word you can make them be (going in little-endian order of bit):

0 0: even fixnum

0 1: odd fixnum;

1 0, 1 1: two other kinds of object

And the clever thing is that this means your fixnums can be one bit bigger than you would expect, because the low-order bit of an even fixnum is 0: it overlaps with the tag bits.  Addition with fixnums represented like this can use machine operations (modulo overflow), while multiplication requires a shift, which is typically essentially free since it does not touch memory.  I don't know if elisp uses low-tags although I kind of assume it does.

Title: the most-positive-fixnum in emacs

Body:
Upon checking the variable in 'most-positive-fixnum' in emacs, it output:

most-positive-fixnum is a variable defined in ‘data.c’.
Its value is 2305843009213693951
Documentation:
The largest value that is representable in a Lisp integer.

It's log2 value:

In [8]: math.log2(2305843009213693951)
Out[8]: 61.0

why set is as 2 **61 rather than 2**62,  or 2**63?


问:
How to align the flex items in three different ways?

So, I want to align items inside flex-box like in the above picture.

I have html as follows:

```<code><div class="flex-row">
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
</div>
</code>```

css as

```<code>   .flex-row {
      min-height: 400px;
      display: flex;
      align-items: flex-start;
   }

   .flex-item:nth-child(2) {
     align-items: center;
   }

   .flex-item:last-child {
      align-items: flex-end;
   }
</code>```

答:
Look at this code

```<code>display:flex;
flex-direction: row;
justify-content: flex-start;
align-items: centre;
</code>```

With flex-direction you specify le principal alignment (horizontal with row , vertical with column). Depending on what you choose here the following properties will have a different effect.

Then with justify-content you specify how your items inside your elements should align on the principal axis you just defined (vertical or horizontal).
In this case flex-start means at the beginning of my axis.

And with align-items you specify the alignment for the secondary axe.The vertical one because we choose flex-direction: row; and not flex-direction: column;. So in the vertical axis items will align at centre

And don't forget to take look at the available properties like space-between or flex-end

Body:
So, I want to align items inside flex-box like in the above picture.

I have html as follows:

css as

   .flex-row {
      min-height: 400px;
      display: flex;
      align-items: flex-start;
   }

   .flex-item:nth-child(2) {
     align-items: center;
   }

   .flex-item:last-child {
      align-items: flex-end;
   }

Body:
Look at this code

display:flex;
flex-direction: row;
justify-content: flex-start;
align-items: centre;

With flex-direction you specify le principal alignment (horizontal with row , vertical with column). Depending on what you choose here the following properties will have a different effect.

Then with justify-content you specify how your items inside your elements should align on the principal axis you just defined (vertical or horizontal).
In this case flex-start means at the beginning of my axis.

And with align-items you specify the alignment for the secondary axe.The vertical one because we choose flex-direction: row; and not flex-direction: column;. So in the vertical axis items will align at centre

And don't forget to take look at the available properties like space-between or flex-end


问:
How to merge excel cells based on the cell value using c#
I am using excel interop with C#. I want to merge all adjacent cells that contain a specific value using C# code.

How to merge all the cells that contain the value (Merged cells) using C# code
[![image 1][1]][1]

But I want something like this below,

[![image 2][2]][2]

Here is my full code, but it shows COM Exception handling

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop;
using OfficeOpenXml;

namespace ExportExcel
{
public partial class Form1 : Form
{
    DataTable ctr_raw_table = new DataTable();
    public Form1()
    {
        InitializeComponent();
        ctr_raw_table.Columns.Add("Name", typeof(String));
        ctr_raw_table.Columns.Add("Company", typeof(String));
        ctr_raw_table.Columns.Add("Job", typeof(String));
        ctr_raw_table.Columns.Add("Level", typeof(String));
        ctr_raw_table.Columns.Add("ID", typeof(String));
        ctr_raw_table.Columns.Add("Address", typeof(String));
        string[] row = new string[] { "John", "Wipro", "Engineer", "0203794", "India", "Mumbai" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "David", "TCS", "Engineer", "02065394", "India", "Thane" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "Albert", "Infosys", "Engineer", "0206394", "India", "Mumbai" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "Daniel", "IBM", "Engineer", "02036594", "India", "Mumbra" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "James", "Accenture", "Engineer", "02560394", "India", "Bhiwandi" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "Jacob", "L&T", "Engineer", "02036594", "India", "kalyan" };
        ctr_raw_table.Rows.Add(row);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Export_Ctr_Excel(ctr_raw_table, "Output");
    }
    private void Export_Ctr_Excel(DataTable tablelist, string excelFilename)
    {

        Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
        objexcelapp.Application.Workbooks.Add(Type.Missing);
        objexcelapp.Columns.AutoFit();
        for (int i = 1; i < tablelist.Columns.Count + 1; i++)
        {
            Microsoft.Office.Interop.Excel.Range xlRange = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[1, i];
            xlRange.Font.Bold = -1;
            //xlRange[objexcelapp.Cells["C2:C7"]].Merge();

            int Row = 1;
            int Column = 1;

            Microsoft.Office.Interop.Excel.Range rng = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[Row, Column];
            rng.EntireColumn.Font.Bold = true;
            rng.EntireColumn.Font.Italic = true;
            //rng.EntireColumn.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.HotPink);
            rng.EntireColumn.BorderAround();

            xlRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

            xlRange.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

            //String startRange = "C1";
            //String endRange = "C7";
            //String repetitiveValue = "Merged Cells";
            //Microsoft.Office.Interop.Excel.Range xlrange = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[startRange, endRange];
            //xlrange.Value2 = repetitiveValue;
            //xlRange.Select();
            //xlrange.Merge(System.Reflection.Missing.Value);

            objexcelapp.Cells[1, i] = tablelist.Columns[i - 1].ColumnName;

            using (var excel = new ExcelPackage(new System.IO.FileInfo(@"physical_address_of_your_xslx_file")))
            {
                var sheetName = "Sheet1";
                var sheet1 = excel.Workbook.Worksheets["Output"];
                // or :
                //var sheet1 = excel.Workbook.Worksheets.First();

                sheet1.Cells["C2:C7"].Merge = true;
                sheet1.Cells["C2:C7"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Bottom;
                sheet1.Cells["C2"].Value = "The value";

                excel.Save();
            }

            //DataTable dt = tablelist.Columns[i];
            //if (DataColumnCollection.tablelist.Column.Company = "Wipro")

            //{
            //    Console.WriteLine(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow));
            //}
            //else
            //{
            //    Console.WriteLine(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red));
            //}

        }
        for (int i = 0; i < tablelist.Rows.Count; i++)
        {
            for (int j = 0; j < tablelist.Columns.Count; j++)
            {
                if (tablelist.Rows[i][j] != null)
                {
                    Microsoft.Office.Interop.Excel.Range xlRange = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[i + 2, j + 1];

                    xlRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                    xlRange.Borders.Weight = 1d;
                    xlRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    objexcelapp.Cells[i + 2, j + 1] = tablelist.Rows[i][j].ToString();
                }
            }
        }
        objexcelapp.Columns.AutoFit();
        System.Windows.Forms.Application.DoEvents();
        if (Directory.Exists("C:\\CTR_Data\\"))
        {
            objexcelapp.ActiveWorkbook.SaveCopyAs("C:\\CTR_Data\\" + excelFilename + ".xlsx");
        }
        else
        {
            Directory.CreateDirectory("C:\\CTR_Data\\");
            objexcelapp.ActiveWorkbook.SaveCopyAs("C:\\CTR_Data\\" + excelFilename + ".xlsx");
        }
        objexcelapp.ActiveWorkbook.Saved = true;
        System.Windows.Forms.Application.DoEvents();
        foreach (Process proc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            proc.Kill();
        }
    }

    private object Worksheets(string v)
    {
        throw new NotImplementedException();

    }
}
}
</code>```

答:
Welcome to Stack-overflow, I don't recommend to use OfficeInterLopos since they are not easy to use. They are dependent on Office dlls and etc.

There is a cool library calls EPPLUS. EPPlus is a .NET library that reads and writes Excel files using the Office Open XML format (xlsx). EPPlus has no dependencies other than .NET.  You can install it via NUGET.

```<code>        using (var excel = new ExcelPackage(new System.IO.FileInfo(@"physical_address_of_your_xslx_file")))
        {
            var sheetName = "Sheet1";
            var sheet1 = excel.Workbook.Worksheets[sheetName];
            // or :
            // var sheet1 = excel.Workbook.Workseets.First();

            sheet1.Cells["C2:C7"].Merge = true;
            sheet1.Cells["C2:C7"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Bottom;
            sheet1.Cells["C2"].Value = "The value";

            excel.Save();
        }
</code>```

Not only it's easy to use but also very powerful and well-documented.

p.s: Don't forget to reference using OfficeOpenXml; on your code.

Body:
I am using excel interop with C#. I want to merge all adjacent cells that contain a specific value using C# code.

How to merge all the cells that contain the value (Merged cells) using C# code
[![image 1][1]][1]

But I want something like this below,

[![image 2][2]][2]

Here is my full code, but it shows COM Exception handling

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Office.Interop;
using OfficeOpenXml;

namespace ExportExcel
{
public partial class Form1 : Form
{
    DataTable ctr_raw_table = new DataTable();
    public Form1()
    {
        InitializeComponent();
        ctr_raw_table.Columns.Add("Name", typeof(String));
        ctr_raw_table.Columns.Add("Company", typeof(String));
        ctr_raw_table.Columns.Add("Job", typeof(String));
        ctr_raw_table.Columns.Add("Level", typeof(String));
        ctr_raw_table.Columns.Add("ID", typeof(String));
        ctr_raw_table.Columns.Add("Address", typeof(String));
        string[] row = new string[] { "John", "Wipro", "Engineer", "0203794", "India", "Mumbai" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "David", "TCS", "Engineer", "02065394", "India", "Thane" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "Albert", "Infosys", "Engineer", "0206394", "India", "Mumbai" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "Daniel", "IBM", "Engineer", "02036594", "India", "Mumbra" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "James", "Accenture", "Engineer", "02560394", "India", "Bhiwandi" };
        ctr_raw_table.Rows.Add(row);
        row = new string[] { "Jacob", "L&T", "Engineer", "02036594", "India", "kalyan" };
        ctr_raw_table.Rows.Add(row);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Export_Ctr_Excel(ctr_raw_table, "Output");
    }
    private void Export_Ctr_Excel(DataTable tablelist, string excelFilename)
    {

        Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
        objexcelapp.Application.Workbooks.Add(Type.Missing);
        objexcelapp.Columns.AutoFit();
        for (int i = 1; i < tablelist.Columns.Count + 1; i++)
        {
            Microsoft.Office.Interop.Excel.Range xlRange = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[1, i];
            xlRange.Font.Bold = -1;
            //xlRange[objexcelapp.Cells["C2:C7"]].Merge();

            int Row = 1;
            int Column = 1;

            Microsoft.Office.Interop.Excel.Range rng = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[Row, Column];
            rng.EntireColumn.Font.Bold = true;
            rng.EntireColumn.Font.Italic = true;
            //rng.EntireColumn.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.HotPink);
            rng.EntireColumn.BorderAround();

            xlRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

            xlRange.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

            //String startRange = "C1";
            //String endRange = "C7";
            //String repetitiveValue = "Merged Cells";
            //Microsoft.Office.Interop.Excel.Range xlrange = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[startRange, endRange];
            //xlrange.Value2 = repetitiveValue;
            //xlRange.Select();
            //xlrange.Merge(System.Reflection.Missing.Value);

            objexcelapp.Cells[1, i] = tablelist.Columns[i - 1].ColumnName;

            using (var excel = new ExcelPackage(new System.IO.FileInfo(@"physical_address_of_your_xslx_file")))
            {
                var sheetName = "Sheet1";
                var sheet1 = excel.Workbook.Worksheets["Output"];
                // or :
                //var sheet1 = excel.Workbook.Worksheets.First();

                sheet1.Cells["C2:C7"].Merge = true;
                sheet1.Cells["C2:C7"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Bottom;
                sheet1.Cells["C2"].Value = "The value";

                excel.Save();
            }

            //DataTable dt = tablelist.Columns[i];
            //if (DataColumnCollection.tablelist.Column.Company = "Wipro")

            //{
            //    Console.WriteLine(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow));
            //}
            //else
            //{
            //    Console.WriteLine(System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red));
            //}

        }
        for (int i = 0; i < tablelist.Rows.Count; i++)
        {
            for (int j = 0; j < tablelist.Columns.Count; j++)
            {
                if (tablelist.Rows[i][j] != null)
                {
                    Microsoft.Office.Interop.Excel.Range xlRange = (Microsoft.Office.Interop.Excel.Range)objexcelapp.Cells[i + 2, j + 1];

                    xlRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;

                    xlRange.Borders.Weight = 1d;
                    xlRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
                    objexcelapp.Cells[i + 2, j + 1] = tablelist.Rows[i][j].ToString();
                }
            }
        }
        objexcelapp.Columns.AutoFit();
        System.Windows.Forms.Application.DoEvents();
        if (Directory.Exists("C:\\CTR_Data\\"))
        {
            objexcelapp.ActiveWorkbook.SaveCopyAs("C:\\CTR_Data\\" + excelFilename + ".xlsx");
        }
        else
        {
            Directory.CreateDirectory("C:\\CTR_Data\\");
            objexcelapp.ActiveWorkbook.SaveCopyAs("C:\\CTR_Data\\" + excelFilename + ".xlsx");
        }
        objexcelapp.ActiveWorkbook.Saved = true;
        System.Windows.Forms.Application.DoEvents();
        foreach (Process proc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
        {
            proc.Kill();
        }
    }

    private object Worksheets(string v)
    {
        throw new NotImplementedException();

    }
}
}

Body:
Welcome to Stack-overflow, I don't recommend to use OfficeInterLopos since they are not easy to use. They are dependent on Office dlls and etc.

There is a cool library calls EPPLUS. EPPlus is a .NET library that reads and writes Excel files using the Office Open XML format (xlsx). EPPlus has no dependencies other than .NET.  You can install it via NUGET.

        using (var excel = new ExcelPackage(new System.IO.FileInfo(@"physical_address_of_your_xslx_file")))
        {
            var sheetName = "Sheet1";
            var sheet1 = excel.Workbook.Worksheets[sheetName];
            // or :
            // var sheet1 = excel.Workbook.Workseets.First();

            sheet1.Cells["C2:C7"].Merge = true;
            sheet1.Cells["C2:C7"].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Bottom;
            sheet1.Cells["C2"].Value = "The value";

            excel.Save();
        }

Not only it's easy to use but also very powerful and well-documented.

p.s: Don't forget to reference using OfficeOpenXml; on your code.


问:
How to write very small text in HTML
I would like to have a font smaller than an Arial 9px text.

I've tried to find other font name but I did not succeed to get a very small text. Is there a way to achieve this easily using css ?

EDIT :
I can't go under 9px using Arial
I have tried font-size, small, transform, scale, other fonts... everything as I am an experienced web developper.

答:
Few thing you must consider

 1. make sure the .css file is the last one you load in your html (after Bootstrap for example).

 2. use the !important attribute to your css property (font-size: 4px !important;)

 3. if these 2 suggestions do not work, try adding an inline-css to your element
I'm a 4 px paragraph

Title: How to write very small text in HTML

Body:
Few thing you must consider

 1. make sure the .css file is the last one you load in your html (after Bootstrap for example).

 2. use the !important attribute to your css property (font-size: 4px !important;)

 3. if these 2 suggestions do not work, try adding an inline-css to your element <p style="font-size: 4px">I'm a 4 px paragraph</p>


问:
How to access ElasticSearch domain endpoint URL in AWS?
I have created elasticsearch domain in AWS and integrated with cloudwatch logs which eventually sends logs to elasticsearch cluster with help of lambda function. It has got successfully created and it gives me one endpoint URL, something like this `https://search-elkprod-c63hwtlyqgdogkw55w6osdfzwu.eu-west-1.es.amazonaws.com'.

When i click this link i get this message :

```<code>{
  "name" : "S7hluCW",
  "cluster_name" : "567294256180:elkprod",
  "cluster_uuid" : "4UdCvJT9R4-H05MSXqg9tQ",
  "version" : {
    "number" : "6.5.4",
    "build_flavor" : "oss",
    "build_type" : "zip",
    "build_hash" : "d2ef93d",
    "build_date" : "2019-04-08T13:15:27.206923Z",
    "build_snapshot" : false,
    "lucene_version" : "7.5.0",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}
</code>```

Now my questions are:

How to access this cluster? I want to check whether my logs are going to the
cluster or not.

If this is a cluster, where are the instances that would have been launched with this cluster?

Please help me on this. Please let me know if you need any more clarification.

答:
Answering your two questions.

You can use Kibana which is a popular visualization tool. This will help you to see the total number of indexes created. With this you can add the graphs to tell the number of indexes added in the past 1hr,1day, 1week ..etc

To Access Kibana you can use the URL elasticsearch-domain-endpoint/_plugin/kibana/

AWS will take care of managing infrastructure for elastic search. Thus in case the increase in load or storage, you can manage with a single click or with an API.

Body:
I have created elasticsearch domain in AWS and integrated with cloudwatch logs which eventually sends logs to elasticsearch cluster with help of lambda function. It has got successfully created and it gives me one endpoint URL, something like this `https://search-elkprod-c63hwtlyqgdogkw55w6osdfzwu.eu-west-1.es.amazonaws.com'.

When i click this link i get this message :

{
  "name" : "S7hluCW",
  "cluster_name" : "567294256180:elkprod",
  "cluster_uuid" : "4UdCvJT9R4-H05MSXqg9tQ",
  "version" : {
    "number" : "6.5.4",
    "build_flavor" : "oss",
    "build_type" : "zip",
    "build_hash" : "d2ef93d",
    "build_date" : "2019-04-08T13:15:27.206923Z",
    "build_snapshot" : false,
    "lucene_version" : "7.5.0",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}

Now my questions are:

How to access this cluster? I want to check whether my logs are going to the
cluster or not.

If this is a cluster, where are the instances that would have been launched with this cluster?

Please help me on this. Please let me know if you need any more clarification.


问:
Protractor test + manage order of execution
I have a Protractor test which looks like

```<code>pageObject1.method1();
pageObject1.method2();
pageObject2.method1();
expect(pageObject2.method2());
let allDataList = pageObject2.method3();
expect(allDataList.includes('test1')).toBeTruthy();
</code>```

How do I make sure that the call to pageObject2.method3() happens before the next expect call? method3() returns an array of the text of all span elements.

答:
This case you need to use promises

Way-1:

```<code>await pageObject1.method2();
await pageObject2.method1();
expect(pageObject2.method2());
let allDataList = await pageObject2.method3();
expect(allDataList.includes('test1')).toBeTruthy();
</code>```

Description On await

Way-2:

```<code>pageObject1.method2().then(function() {
    pageObject2.method1().then(function() {
        expect(pageObject2.method2());
        pageObject2.method3().then(function(allDataList) {
            expect(allDataList.includes('test1')).toBeTruthy();
        });
    });
});
</code>```

Body:
I have a Protractor test which looks like

pageObject1.method1();
pageObject1.method2();
pageObject2.method1();
expect(pageObject2.method2());
let allDataList = pageObject2.method3();
expect(allDataList.includes('test1')).toBeTruthy();

How do I make sure that the call to pageObject2.method3() happens before the next expect call? method3() returns an array of the text of all span elements.

Body:
This case you need to use promises

Way-1:

await pageObject1.method2();
await pageObject2.method1();
expect(pageObject2.method2());
let allDataList = await pageObject2.method3();
expect(allDataList.includes('test1')).toBeTruthy();

Description On await

Way-2:

pageObject1.method2().then(function() {
    pageObject2.method1().then(function() {
        expect(pageObject2.method2());
        pageObject2.method3().then(function(allDataList) {
            expect(allDataList.includes('test1')).toBeTruthy();
        });
    });
});


问:
Multiplying a pd.Series vector against a multindex pd.Dataframe
I have a pandas Series and a pandas multiindex Dataframe.

Here is a simplistic example of the situation:

```<code>iterables = [['milk', 'honey', 'dates'], ['jan', 'feb', 'mar', 'apr']]
i = pd.MultiIndex.from_product(iterables, names=['good', 'month'])
xf = pd.DataFrame(index = i)
xf['price'] = np.random.randint(1, 25, xf.shape[0])

allocation_vector = pd.Series([0.3, 0.6, 0.1], index = ['milk', 'honey', 'dates'])
</code>```

This dataframe represents 'price of three products in each month jan through apr'  The allocation_vector represents some fractional share of prices.

What I want to  achieve is  multiplying the allocation vector times my dataframe resulting in a series with index 'jan', 'feb', 'mar', 'apr' and the value equaling the dotproduct in that month (IE:  jan_date_price*date_pct + jan_milk_price*milk_pct + jan_honey_price*jan_pct for each of jan, feb, mar, apr)

I've only been able to solve this with nasty iterative hacky solutions. I figure there must be a much more pythonic way to do this, and where I don't have to worry about vector columns being in the wrong order for the multiplication against the dataframe columns etc.  Of course the actual dataframe has more columns that aren't involved in the calculation.

答:
I believe you need multiple by first level by Series.mul and then sum per first level:

```<code>np.random.seed(2019)

iterables = [['milk', 'honey', 'dates'], ['jan', 'feb', 'mar', 'apr']]
i = pd.MultiIndex.from_product(iterables, names=['good', 'month'])
xf = pd.DataFrame(index = i)
xf['price'] = np.random.randint(1, 25, xf.shape[0])
print (xf)
             price
good  month
milk  jan        9
      feb       19
      mar        6
      apr       23
honey jan       16
      feb       13
      mar       11
      apr       17
dates jan       17
      feb        8
      mar        6
      apr       20

allocation_vector = pd.Series([0.3, 0.6, 0.1], index = ['milk', 'honey', 'dates'])
</code>```

```<code>print (17*0.1+9*0.3+16*0.6)
14.0

s = xf['price'].mul(allocation_vector, level=0).sum(level=1)
print (s)
month
jan    14.0
feb    14.3
mar     9.0
apr    19.1
dtype: float64
</code>```

Or reshape by Series.unstack, transpose and use DataFrame.dot, but order of values in output is changed:

```<code>s = xf['price'].unstack().T.dot(allocation_vector)
print (s)
month
apr    19.1
feb    14.3
jan    14.0
mar     9.0
dtype: float64
</code>```

Body:
I have a pandas Series and a pandas multiindex Dataframe.

Here is a simplistic example of the situation:

iterables = [['milk', 'honey', 'dates'], ['jan', 'feb', 'mar', 'apr']]
i = pd.MultiIndex.from_product(iterables, names=['good', 'month'])
xf = pd.DataFrame(index = i)
xf['price'] = np.random.randint(1, 25, xf.shape[0])

allocation_vector = pd.Series([0.3, 0.6, 0.1], index = ['milk', 'honey', 'dates'])

This dataframe represents 'price of three products in each month jan through apr'  The allocation_vector represents some fractional share of prices.

What I want to  achieve is  multiplying the allocation vector times my dataframe resulting in a series with index 'jan', 'feb', 'mar', 'apr' and the value equaling the dotproduct in that month (IE:  jan_date_price*date_pct + jan_milk_price*milk_pct + jan_honey_price*jan_pct for each of jan, feb, mar, apr)

I've only been able to solve this with nasty iterative hacky solutions. I figure there must be a much more pythonic way to do this, and where I don't have to worry about vector columns being in the wrong order for the multiplication against the dataframe columns etc.  Of course the actual dataframe has more columns that aren't involved in the calculation.

Body:
I believe you need multiple by first level by Series.mul and then sum per first level:

np.random.seed(2019)

iterables = [['milk', 'honey', 'dates'], ['jan', 'feb', 'mar', 'apr']]
i = pd.MultiIndex.from_product(iterables, names=['good', 'month'])
xf = pd.DataFrame(index = i)
xf['price'] = np.random.randint(1, 25, xf.shape[0])
print (xf)
             price
good  month
milk  jan        9
      feb       19
      mar        6
      apr       23
honey jan       16
      feb       13
      mar       11
      apr       17
dates jan       17
      feb        8
      mar        6
      apr       20

allocation_vector = pd.Series([0.3, 0.6, 0.1], index = ['milk', 'honey', 'dates'])

print (17*0.1+9*0.3+16*0.6)
14.0

s = xf['price'].mul(allocation_vector, level=0).sum(level=1)
print (s)
month
jan    14.0
feb    14.3
mar     9.0
apr    19.1
dtype: float64

Or reshape by Series.unstack, transpose and use DataFrame.dot, but order of values in output is changed:

s = xf['price'].unstack().T.dot(allocation_vector)
print (s)
month
apr    19.1
feb    14.3
jan    14.0
mar     9.0
dtype: float64


问:
Python Hangman not ending when player guesses all letters
My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.</p>

```<code>import random
import time

name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")

lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
   dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"

if start == "y":
    print("One game of Hangman comin' right up,",name)
    letter = input("Alright then, Guess a letter: ")
    thing = ''.join(dash)

    while guesscomb != thing:
        if letter == "" or letter == " " or len(letter) != 1:
            print("I don't understand. Please only use singular letters.")
            letter = input("Guess a letter: ")

        elif letter in lis and letter in alphabet:
            print("Nice!")

            location = lis.find(letter)
            dash[location] = letter
            guess.append(letter)
            alphabet.replace(letter," ")
            guesscomb = "".join(guess)

            letter = input("Guess a letter: ")

        else:
            print("Wrong.")
            wrongcount = wrongcount + 1

            print("Total Mistakes:",wrongcount)
            letter = input("Guess a letter: ")

elif start == "n":
    input("Shame.")
    quit()

print("Good Job!")
time.sleep(10)
</code>```

答:
You can use print with the parameter end="" so that the cursor don't go new line.
You can use the method isalpha on string to check if it is all characters instead of comparing it with the alphabets.
And as Ben said, thing is always ___

Modify this part of your code, and it will work

```<code>if start == "y":
    print("One game of Hangman comin' right up,", name)
    print("Alright then, ", end="")
    # letter = input("Alright then, Guess a letter: ")
    thing = ''.join(dash)

    while guesscomb != thing:
        letter = input("Guess a letter: ")
        if letter == "" or letter == " " or len(letter) != 1:
            print("I don't understand. Please only use singular letters.")

        elif letter in lis and letter in alphabet:
            print("Nice!")
            location = lis.find(letter)
            dash[location] = letter
            guess.append(letter)
            alphabet.replace(letter, " ")
            guesscomb = "".join(guess)
        else:
            print("Wrong.")
            wrongcount = wrongcount + 1
            print("Total Mistakes:", wrongcount)
        thing = ''.join(dash)
</code>```

Body:
My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.

import random
import time

name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")

lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
   dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"

if start == "y":
    print("One game of Hangman comin' right up,",name)
    letter = input("Alright then, Guess a letter: ")
    thing = ''.join(dash)

    while guesscomb != thing:
        if letter == "" or letter == " " or len(letter) != 1:
            print("I don't understand. Please only use singular letters.")
            letter = input("Guess a letter: ")

        elif letter in lis and letter in alphabet:
            print("Nice!")

            location = lis.find(letter)
            dash[location] = letter
            guess.append(letter)
            alphabet.replace(letter," ")
            guesscomb = "".join(guess)

            letter = input("Guess a letter: ")

        else:
            print("Wrong.")
            wrongcount = wrongcount + 1

            print("Total Mistakes:",wrongcount)
            letter = input("Guess a letter: ")

elif start == "n":
    input("Shame.")
    quit()

print("Good Job!")
time.sleep(10)

Body:
You can use print with the parameter end="" so that the cursor don't go new line.
You can use the method isalpha on string to check if it is all characters instead of comparing it with the alphabets.
And as Ben said, thing is always ___

Modify this part of your code, and it will work

if start == "y":
    print("One game of Hangman comin' right up,", name)
    print("Alright then, ", end="")
    # letter = input("Alright then, Guess a letter: ")
    thing = ''.join(dash)

    while guesscomb != thing:
        letter = input("Guess a letter: ")
        if letter == "" or letter == " " or len(letter) != 1:
            print("I don't understand. Please only use singular letters.")

        elif letter in lis and letter in alphabet:
            print("Nice!")
            location = lis.find(letter)
            dash[location] = letter
            guess.append(letter)
            alphabet.replace(letter, " ")
            guesscomb = "".join(guess)
        else:
            print("Wrong.")
            wrongcount = wrongcount + 1
            print("Total Mistakes:", wrongcount)
        thing = ''.join(dash)


问:
mongoose aggregate with conditional parameters
I have this working aggregation code for mongoose

```<code>    const AccountProduct = await AccountProductModel.aggregate([
            {
                $match: { userID: userID }
            },
            {
                $addFields: {
                    taggedProducts: {
                        $filter: {
                            input: "$taggedProducts",
                            cond: {
                                 $and: {
                                    $eq: [ "$$this.isChecked", true ],
                                    $eq: [ "$$this.walletID", walletID]
                                 }
                            }
                        }
                    }
                }
            }
        ])
</code>```

it does return the required data but I want to have a condition if walletID is not supplied then condition should look like this

```<code>                        cond: {
                             $and: {
                                $eq: [ "$$this.isChecked", true ]
                             }
                        }
</code>```

how do I do this?

答:
You can extract the condition into a variable before the query.

```<code>let myCond = [{$eq: [ "$$this.isChecked", true ]}];

if (walletID) myCond.push({$eq: [ "$$this.walletID", walletID]});
</code>```

Then

```<code>cond: {$and: myCond}
</code>```

Body:
I have this working aggregation code for mongoose

    const AccountProduct = await AccountProductModel.aggregate([
            {
                $match: { userID: userID }
            },
            {
                $addFields: {
                    taggedProducts: {
                        $filter: {
                            input: "$taggedProducts",
                            cond: {
                                 $and: {
                                    $eq: [ "$$this.isChecked", true ],
                                    $eq: [ "$$this.walletID", walletID]
                                 }
                            }
                        }
                    }
                }
            }
        ])

it does return the required data but I want to have a condition if walletID is not supplied then condition should look like this

                        cond: {
                             $and: {
                                $eq: [ "$$this.isChecked", true ]
                             }
                        }

how do I do this?

Body:
You can extract the condition into a variable before the query.

let myCond = [{$eq: [ "$$this.isChecked", true ]}];

if (walletID) myCond.push({$eq: [ "$$this.walletID", walletID]});

Then

cond: {$and: myCond}


问:
display new Django object with jQuery
I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List AJAX-ly?

views.py:

```<code>def add_post(request):
error_msg = u"No POST data sent."
post = Post()
if request.method == "POST":
    #do stuff

return HttpResponse("success")
</code>```

So far I am able to return "success" and save the new Post just fine.

jQuery:

```<code>       $("form#add_post").submit(function() {
       //do stuff
       var args = {type:"POST", url:"add_post/", data:data, complete:function(res, status) {
            if (status == "success") {
                alert("success");
            } else {

            }
        }};

       $.ajax(args);

       return false;

   })
</code>```

Just alerting "success" here, and that works fine. I can see the new Post in the Post List if I refresh the page. Now how do I load the new Post AJAX-ly? Do I have to grab Post's attributes and prepend them to my DIV manually? Is there an easy way to just reload my Post List?

Thank you!

答:
In your Django backend service, you need to give back some information related to the logic of your application. Mostly, people tend to use JSON for this.

```<code>def add_post(request):
   error_msg = u"No POST data sent."
   post = Post()
   if request.method == "POST":
      #do stuff
      response = HttpResponse(content_type = 'application/javascript')
      data = dict()
      #here it comes your logic
      #that fills 'data' with whichever
      #information you need.
      data['message']='post added !!'
      response.write(json.dumps(data))
      return response
   else:
      return HttpResponse("NO POST REQUEST HANDLE")
</code>```

Your client side next to handle that response accordingly to the data written in the HttpResponse object.

```<code>   complete: function(res, status) {
            //In here you can do whatever you want to modify your
            //HTML dynamically
            // the variable res contains the JSON object dumped in the
            // django HTTPResponse object.
            $("#message").text = res['message'];
    }

   error: function(res, status) {
            $("#message").text = "error handling ajax request";
    }
</code>```

Make sure you handle both error and complete callbacks.

In the example I have given you'll need to have an HTML element with message as id, i.e:

```<code><div id="message"></div>
</code>```

ContentLicense: CC BY-SA 3.0

Title: display new Django object with jQuery

Body:
I've been learning Django + jQuery and so far have been able to AJAX-ify a New Post functionality. My question now is how do I display the new Post nicely and easily in the Post List AJAX-ly?

views.py:

def add_post(request):
error_msg = u"No POST data sent."
post = Post()
if request.method == "POST":
    #do stuff

return HttpResponse("success")

So far I am able to return "success" and save the new Post just fine.

jQuery:

       $("form#add_post").submit(function() {
       //do stuff
       var args = {type:"POST", url:"add_post/", data:data, complete:function(res, status) {
            if (status == "success") {
                alert("success");
            } else {

            }
        }};

       $.ajax(args);

       return false;

   })

Just alerting "success" here, and that works fine. I can see the new Post in the Post List if I refresh the page. Now how do I load the new Post AJAX-ly? Do I have to grab Post's attributes and prepend them to my DIV manually? Is there an easy way to just reload my Post List?

Thank you!

Body:
In your Django backend service, you need to give back some information related to the logic of your application. Mostly, people tend to use JSON for this.

def add_post(request):
   error_msg = u"No POST data sent."
   post = Post()
   if request.method == "POST":
      #do stuff
      response = HttpResponse(content_type = 'application/javascript')
      data = dict()
      #here it comes your logic
      #that fills 'data' with whichever
      #information you need.
      data['message']='post added !!'
      response.write(json.dumps(data))
      return response
   else:
      return HttpResponse("NO POST REQUEST HANDLE")

Your client side next to handle that response accordingly to the data written in the HttpResponse object.

   complete: function(res, status) {
            //In here you can do whatever you want to modify your
            //HTML dynamically
            // the variable res contains the JSON object dumped in the
            // django HTTPResponse object.
            $("#message").text = res['message'];
    }

   error: function(res, status) {
            $("#message").text = "error handling ajax request";
    }

Make sure you handle both error and complete callbacks.

In the example I have given you'll need to have an HTML element with message as id, i.e:

<div id="message"></div>


问:
How to make rest api in to to display data in react js
Please help me to make simple rest api in php to fetch data from the database and display into react js

I have 3 columns name,department and marks.
here is my php code -

```<code><?php

header("Content-Type: application/json; charset=UTF-8");
$con = mysqli_connect("mysql1004.mochahost.com","a310387_task_for","task_force","a310387_task_force");

    $query=mysqli_query($con,'select * from student');
$json_array=array();
while($rows=mysqli_fetch_assoc($query)){
    $json_array[]=$rows;
 }
 echo json_encode($json_array);

 ?>
</code>```

and here is my react code -

```<code> componentDidMount(){
    fetch('http://veomit.com/test/zend/api/fetch.php')
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                });
    });
  }
</code>```

displaying like-

```<code> <tbody>
            <tr>
              {
                        this.state.UserData.map(function(item, key) {
                        return (
                                <tr key = {key}>
                                  <td>{item.name}</td>
                                  <td>{item.department}</td>
                                  <td>{item.marks}</td>
                                </tr>
                            )
                        })
                    }
            </tr>
          </tbody>
</code>```

please help me to correct this.
thanks in advance.

答:
Working code

```<code>import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    userData: []
  };
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts") // could be any rest get url
      .then(response => response.json())
      .then(result =>
        this.setState({
          userData: result
        })
      );
  }
  render() {
    return (
      <div className="App">
        <table>
          <tbody>
            {this.state.userData.map((data, key) => {
              return (
                <tr key={key}>
                  <td>{data.userId}</td> // column data received
                  <td>{data.title}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

Hope that helps!!!

Body:
Please help me to make simple rest api in php to fetch data from the database and display into react js

I have 3 columns name,department and marks.
here is my php code -

<?php

header("Content-Type: application/json; charset=UTF-8");
$con = mysqli_connect("mysql1004.mochahost.com","a310387_task_for","task_force","a310387_task_force");

    $query=mysqli_query($con,'select * from student');
$json_array=array();
while($rows=mysqli_fetch_assoc($query)){
    $json_array[]=$rows;
 }
 echo json_encode($json_array);

 ?>

and here is my react code -

 componentDidMount(){
    fetch('http://veomit.com/test/zend/api/fetch.php')
    .then(response => {
                return response.json();
            })
    .then(result => {
                this.setState({
                    UserData:result
                });
    });
  }

displaying like-

              {
                        this.state.UserData.map(function(item, key) {
                        return (

                                  {item.name}
                                  {item.department}
                                  {item.marks}

                            )
                        })
                    }

please help me to correct this.
thanks in advance.

Body:
Working code

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    userData: []
  };
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts") // could be any rest get url
      .then(response => response.json())
      .then(result =>
        this.setState({
          userData: result
        })
      );
  }
  render() {
    return (
      <div className="App">
        <table>
          <tbody>
            {this.state.userData.map((data, key) => {
              return (
                <tr key={key}>
                  <td>{data.userId}</td> // column data received
                  <td>{data.title}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Hope that helps!!!


答:
Most (all?) browsers have a minimum font size, to avoid underhanded people displaying unreadable text for some reason. Some browsers let you adjust this, but you simply can't count on being able to display smaller than 9pt on anyone else's machine.

Unless you opt for very old school: create your text as a graphic.

Or: Create your own custom, tiny font - as long as it has all the features of (say) a 12pt font, it will display fine, but if the glyphs are only two dots high, that is what you will see.

Title: How to write very small text in HTML

Body:
I would like to have a font smaller than an Arial 9px text.

I've tried to find other font name but I did not succeed to get a very small text. Is there a way to achieve this easily using css ?

EDIT :
I can't go under 9px using Arial
I have tried font-size, small, transform, scale, other fonts... everything as I am an experienced web developper.


问:
How can I order a dictionary list by one specified key with some values being None?
There is a list like

```<code>l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]
</code>```

And I want to order it by one specified key, n for example.
Besides, some value of the key may be None, and I want to leave them at behind

Here's my trial

```<code>l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

from functools import partial
def order(key, item):
    if item[key]:
        return item[key]
    else:
        return 0
order_key = "n"
r = sorted(l, key=partial(order, order_key), reverse=True)
print(r)
</code>```

Is there a better way to make it happen?

Body:
There is a list like

l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

And I want to order it by one specified key, n for example.
Besides, some value of the key may be None, and I want to leave them at behind

Here's my trial

l = [{"n": 1, "m": 3}, {"n": None, "m": 1}, {"n": 3, "m": None}, {"n": None, "m": 0}]

from functools import partial
def order(key, item):
    if item[key]:
        return item[key]
    else:
        return 0
order_key = "n"
r = sorted(l, key=partial(order, order_key), reverse=True)
print(r)

Is there a better way to make it happen?

Body:
Here's one approach using sorted with a key:

sorted(l, key=lambda x: -x['n'] if x['n'] is not None else float('inf'))

[{'n': 3, 'm': None},
 {'n': 1, 'm': 3},
 {'n': None, 'm': 1},
 {'n': None, 'm': 0}]

Let's check with another example:

l = [ {"n":1, "m":3}, {"n":None, "m":1}, {"n":3, "m":None}, {"n":None, "m":0},
      {"n":0, "m":0}, {"n":-1, "m":0}]

sorted(l, key=lambda x: -x['n'] if x['n'] is not None else float('inf'))

[{'n': 3, 'm': None},
 {'n': 1, 'm': 3},
 {'n': 0, 'm': 0},
 {'n': -1, 'm': 0},
 {'n': None, 'm': 1},
 {'n': None, 'm': 0}]


问:
GPO not being applied
I am using the powershell GroupPolicy module to create and link new GPOs. I have a large number of GPOs to create, and thus I wish to automate the process without having to interact with the Group Policy Editor.

I noticed while creating GPOs through the editor that each policy object would be contained in either one or several XML files or .INI files.

Having noted above, I started creating GPOs with the New-GPO command, passing the -Name and -Domain flags. After the GPO has been successfully created, I would (via my script) generate an XML file containing all of the information that the policy would consume. Shown below is an extract of the XML file that I would create to set up a mapped drives policy.

When inspecting the policy in the editor, everything looks fine. The correct drives are showing up and all of the settings appear to be correct. However, the policy is never applied. If I create an identical policy manually via the Group Policy Editor, all of the policies start working, including the ones that I created with powershell.

The error therefore seems to be that the domain controller is never made aware of the changes, but they get applied when a manual change is made.

I have tried running gpupdate /force, which does not seem to update or propagate the changes

    New-Item \\$($MappedDrivesGPO.DomainName)\SYSVOL\$($MappedDrivesGPO.DomainName)\Policies\$("{"+$MappedDrivesGPO.Id+"}")\User\Preferences\Drives\Drives.xml -ItemType File -Force
    Set-Content \\$($MappedDrivesGPO.DomainName)\SYSVOL\$($MappedDrivesGPO.DomainName)\Policies\$("{"+$MappedDrivesGPO.Id+"}")\User\Preferences\Drives\Drives.xml $xml

```

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
    <Drives clsid="{8FDDCC1A-0C3C-43cd-A6B4-71A6DF20DA8C}">
        <Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="P:" status="P:" image="2" changed="2019-04-26 10:41:54" uid="{$guid1}" bypassErrors="1">
            <Properties action="U" thisDrive="NOCHANGE" allDrives="NOCHANGE" userName="" path="\\fs1\Projects" label="Projects" persistent="0" useLetter="1" letter="P"/>
            <Filters>
                <FilterGroup bool="AND" not="0" name="$($domainName)\Drive P Access" sid="$($filterGroupSidDriveP)" userContext="1" primaryGroup="0" localGroup="0"/>
            </Filters>
        </Drive>
        <Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="S:" status="S:" image="2" changed="2019-04-26 10:39:21" uid="{$guid2}" bypassErrors="1">
            <Properties action="U" thisDrive="NOCHANGE" allDrives="NOCHANGE" userName="" path="\\as1\Software" label="Software" persistent="0" useLetter="1" letter="S"/>
            <Filters>
                <FilterGroup bool="AND" not="0" name="$($domainName)\Drive S Access" sid="$($filterGroupSidDriveS)" userContext="1" primaryGroup="0" localGroup="0"/>
            </Filters>
        </Drive>
    </Drives>
</code>```

I expected the policy to start working as intended after the XML file had been created

The actual result is that the policy appears to be well formed, but never applied

答:
I managed to resolve this on my own, posting here in case someone else runs into the same issue. If you're creating GPOs programmatically and not via the editor, you will have to extend your script/program to add CSE (in this case for drive mapping) and SnapIn GUID to gPCUserExtensionNames.

[{00000000-0000-0000-0000-000000000000}{2EA1A81B-48E5-45E9-8BB7-A6E3AC170006}][{5794DAFD-BE60-433F-88A2-1A31939AC01F}{2EA1A81B-48E5-45E9-8BB7-A6E3AC170006}]
```

The 0000.. is the Core GPO Engine, 23EA.. is the Preference Tool CSE GUID Drives, 5794.. is Preference CSE GUID Drives.

If you create the policy manually with the desired changes, you can then open dsa.msc, enable advanced features and then view the policy object properties. Under gPCUserExtensionNames you will be able to see the arrays containing the GUIDs that you need to incorporate in your software.

Title: GPO not being applied

Body:
I am using the powershell GroupPolicy module to create and link new GPOs. I have a large number of GPOs to create, and thus I wish to automate the process without having to interact with the Group Policy Editor.

I noticed while creating GPOs through the editor that each policy object would be contained in either one or several XML files or .INI files.

Having noted above, I started creating GPOs with the New-GPO command, passing the -Name and -Domain flags. After the GPO has been successfully created, I would (via my script) generate an XML file containing all of the information that the policy would consume. Shown below is an extract of the XML file that I would create to set up a mapped drives policy.

When inspecting the policy in the editor, everything looks fine. The correct drives are showing up and all of the settings appear to be correct. However, the policy is never applied. If I create an identical policy manually via the Group Policy Editor, all of the policies start working, including the ones that I created with powershell.

The error therefore seems to be that the domain controller is never made aware of the changes, but they get applied when a manual change is made.

I have tried running gpupdate /force, which does not seem to update or propagate the changes

    New-Item \\$($MappedDrivesGPO.DomainName)\SYSVOL\$($MappedDrivesGPO.DomainName)\Policies\$("{"+$MappedDrivesGPO.Id+"}")\User\Preferences\Drives\Drives.xml -ItemType File -Force
    Set-Content \\$($MappedDrivesGPO.DomainName)\SYSVOL\$($MappedDrivesGPO.DomainName)\Policies\$("{"+$MappedDrivesGPO.Id+"}")\User\Preferences\Drives\Drives.xml $xml

<?xml version="1.0" encoding="utf-8"?>
    <Drives clsid="{8FDDCC1A-0C3C-43cd-A6B4-71A6DF20DA8C}">
        <Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="P:" status="P:" image="2" changed="2019-04-26 10:41:54" uid="{$guid1}" bypassErrors="1">
            <Properties action="U" thisDrive="NOCHANGE" allDrives="NOCHANGE" userName="" path="\\fs1\Projects" label="Projects" persistent="0" useLetter="1" letter="P"/>
            <Filters>
                <FilterGroup bool="AND" not="0" name="$($domainName)\Drive P Access" sid="$($filterGroupSidDriveP)" userContext="1" primaryGroup="0" localGroup="0"/>
            </Filters>
        </Drive>
        <Drive clsid="{935D1B74-9CB8-4e3c-9914-7DD559B7A417}" name="S:" status="S:" image="2" changed="2019-04-26 10:39:21" uid="{$guid2}" bypassErrors="1">
            <Properties action="U" thisDrive="NOCHANGE" allDrives="NOCHANGE" userName="" path="\\as1\Software" label="Software" persistent="0" useLetter="1" letter="S"/>
            <Filters>
                <FilterGroup bool="AND" not="0" name="$($domainName)\Drive S Access" sid="$($filterGroupSidDriveS)" userContext="1" primaryGroup="0" localGroup="0"/>
            </Filters>
        </Drive>
    </Drives>

I expected the policy to start working as intended after the XML file had been created

The actual result is that the policy appears to be well formed, but never applied

Body:
I managed to resolve this on my own, posting here in case someone else runs into the same issue. If you're creating GPOs programmatically and not via the editor, you will have to extend your script/program to add CSE (in this case for drive mapping) and SnapIn GUID to gPCUserExtensionNames.

[{00000000-0000-0000-0000-000000000000}{2EA1A81B-48E5-45E9-8BB7-A6E3AC170006}][{5794DAFD-BE60-433F-88A2-1A31939AC01F}{2EA1A81B-48E5-45E9-8BB7-A6E3AC170006}]

The 0000.. is the Core GPO Engine, 23EA.. is the Preference Tool CSE GUID Drives, 5794.. is Preference CSE GUID Drives.

If you create the policy manually with the desired changes, you can then open dsa.msc, enable advanced features and then view the policy object properties. Under gPCUserExtensionNames you will be able to see the arrays containing the GUIDs that you need to incorporate in your software.


问:
gets() problem in C
I wrote the following code:

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

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !

答: Consider replace with "scanf( "%s", &string)" instead.

Title: gets() problem in C

Body:
I wrote the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int const count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

The problem is that the gcc gives me an error for the 'int const count': " increment of read-only variable ‘count’".

What seems to be wrong ?

Thank !