问:
ARM Template deployment resource namespace not found
I have a custom ARM template which deploys an EventHub Namespace with a child EventHub, which in turn has two AuthorizationRules and one ConsumerGroup as children. The validation passes but I get a deployment error. It seems the Azure Resource Manager starts by trying to deploy the Authorization Rules before the namespace even exist, even though I added the required "dependsOn" properties, but then the deployment goes on from start to finish and successfully deploys every resource. It could be tolerable if I only deployed it from the portal, but when I deploy this template programmatically, I get an error even though the deployment was "successful" and my rollback mechanism triggers.

Here are links to the errors given by the portal :

Deployment Steps

Error Messages

Here is my ARM Template (comments are there only to help you find resources):

```<code>{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "namespaceName": {
      "type": "string"
    },
    "eventHubName": {
      "type": "string"
    }
  },

  "variables": {
    "SharedAccessKeyName": "Event-Dispatcher-Send-Access-Key",
    "ReadOnlySharedAccessKeyName": "Plugin-Listen-Access-Key",
    "ConsumerGroup": "plugin"
  },

  "resources": [
    {
      // Event Hub Namespace
      "type": "Microsoft.EventHub/namespaces",
      "apiVersion": "2018-01-01-preview",
      "name": "[parameters('namespaceName')]",
      "location": "[resourceGroup().location]",
      "sku": {
        "name": "Standard",
        "tier": "Standard",
        "capacity": 1
      },
      "properties": {
        "zoneRedundant": false,
        "isAutoInflateEnabled": false,
        "maximumThroughputUnits": 0,
        "kafkaEnabled": true
      },
      "resources": [
        {
          // Event Hub
          "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'))]",
          "type": "Microsoft.EventHub/namespaces/eventhubs",
          "apiVersion": "2017-04-01",
          "location": "[resourceGroup().location]",
          "properties": {
            "messageRetention": 1
          },
          "dependsOn": [
            "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]"
          ],
          "resources": [
            {
              // Shared Access Key
              "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('SharedAccessKeyName'))]",
              "type": "Microsoft.EventHub/namespaces/eventhubs/authorizationRules",
              "apiVersion": "2017-04-01",
              "dependsOn": [
                "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]",
                "[resourceId('Microsoft.EventHub/namespaces/eventhubs', parameters('namespaceName'), parameters('eventHubName'))]"
              ],
              "properties": {
                "rights": [
                  "Send",
                  "Listen"
                ]
              }
            },
            {
              // Read-only Shared Access Key
              "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('ReadOnlySharedAccessKeyName'))]",
              "type": "Microsoft.EventHub/namespaces/eventhubs/authorizationRules",
              "apiVersion": "2017-04-01",
              "dependsOn": [
                "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]",
                "[resourceId('Microsoft.EventHub/namespaces/eventhubs', parameters('namespaceName'), parameters('eventHubName'))]"
              ],
              "properties": {
                "rights": [
                  "Listen"
                ]
              }
            },
            {
              // Consumer Groups
              "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('ConsumerGroup'))]",
              "type": "Microsoft.EventHub/namespaces/eventhubs/consumergroups",
              "apiVersion": "2017-04-01",
              "dependsOn": [
                "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]",
                "[resourceId('Microsoft.EventHub/namespaces/eventhubs', parameters('namespaceName'), parameters('eventHubName'))]"
              ],
              "properties": {}
            }
          ]
        }
      ]
    }
  ],

  "outputs": {
    "SharedAccessKey": {
      "type": "string",
      "value": "[listKeys(concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('SharedAccessKeyName')), '2017-04-01').primaryKey.value]"
    },
    "SharedAccessKeyName": {
      "type": "string",
      "value": "[variables('SharedAccessKeyName')]"
    },
    "ReadOnlySharedAccessKey": {
      "type": "string",
      "value": "[listKeys(concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('ReadOnlySharedAccessKeyName')), '2017-04-01').primaryKey.value]"
    },
    "ReadOnlySharedAccessKeyName": {
      "type": "string",
      "value": "[variables('ReadOnlySharedAccessKeyName')]"
    },
    "ConsumerGroup": {
      "type": "string",
      "value": "[variables('ConsumerGroup')]"
    }
  }
}

</code>```

Thank you.

答:
Below example is similar to your requirements and I have tested this template and it is working fine. So you can modify your template according to this example and get it working.</p>

```<code>{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "namespaceName": {
            "type": "String",
            "metadata": {
                "description": "Name of EventHub namespace"
            }
        },
        "namespaceAuthorizationRuleName": {
            "type": "String",
            "metadata": {
                "description": "Name of Namespace Authorization Rule"
            }
        },
        "isAutoInflateEnabled": {
            "defaultValue": "True",
            "allowedValues": [
                "True",
                "False"
            ],
            "type": "String",
            "metadata": {
                "description": "Enable or disable AutoInflate"
            }
        },
        "maximumThroughputUnits": {
            "defaultValue": 0,
            "minValue": 0,
            "maxValue": 20,
            "type": "Int",
            "metadata": {
                "description": "Enable or disable AutoInflate"
            }
        },
        "eventHubName": {
            "type": "String",
            "metadata": {
                "description": "Name of Event Hub"
            }
        },
        "eventhubAuthorizationRuleName": {
            "type": "String",
            "metadata": {
                "description": "Name of Eventhub Authorization Rule"
            }
        },
        "eventhubAuthorizationRuleName1": {
            "type": "String",
            "metadata": {
                "description": "Name of Eventhub Authorization Rule"
            }
        },
        "consumerGroupName": {
            "type": "String",
            "metadata": {
                "description": "Name of Consumer Group"
            }
        },
        "messageRetentionInDays": {
            "defaultValue": 1,
            "minValue": 1,
            "maxValue": 7,
            "type": "Int",
            "metadata": {
                "description": "How long to retain the data in Event Hub"
            }
        },
        "partitionCount": {
            "defaultValue": 4,
            "minValue": 2,
            "maxValue": 32,
            "type": "Int",
            "metadata": {
                "description": "Number of partitions chosen"
            }
        },
        "location": {
            "defaultValue": "[resourceGroup().location]",
            "type": "String",
            "metadata": {
                "description": "Location for all resources."
            }
        }
    },
    "variables": {
        "defaultSASKeyName": "RootManageSharedAccessKey",
        "authRuleResourceId": "[resourceId('Microsoft.EventHub/namespaces/authorizationRules', parameters('namespaceName'), variables('defaultSASKeyName'))]",
        "nsAuthorizationRuleId": "[resourceId('Microsoft.EventHub/namespaces/authorizationRules', parameters('namespaceName'), parameters('namespaceAuthorizationRuleName'))]",
        "ehAuthorizationRuleId1": "[resourceId('Microsoft.EventHub/namespaces/eventhubs/authorizationRules', parameters('namespaceName'),parameters('eventHubName'), parameters('eventhubAuthorizationRuleName'))]",
        "ehAuthorizationRuleId2": "[resourceId('Microsoft.EventHub/namespaces/eventhubs/authorizationRules', parameters('namespaceName'),parameters('eventHubName'), parameters('eventhubAuthorizationRuleName1'))]"
    },
    "resources": [
        {
            "type": "Microsoft.EventHub/namespaces",
            "apiVersion": "2017-04-01",
            "name": "[parameters('namespaceName')]",
            "location": "[parameters('location')]",
            "sku": {
                "name": "Standard"
            },
            "properties": {
                "isAutoInflateEnabled": true,
                "maximumThroughputUnits": 7
            },
            "resources": [
                {
                    "type": "eventhubs",
                    "apiVersion": "2017-04-01",
                    "name": "[parameters('eventHubName')]",
                    "dependsOn": [
                        "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'))]"
                    ],
                    "properties": {
                        "messageRetentionInDays": 4,
                        "partitionCount": 4
                    },
                    "resources": [
                        {
                            "type": "consumergroups",
                            "apiVersion": "2017-04-01",
                            "name": "[parameters('consumerGroupName')]",
                            "dependsOn": [
                                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'),'/eventhubs/',parameters('eventHubName'))]"
                            ],
                            "properties": {
                                "userMetadata": "User Metadata"
                            }
                        },
                        {
                            "type": "authorizationRules",
                            "apiVersion": "2017-04-01",
                            "name": "[parameters('eventhubAuthorizationRuleName')]",
                            "dependsOn": [
                                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'),'/eventhubs/',parameters('eventHubName'))]"
                            ],
                            "properties": {
                                "rights": [
                                    "Send",
                                    "Listen",
                                    "Manage"
                                ]
                            }
                        },
                        {
                            "type": "authorizationRules",
                            "apiVersion": "2017-04-01",
                            "name": "[parameters('eventhubAuthorizationRuleName1')]",
                            "dependsOn": [
                                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'),'/eventhubs/',parameters('eventHubName'))]"
                            ],
                            "properties": {
                                "rights": [
                                    "Send"
                                ]
                            }
                        }
                    ]
                }
            ]
        },
        {
            "type": "Microsoft.EventHub/namespaces/AuthorizationRules",
            "apiVersion": "2017-04-01",
            "name": "[concat(parameters('namespaceName'), '/', parameters('namespaceAuthorizationRuleName'))]",
            "dependsOn": [
                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'))]"
            ],
            "properties": {
                "rights": [
                    "Send",
                    "Listen",
                    "Manage"
                ]
            }
        }
    ],
    "outputs": {
        "defaultNamespaceConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('authRuleResourceId'), '2017-04-01').primaryConnectionString]"
        },
        "defaultSharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('authRuleResourceId'), '2017-04-01').primaryKey]"
        },
        "NamespaceConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('nsAuthorizationRuleId'), '2017-04-01').primaryConnectionString]"
        },
        "SharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('nsAuthorizationRuleId'), '2017-04-01').primaryKey]"
        },
        "EventHubConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId1'), '2017-04-01').primaryConnectionString]"
        },
        "EventHubSharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId1'), '2017-04-01').primaryKey]"
        },
        "EventHub1ConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId2'), '2017-04-01').primaryConnectionString]"
        },
        "EventHub1SharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId2'), '2017-04-01').primaryKey]"
        }
    }
}
</code>```

Body:
I have a custom ARM template which deploys an EventHub Namespace with a child EventHub, which in turn has two AuthorizationRules and one ConsumerGroup as children. The validation passes but I get a deployment error. It seems the Azure Resource Manager starts by trying to deploy the Authorization Rules before the namespace even exist, even though I added the required "dependsOn" properties, but then the deployment goes on from start to finish and successfully deploys every resource. It could be tolerable if I only deployed it from the portal, but when I deploy this template programmatically, I get an error even though the deployment was "successful" and my rollback mechanism triggers.

Here are links to the errors given by the portal :

Deployment Steps

Error Messages

Here is my ARM Template (comments are there only to help you find resources):

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "namespaceName": {
      "type": "string"
    },
    "eventHubName": {
      "type": "string"
    }
  },

  "variables": {
    "SharedAccessKeyName": "Event-Dispatcher-Send-Access-Key",
    "ReadOnlySharedAccessKeyName": "Plugin-Listen-Access-Key",
    "ConsumerGroup": "plugin"
  },

  "resources": [
    {
      // Event Hub Namespace
      "type": "Microsoft.EventHub/namespaces",
      "apiVersion": "2018-01-01-preview",
      "name": "[parameters('namespaceName')]",
      "location": "[resourceGroup().location]",
      "sku": {
        "name": "Standard",
        "tier": "Standard",
        "capacity": 1
      },
      "properties": {
        "zoneRedundant": false,
        "isAutoInflateEnabled": false,
        "maximumThroughputUnits": 0,
        "kafkaEnabled": true
      },
      "resources": [
        {
          // Event Hub
          "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'))]",
          "type": "Microsoft.EventHub/namespaces/eventhubs",
          "apiVersion": "2017-04-01",
          "location": "[resourceGroup().location]",
          "properties": {
            "messageRetention": 1
          },
          "dependsOn": [
            "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]"
          ],
          "resources": [
            {
              // Shared Access Key
              "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('SharedAccessKeyName'))]",
              "type": "Microsoft.EventHub/namespaces/eventhubs/authorizationRules",
              "apiVersion": "2017-04-01",
              "dependsOn": [
                "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]",
                "[resourceId('Microsoft.EventHub/namespaces/eventhubs', parameters('namespaceName'), parameters('eventHubName'))]"
              ],
              "properties": {
                "rights": [
                  "Send",
                  "Listen"
                ]
              }
            },
            {
              // Read-only Shared Access Key
              "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('ReadOnlySharedAccessKeyName'))]",
              "type": "Microsoft.EventHub/namespaces/eventhubs/authorizationRules",
              "apiVersion": "2017-04-01",
              "dependsOn": [
                "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]",
                "[resourceId('Microsoft.EventHub/namespaces/eventhubs', parameters('namespaceName'), parameters('eventHubName'))]"
              ],
              "properties": {
                "rights": [
                  "Listen"
                ]
              }
            },
            {
              // Consumer Groups
              "name": "[concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('ConsumerGroup'))]",
              "type": "Microsoft.EventHub/namespaces/eventhubs/consumergroups",
              "apiVersion": "2017-04-01",
              "dependsOn": [
                "[resourceId('Microsoft.EventHub/namespaces', parameters('namespaceName'))]",
                "[resourceId('Microsoft.EventHub/namespaces/eventhubs', parameters('namespaceName'), parameters('eventHubName'))]"
              ],
              "properties": {}
            }
          ]
        }
      ]
    }
  ],

  "outputs": {
    "SharedAccessKey": {
      "type": "string",
      "value": "[listKeys(concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('SharedAccessKeyName')), '2017-04-01').primaryKey.value]"
    },
    "SharedAccessKeyName": {
      "type": "string",
      "value": "[variables('SharedAccessKeyName')]"
    },
    "ReadOnlySharedAccessKey": {
      "type": "string",
      "value": "[listKeys(concat(parameters('namespaceName'), '/', parameters('eventHubName'), '/', variables('ReadOnlySharedAccessKeyName')), '2017-04-01').primaryKey.value]"
    },
    "ReadOnlySharedAccessKeyName": {
      "type": "string",
      "value": "[variables('ReadOnlySharedAccessKeyName')]"
    },
    "ConsumerGroup": {
      "type": "string",
      "value": "[variables('ConsumerGroup')]"
    }
  }
}

Thank you.

Body:
Below example is similar to your requirements and I have tested this template and it is working fine. So you can modify your template according to this example and get it working.

{
    "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "namespaceName": {
            "type": "String",
            "metadata": {
                "description": "Name of EventHub namespace"
            }
        },
        "namespaceAuthorizationRuleName": {
            "type": "String",
            "metadata": {
                "description": "Name of Namespace Authorization Rule"
            }
        },
        "isAutoInflateEnabled": {
            "defaultValue": "True",
            "allowedValues": [
                "True",
                "False"
            ],
            "type": "String",
            "metadata": {
                "description": "Enable or disable AutoInflate"
            }
        },
        "maximumThroughputUnits": {
            "defaultValue": 0,
            "minValue": 0,
            "maxValue": 20,
            "type": "Int",
            "metadata": {
                "description": "Enable or disable AutoInflate"
            }
        },
        "eventHubName": {
            "type": "String",
            "metadata": {
                "description": "Name of Event Hub"
            }
        },
        "eventhubAuthorizationRuleName": {
            "type": "String",
            "metadata": {
                "description": "Name of Eventhub Authorization Rule"
            }
        },
        "eventhubAuthorizationRuleName1": {
            "type": "String",
            "metadata": {
                "description": "Name of Eventhub Authorization Rule"
            }
        },
        "consumerGroupName": {
            "type": "String",
            "metadata": {
                "description": "Name of Consumer Group"
            }
        },
        "messageRetentionInDays": {
            "defaultValue": 1,
            "minValue": 1,
            "maxValue": 7,
            "type": "Int",
            "metadata": {
                "description": "How long to retain the data in Event Hub"
            }
        },
        "partitionCount": {
            "defaultValue": 4,
            "minValue": 2,
            "maxValue": 32,
            "type": "Int",
            "metadata": {
                "description": "Number of partitions chosen"
            }
        },
        "location": {
            "defaultValue": "[resourceGroup().location]",
            "type": "String",
            "metadata": {
                "description": "Location for all resources."
            }
        }
    },
    "variables": {
        "defaultSASKeyName": "RootManageSharedAccessKey",
        "authRuleResourceId": "[resourceId('Microsoft.EventHub/namespaces/authorizationRules', parameters('namespaceName'), variables('defaultSASKeyName'))]",
        "nsAuthorizationRuleId": "[resourceId('Microsoft.EventHub/namespaces/authorizationRules', parameters('namespaceName'), parameters('namespaceAuthorizationRuleName'))]",
        "ehAuthorizationRuleId1": "[resourceId('Microsoft.EventHub/namespaces/eventhubs/authorizationRules', parameters('namespaceName'),parameters('eventHubName'), parameters('eventhubAuthorizationRuleName'))]",
        "ehAuthorizationRuleId2": "[resourceId('Microsoft.EventHub/namespaces/eventhubs/authorizationRules', parameters('namespaceName'),parameters('eventHubName'), parameters('eventhubAuthorizationRuleName1'))]"
    },
    "resources": [
        {
            "type": "Microsoft.EventHub/namespaces",
            "apiVersion": "2017-04-01",
            "name": "[parameters('namespaceName')]",
            "location": "[parameters('location')]",
            "sku": {
                "name": "Standard"
            },
            "properties": {
                "isAutoInflateEnabled": true,
                "maximumThroughputUnits": 7
            },
            "resources": [
                {
                    "type": "eventhubs",
                    "apiVersion": "2017-04-01",
                    "name": "[parameters('eventHubName')]",
                    "dependsOn": [
                        "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'))]"
                    ],
                    "properties": {
                        "messageRetentionInDays": 4,
                        "partitionCount": 4
                    },
                    "resources": [
                        {
                            "type": "consumergroups",
                            "apiVersion": "2017-04-01",
                            "name": "[parameters('consumerGroupName')]",
                            "dependsOn": [
                                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'),'/eventhubs/',parameters('eventHubName'))]"
                            ],
                            "properties": {
                                "userMetadata": "User Metadata"
                            }
                        },
                        {
                            "type": "authorizationRules",
                            "apiVersion": "2017-04-01",
                            "name": "[parameters('eventhubAuthorizationRuleName')]",
                            "dependsOn": [
                                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'),'/eventhubs/',parameters('eventHubName'))]"
                            ],
                            "properties": {
                                "rights": [
                                    "Send",
                                    "Listen",
                                    "Manage"
                                ]
                            }
                        },
                        {
                            "type": "authorizationRules",
                            "apiVersion": "2017-04-01",
                            "name": "[parameters('eventhubAuthorizationRuleName1')]",
                            "dependsOn": [
                                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'),'/eventhubs/',parameters('eventHubName'))]"
                            ],
                            "properties": {
                                "rights": [
                                    "Send"
                                ]
                            }
                        }
                    ]
                }
            ]
        },
        {
            "type": "Microsoft.EventHub/namespaces/AuthorizationRules",
            "apiVersion": "2017-04-01",
            "name": "[concat(parameters('namespaceName'), '/', parameters('namespaceAuthorizationRuleName'))]",
            "dependsOn": [
                "[concat('Microsoft.EventHub/namespaces/', parameters('namespaceName'))]"
            ],
            "properties": {
                "rights": [
                    "Send",
                    "Listen",
                    "Manage"
                ]
            }
        }
    ],
    "outputs": {
        "defaultNamespaceConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('authRuleResourceId'), '2017-04-01').primaryConnectionString]"
        },
        "defaultSharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('authRuleResourceId'), '2017-04-01').primaryKey]"
        },
        "NamespaceConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('nsAuthorizationRuleId'), '2017-04-01').primaryConnectionString]"
        },
        "SharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('nsAuthorizationRuleId'), '2017-04-01').primaryKey]"
        },
        "EventHubConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId1'), '2017-04-01').primaryConnectionString]"
        },
        "EventHubSharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId1'), '2017-04-01').primaryKey]"
        },
        "EventHub1ConnectionString": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId2'), '2017-04-01').primaryConnectionString]"
        },
        "EventHub1SharedAccessPolicyPrimaryKey": {
            "type": "String",
            "value": "[listkeys(variables('ehAuthorizationRuleId2'), '2017-04-01').primaryKey]"
        }
    }
}


来源: stackexchange

问:
Python for loop for list
I have a list containing some integer values.

My list is l = [5,10,15,25,30,45].

I want to write a program that the values in list is between 5 to 35

```<code>list1 = [15,35]
list2 = ['Height','Weight','5','10','25','30','40']
res = [int(ele) if ele.isdigit() else ele for ele in list2]
print([ x for x in res if type(x)==int ])
</code>```

this is the code that I written,now I want to compare list 1 and list 2 , then print values in list 2 of range in the first list

ContentLicense: CC BY-SA 4.0

Title: Python for loop for list

Body:
I have a list containing some integer values.

My list is l = [5,10,15,25,30,45].

I want to write a program that the values in list is between 5 to 35

list1 = [15,35]
list2 = ['Height','Weight','5','10','25','30','40']
res = [int(ele) if ele.isdigit() else ele for ele in list2]
print([ x for x in res if type(x)==int ])

this is the code that I written,now I want to compare list 1 and list 2 , then print values in list 2 of range in the first list

Body:
l = [5,10,15,25,30,45, 35]
a = [i for i in l if 5 <= i <= 35]


答:
```<code>l = [5,10,15,25,30,45]
for x in l:
  if(x>=5) and (x<=35):
     print(x)
</code>```

<p>for every number in the array print if it's between and including 5 and 35. </p>

Title: Python for loop for list

Body:
l = [5,10,15,25,30,45]
for x in l:
  if(x>=5) and (x<=35):
     print(x)

for every number in the array print if it's between and including 5 and 35.


问:
LINQ dictionary to jagged array?
There is a method that returns 2D array, this method querying a dictionary from LINQ query and trying to store keys and values in 2D array.

But I am not able to do that

```<code>public string[][] GetRecordFields(string selectedRecord)
    {

        var recordFields = (from record in _recordMasterList
                            where record.Item1 == selectedRecord
                            select new
                            {
                                record.Item2.Keys,
                                record.Item2.Values
                            }).ToArray();
      return recordFields;
  }
</code>```

But its failed, is there any way?

EDIT:
Type of _recordMasterList

```<code>List<Tuple<string, Dictionary<string, string>>> _recordMasterList;
</code>```

答:
Your question is still a little bit confussing.  Is this the behaviour you are looking for?

(I know that this answer could be optimised a lot, but it seams the easiest way to figue out what you want.)

```<code>public string[,] GetRecordFields(string selectedRecord)
{
    //List<Tuple<string, Dictionary<string, string>>> _recordMasterList;

    List<Dictionary<string, string>> selectedRecords
        = (from record in _recordMasterList
            where record.Item1 == selectedRecord
            select record.Item2)
            .ToList();

    int totalNumberOfRecords = 0;

    foreach(Dictionary<string, string> d in selectedRecords)
    {
        totalNumberOfRecords += d.Count();
    }

    string[,] result = new string[2, totalNumberOfRecords];

    int i = 0;
    foreach(Dictionary<string, string> d in selectedRecords)
    {
        foreach(KeyValuePair<string, string> kvp in d)
        {
            result[0,i] = kvp.Key;
            result[1,i] = kvp.Value;
            ii++;
        }
    }

    return result;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: LINQ dictionary to jagged array?

Body:
There is a method that returns 2D array, this method querying a dictionary from LINQ query and trying to store keys and values in 2D array.

But I am not able to do that

public string[][] GetRecordFields(string selectedRecord)
    {

        var recordFields = (from record in _recordMasterList
                            where record.Item1 == selectedRecord
                            select new
                            {
                                record.Item2.Keys,
                                record.Item2.Values
                            }).ToArray();
      return recordFields;
  }

But its failed, is there any way?

EDIT:
Type of _recordMasterList

List<Tuple<string, Dictionary<string, string>>> _recordMasterList;

Body:
Your question is still a little bit confussing.  Is this the behaviour you are looking for?

(I know that this answer could be optimised a lot, but it seams the easiest way to figue out what you want.)

public string[,] GetRecordFields(string selectedRecord)
{
    //List<Tuple<string, Dictionary<string, string>>> _recordMasterList;

    List<Dictionary<string, string>> selectedRecords
        = (from record in _recordMasterList
            where record.Item1 == selectedRecord
            select record.Item2)
            .ToList();

    int totalNumberOfRecords = 0;

    foreach(Dictionary<string, string> d in selectedRecords)
    {
        totalNumberOfRecords += d.Count();
    }

    string[,] result = new string[2, totalNumberOfRecords];

    int i = 0;
    foreach(Dictionary<string, string> d in selectedRecords)
    {
        foreach(KeyValuePair<string, string> kvp in d)
        {
            result[0,i] = kvp.Key;
            result[1,i] = kvp.Value;
            ii++;
        }
    }

    return result;
}


问:
Getting "No command 'pew' found" every time I open the Terminal (Ubuntu 16.04)
I am currently using Ubuntu 16.04 LTS.

The problem is when I open up a Terminal, I get this message.

```<code>No command 'pew' found, did you mean:
 Command 'pyew' from package 'pyew' (universe)
 Command 'new' from package 'nmh' (universe)
 Command 'pen' from package 'pen' (universe)
 Command 'pex' from package 'pex' (universe)
 Command 'pmw' from package 'pmw' (universe)
 Command 'peg' from package 'peg' (universe)
 Command 'paw' from package 'paw-common' (universe)
 Command 'spew' from package 'spew' (universe)
 Command 'pev' from package 'pev' (universe)
 Command 'pee' from package 'moreutils' (universe)
 Command 'psw' from package 'wise' (universe)
pew: command not found
bash: : No such file or directory
ubuntu@ubuntupc:~$
</code>```

I got this message while I was trying to install and run this CVPR project.

What I did was

made a virtual environment ubuntu@ubuntupc:~/Downloads/camconvs-master$ virtualenv -p /usr/bin/python3.5 cvpr_env

activated virtual environment ubuntu@ubuntupc:~/Downloads/camconvs-master$ source cvpr_env/bin/activate

installed project requirements (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pip install -r
  requirements.txt

installed cmake-setuptools (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pip install
  cmake-setuptools

installed pew (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pip install pew

did these (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ cd lmbspecialops

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master/lmbspecialops$ python setup.py install

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master/lmbspecialops$ pew add python

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master/lmbspecialops$ cd ..

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ export LMBSPECIALOPS_LIB="/path/to/camconvs/lmbspecialops/build/lib.linux-x86_64-3.5/lmbspecialops.so"

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pew add python/

After doing these, the message showed up every time while opening a new terminal and rebooting the system did not fix this issue.

I am new to Ubuntu and I don't know what I have done to the system. Question is, how do I stop these messages showing up?

UPDATE 2

My ~/profile is this? Sorry, I am not sure.

```<code>ubuntu@ubuntupc:/etc$ sudo cat profile
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "$PS1" ]; then
  if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi
</code>```

I also checked profile.d folder and I cannot see any pew related ones.

```<code>ubuntu@ubuntupc:/etc$ ls profile.d
appmenu-qt5.sh    bash_completion.sh     vte-2.91.sh
apps-bin-path.sh  cedilla-portuguese.sh
</code>```

答: It looks to me what you did here is you installed pew while within your virtual environment (cvpr_env) instead of on your host system. When you open a new terminal it runs through and executes the commands in your ~/.profile, so my guess is that pew perhaps edited that file? Is there anything in there that's pew-related?

Body:
I am currently using Ubuntu 16.04 LTS.

The problem is when I open up a Terminal, I get this message.

No command 'pew' found, did you mean:
 Command 'pyew' from package 'pyew' (universe)
 Command 'new' from package 'nmh' (universe)
 Command 'pen' from package 'pen' (universe)
 Command 'pex' from package 'pex' (universe)
 Command 'pmw' from package 'pmw' (universe)
 Command 'peg' from package 'peg' (universe)
 Command 'paw' from package 'paw-common' (universe)
 Command 'spew' from package 'spew' (universe)
 Command 'pev' from package 'pev' (universe)
 Command 'pee' from package 'moreutils' (universe)
 Command 'psw' from package 'wise' (universe)
pew: command not found
bash: : No such file or directory
ubuntu@ubuntupc:~$

I got this message while I was trying to install and run this CVPR project.

What I did was

made a virtual environment ubuntu@ubuntupc:~/Downloads/camconvs-master$ virtualenv -p /usr/bin/python3.5 cvpr_env

activated virtual environment ubuntu@ubuntupc:~/Downloads/camconvs-master$ source cvpr_env/bin/activate

installed project requirements (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pip install -r
  requirements.txt

installed cmake-setuptools (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pip install
  cmake-setuptools

installed pew (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pip install pew

did these (cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ cd lmbspecialops

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master/lmbspecialops$ python setup.py install

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master/lmbspecialops$ pew add python

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master/lmbspecialops$ cd ..

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ export LMBSPECIALOPS_LIB="/path/to/camconvs/lmbspecialops/build/lib.linux-x86_64-3.5/lmbspecialops.so"

(cvpr_env) ubuntu@ubuntupc:~/Downloads/camconvs-master$ pew add python/

After doing these, the message showed up every time while opening a new terminal and rebooting the system did not fix this issue.

I am new to Ubuntu and I don't know what I have done to the system. Question is, how do I stop these messages showing up?

UPDATE 2

My ~/profile is this? Sorry, I am not sure.

ubuntu@ubuntupc:/etc$ sudo cat profile
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

if [ "$PS1" ]; then
  if [ "$BASH" ] && [ "$BASH" != "/bin/sh" ]; then
    # The file bash.bashrc already sets the default PS1.
    # PS1='\h:\w\$ '
    if [ -f /etc/bash.bashrc ]; then
      . /etc/bash.bashrc
    fi
  else
    if [ "`id -u`" -eq 0 ]; then
      PS1='# '
    else
      PS1='$ '
    fi
  fi
fi

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

I also checked profile.d folder and I cannot see any pew related ones.

ubuntu@ubuntupc:/etc$ ls profile.d
appmenu-qt5.sh    bash_completion.sh     vte-2.91.sh
apps-bin-path.sh  cedilla-portuguese.sh


问:
how to place a listview inside a SingleChildScrollView but prevent them from scrolling separately?
I have a widget tree like this:

```<code>SingleChildScrollView
   Column
     Container
       ListView(or GridView)
</code>```

the problem is that when my widget tree is like above, it gives me error of

NEEDS PAINT

so I change my widget tree like this:

```<code>Column
     Container
       ListView(or GridView)
</code>```

but in this situation the ListView or GridView part scrolls separately, and I want the whole widget tree to scroll. how do you think I can achieve it?

答:
As suggested by other answers, you can do that by setting shrinkWrap: true, physics: NeverScrollableScrollPhysics(), but building a shrinkwrapped listview is more expensive than building a normal listview, I think it will be a good idea to use a map() on the list.

```<code>Column(
  children: itemList.map((item) {
       return Text(item);
    }).toList()
),
</code>```

Body:
I have a widget tree like this:

SingleChildScrollView
   Column
     Container
       ListView(or GridView)

the problem is that when my widget tree is like above, it gives me error of

NEEDS PAINT

so I change my widget tree like this:

Column
     Container
       ListView(or GridView)

but in this situation the ListView or GridView part scrolls separately, and I want the whole widget tree to scroll. how do you think I can achieve it?

Body:
As suggested by other answers, you can do that by setting shrinkWrap: true, physics: NeverScrollableScrollPhysics(), but building a shrinkwrapped listview is more expensive than building a normal listview, I think it will be a good idea to use a map() on the list.

Column(
  children: itemList.map((item) {
       return Text(item);
    }).toList()
),


问:
How to detect encoding of a file format
I have files in bucket of s3 and i am reading them as stream. I want to detect the encoding of the diffrent files.

I used chardet library , i am getting this error:

```<code>TypeError: Expected object of type bytes or bytearray, got: <class
'botocore.response.StreamingBody'>
</code>```

and my code is:

```<code>a = (obj.get()['Body'])
reader = chardet.detect(a).get('encoding')
print(reader)
</code>```

And is there any other ways to detect the encoding before opening of a file

答:
i got this

you need to use read function again!

```<code>      a = (obj.get()['Body']._raw_stream).read()
</code>```

Title: How to detect encoding of a file format

Body:
I have files in bucket of s3 and i am reading them as stream. I want to detect the encoding of the diffrent files.

I used chardet library , i am getting this error:

TypeError: Expected object of type bytes or bytearray, got: <class
'botocore.response.StreamingBody'>

and my code is:

a = (obj.get()['Body'])
reader = chardet.detect(a).get('encoding')
print(reader)

And is there any other ways to detect the encoding before opening of a file

Body:
i got this

you need to use read function again!

      a = (obj.get()['Body']._raw_stream).read()


问:
Child component height and width is not applying in angular
I am not able to apply height/width to a child component in angular. Please have a look and let me know where and what I am doing wrong

app.component.html

```<code><app-child [width]="10" [height]="10"></app-child>
</code>```

.child.ts

```<code>import { Component, OnInit, Input, ViewEncapsulation, Renderer2, ElementRef } from '@angular/core';

@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor(private renderer: Renderer2, private elRef: ElementRef) { }

  @Input() width
  @Input() height

  ngAfterViewInit() {
    this.renderer.setStyle(this.elRef.nativeElement, 'height', this.height + "%");
    this.renderer.setStyle(this.elRef.nativeElement, 'width', this.width + "%");
  }
}
</code>```

.child.html

```<code><div class="wrapper" [style.width.%]="width" [style.height.%]="height">
 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div>

Issues :
</code>```

app-child component still takes full width and hight it should be 10%
div inside app-child taking correct width but height is still 100%

Example link

https://stackblitz.com/edit/angular-qgobau

答:
Your issue is with CSS. Your component is taking correct values (10%) but you also need to set height on the parent elements (maybe body or html).
You could set a fixed height on html, something like:

```<code>html {
height: 500px;
}
</code>```

Body:
I am not able to apply height/width to a child component in angular. Please have a look and let me know where and what I am doing wrong

app.component.html

<app-child [width]="10" [height]="10"></app-child>

.child.ts

import { Component, OnInit, Input, ViewEncapsulation, Renderer2, ElementRef } from '@angular/core';

@Component({
  encapsulation: ViewEncapsulation.None,
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor(private renderer: Renderer2, private elRef: ElementRef) { }

  @Input() width
  @Input() height

  ngAfterViewInit() {
    this.renderer.setStyle(this.elRef.nativeElement, 'height', this.height + "%");
    this.renderer.setStyle(this.elRef.nativeElement, 'width', this.width + "%");
  }
}

.child.html

 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Issues :

app-child component still takes full width and hight it should be 10%
div inside app-child taking correct width but height is still 100%

Example link

https://stackblitz.com/edit/angular-qgobau

Body:
Your issue is with CSS. Your component is taking correct values (10%) but you also need to set height on the parent elements (maybe body or html).
You could set a fixed height on html, something like:

html {
height: 500px;
}


问:
How to create mocked post object with specific size in Mocha
In my nodejs code I created a function that if request body is bigger than 1MB (I check size with req.get("content-length") ) then do something.
I would like to create test in mocha to POST object with mocked 1MB request body size to test it if my functionality works.</p>

答:
Short answer, you can create a specific size request body like this:

const buf = Buffer.alloc(1024 * 1024, '.');

Create a 1MB size request body for your case.

Long answer, here is a working example using express.js web framework and supertest test framework.

index.ts:

import express from 'express';
import bodyParser from 'body-parser';

function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

function createServer() {
  const app = express();
  const port = 3000;

  app.use(bodyParser.text({ limit: 10 * 1024 * 1024 /** 10MB */ }));
  app.post('/', (req, res) => {
    console.log(JSON.stringify(req.body));
    const contentLength = req.get('content-length');
    console.log('content length: ', formatBytes(contentLength));
    res.sendStatus(200);
  });

  return app.listen(port, () => {
    console.log(`HTTP server is listening to http://localhost:${port}`);
  });
}

export { createServer };
```

<p><code>index.test.ts</code>:</p>

<pre class="lang-js prettyprint-override"><code>import { createServer } from './';
import request from 'supertest';

describe('60286487', () => {
  let server;
  beforeEach(() => {
    server = createServer();
  });
  afterEach((done) => {
    server.close(done);
  });
  it('should pass', (done) => {
    const buf = Buffer.alloc(1024 * 1024, '.');
    request(server)
      .post('/')
      .send(buf.toString())
      .set('Content-Type', 'text/plain')
      .set('Content-Length', buf.byteLength.toString())
      .expect(200, done);
  });
});
</code>```

Integration test results:

.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."
content length:  1 MB
    ✓ should pass (3877ms)
```

Body:
Short answer, you can create a specific size request body like this:

const buf = Buffer.alloc(1024 * 1024, '.');

Create a 1MB size request body for your case.

Long answer, here is a working example using express.js web framework and supertest test framework.

index.ts:

import express from 'express';
import bodyParser from 'body-parser';

function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const dm = decimals < 0 ? 0 : decimals;
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];

  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

function createServer() {
  const app = express();
  const port = 3000;

  app.use(bodyParser.text({ limit: 10 * 1024 * 1024 /** 10MB */ }));
  app.post('/', (req, res) => {
    console.log(JSON.stringify(req.body));
    const contentLength = req.get('content-length');
    console.log('content length: ', formatBytes(contentLength));
    res.sendStatus(200);
  });

  return app.listen(port, () => {
    console.log(`HTTP server is listening to http://localhost:${port}`);
  });
}

export { createServer };

index.test.ts:

import { createServer } from './';
import request from 'supertest';

describe('60286487', () => {
  let server;
  beforeEach(() => {
    server = createServer();
  });
  afterEach((done) => {
    server.close(done);
  });
  it('should pass', (done) => {
    const buf = Buffer.alloc(1024 * 1024, '.');
    request(server)
      .post('/')
      .send(buf.toString())
      .set('Content-Type', 'text/plain')
      .set('Content-Length', buf.byteLength.toString())
      .expect(200, done);
  });
});

Integration test results:

.........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................."
content length:  1 MB
    ✓ should pass (3877ms)


问:
Thread-safe uniform random number generator
I have some parallel Fortran90 code in which each thread needs to generate the same sequence of random numbers.

I have a random number generator that seems to be thread-unsafe, since, for a given seed, I'm completely unable to repeat the same results each time I run the program.

I surfed unsuccessfully (almost) the entire web looking for some code of a thread-safe RNG. Could anyone provide me with (the link to) the code of one?

Thanks in advance!

答:
I understand you need every thread to produce the same stream of random numbers.

A very good Pseudo Random Generator that will generate a reproducable stream of numbers and is quite fast is the MT19937. Just make sure that you generate the seed before spawning off the threads, but generate a separate instance of the MT in every thread (make the instance of the MT thread local). That way it will be guaranteed that every MT will produce the same stream of numbers.

OwnerDisplayName: Bellman

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Eric P


问:
getting sprites superposed on spritesheet
I am designing a game in which I have an animal on the center of the screen and I am trying to highlight some parts of the animal by changing the color using setRGB (in cocos2d). I have already decomposed the animal into several sprites and I am trying to re-build the animal on the screen. The problem is that I don't want to have to write all the coordinates of the different sprites and place them on the screen (I have over 20). So I am trying to make a spritesheet with superposed sprites out of them and change their color by just calling the appropriate sprite. Is there a software to do that ? I tried Zwoptex and texturePacker but they force the sprite to be next to each other, not superposed.
Can it be done ? </p>

答:
You can use zwoptex to do this.

Make your sprite (whole), lets pretend it is 100x100 in width and height.

Lets imagine there are 5 body parts, 2 legs, 2 arms and the torso/head.

Save out 5 identical images of your sprite, then erase all but the body parts required, (so on your first image, leave only the left arm etc)

Make sure they are saved out all exactly the same size (100x100), leaving all the transparent size as pure alpha.

When you bring these into zwoptex, it will remove the blank transparent space (saving your texture space on the spritesheet, but it remembers the sprite size).

So you can place all 5 sprites onto the same co-ordinate, and they will line up correctly, drawing your full sprite.


问:
Attribute app:cornerRadius doen't work for the MaterialButton
Inside screen's layout I'm trying yo implement MaterialButton from new Material Components with rounded corners

```<code><android.support.design.button.MaterialButton
        android:text="@string/login"
        android:id="@+id/btnEntrance"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="104dp"
        style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
        android:layout_height="40dp"
        app:cornerRadius="8dp"/>
</code>```

But on preview screen rounded corners are not visible - this attribute doen't bring any effect on view. Can anybody explain me why?

答:
```<code>android:theme="@style/Theme.MaterialComponents"
</code>```

Add this line line to your Material button.

Body:
Inside screen's layout I'm trying yo implement MaterialButton from new Material Components with rounded corners

<android.support.design.button.MaterialButton
        android:text="@string/login"
        android:id="@+id/btnEntrance"
        app:layout_constraintStart_toStartOf="parent"
        android:layout_marginStart="104dp"
        style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
        android:layout_height="40dp"
        app:cornerRadius="8dp"/>

But on preview screen rounded corners are not visible - this attribute doen't bring any effect on view. Can anybody explain me why?

Body:
android:theme="@style/Theme.MaterialComponents"

Add this line line to your Material button.


问:
How can I fetch data from an HTTPS Url via Proxy?
I am getting Connection timed out: connect.

My code:

```<code>    System.setProperty("http.proxyHost", "proxy.mycompany.com");
    System.setProperty("http.proxyPort", "8080");

    String url = URL_BASE + "&limit=5";
    URL u = new URL(url);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
            u.openStream()));

    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();
</code>```

答: I suggest you fetch the content using apache http commons httpclient. There you can set proxy authentication on the client without the need to modify the global jvm properties.</p>

Body:
I am getting Connection timed out: connect.

My code:

    System.setProperty("http.proxyHost", "proxy.mycompany.com");
    System.setProperty("http.proxyPort", "8080");

    String url = URL_BASE + "&limit=5";
    URL u = new URL(url);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(
            u.openStream()));

    String inputLine;

    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);

    in.close();


问:
How can I get additional data from one promise to another?
I have one promise that relies on the return value of another promise. I'm successfully passing that value to the second promise, but there's additional data that's created in the first promise that I'd like to get into the second promise somehow.

Here's my code:

```<code>const getAlbumInfo = async (album, artist) => {
        let hostname = 'http://www.musicbrainz.org';
        let path = `/ws/2/release-group/?query=release:${album}%20AND%20artist:${artist}&fmt=json`;
        let res = await fetch(hostname + path);
        return res.json();
};

const getAlbumArt = async (albumInfo) => {
    let res = await fetch(`${albumInfo.url}`);
    return res.json();
};

let artist = '', album = '';

getAlbumInfo(album, artist)
    .then((res) => {
        const metadata = {
            album: res['album'],
            artist: res['artist'],
            url: res['url']
        };

        return getAlbumArt(metadata);
    })
    .then((res) => {
        console.log(res);  // prints result from getAlbumArt

        // I also need the contents of metadata here
    })
    .catch(e => { console.error(e); });
</code>```

So I'm getting album metadata in the first promise, which includes a URL, and then I'm running a fetch on that URL, which returns a second promise. The problem is that I need access to the album metadata in the second promise.

Since I'm returning/passing the metadata into the second promise, I tried using Object.assign() inside getAlbumArt() to combine the metadata and the fetch result, but that didn't seem to work.

答:
await for the second promise and then return both to the next .then block. Use deconstruct for a simpler use case:

```<code>getAlbumInfo(album, artist)
    .then(async ({album, artist, url}) => {
        const metadata = {album, artist, url};
        const arts = await getAlbumArt(metadata);

        return {arts, metadata};
    })
    .then(({arts, metadata}) => {
        // You have both here
    })
    .catch(console.log);
</code>```

Alternatively, this entire action can be inside an async function:

```<code>const getAlbum = async (album, artist) => {
  const info = await getAlbumInfo(album, artist);
  const metadata = {
    album: info.album,
    artist: info.artist,
    url: info.url,
  };
  const arts = await getAlbumArt(metadata);

  // everything is available;
};
</code>```

Body:
I have one promise that relies on the return value of another promise. I'm successfully passing that value to the second promise, but there's additional data that's created in the first promise that I'd like to get into the second promise somehow.

Here's my code:

const getAlbumInfo = async (album, artist) => {
        let hostname = 'http://www.musicbrainz.org';
        let path = `/ws/2/release-group/?query=release:${album}%20AND%20artist:${artist}&fmt=json`;
        let res = await fetch(hostname + path);
        return res.json();
};

const getAlbumArt = async (albumInfo) => {
    let res = await fetch(`${albumInfo.url}`);
    return res.json();
};

let artist = '', album = '';

getAlbumInfo(album, artist)
    .then((res) => {
        const metadata = {
            album: res['album'],
            artist: res['artist'],
            url: res['url']
        };

        return getAlbumArt(metadata);
    })
    .then((res) => {
        console.log(res);  // prints result from getAlbumArt

        // I also need the contents of metadata here
    })
    .catch(e => { console.error(e); });

So I'm getting album metadata in the first promise, which includes a URL, and then I'm running a fetch on that URL, which returns a second promise. The problem is that I need access to the album metadata in the second promise.

Since I'm returning/passing the metadata into the second promise, I tried using Object.assign() inside getAlbumArt() to combine the metadata and the fetch result, but that didn't seem to work.

Body:
await for the second promise and then return both to the next .then block. Use deconstruct for a simpler use case:

getAlbumInfo(album, artist)
    .then(async ({album, artist, url}) => {
        const metadata = {album, artist, url};
        const arts = await getAlbumArt(metadata);

        return {arts, metadata};
    })
    .then(({arts, metadata}) => {
        // You have both here
    })
    .catch(console.log);

Alternatively, this entire action can be inside an async function:

const getAlbum = async (album, artist) => {
  const info = await getAlbumInfo(album, artist);
  const metadata = {
    album: info.album,
    artist: info.artist,
    url: info.url,
  };
  const arts = await getAlbumArt(metadata);

  // everything is available;
};


问:
Elasticsearch - Return documents only if all given terms are present
Suppose I have a field called message. This field would contain a sentence.
Also, I have an array of terms. This Array would contain multiple words.
Something like,

```<code>"query": {
                "bool": {
                  "must": [
                    {
                      "terms": {
                        "message": [
                          "domain",
                          "rejected"
                        ],
                        "boost": 1
                      }
                    }
                  ]
                }
</code>```

Suppose, I want to return only those documents where domain and rejected, both must be present irrespective of their order in the sentence. What should the query be like?

答:
You should be able to leverage the intervals query to achieve what you need, like this:

```<code>{
  "query": {
    "intervals": {
      "message": {
        "match": {
          "query": "domain rejected",
          "max_gaps": -1,
          "ordered": false
        }
      }
    }
  }
}
</code>```

What this query says is basically this:

within the message field, find the terms domain and rejected in no particular order and no particular proximity

Body:
Suppose I have a field called message. This field would contain a sentence.
Also, I have an array of terms. This Array would contain multiple words.
Something like,

"query": {
                "bool": {
                  "must": [
                    {
                      "terms": {
                        "message": [
                          "domain",
                          "rejected"
                        ],
                        "boost": 1
                      }
                    }
                  ]
                }

Suppose, I want to return only those documents where domain and rejected, both must be present irrespective of their order in the sentence. What should the query be like?

Body:
You should be able to leverage the intervals query to achieve what you need, like this:

{
  "query": {
    "intervals": {
      "message": {
        "match": {
          "query": "domain rejected",
          "max_gaps": -1,
          "ordered": false
        }
      }
    }
  }
}

What this query says is basically this:

within the message field, find the terms domain and rejected in no particular order and no particular proximity


问:
Accessing artefacts within a Windows file share (domain) from Docker container
So....

I was wondering if anyone is able to assist me on this one?

Basically I have created a self-hosted docker container for use to use as a build agent (Azure DevOps)

Now I have started to test the agent, and I am having issues being able to publish artefacts to the destination due to the fact our drop folder is on a windows file share (domain joined)

Is anyone able to shed some light on how I can go about being able to access this file share to drop artefacts from the build and also to be able to download them for the release stage?

We use on-prem TFS Azure DevOps rather than Azure DevOps Services :(

TIA,

Update

In the end, I was able to resolve this issue.

What I did to resolve this issue was I created a gMSA account on the domain controller, then created a credspec file on the machine hosting the docker container, then finally I ran the container using the following command docker run --security-opt "credentialspec=file://<credspecfilename>.json" --hostname <hostname> -it <Image-name> PowerShell

Once the container was up and running I was able to confirm that the directories were available by running the following command dir <server>\\<share> - Also I had to make sure that the newly created gMSA account had permissions to the share.

So I continued to join the container to the agent pool of our DevOps server and then I ran a test build. As expected I was able to pull/publish artefacts from our on-prem domain-joined server.

Again, thanks guys for assisting me on this issue.

答:
You could use Build.ArtifactStagingDirectory, just as Daniel mentioned in the comment, publish your build artifacts to server.

Build.ArtifactStagingDirectory

The local path on the agent where any artifacts are copied to before
  being pushed to their destination. For example: c:\agent_work\1\a

A typical way to use this folder is to publish your build artifacts
  with the Copy files and Publish build artifacts tasks.

Details steps you could refer Thomas F. Abraham's reply in this question: How to copy azure pipeline artifacts to a docker image which is microsoft dotnetcore runtime image

Add a Docker task after the publish, configured to "Build"

Set the "Build Context" in the task to $(Build.ArtifactStagingDirectory). That's the root path Docker will
  use for commands like COPY in a Dockerfile.

Commit a Dockerfile to your repo, and set the Dockerfile path in the task to match its location

Set up the Dockerfile like this (I'm assuming .NET Core 2.2 here):
  FROM mcr.microsoft.com/dotnet/core/aspnet:2.2 WORKDIR /app COPY . .
  ENTRYPOINT ["dotnet", "myAppNameHere.dll"] Because you've set the
  Docker Build Context to $(Build.ArtifactStagingDirectory), where your
  app has been published, the COPY command will use that as a "current
  working directory." The translation of the COPY is "copy everything in
  $(Build.ArtifactStagingDirectory) to the /app folder inside the
  container."

That'll get you a basic Docker container that simply contains your
  pre-built and published app files.

Besides, you could also choose to publish these artifacts as a Nuget package. For this way, you could kindly refer this blog: Accessing Azure Artifacts from a docker container in a Pipelines build.


问:
Why is the api url blocked and helm not installed while I'm linking gitlab to Kubernetes?
I want to integrate Kubernetes cluster configured in on-premises environment with gitlab.

When adding a cluster, I clicked Add Existing Cluster and filled in all other spaces, and the API URL entered the IP output by the following command.

```<code>kubectl cluster-info | grep 'Kubernetes master' | awk '/http/ {print $NF}'
</code>```

```<code>https://10.0.0.xxx:6443
</code>```

However, it did not proceed with the error "platform kubernetes api url is blocked: requests to the local network are not allowed".

I saw an article in the admin area to do a webhook check, but I'm on the gitlab website, and no matter where I find it, I can't find the admin area. I'm guessing that it only comes with gitlab to install.

https://edenmal.moe/post/2019/GitLab-Kubernetes-Using-GitLab-CIs-Kubernetes-Cluster-feature/

When I saw and followed the example, I entered the API URL as "https: //kubernetes.default.svc.cluster.local: 443" and the cluster connection was established. But helm won't install.

So I tried to install helm on a Kubernetes cluster manually, but gitlab does not recognize helm.

What is the difference between the two API URLs above??

How can i solve it ??

答: As mentioned in comments, you are running your CI job on someone else's network. As such, it cannot talk to your private IPs in your own network. You will need to expose your kube-apiserver to the internet somehow. This is usually done using a LoadBalancer service called kubernetes that is created automatically. However that would only work if you have set up something that supports LoadBalancer services like MetalLB.

Body:
I want to integrate Kubernetes cluster configured in on-premises environment with gitlab.

When adding a cluster, I clicked Add Existing Cluster and filled in all other spaces, and the API URL entered the IP output by the following command.

kubectl cluster-info | grep 'Kubernetes master' | awk '/http/ {print $NF}'

https://10.0.0.xxx:6443

However, it did not proceed with the error "platform kubernetes api url is blocked: requests to the local network are not allowed".

I saw an article in the admin area to do a webhook check, but I'm on the gitlab website, and no matter where I find it, I can't find the admin area. I'm guessing that it only comes with gitlab to install.

https://edenmal.moe/post/2019/GitLab-Kubernetes-Using-GitLab-CIs-Kubernetes-Cluster-feature/

When I saw and followed the example, I entered the API URL as "https: //kubernetes.default.svc.cluster.local: 443" and the cluster connection was established. But helm won't install.

So I tried to install helm on a Kubernetes cluster manually, but gitlab does not recognize helm.

What is the difference between the two API URLs above??

How can i solve it ??


问:
Is it possible to train data on 4 features and test on only using features?
I have done training on four features including Month, day, Hour and Temperature which is predicting some value , what i wan to do is to predict value on basis of month ,hour and day of next day only because i don't know the temp of next day(which is going to be unseen data not used in training) so this makes the testing of data using only 3 features.
Classifier used is SVR.
I am a beginner in machine learning.

Your response will be appreciated

答:
Your idea does not work, the SVR will be trained on 4 features and you cannot run it with 3 features. So short answer: No

Longer answer: If you want to predict that value train the algorithm only with the 3 known features: Month, day, Hour (btw this is one feature: time), and you will have to work with a timeseries.


问:
Android DataBinding custom adapter in multiple modules

Context

I have 3 modules: A, B, and app. app depends on A, and A depends on B.

Custom data binding adapters are in B.

```<code>app -> A -> B
</code>```

All modules have data binding enabled, as well as kapt plugin.

```<code>plugins {
    kotlin("kapt")
}

android {
    dataBinding.isEnabled = true
}
</code>```

Problem

Let's say I have the following binding adpater function:

```<code>@BindingAdapter("fontWeight")
fun TextView.setFontWeight(family: String)
</code>```

In app, I can use it as an extension function, but cannot use it as a custom binding adapter.

```<code>textView.setFontWeight("bold") // It works

<TextView
  app:fontWeight='@{"bold"}' // It doesn't work
</code>```

What's interesting is that If I make app module directly depends on B, then the binding adapter works as expected.

```<code>app -> B
</code>```

What's the problem? Do you have any ideas? Thanks in advance.

Update

When I remove this lines of code from build.gradle.kts it works properly, but I cannot figure out what's going on.

```<code>flavorDimensions("dimension")

productFlavors {
    create("dev")
    create("staging")
    create("production")

    forEach { flavor ->
        with(flavor) {
            dimension = "dimension"
            versionCode = generateVersionCode(name)
            versionName = generateVersionName(name)

            if (name != "production") {
                applicationIdSuffix = ".$name"
            }
        }
    }
}
</code>```

答:
I think this be difference of implementation and api in gradle.
When you use implementation for A and you can use that modules and when use api   your app is depend on A and all its dependencies like B.

Body:
Context

I have 3 modules: A, B, and app. app depends on A, and A depends on B.

Custom data binding adapters are in B.

app -> A -> B

All modules have data binding enabled, as well as kapt plugin.

plugins {
    kotlin("kapt")
}

android {
    dataBinding.isEnabled = true
}

Problem

Let's say I have the following binding adpater function:

@BindingAdapter("fontWeight")
fun TextView.setFontWeight(family: String)

In app, I can use it as an extension function, but cannot use it as a custom binding adapter.

textView.setFontWeight("bold") // It works

<TextView
  app:fontWeight='@{"bold"}' // It doesn't work

What's interesting is that If I make app module directly depends on B, then the binding adapter works as expected.

app -> B

What's the problem? Do you have any ideas? Thanks in advance.

Update

When I remove this lines of code from build.gradle.kts it works properly, but I cannot figure out what's going on.

flavorDimensions("dimension")

productFlavors {
    create("dev")
    create("staging")
    create("production")

    forEach { flavor ->
        with(flavor) {
            dimension = "dimension"
            versionCode = generateVersionCode(name)
            versionName = generateVersionName(name)

            if (name != "production") {
                applicationIdSuffix = ".$name"
            }
        }
    }
}


问:
What is the right way to get an NSString object from an NSArray, keeping Memory Managment in mind?
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

```<code>NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
</code>```

Now I want to get an object from this NSArray at index 2.

```<code>NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?
</code>```

OR I should first alloc nameString and then assign value to it ?

答:
Check out the Cocoa Memory Management rules (how many times have I started a post with that sentence?).  In particular

You only release or autorelease objects you own.

You take ownership of an object if you create it using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message.

You use release or autorelease to relinquish ownership of an object. autorelease just means “send a release message in the future” (specifically: when the used autorelease pool receives a drain message—to understand when this will be, see “Autorelease Pools”).

Does the method objectAtIndex: begin with "alloc"?  No.  Does it begin with "new"?  No.  Does it begin with "copy" or "mutableCopy"?  No.  Have you sent retain to the returned object? No.

Therefore you do not own nameString.  Therefore you must not release or auto release it.

Sorry if the above seems a bit "leading by the nose" but when I first started with Objective-C, I found it useful to pretty much go through all the above in my head in exactly that way, otherwise I tended to get it wrong.  It doesn't take long for it all to become second nature.

Body:
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];

Now I want to get an object from this NSArray at index 2.

NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?

OR I should first alloc nameString and then assign value to it ?


问:
Close menu on document but not on menu
I am using vue.js with vuetify and i'm building a main navigation. When you click a link it opens a menu and when to click the link it closes the menu so a toggle.

When you click away from the link I have an event listener that listens for a click event and closes the menu if you click anywhere else on the page.

However when you click the menu that is now open it closes it. How can I exclude the main menu from being clicked and keep the menu open but close it when you click anywhere else except the link being clicked or the main menu that it is opening.

The Main menu

```<code><div ref="ddm">
    <ul class="sau-c-nav__main-nav">
       <li><a href="#" v-on:click="setActive('products')" :class="{ active:isActive('products') }">Products</a> <i class="fal fa-chevron-down"></i></li>
       <li><a href="#" v-on:click="setActive('solutions')" :class="{ active:isActive('solutions') }">Solutions</a> <i class="fal fa-chevron-down"></i></li>
       <li><a href="#" v-on:click="setActive('resources')" :class="{ active:isActive('resources') }">Resources</a> <i class="fal fa-chevron-down"></i></li>
       <li><a href="#" v-on:click="setActive('about-us')" :class="{ active:isActive('about-us') }">About Us</a> <i class="fal fa-chevron-down"></i></li>
     </ul>
 </div>
</code>```

The Navigation (sub menu)

```<code><v-row ref="abc" v-if="mainMenuIsOpen" class="msg" no-gutters>
     <v-col>
        <v-container id="ll">
            <v-row no-gutters>
                 <v-col xl="8" offset-xl="2">
                      <div v-if="activeItem === 'products'" style="height:50px;">this is the menu for products</div>
                       <div v-if="activeItem === 'solutions'" style="height:50px;">this is the menu for solutions</div>
                       <div v-if="activeItem === 'resources'" style="height:50px;">this is the menu for Resources</div>
                       <div v-if="activeItem === 'about-us'" style="height:50px;">this is the menu for about us</div>
                  </v-col>
              </v-row>
         </v-container>
      </v-col>
  </v-row>
</code>```

The JS

```<code><script>
    export default {
        data:()=>({
            activeItem: '',
            mainMenuIsOpen:false,
            main:false,
            isOpen:true
        }),
        created() {
            document.addEventListener('click', this.documentClick)
        },
        destroyed() {
            // important to clean up!!
            document.removeEventListener('click', this.documentClick)
        },
        methods:{
            documentClick(e){
                let el = this.$refs.ddm;
                let target = e.target;
                //close menu if it is outside
                if ((el !== target) && !el.contains(target)) {
                    this.mainMenuIsOpen=false;
                }
            },
            isActive: function (menuItem) {
                return this.activeItem === menuItem;
            },
            setActive: function (menuItem) {
                if(this.activeItem === menuItem){
                    this.mainMenuIsOpen = !this.mainMenuIsOpen;
                }
                else{
                    this.activeItem = menuItem;
                    this.mainMenuIsOpen = true;
                }
            }
        }
    }
</script>
</code>```

答:
You need to pass the specific id of the element on which you want to perform the action.

```<code>new Vue({
  el: '#app', // id of element
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    trigger () {
        this.$refs.fileInput.click()
    }
  }
})
</code>```

You can check the JS Fiddle link

Title: Close menu on document but not on menu

Body:
I am using vue.js with vuetify and i'm building a main navigation. When you click a link it opens a menu and when to click the link it closes the menu so a toggle.

When you click away from the link I have an event listener that listens for a click event and closes the menu if you click anywhere else on the page.

However when you click the menu that is now open it closes it. How can I exclude the main menu from being clicked and keep the menu open but close it when you click anywhere else except the link being clicked or the main menu that it is opening.

The Main menu

Products

Solutions

Resources

About Us

The Navigation (sub menu)

<v-row ref="abc" v-if="mainMenuIsOpen" class="msg" no-gutters>
     <v-col>
        <v-container id="ll">
            <v-row no-gutters>
                 <v-col xl="8" offset-xl="2">

this is the menu for products

this is the menu for solutions

this is the menu for Resources

this is the menu for about us

                  </v-col>
              </v-row>
         </v-container>
      </v-col>
  </v-row>

The JS

Body:
You need to pass the specific id of the element on which you want to perform the action.

new Vue({
  el: '#app', // id of element
  data: {
    message: 'Hello Vue.js!'
  },
  methods: {
    trigger () {
        this.$refs.fileInput.click()
    }
  }
})

You can check the JS Fiddle link


问:
Is it possible to integrate AWS Codepipeline and Jenkins in such a way?
I'm trying to set up a pipeline for CI for a project, which is heavily using AWS stack. We already have Bitbucket and Jenkins servers, so ideally I would like to avoid the creation of infrastructure components with duplicating functionality.

What I would like to get: Jenkins executes unit/integration tests, builds artifacts and then triggers Codepipeline, which deploys CF stacks and performs end-to-end tests. I was able to create a primitive pipeline with a combination of AWS steps plugin, S3 and Codepipeline.

Jenkinsfile:

```<code>#!groovy

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building..'
                sh "mvn clean package"
            }
        }
        stage('S3upload') {
            steps {
                withAWS(region:'us-east-1',credentials:'JENKINS') {
                    s3Upload(bucket: 'somebucket', workingDir:'target', includePathPattern:'some.jar');

                }
            }
        }
    }
}
</code>```

Codepipeline:

```<code>{
    "pipeline": {
        "name": "SomePipeline",
        <...>
        ,
        "stages": [
            {
                "name": "Source",
                "actions": [
                    {
                        "name": "Source",
                        "actionTypeId": {
                            "category": "Source",
                            "owner": "AWS",
                            "provider": "S3",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "PollForSourceChanges": "false",
                            "S3Bucket": "somebucket",
                            "S3ObjectKey": "some.jar"
                        },
                        "outputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "inputArtifacts": [],
                        "region": "us-east-1"
                    }
                ]
            },
            {
                "name": "DeployCognitoStack",
                "actions": [
                    {
                        "name": "DeployCognitoStack",
                        "actionTypeId": {
                            "category": "Deploy",
                            "owner": "AWS",
                            "provider": "CloudFormation",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "ActionMode": "CREATE_UPDATE",
                            "Capabilities": "CAPABILITY_IAM,CAPABILITY_AUTO_EXPAND",
                            "RoleArn": "arn:aws:iam::*:role/CloudFormationRole",
                            "StackName": "cognitostacktest",
                            "TemplatePath": "SourceArtifact::cognito-stack.yaml"
                        },
                        "outputArtifacts": [],
                        "inputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "region": "us-east-1"
                    }
                ]
            },
            {
                "name": "DeployLambdaStack",
                "actions": [
                    {
                        "name": "DeployLambdaStack",
                        "actionTypeId": {
                            "category": "Deploy",
                            "owner": "AWS",
                            "provider": "CloudFormation",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "ActionMode": "CREATE_UPDATE",
                            "Capabilities": "CAPABILITY_NAMED_IAM,CAPABILITY_AUTO_EXPAND",
                            "RoleArn": "arn:aws:iam::*:role/CloudFormationRole",
                            "StackName": "lambdatest",
                            "TemplatePath": "SourceArtifact::lambda-stack.yaml"
                        },
                        "outputArtifacts": [],
                        "inputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "region": "us-east-1"
                    }
                ]
            },
            <here should be test stage>
        ],
        "version": 5
    }
}
</code>```

What I do not like is that I need to look separately to the results of Jenkins job execution and to results of Codepipeline execution. I would prefer to see everything in Jenkins.

Which options do I see:

Forget about Codepipeline, use only commands from AWS Steps plugin to deploy test stacks and execute end-to-end tests by scripts.

Follow AWS four-steps pipeline tutorial. If I understand it correctly, this solution will require active polling of SCM and pulling code to AWS.

Am I missing something?

答:
As now CodePipeline has direct Bitbucket cloud support [1] and also supports the jenkins as custom stage directly [2] you can setup the CodePipeline which will use the bitbucket as source stage and jenkins actions as part of stage so that we can still use the jenkins for all the testing and once there is success from the jenkis we can go ahead and do the Deployment to CloudFormation.

[1]https://aws.amazon.com/about-aws/whats-new/2019/12/aws-codepipeline-now-supports-atlassian-bitbucket-cloud/

[2]https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-four-stage-pipeline.html

Body:
I'm trying to set up a pipeline for CI for a project, which is heavily using AWS stack. We already have Bitbucket and Jenkins servers, so ideally I would like to avoid the creation of infrastructure components with duplicating functionality.

What I would like to get: Jenkins executes unit/integration tests, builds artifacts and then triggers Codepipeline, which deploys CF stacks and performs end-to-end tests. I was able to create a primitive pipeline with a combination of AWS steps plugin, S3 and Codepipeline.

Jenkinsfile:

#!groovy

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo 'Building..'
                sh "mvn clean package"
            }
        }
        stage('S3upload') {
            steps {
                withAWS(region:'us-east-1',credentials:'JENKINS') {
                    s3Upload(bucket: 'somebucket', workingDir:'target', includePathPattern:'some.jar');

                }
            }
        }
    }
}

Codepipeline:

{
    "pipeline": {
        "name": "SomePipeline",
        <...>
        ,
        "stages": [
            {
                "name": "Source",
                "actions": [
                    {
                        "name": "Source",
                        "actionTypeId": {
                            "category": "Source",
                            "owner": "AWS",
                            "provider": "S3",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "PollForSourceChanges": "false",
                            "S3Bucket": "somebucket",
                            "S3ObjectKey": "some.jar"
                        },
                        "outputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "inputArtifacts": [],
                        "region": "us-east-1"
                    }
                ]
            },
            {
                "name": "DeployCognitoStack",
                "actions": [
                    {
                        "name": "DeployCognitoStack",
                        "actionTypeId": {
                            "category": "Deploy",
                            "owner": "AWS",
                            "provider": "CloudFormation",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "ActionMode": "CREATE_UPDATE",
                            "Capabilities": "CAPABILITY_IAM,CAPABILITY_AUTO_EXPAND",
                            "RoleArn": "arn:aws:iam::*:role/CloudFormationRole",
                            "StackName": "cognitostacktest",
                            "TemplatePath": "SourceArtifact::cognito-stack.yaml"
                        },
                        "outputArtifacts": [],
                        "inputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "region": "us-east-1"
                    }
                ]
            },
            {
                "name": "DeployLambdaStack",
                "actions": [
                    {
                        "name": "DeployLambdaStack",
                        "actionTypeId": {
                            "category": "Deploy",
                            "owner": "AWS",
                            "provider": "CloudFormation",
                            "version": "1"
                        },
                        "runOrder": 1,
                        "configuration": {
                            "ActionMode": "CREATE_UPDATE",
                            "Capabilities": "CAPABILITY_NAMED_IAM,CAPABILITY_AUTO_EXPAND",
                            "RoleArn": "arn:aws:iam::*:role/CloudFormationRole",
                            "StackName": "lambdatest",
                            "TemplatePath": "SourceArtifact::lambda-stack.yaml"
                        },
                        "outputArtifacts": [],
                        "inputArtifacts": [
                            {
                                "name": "SourceArtifact"
                            }
                        ],
                        "region": "us-east-1"
                    }
                ]
            },
            <here should be test stage>
        ],
        "version": 5
    }
}

What I do not like is that I need to look separately to the results of Jenkins job execution and to results of Codepipeline execution. I would prefer to see everything in Jenkins.

Which options do I see:

Forget about Codepipeline, use only commands from AWS Steps plugin to deploy test stacks and execute end-to-end tests by scripts.

Follow AWS four-steps pipeline tutorial. If I understand it correctly, this solution will require active polling of SCM and pulling code to AWS.

Am I missing something?


问:
Creating a Master excel file from dynamic CSV output using Python
I am trying to create a repository "Master" excel file from a CSV which will be generated and overwritten every couple of hours. The code below creates a new excel file and writes the content from "combo1.csv" to "master.xlsx". However, whenever the combo1 file is updated, the code basically overwrites the contents in the "master.xlsx" file. I need to append the contents from "combo1" to "Master" without the headers being inserted every time. Can someone help me with this?   </p>

```<code>import pandas as pd

writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')
df = pd.read_csv('combo1.csv')
df.to_excel(writer, sheet_name='sheetname')
writer.save()
</code>```

答:
First read the excel file and then need to perform below method to append the rows.</p>

```<code>import pandas as pd
from xlsxwriter import load_workbook

df = pd.DataFrame({'Name': ['abc','def','xyz','ysv'],
                   'Age': [08,45,32,26]})
writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')

writer.book = load_workbook('Master.xlsx')

writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)

reader = pd.read_excel(r'master.xlsx')

df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)

writer.close()
</code>```

Body:
I am trying to create a repository "Master" excel file from a CSV which will be generated and overwritten every couple of hours. The code below creates a new excel file and writes the content from "combo1.csv" to "master.xlsx". However, whenever the combo1 file is updated, the code basically overwrites the contents in the "master.xlsx" file. I need to append the contents from "combo1" to "Master" without the headers being inserted every time. Can someone help me with this?

import pandas as pd

writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')
df = pd.read_csv('combo1.csv')
df.to_excel(writer, sheet_name='sheetname')
writer.save()

Body:
First read the excel file and then need to perform below method to append the rows.

import pandas as pd
from xlsxwriter import load_workbook

df = pd.DataFrame({'Name': ['abc','def','xyz','ysv'],
                   'Age': [08,45,32,26]})
writer = pd.ExcelWriter('master.xlsx', engine='xlsxwriter')

writer.book = load_workbook('Master.xlsx')

writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)

reader = pd.read_excel(r'master.xlsx')

df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)

writer.close()


问:
jQuery form repeater and select2 dont work together
I am using Select2 and jQuery form repeater (https://github.com/DubFriend/jquery.repeater)

I have searched on google/so for 2 days, but cant seem to get it to work.

```<code>include jquery/select2.js/jquery.repeater.js

var form = $('#form');
form.find('select').select2();

form.repeater({
    show: function () {
    $(this).show(function(){
        form.find('select').select2('destroy').select2();
    });
    },
    hide: function (remove) {
      $(this).hide(remove);
    }
});
</code>```

The problem is the jQuery.repeater clones the div tag in which the input and select elements are when select2 is already initialized and has already changed the DOM, so jQuery.repeater copies the changed DOM. I tried to destroy select2 before the repeat action is called, but that dindt work either.

答:
The main thing is select2 is being initialized before repeater is initialized,

As repeater change the name of all type of input fields so after repeater getting initialized select2 couldn't find the correct reference , so its make a mess.

So we need to initialize select2 once our repeater is ready. Here is the code below:

 $(document).ready(function () {
        $('.repeater').repeater({
            initEmpty: false, // it also could be true
            show: function () {
    $(this).slideDown(function(){
     $(this).find('.select2').select2({
      placeholder: 'Select an option'
     });
    });
            },

            hide: function (deleteElement) {
                $(this).slideUp(deleteElement);
            },

            ready: function (setIndexes) {
               $('.select2').select2({
     placeholder: 'Select an option'
    });
            },
            isFirstItemUndeletable: false
        })
    });```

Body:
I am using Select2 and jQuery form repeater (https://github.com/DubFriend/jquery.repeater)

I have searched on google/so for 2 days, but cant seem to get it to work.

include jquery/select2.js/jquery.repeater.js

var form = $('#form');
form.find('select').select2();

form.repeater({
    show: function () {
    $(this).show(function(){
        form.find('select').select2('destroy').select2();
    });
    },
    hide: function (remove) {
      $(this).hide(remove);
    }
});

The problem is the jQuery.repeater clones the div tag in which the input and select elements are when select2 is already initialized and has already changed the DOM, so jQuery.repeater copies the changed DOM. I tried to destroy select2 before the repeat action is called, but that dindt work either.