问:
'for' statements should use the format 'for x in y': while iterating over value retrieved from dictionary using django template
I have a context dictionary entry objectives that maps objective query objects to a list of tests that belong to that objective.  Example code:

```<code>objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objectives:
    tests = Test.objects.filter(objective=objective)
    context_dict["objectives"][objective] = tests
</code>```

In my django html template, I iterate over objectives and display them.  I then want to iterate over the tests that belong to these objectives.  When I do this:

```<code>{% for test in {{ objectives|get_item:objective }} %}
</code>```

I get a TemplateSyntaxError: 'for' statements should use the format 'for x in y':

In the application/templatetags directory, I have:

```<code>from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)
</code>```

If instead I make {{ objectives|get_item:objective }} a JS variable, I see that it does indeed produce a list, which I should be able to iterate over.  Of course, I can't mix JS variables and the django template tags, so this is only for debugging:

```<code>var tests = {{ objectives|get_item:objective }}

var tests = [<Test: AT399_8_1>, <Test: AT399_8_2>, <Test: AT399_8_3>, <Test: AT399_8_4>, <Test: AT399_8_5> '...(remaining elements truncated)...']
</code>```

How do I iterate over this list in the django template tag?

答:
**This is Right Answer for  Using Django if else and for loop **

Note :- We Have to Put  Key in  " " string (Double quotes) some time produce an error so That is good way bcz i faced that problem whwn i Learned

```<code>{% if    'numbers'|length > 0  %}
            {% for i in numbers %}
                 {% if i > 20 %}
                     {{i}}
                {% endif %}
            {% endfor %}

 {% else %}
    Empty
 {% endif %}
</code>```

Body:
I have a context dictionary entry objectives that maps objective query objects to a list of tests that belong to that objective.  Example code:

objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objectives:
    tests = Test.objects.filter(objective=objective)
    context_dict["objectives"][objective] = tests

In my django html template, I iterate over objectives and display them.  I then want to iterate over the tests that belong to these objectives.  When I do this:

{% for test in {{ objectives|get_item:objective }} %}

I get a TemplateSyntaxError: 'for' statements should use the format 'for x in y':

In the application/templatetags directory, I have:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

If instead I make {{ objectives|get_item:objective }} a JS variable, I see that it does indeed produce a list, which I should be able to iterate over.  Of course, I can't mix JS variables and the django template tags, so this is only for debugging:

var tests = {{ objectives|get_item:objective }}

var tests = [<Test: AT399_8_1>, <Test: AT399_8_2>, <Test: AT399_8_3>, <Test: AT399_8_4>, <Test: AT399_8_5> '...(remaining elements truncated)...']

How do I iterate over this list in the django template tag?

Body:
**This is Right Answer for  Using Django if else and for loop **

Note :- We Have to Put  Key in  " " string (Double quotes) some time produce an error so That is good way bcz i faced that problem whwn i Learned

{% if    'numbers'|length > 0  %}
            {% for i in numbers %}
                 {% if i > 20 %}
                     {{i}}
                {% endif %}
            {% endfor %}

 {% else %}
    Empty
 {% endif %}


来源: stackexchange

问:
Incorrect routing in routerLink Angular
Something I'm confused with this routing.

app-routing file

```<code>const routes: Routes = [
  {
    path: '',
    redirectTo: 'main',
    pathMatch: 'full'
  },
  {
    path: 'main',
    loadChildren: () =>
      import('./modules/main/main.module').then(m => m.MainModule)
  },
  {
    path: 'auth',
    loadChildren: () =>
      import('./modules/auth/auth.module').then(m => m.AuthModule)
  },
  {
    path: '', component: HomeMenuComponent, children: [
    ],
  }];
</code>```

file auth-routing

```<code>const routes: Routes = [
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: '',
    children: [
      {
        path: 'login',
        component: LoginComponent
      },
      {
        path: 'register',
        component: RegisterComponent
      }
    ]
  }
];
</code>```

But when in the template login-component.html I'm trying to follow the link:

```<code><span class="link" routerLink="register" routerLinkActive="active-link">Зарегистрироваться</span>
</code>```

it throws me to this address:

```<code>auth/login/register
</code>```

Why is this happening?
On the one hand, that's right, I'm at the auth/login level. But on the other hand, when I look at other examples, they somehow turn out at such addresses. That's just I don't understand what I need to add for this.

答:
From https://angular.io/api/router/RouterLink

"If the first segment begins with /, the router looks up the route from the root of the app.

If the first segment begins with ./, or doesn't begin with a slash, the router looks in the children of the current activated route."

You're probably at auth/login when you use the routerLink='register', which as per the above quote, takes you to auth/login/register

Try routerLink="/auth/register"

ContentLicense: CC BY-SA 4.0

Title: Incorrect routing in routerLink Angular

Body:
Something I'm confused with this routing.

app-routing file

const routes: Routes = [
  {
    path: '',
    redirectTo: 'main',
    pathMatch: 'full'
  },
  {
    path: 'main',
    loadChildren: () =>
      import('./modules/main/main.module').then(m => m.MainModule)
  },
  {
    path: 'auth',
    loadChildren: () =>
      import('./modules/auth/auth.module').then(m => m.AuthModule)
  },
  {
    path: '', component: HomeMenuComponent, children: [
    ],
  }];

file auth-routing

const routes: Routes = [
  {
    path: '',
    redirectTo: 'login',
    pathMatch: 'full'
  },
  {
    path: '',
    children: [
      {
        path: 'login',
        component: LoginComponent
      },
      {
        path: 'register',
        component: RegisterComponent
      }
    ]
  }
];

But when in the template login-component.html I'm trying to follow the link:

Зарегистрироваться

it throws me to this address:

auth/login/register

Why is this happening?
On the one hand, that's right, I'm at the auth/login level. But on the other hand, when I look at other examples, they somehow turn out at such addresses. That's just I don't understand what I need to add for this.


问:
What is annotations? In simple terms?
In Groovy++ I often hear of the term Annotations. Can anyone explain me what is that in simple terms?</p>

答:
In short It's a way to label a piece of code.  But it's not Groovy specific thing.

These labels can be used as meta-data by other applications to perform tasks like identifying unit test, dependency injection, or just a way to tell someone that a method is deprecated.

Here is a link to some java documentation.

ContentLicense: CC BY-SA 3.0

Title: What is annotations? In simple terms?


问:
Typescript: Why doesn't typeguard work with previous state
When making a simple rock, paper, scissors game with typescript I cam across an interaction I couldn't understand.

```<code>const [gameState, setGameState] = useState<gameState>({
    choice: null,
    score: 0,
  });

function fetchScore() {
    let score = localStorage.getItem("score");
    if (typeof score === "string") {
      setGameState((prev) => ({ ...prev, score:
      parseInt(score) })); // Typescript still thinks score can be null
    }
}
</code>```

parseInt throws an error saying score could be set to null despite the type guard.

I did some messing around and found that it was only happening when I used prev state.

```<code> const [test,setTest] = useState(0);

 function fetchScore() {
    let score = localStorage.getItem("score");
    if (typeof score === "string") {
      setTest(parseInt(score))//Score is correctly guarded
    }
  }
</code>```

I am currently handling it by typecasting score as a string but I would like to understand what cause this to happen?

答:
That is because you are using score inside of a callback function. So typescript assumes that score variable can be changed before callback function will be executed and score potentially can null inside callback function.
Solutions:
the best solution I see is to use const instead of let.

```<code>const score = localStorage.getItem("score");
</code>```

this way typescript know that score cannot be changed later.

Also you could check typeof score inside of callback function and typescript will not complaine. I would prefer const. But this will work too. Just for understanding how it works here:

```<code>function fetchScore() {
  let score = localStorage.getItem("score");
  setGameState((prev: any) => {
    if (typeof score === "string") {
      // no complaining, checking inside of callback function
      return { ...prev, score: parseInt(score) };
    }
    return prev;
  });
}
</code>```

Body:
When making a simple rock, paper, scissors game with typescript I cam across an interaction I couldn't understand.

const [gameState, setGameState] = useState<gameState>({
    choice: null,
    score: 0,
  });

function fetchScore() {
    let score = localStorage.getItem("score");
    if (typeof score === "string") {
      setGameState((prev) => ({ ...prev, score:
      parseInt(score) })); // Typescript still thinks score can be null
    }
}

parseInt throws an error saying score could be set to null despite the type guard.

I did some messing around and found that it was only happening when I used prev state.

 const [test,setTest] = useState(0);

 function fetchScore() {
    let score = localStorage.getItem("score");
    if (typeof score === "string") {
      setTest(parseInt(score))//Score is correctly guarded
    }
  }

I am currently handling it by typecasting score as a string but I would like to understand what cause this to happen?

Body:
That is because you are using score inside of a callback function. So typescript assumes that score variable can be changed before callback function will be executed and score potentially can null inside callback function.
Solutions:
the best solution I see is to use const instead of let.

const score = localStorage.getItem("score");

this way typescript know that score cannot be changed later.

Also you could check typeof score inside of callback function and typescript will not complaine. I would prefer const. But this will work too. Just for understanding how it works here:

function fetchScore() {
  let score = localStorage.getItem("score");
  setGameState((prev: any) => {
    if (typeof score === "string") {
      // no complaining, checking inside of callback function
      return { ...prev, score: parseInt(score) };
    }
    return prev;
  });
}


问:
Where is MSBuild.exe installed in Windows when installed using BuildTools_Full.exe?
I'm trying to set up a build server for .NET, but can't figure out where MSBuild.exe is installed.

I'm trying to install MSBuild using the Microsoft Build Tools 2013:
https://www.microsoft.com/en-us/download/details.aspx?id=40760

答:
For MsBuild 17:

C:\Program Files\Microsoft Visual Studio\2022\Professional\MSBuild\Current\Bin

For MsBuild 16:

C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin

For MsBuild 15:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild (or replace 'Enterprise' with 'Professional' or 'Community')


问:
AttributeError: 'tuple' object has no attribute 'layout' when I tried to use app.layout=dbc.Container() to structure the layout of the dash app
the script I got is:

```<code>import dash
import pandas as pd
import numpy as np
import database
from dash import Dash, dcc, html
import dash_bootstrap_components as dbc

# create a dash app which is compatible with mobile devices
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{'name': 'viewport',
                'content': 'width=device-width, initial-scale=1.0'}]
                ),
# structure the layout of the web app
app.layout =dbc.Container(
    html.H1(children='Hello Dash'))

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

the error I got is:

This is so weird, I don't get it why is app a tuple, isn't it class(Dash.dash)?
Please help, any suggestion is strongly appreciated!
Also I tried removing the layout, but it will just makes app a variable that is a container, which give an error: AttributeError: 'Container' object has no attribute 'run_server'. I tried to change app=dash.Dash(...) to app=dash(...) still doesn't work

答:
There is trailing comma which is leading to unintended behavior.

```<code>app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{'name': 'viewport',
                'content': 'width=device-width, initial-scale=1.0'}]
                ),
</code>```

This will set app equal to the one item tuple (<dash.dash.Dash object at ...>,). instead of the intended <dash.dash.Dash object at ...>.

Similarly, foo = 1, will set foo equal to a tuple containing 1 which can be confusing if you haven't seen this syntax before in python.

This should work:

```<code>app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],
                    meta_tags=[{'name': 'viewport',
                    'content': 'width=device-width, initial-scale=1.0'}]
                    )
</code>```

Body:
the script I got is:

import dash
import pandas as pd
import numpy as np
import database
from dash import Dash, dcc, html
import dash_bootstrap_components as dbc

# create a dash app which is compatible with mobile devices
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{'name': 'viewport',
                'content': 'width=device-width, initial-scale=1.0'}]
                ),
# structure the layout of the web app
app.layout =dbc.Container(
    html.H1(children='Hello Dash'))

if __name__ == '__main__':
    app.run_server(debug=True)

the error I got is:

This is so weird, I don't get it why is app a tuple, isn't it class(Dash.dash)?
Please help, any suggestion is strongly appreciated!
Also I tried removing the layout, but it will just makes app a variable that is a container, which give an error: AttributeError: 'Container' object has no attribute 'run_server'. I tried to change app=dash.Dash(...) to app=dash(...) still doesn't work

Body:
There is trailing comma which is leading to unintended behavior.

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],
                meta_tags=[{'name': 'viewport',
                'content': 'width=device-width, initial-scale=1.0'}]
                ),

This will set app equal to the one item tuple (<dash.dash.Dash object at ...>,). instead of the intended <dash.dash.Dash object at ...>.

Similarly, foo = 1, will set foo equal to a tuple containing 1 which can be confusing if you haven't seen this syntax before in python.

This should work:

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],
                    meta_tags=[{'name': 'viewport',
                    'content': 'width=device-width, initial-scale=1.0'}]
                    )


问:
How to get the dynamic height of UIView which contains two or more UILabels vertically?
I am trying to find the dynamic height of a UIView at the run time. So, for this I calculated the run time height of UILabels in it and the constraint constants and add them all to get the desired height. But this doesn't seems to be the correct way of doing it, because in case I alter the count of UILabel or constraints in future then I do have to change the code to calculate the dynamic height. So, is there any way to get the height of UIView at run time with any number of labels and constraints in it?

MY CODE

Here uiview is UIView of which I need to calculate the dynamic height, label1 and label2 are the UILabels in which I inserted text programatically. height is a string extension to find dynamic height of UILabel. label1TopConstraint, label1BottonContraint, label2BottomConstraint are constraints IBOutlets.

```<code>let label1Height = label1.text!.height(withConstrainedWidth: label1.frame.width, font: label1.font)
let label2Height = label2.text!.height(withConstrainedWidth: label2.frame.width, font: label2.font)
uiviewHeight = label1Height + label2Height + label1TopConstraint.constant + label1BottonContraint.constant + label2BottomConstraint.constant
</code>```

答: Instead of using multiple constraints on multiple labels, you can use UIStackViews vertically or horizontally according to your preference.</p>

Body:
I am trying to find the dynamic height of a UIView at the run time. So, for this I calculated the run time height of UILabels in it and the constraint constants and add them all to get the desired height. But this doesn't seems to be the correct way of doing it, because in case I alter the count of UILabel or constraints in future then I do have to change the code to calculate the dynamic height. So, is there any way to get the height of UIView at run time with any number of labels and constraints in it?

MY CODE

Here uiview is UIView of which I need to calculate the dynamic height, label1 and label2 are the UILabels in which I inserted text programatically. height is a string extension to find dynamic height of UILabel. label1TopConstraint, label1BottonContraint, label2BottomConstraint are constraints IBOutlets.

let label1Height = label1.text!.height(withConstrainedWidth: label1.frame.width, font: label1.font)
let label2Height = label2.text!.height(withConstrainedWidth: label2.frame.width, font: label2.font)
uiviewHeight = label1Height + label2Height + label1TopConstraint.constant + label1BottonContraint.constant + label2BottomConstraint.constant


问:
Retrieving more than one blob when using "When a blob is added or modified (properties only) (V2)"
I've an automated task elsewhere that creates 2 files within an Azure Blob Storage container:

Once this has been done, I then fire a Logic app which has uses the trigger "When a blob is added or modified (properties only) (V2)"

As you can see I have number of blobs to return set to 2, and if we look at the setting I have "split-on" off:

However when logic app is triggered its only retrieving 1 file in the array at a time:

The rest of my logic app is setup to handle and array - as the end game is send an email with a list of attachments, but given how this is being triggered end up with 2 emails each one with a single attachment.

Is this the way this trigger should work? or am I wrong somewhere?

EDIT: Including the code for the trigger:

答:
The reason that you are facing this is due to the number of files that you are uploading.

To make this work one of the workarounds is that you can use recurrence trigger having an interval of 1 minute and use a filter array to get the list of blobs that got added for that minute.

In the filter array, I am filtering it for that instance of a minute only. The syntax I'm using here for greater than or equal to operation on the last modified time  is formatDateTime(utcNow(), 'yyyy-MM-ddTHH:mm:00Z').

Then I'm using a variable to store the resultant list in an array by having an append to array variable connector for each item.

Then I'm using a Condition Connector to check if I'm receiving anything in the array and then send the list of blobs using the outlook connector. If there is no content or there are no blobs that got added in that minute the goes into false section, else true.

The condition that I'm checking here is the length of the listOfBlobs array:-
length(variables('listOfBlobs')) is not equal to 0

So here is what I receive when the length of listOfArray variable is 0, It won't trigger any mail as there are no blobs uploaded and goes into false section.

here is what I receive when the length of listOfArray variable is not 0, It triggers mail with the blob content in it.

Here is what I have uploaded to my storage account:-

Here is the mail that triggered in my inbox.

```<code>[{"pysamp.txt":"{\"Id\":\"<ID>",\"Name\":\"pysamp.txt\",\"DisplayName\":\"pysamp.txt\",\"Path\":\"/container2408/pysamp.txt\",\"LastModified\":\"2022-02-14T05:26:08Z\",\"Size\":58,\"MediaType\":\"text/plain\",\"IsFolder\":false,\"ETag\":\"\\\"0x8D9EF7A8133FFF9\\\"\",\"FileLocator\":\"JTJmY29udGFpbmVyMjQwOCUyZnB5c2FtcC50eHQ=\",\"LastModifiedBy\":null}\\n"},
{"aaa.txt":"{\"Id\":\"<ID>\",\"Name\":\"aaa.txt\",\"DisplayName\":\"aaa.txt\",\"Path\":\"/container2408/aaa.txt\",\"LastModified\":\"2022-02-14T05:26:08Z\",\"Size\":8686,\"MediaType\":\"text/plain\",\"IsFolder\":false,\"ETag\":\"\\\"0x8D9EF7A813F6FFB\\\"\",\"FileLocator\":\"JTJmY29udGFpbmVyMjQwOCUyZmFhYS50eHQ=\",\"LastModifiedBy\":null}\\n"}]
</code>```

Here is the code view of my logic app

```<code>{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "Compose": {
                "inputs": "@variables('listOfBlobs')",
                "runAfter": {
                    "For_each_2": [
                        "Succeeded"
                    ]
                },
                "type": "Compose"
            },
            "Condition": {
                "actions": {
                    "Send_an_email_(V2)": {
                        "inputs": {
                            "body": {
                                "Body": "<p>@{outputs('Compose')}</p>",
                                "Subject": "Sample",
                                "To": "v-swethaka@microsoft.com"
                            },
                            "host": {
                                "connection": {
                                    "name": "@parameters('$connections')['office365']['connectionId']"
                                }
                            },
                            "method": "post",
                            "path": "/v2/Mail"
                        },
                        "runAfter": {},
                        "type": "ApiConnection"
                    }
                },
                "expression": {
                    "and": [
                        {
                            "not": {
                                "equals": [
                                    "@length(variables('listOfBlobs'))",
                                    0
                                ]
                            }
                        }
                    ]
                },
                "runAfter": {
                    "Compose": [
                        "Succeeded"
                    ]
                },
                "type": "If"
            },
            "Filter_array": {
                "inputs": {
                    "from": "@body('Lists_blobs_(V2)')?['value']",
                    "where": "@greaterOrEquals(item()?['LastModified'], formatDateTime(utcNow(), 'yyyy-MM-ddTHH:mm:00Z'))"
                },
                "runAfter": {
                    "Lists_blobs_(V2)": [
                        "Succeeded"
                    ]
                },
                "type": "Query"
            },
            "For_each_2": {
                "actions": {
                    "Append_to_array_variable": {
                        "inputs": {
                            "name": "listOfBlobs",
                            "value": {
                                "@items('For_each_2')?['DisplayName']": "@{items('For_each_2')}\\n"
                            }
                        },
                        "runAfter": {},
                        "type": "AppendToArrayVariable"
                    }
                },
                "foreach": "@body('Filter_array')",
                "runAfter": {
                    "Initialize_variable": [
                        "Succeeded"
                    ]
                },
                "type": "Foreach"
            },
            "Initialize_variable": {
                "inputs": {
                    "variables": [
                        {
                            "name": "listOfBlobs",
                            "type": "array"
                        }
                    ]
                },
                "runAfter": {
                    "Filter_array": [
                        "Succeeded"
                    ]
                },
                "type": "InitializeVariable"
            },
            "Lists_blobs_(V2)": {
                "inputs": {
                    "host": {
                        "connection": {
                            "name": "@parameters('$connections')['azureblob']['connectionId']"
                        }
                    },
                    "method": "get",
                    "path": "/v2/datasets/@{encodeURIComponent(encodeURIComponent('AccountNameFromSettings'))}/foldersV2/@{encodeURIComponent(encodeURIComponent('JTJmY29udGFpbmVyMjQwOA=='))}",
                    "queries": {
                        "nextPageMarker": ""
                    }
                },
                "metadata": {
                    "JTJmY29udGFpbmVyMjQwOA==": "/container2408"
                },
                "runAfter": {},
                "type": "ApiConnection"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {
            "$connections": {
                "defaultValue": {},
                "type": "Object"
            }
        },
        "triggers": {
            "Recurrence": {
                "recurrence": {
                    "frequency": "Minute",
                    "interval": 1
                },
                "type": "recurrence"
            }
        }
    },
    "parameters": {
        "$connections": {
            "value": {
                "azureblob": {
                    "connectionId": "/subscriptions/<YOUR_SUBSCRIPTION>/resourceGroups/<YOUR_RESOURCEGROUP>/providers/Microsoft.Web/connections/azureblob",
                    "connectionName": "azureblob",
                    "id": "/subscriptions/<YOUR_SUBSCRIPTION>/providers/Microsoft.Web/locations/northcentralus/managedApis/azureblob"
                },
                "office365": {
                    "connectionId": "/subscriptions/<YOUR_SUBSCRIPTION>/resourceGroups/<YOUR_RESOURCEGROUP>/providers/Microsoft.Web/connections/office365",
                    "connectionName": "office365",
                    "id": "/subscriptions/<YOUR_SUBSCRIPTION>/providers/Microsoft.Web/locations/northcentralus/managedApis/office365"
                }
            }
        }
    }
}
</code>```

Body:
The reason that you are facing this is due to the number of files that you are uploading.

To make this work one of the workarounds is that you can use recurrence trigger having an interval of 1 minute and use a filter array to get the list of blobs that got added for that minute.

In the filter array, I am filtering it for that instance of a minute only. The syntax I'm using here for greater than or equal to operation on the last modified time  is formatDateTime(utcNow(), 'yyyy-MM-ddTHH:mm:00Z').

Then I'm using a variable to store the resultant list in an array by having an append to array variable connector for each item.

Then I'm using a Condition Connector to check if I'm receiving anything in the array and then send the list of blobs using the outlook connector. If there is no content or there are no blobs that got added in that minute the goes into false section, else true.

The condition that I'm checking here is the length of the listOfBlobs array:-
length(variables('listOfBlobs')) is not equal to 0

So here is what I receive when the length of listOfArray variable is 0, It won't trigger any mail as there are no blobs uploaded and goes into false section.

here is what I receive when the length of listOfArray variable is not 0, It triggers mail with the blob content in it.

Here is what I have uploaded to my storage account:-

Here is the mail that triggered in my inbox.

[{"pysamp.txt":"{\"Id\":\"<ID>",\"Name\":\"pysamp.txt\",\"DisplayName\":\"pysamp.txt\",\"Path\":\"/container2408/pysamp.txt\",\"LastModified\":\"2022-02-14T05:26:08Z\",\"Size\":58,\"MediaType\":\"text/plain\",\"IsFolder\":false,\"ETag\":\"\\\"0x8D9EF7A8133FFF9\\\"\",\"FileLocator\":\"JTJmY29udGFpbmVyMjQwOCUyZnB5c2FtcC50eHQ=\",\"LastModifiedBy\":null}\\n"},
{"aaa.txt":"{\"Id\":\"<ID>\",\"Name\":\"aaa.txt\",\"DisplayName\":\"aaa.txt\",\"Path\":\"/container2408/aaa.txt\",\"LastModified\":\"2022-02-14T05:26:08Z\",\"Size\":8686,\"MediaType\":\"text/plain\",\"IsFolder\":false,\"ETag\":\"\\\"0x8D9EF7A813F6FFB\\\"\",\"FileLocator\":\"JTJmY29udGFpbmVyMjQwOCUyZmFhYS50eHQ=\",\"LastModifiedBy\":null}\\n"}]

Here is the code view of my logic app

{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "Compose": {
                "inputs": "@variables('listOfBlobs')",
                "runAfter": {
                    "For_each_2": [
                        "Succeeded"
                    ]
                },
                "type": "Compose"
            },
            "Condition": {
                "actions": {
                    "Send_an_email_(V2)": {
                        "inputs": {
                            "body": {
                                "Body": "<p>@{outputs('Compose')}</p>",
                                "Subject": "Sample",
                                "To": "v-swethaka@microsoft.com"
                            },
                            "host": {
                                "connection": {
                                    "name": "@parameters('$connections')['office365']['connectionId']"
                                }
                            },
                            "method": "post",
                            "path": "/v2/Mail"
                        },
                        "runAfter": {},
                        "type": "ApiConnection"
                    }
                },
                "expression": {
                    "and": [
                        {
                            "not": {
                                "equals": [
                                    "@length(variables('listOfBlobs'))",
                                    0
                                ]
                            }
                        }
                    ]
                },
                "runAfter": {
                    "Compose": [
                        "Succeeded"
                    ]
                },
                "type": "If"
            },
            "Filter_array": {
                "inputs": {
                    "from": "@body('Lists_blobs_(V2)')?['value']",
                    "where": "@greaterOrEquals(item()?['LastModified'], formatDateTime(utcNow(), 'yyyy-MM-ddTHH:mm:00Z'))"
                },
                "runAfter": {
                    "Lists_blobs_(V2)": [
                        "Succeeded"
                    ]
                },
                "type": "Query"
            },
            "For_each_2": {
                "actions": {
                    "Append_to_array_variable": {
                        "inputs": {
                            "name": "listOfBlobs",
                            "value": {
                                "@items('For_each_2')?['DisplayName']": "@{items('For_each_2')}\\n"
                            }
                        },
                        "runAfter": {},
                        "type": "AppendToArrayVariable"
                    }
                },
                "foreach": "@body('Filter_array')",
                "runAfter": {
                    "Initialize_variable": [
                        "Succeeded"
                    ]
                },
                "type": "Foreach"
            },
            "Initialize_variable": {
                "inputs": {
                    "variables": [
                        {
                            "name": "listOfBlobs",
                            "type": "array"
                        }
                    ]
                },
                "runAfter": {
                    "Filter_array": [
                        "Succeeded"
                    ]
                },
                "type": "InitializeVariable"
            },
            "Lists_blobs_(V2)": {
                "inputs": {
                    "host": {
                        "connection": {
                            "name": "@parameters('$connections')['azureblob']['connectionId']"
                        }
                    },
                    "method": "get",
                    "path": "/v2/datasets/@{encodeURIComponent(encodeURIComponent('AccountNameFromSettings'))}/foldersV2/@{encodeURIComponent(encodeURIComponent('JTJmY29udGFpbmVyMjQwOA=='))}",
                    "queries": {
                        "nextPageMarker": ""
                    }
                },
                "metadata": {
                    "JTJmY29udGFpbmVyMjQwOA==": "/container2408"
                },
                "runAfter": {},
                "type": "ApiConnection"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {
            "$connections": {
                "defaultValue": {},
                "type": "Object"
            }
        },
        "triggers": {
            "Recurrence": {
                "recurrence": {
                    "frequency": "Minute",
                    "interval": 1
                },
                "type": "recurrence"
            }
        }
    },
    "parameters": {
        "$connections": {
            "value": {
                "azureblob": {
                    "connectionId": "/subscriptions/<YOUR_SUBSCRIPTION>/resourceGroups/<YOUR_RESOURCEGROUP>/providers/Microsoft.Web/connections/azureblob",
                    "connectionName": "azureblob",
                    "id": "/subscriptions/<YOUR_SUBSCRIPTION>/providers/Microsoft.Web/locations/northcentralus/managedApis/azureblob"
                },
                "office365": {
                    "connectionId": "/subscriptions/<YOUR_SUBSCRIPTION>/resourceGroups/<YOUR_RESOURCEGROUP>/providers/Microsoft.Web/connections/office365",
                    "connectionName": "office365",
                    "id": "/subscriptions/<YOUR_SUBSCRIPTION>/providers/Microsoft.Web/locations/northcentralus/managedApis/office365"
                }
            }
        }
    }
}


问:
Why my discord bot spams messages by adding the following code?
I am coding a basic moderation bot for Discord in discord.js. But by adding the following code for replying "Hello!" everytime someone sends message from the list, the bot spams a lot of "Hello!" messages in the channel.

client.on("message", async message =>{
  if (message.content == "Hi" || message.content == "hi" || message.content == "hello" || message.content == "Hello" || message.content == "hi!" || message.content == "Hi!" || message.content == "Hello!" || message.content == "hello!")
  {
    message.channel.send(`Hello!`)
  }
});
```

Can someone explain why does this happen and provide a solution to it? I tried to search on the web but was not able to phrase the question properly, so I got no answers.

P.S.: I am still learning JavaScript and I am coding this in replit.com, if that matters!

答:
As esqew pointed out in their comment, your bot is stuck in an event loop of replying to its own message. An easy way to deal with this problem would be to ignore messages from either all bots, or just the bot's own messages, as demonstrated below.

client.on("message", async message => {
    // Method A: Ignore all Bots
    if(message.author.bot) return;

    // Method B: Ignore self only
    if(message.author.id == client.user.id) return;

    // Insert rest of event code here, etc...
});
```

See User.bot (Discord.js Docs)

Body:
I am coding a basic moderation bot for Discord in discord.js. But by adding the following code for replying "Hello!" everytime someone sends message from the list, the bot spams a lot of "Hello!" messages in the channel.

client.on("message", async message =>{
  if (message.content == "Hi" || message.content == "hi" || message.content == "hello" || message.content == "Hello" || message.content == "hi!" || message.content == "Hi!" || message.content == "Hello!" || message.content == "hello!")
  {
    message.channel.send(`Hello!`)
  }
});

Can someone explain why does this happen and provide a solution to it? I tried to search on the web but was not able to phrase the question properly, so I got no answers.

P.S.: I am still learning JavaScript and I am coding this in replit.com, if that matters!

Body:
As esqew pointed out in their comment, your bot is stuck in an event loop of replying to its own message. An easy way to deal with this problem would be to ignore messages from either all bots, or just the bot's own messages, as demonstrated below.

client.on("message", async message => {
    // Method A: Ignore all Bots
    if(message.author.bot) return;

    // Method B: Ignore self only
    if(message.author.id == client.user.id) return;

    // Insert rest of event code here, etc...
});

See User.bot (Discord.js Docs)


问:
Python certificate verify failed: unable to get local issuer certificate
I am a novice programmer so pardon my mistakes. I have written the below code to verify a list of Websites are still active and all my work is based off this problem statement.

The script is able to check most sites but stumbled with below error for https://precisionit.net/

```<code><urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>
</code>```

The above URL opens fine in Firefox and Chrome but fails to open in Python code. I have updated certifi and used it in my code as suggested by many folks but the error would not go away.

I am using Conda Python Env and I also executed the below command

```<code>conda install -c conda-forge certifi
</code>```

There were multiple posts that suggested running "Install Certificates.command" which does not apply to Conda Python so I downloaded Python 3.9 installer and executed "Install Certificates.command" and executed the script with Python 3.9 yet no luck. I feel the issue is that even with latest version of certifi the sites certificate is not validated. Although certifi page says the list is based off Mozilla’s root certificates I guess it's not an exact replica which is why Firefox is able to open the site. Not sure if my understanding makes sense and will be glad to be corrected.

Pasting my script below. I am not sure what else needs to be done to fix the issue, kindly advise.

```<code>import urllib.request
import sys
import certifi
import ssl

def checkURL(url):
    try:

        hdr = { 'User-Agent' : 'Mozilla/79.0 (Windows NT 6.1; Win64; x64)' }
        req=urllib.request.Request(url,headers=hdr)
        r = urllib.request.urlopen(req,timeout=100,context=ssl.create_default_context(cafile=certifi.where()))

    except Exception as e:
        #print(r.read())
        print('Failed Connecting to Website')
        print(e)
        return(1)

    print(r.status)
    finalurl = r.geturl()
    if r.status==200:
        print(finalurl)
        return(0)
    else:
        print("Website Not Found")
        return(2)

checkURL('https://precisionit.net/')
</code>```

答:
first : save the site public key as base74
second: add code for verfify with your saved file.

enter image description here

```<code>with requests.Session() as s:
        CC_host = 'https://precisionit.net'
        first_page = s.get(CC_host,verify='./theSiteCert.cer')
        html = first_page.text
        print(html)
</code>```

Body:
I am a novice programmer so pardon my mistakes. I have written the below code to verify a list of Websites are still active and all my work is based off this problem statement.

The script is able to check most sites but stumbled with below error for https://precisionit.net/

<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)>

The above URL opens fine in Firefox and Chrome but fails to open in Python code. I have updated certifi and used it in my code as suggested by many folks but the error would not go away.

I am using Conda Python Env and I also executed the below command

conda install -c conda-forge certifi

There were multiple posts that suggested running "Install Certificates.command" which does not apply to Conda Python so I downloaded Python 3.9 installer and executed "Install Certificates.command" and executed the script with Python 3.9 yet no luck. I feel the issue is that even with latest version of certifi the sites certificate is not validated. Although certifi page says the list is based off Mozilla’s root certificates I guess it's not an exact replica which is why Firefox is able to open the site. Not sure if my understanding makes sense and will be glad to be corrected.

Pasting my script below. I am not sure what else needs to be done to fix the issue, kindly advise.

import urllib.request
import sys
import certifi
import ssl

def checkURL(url):
    try:

        hdr = { 'User-Agent' : 'Mozilla/79.0 (Windows NT 6.1; Win64; x64)' }
        req=urllib.request.Request(url,headers=hdr)
        r = urllib.request.urlopen(req,timeout=100,context=ssl.create_default_context(cafile=certifi.where()))

    except Exception as e:
        #print(r.read())
        print('Failed Connecting to Website')
        print(e)
        return(1)

    print(r.status)
    finalurl = r.geturl()
    if r.status==200:
        print(finalurl)
        return(0)
    else:
        print("Website Not Found")
        return(2)

checkURL('https://precisionit.net/')

Body:
first : save the site public key as base74
second: add code for verfify with your saved file.

enter image description here

with requests.Session() as s:
        CC_host = 'https://precisionit.net'
        first_page = s.get(CC_host,verify='./theSiteCert.cer')
        html = first_page.text
        print(html)


问:
Django How to check a request is Ajax
The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header.</p>

答:
If you are writing your own AJAX detection method, request.is_ajax() can be reproduced exactly as</p>
```<code>if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
    is_ajax = True
else:
    is_ajax = False
</code>```

Title: Django How to check a request is Ajax

Body:
If you are writing your own AJAX detection method, request.is_ajax() can be reproduced exactly as

if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
    is_ajax = True
else:
    is_ajax = False


问:
js join("\n") not start at new line
I am using an Ant Design table, and this is one of my columns. I would like to show every name on a new line, and I'm using "\n" but it's not working - it only adds spaces, it doesn't start the second name at the new line.</p>
```<code>{
    title: "Borrower Name",
    width: 150,
    dataIndex: "borrower",
    render: (record) => record.map((a) => a.name).join("\n"),
}
</code>```

答:
Another solution is using HTML tag (i have used paragraph tag, you can use br tag), this will display all the names on new line.

```<code>{
  title: 'Borrower Name',
  width: 150,
  dataIndex: 'borrower',
  render: (record) => record.map((a) => <p>{a.name}</p>),
},
</code>```

Or

```<code>{
  title: 'Borrower Name',
  width: 150,
  dataIndex: 'borrower',
  render: (record) => record.map((a) => <>{a.name}<br/></>),
},
</code>```

Title: js join("\n") not start at new line

Body:
I am using an Ant Design table, and this is one of my columns. I would like to show every name on a new line, and I'm using "\n" but it's not working - it only adds spaces, it doesn't start the second name at the new line.

{
    title: "Borrower Name",
    width: 150,
    dataIndex: "borrower",
    render: (record) => record.map((a) => a.name).join("\n"),
}

Body:
Another solution is using HTML tag (i have used paragraph tag, you can use br tag), this will display all the names on new line.

{
  title: 'Borrower Name',
  width: 150,
  dataIndex: 'borrower',
  render: (record) => record.map((a) => <p>{a.name}</p>),
},

Or

{
  title: 'Borrower Name',
  width: 150,
  dataIndex: 'borrower',
  render: (record) => record.map((a) => <>{a.name}<br/></>),
},


问:
I am trying to use an user HTML input to change a javascript object value
I am trying to use HTML 'input' to change apiData.id value. I'm new to javascript and not sure if this is correct. Any suggestions would be greatly appreciated.

const apiData = {
    url: 'https://pokeapi.co/api/v2/',
    type: 'pokemon',
    id: '76',
}

const input = document.getElementById('container');
const newId = apiData.id;

function eventController(event) {
    newId = event.target.value;
}
input.addEventListener('change', eventController, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokemon</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="container">
        <input id="input">
        <input type="submit" value="Catch">
    </div>

    <div class="pokemon"></div>
    <script src="main.js"></script>
</body>

</html></code>```

答:
newId is const, so you cannot assign it with a new value after it has been declared.

But even if you could (and you can, by making it a variable), that would not affect apiData.id, as newId is assigned with the value of apiData.id, but they are not bound together.

You should just assign apiData.id directly with a new value:

const apiData = {
    url: 'https://pokeapi.co/api/v2/',
    type: 'pokemon',
    id: '76',
}

const input = document.getElementById('container');
// const newId = apiData.id;

function eventController(event) {
    apiData.id = event.target.value;
}
input.addEventListener('change', eventController, false);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokemon</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="container">
        <input id="input">
        <input type="submit" value="Catch">
    </div>

    <div class="pokemon"></div>
    <script src="main.js"></script>
</body>

</html></code>```

Body:
I am trying to use HTML 'input' to change apiData.id value. I'm new to javascript and not sure if this is correct. Any suggestions would be greatly appreciated.

const apiData = {
    url: 'https://pokeapi.co/api/v2/',
    type: 'pokemon',
    id: '76',
}

const input = document.getElementById('container');
const newId = apiData.id;

function eventController(event) {
    newId = event.target.value;
}
input.addEventListener('change', eventController, false);

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokemon</title>
    <link rel="stylesheet" href="style.css">

        <input id="input">
        <input type="submit" value="Catch">

Body:
newId is const, so you cannot assign it with a new value after it has been declared.

But even if you could (and you can, by making it a variable), that would not affect apiData.id, as newId is assigned with the value of apiData.id, but they are not bound together.

You should just assign apiData.id directly with a new value:

const apiData = {
    url: 'https://pokeapi.co/api/v2/',
    type: 'pokemon',
    id: '76',
}

const input = document.getElementById('container');
// const newId = apiData.id;

function eventController(event) {
    apiData.id = event.target.value;
}
input.addEventListener('change', eventController, false);

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokemon</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div id="container">
        <input id="input">
        <input type="submit" value="Catch">
    </div>

    <div class="pokemon"></div>
    <script src="main.js"></script>
</body>

</html>


问:
npm install with error: `gyp` failed with exit code: 1
I'm try to install modules on Windows 10 using npm 5.6.0. When I enter npm install I get:

```<code>gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (C:\Users\xiaooming\Desktop\app\node_modules\node-gyp\lib\configure.js:336:16)
gyp ERR! stack at emitTwo (events.js:126:13)
gyp ERR! stack at ChildProcess.emit (events.js:214:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 10.0.16299
gyp ERR! command "D:\\Program Files\\nodejs\\node.exe" "C:\\Users\\xiaooming\\Desktop\\app\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Users\xiaooming\Desktop\app\node_modules\node-sass
gyp ERR! node -v v8.10.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
Build failed with error code: 1
npm WARN kingt4.0app@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@3.13.1 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@3.13.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\xiaooming\AppData\Roaming\npm-cache\_logs\2018-03-18T13_02_03_946Z-debug.log
</code>```

It seems like node-sass install error. The environment is below:

Python version: 2.7.14

npm version: 5.6.0

node version: 8.10.0

ruby version: 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

system: win10(x64)

node-gyp: 3.6.2

And I have installed Microsoft Visual Studio express 2015,
the below command has been executed：

```<code>npm config set msvs_version 2015
node-gyp configure --msvs_version=2015
npm install --global --production windows-build-tools
</code>```

package.json

```<code>{
  "name": "kingt4.0app",
  "version": "1.0.0",
  "description": "an kingt4.0 project.",
  "main": "index.js",
  "scripts": {
    "test": "test.js"
  },
  "keywords": [
    "finance"
  ],
  "author": "kingdom",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.11.1",
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.0",
    "gulp-cache": "^0.4.2",
    "gulp-changed": "^1.3.2",
    "gulp-clean-css": "^2.0.2",
    "gulp-file-include": "^0.13.7",
    "gulp-if": "^2.0.0",
    "gulp-imagemin": "^2.4.0",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^2.2.0",
    "gulp-sourcemaps": "^1.6.0",
    "gulp.spritesmith": "^6.2.1",
    "imagemin-jpegtran": "^4.3.2",
    "imagemin-pngquant": "^4.2.2",
    "merge-stream": "^1.0.0",
    "normalize.css": "^4.0.0",
    "spritesheet-templates": "^10.1.2",
    "vinyl-buffer": "^1.0.0"
  },
  "dependencies": {
    "remodal": "^1.0.7",
    "slick-carousel": "^1.6.0"
  }
}
</code>```

How to resolve this problem? thanks for help.

答:
```<code>$ npm i --ignore-script
</code>```

I tried different ways to solve this issue, finally, this comment simply help to install node packages without any errors.

Body:
I'm try to install modules on Windows 10 using npm 5.6.0. When I enter npm install I get:

gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack at ChildProcess.onCpExit (C:\Users\xiaooming\Desktop\app\node_modules\node-gyp\lib\configure.js:336:16)
gyp ERR! stack at emitTwo (events.js:126:13)
gyp ERR! stack at ChildProcess.emit (events.js:214:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
gyp ERR! System Windows_NT 10.0.16299
gyp ERR! command "D:\\Program Files\\nodejs\\node.exe" "C:\\Users\\xiaooming\\Desktop\\app\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd C:\Users\xiaooming\Desktop\app\node_modules\node-sass
gyp ERR! node -v v8.10.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
Build failed with error code: 1
npm WARN kingt4.0app@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-sass@3.13.1 postinstall: `node scripts/build.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-sass@3.13.1 postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\xiaooming\AppData\Roaming\npm-cache\_logs\2018-03-18T13_02_03_946Z-debug.log

It seems like node-sass install error. The environment is below:

Python version: 2.7.14

npm version: 5.6.0

node version: 8.10.0

ruby version: 2.3.3p222 (2016-11-21 revision 56859) [i386-mingw32]

system: win10(x64)

node-gyp: 3.6.2

And I have installed Microsoft Visual Studio express 2015,
the below command has been executed：

npm config set msvs_version 2015
node-gyp configure --msvs_version=2015
npm install --global --production windows-build-tools

package.json

{
  "name": "kingt4.0app",
  "version": "1.0.0",
  "description": "an kingt4.0 project.",
  "main": "index.js",
  "scripts": {
    "test": "test.js"
  },
  "keywords": [
    "finance"
  ],
  "author": "kingdom",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.11.1",
    "gulp": "^3.9.1",
    "gulp-autoprefixer": "^3.1.0",
    "gulp-cache": "^0.4.2",
    "gulp-changed": "^1.3.2",
    "gulp-clean-css": "^2.0.2",
    "gulp-file-include": "^0.13.7",
    "gulp-if": "^2.0.0",
    "gulp-imagemin": "^2.4.0",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^2.2.0",
    "gulp-sourcemaps": "^1.6.0",
    "gulp.spritesmith": "^6.2.1",
    "imagemin-jpegtran": "^4.3.2",
    "imagemin-pngquant": "^4.2.2",
    "merge-stream": "^1.0.0",
    "normalize.css": "^4.0.0",
    "spritesheet-templates": "^10.1.2",
    "vinyl-buffer": "^1.0.0"
  },
  "dependencies": {
    "remodal": "^1.0.7",
    "slick-carousel": "^1.6.0"
  }
}

How to resolve this problem? thanks for help.

Body:
$ npm i --ignore-script

I tried different ways to solve this issue, finally, this comment simply help to install node packages without any errors.


问:
Need for try catch within a constructor
The link http://gotw.ca/gotw/066.htm states that

Moral #1: Constructor function-try-block handlers have only one purpose -- to translate an exception. (And maybe to do logging or some other side effects.) They are not useful for any other purpose.

While http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8

If a constructor throws an exception, the object's destructor is not run. If your object has already done something that needs to be undone (such as allocating some memory, opening a file, or locking a semaphore), this "stuff that needs to be undone" must be remembered by a data member inside the object.

Are these 2 statements not contradictory?  The first one kind of implies that the try catch within a constructor is pretty much useless while the second says that it is needed to free resources.  What am i missing here?

答:
First, a constructor function-try-block isn't the same as a try-catch within a constructor.

Second, saying "stuff that needs to be undone must be remembered by a data member" is not the same as saying, "use try-catch blocks to undo things".

There's no contradiction between the two statements, they're talking about different things. In fact, the second one isn't talking about try-catch at all.

Title: Need for try catch within a constructor


问:
Better way to use JdbcTemplate with Lambda RowMapper
Often in time I use jdbcTemplate.query not to return a resultset but to access the DB and do some computations on each record selected.
For example the code below works

```<code>    Map<String, Double> mAcc = new HashMap<>();
    sql = "select ar.id_codice_art, sum(ar.quantita) quantita\n" +
            "from accettazione a \n" +
            "inner join accettazione_riga ar on a.id_accettazione = ar.id_accettazione\n" +
            "where a.id_ordine = ? \n" +
            "group by ar.id_codice_art";
    jdbcTemplate.query(sql, (rs, i)->{
        mAcc.put(rs.getString("id_codice_art"), rs.getDouble("quantita"));
        return "";
    }, idOrdine);
</code>```

but it's not clean especially when a return "" because it is required by RowMapper interface. At the same time I don't want to create a record or a class just to return a list and work on the list.

Is there a better way to do the same think using jdbcTemplate?

答:
```<code>You can try using the following code. Just create a new map, insert values in it and return it. and then you can copy values from that result map to your map.
</code>```

 Map<String, Double> mAcc = new HashMap<>();
    sql = "select ar.id_codice_art, sum(ar.quantita) quantita\n" +
            "from accettazione a \n" +
            "inner join accettazione_riga ar on a.id_accettazione = ar.id_accettazione\n" +
            "where a.id_ordine = ? \n" +
            "group by ar.id_codice_art";
    Map<String,Double> = jdbcTemplate.query(sql, (rs)->{
    Map<String,Double> map = new HashMap<>();
        while(rs.next()){
        map.put(rs.getString("id_codice_art"), rs.getDouble("quantita"));
        }
        return map;
    }, idOrdine);```

Body:
Often in time I use jdbcTemplate.query not to return a resultset but to access the DB and do some computations on each record selected.
For example the code below works

    Map<String, Double> mAcc = new HashMap<>();
    sql = "select ar.id_codice_art, sum(ar.quantita) quantita\n" +
            "from accettazione a \n" +
            "inner join accettazione_riga ar on a.id_accettazione = ar.id_accettazione\n" +
            "where a.id_ordine = ? \n" +
            "group by ar.id_codice_art";
    jdbcTemplate.query(sql, (rs, i)->{
        mAcc.put(rs.getString("id_codice_art"), rs.getDouble("quantita"));
        return "";
    }, idOrdine);

but it's not clean especially when a return "" because it is required by RowMapper interface. At the same time I don't want to create a record or a class just to return a list and work on the list.

Is there a better way to do the same think using jdbcTemplate?

Body:
You can try using the following code. Just create a new map, insert values in it and return it. and then you can copy values from that result map to your map.

 Map<String, Double> mAcc = new HashMap<>();
    sql = "select ar.id_codice_art, sum(ar.quantita) quantita\n" +
            "from accettazione a \n" +
            "inner join accettazione_riga ar on a.id_accettazione = ar.id_accettazione\n" +
            "where a.id_ordine = ? \n" +
            "group by ar.id_codice_art";
    Map<String,Double> = jdbcTemplate.query(sql, (rs)->{
    Map<String,Double> map = new HashMap<>();
        while(rs.next()){
        map.put(rs.getString("id_codice_art"), rs.getDouble("quantita"));
        }
        return map;
    }, idOrdine);


问:
How to consume messages from kafka producer in batches (kafka-python)
I am having a kafka producer and consumer in python. I wish to consume messages from kafka producer in batches, let's say 2. From the producer, I have been sending email data like the following:

```<code>[{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 1",
    "message" : "this is a test"
},
{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 2",
    "message" : "this is a test"
},
{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 3",
    "message" : "this is a test"
},
{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 4",
    "message" : "this is a test"
}]

</code>```

I am trying to consume these data in batches. I wish to consume 2 message at a time and send emails based on those 2 data and consume the next set of data. The workaround that I tried is:

```<code>consumer = KafkaConsumer(topic, bootstrap_servers=[server], api_version=(0, 10))
for message in consumer[:2]:
    string = message.value.decode("utf-8")
    dict_value = ast.literal_eval(string)
</code>```

The error that I am getting is:

```<code>    for message in consumer[:2]:
TypeError: 'KafkaConsumer' object is not subscriptable

</code>```

Can someone help me getting through this?

答:
The consumer is not a collection; it's iterator is infinite.

If you want to perform an action every two events, use a counter or your own list

```<code>data = []
consumer = KafkaConsumer(topic, bootstrap_servers=[server], api_version=(0, 10))
for message in consumer:
    data.append(message)
    if len(data) >= 2:
        action(data)
        data.clear()
</code>```

Body:
I am having a kafka producer and consumer in python. I wish to consume messages from kafka producer in batches, let's say 2. From the producer, I have been sending email data like the following:

[{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 1",
    "message" : "this is a test"
},
{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 2",
    "message" : "this is a test"
},
{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 3",
    "message" : "this is a test"
},
{
    "email" : "sukhi215c@gmail.com",
    "subject": "Test 4",
    "message" : "this is a test"
}]

I am trying to consume these data in batches. I wish to consume 2 message at a time and send emails based on those 2 data and consume the next set of data. The workaround that I tried is:

consumer = KafkaConsumer(topic, bootstrap_servers=[server], api_version=(0, 10))
for message in consumer[:2]:
    string = message.value.decode("utf-8")
    dict_value = ast.literal_eval(string)

The error that I am getting is:

    for message in consumer[:2]:
TypeError: 'KafkaConsumer' object is not subscriptable

Can someone help me getting through this?

Body:
The consumer is not a collection; it's iterator is infinite.

If you want to perform an action every two events, use a counter or your own list

data = []
consumer = KafkaConsumer(topic, bootstrap_servers=[server], api_version=(0, 10))
for message in consumer:
    data.append(message)
    if len(data) >= 2:
        action(data)
        data.clear()


问:
Why can my merge function for mergeSort not be found? (C++)
I wrote code in C++ in visual studios to try and implement mergesort. Whenever I try to compile it gives the same error, C3681 'merge' identifier not found, which I don't understand what exactly is not being identified. Please help!</p>
```<code>#include <iostream>
#include <limits.h>
using namespace std;
void mergeSort(int A[], int p, int r) {
    int q;
    if (p < r) {
        q = p + (r - 1) / 2;
        mergeSort(A, p, q);
        mergeSort(A, q + 1, r);
        merge(A, p, q, r);
    }
}
void merge(int array[], int p, int q, int r) {
    int a, b, c;
    int m = q - p + 1;
    int n = r - q;
    int* left_array = new int[m + 1];
    int* right_array = new int[n + 1];
    for (int i = 0; i < m; i++) {
        left_array[i] = array[p + 1];
    }
    for (int j = 0; j < n; j++) {
        right_array[j] = array[q + 1 + j];
    }
    left_array[m + 1] = INT_MAX;
    right_array[n + 1] = INT_MAX;
    a = 0;
    b = 0;
    c = 1;
    while (a < m && b < n) {
        if (left_array[a] <= right_array[b]) {
            array[c] = left_array[a];
            a++;
        }
        else {
            array[c] = right_array[b];
            b++;
        }
        c++;
    }
    while (a < m) {
        array[c] = left_array[a];
        a++;
        c++;
    }
    while (b < n) {
        array[c] = left_array[b];
        b++;
        c++;
    }
}
}
int main(int argc, char* argv[]) {
    int A[10] = { 9,8,7,6,5,4,3,2,1,0 };
    mergeSort(A, 0, 9);
}
</code>```

答:
because c++ is very fussy, it likes to see things in the correct order or at least not be surprised by names it hasn't seen yet. You need to declare merge before you call it.

```<code>#include <iostream>
#include <limits.h>
using namespace std;
void merge(int array[], int p, int q, int r); <<<<=======
void mergeSort(int A[], int p, int r) {
 ......
</code>```

Body:
I wrote code in C++ in visual studios to try and implement mergesort. Whenever I try to compile it gives the same error, C3681 'merge' identifier not found, which I don't understand what exactly is not being identified. Please help!

#include <iostream>
#include <limits.h>
using namespace std;
void mergeSort(int A[], int p, int r) {
    int q;
    if (p < r) {
        q = p + (r - 1) / 2;
        mergeSort(A, p, q);
        mergeSort(A, q + 1, r);
        merge(A, p, q, r);
    }
}
void merge(int array[], int p, int q, int r) {
    int a, b, c;
    int m = q - p + 1;
    int n = r - q;
    int* left_array = new int[m + 1];
    int* right_array = new int[n + 1];
    for (int i = 0; i < m; i++) {
        left_array[i] = array[p + 1];
    }
    for (int j = 0; j < n; j++) {
        right_array[j] = array[q + 1 + j];
    }
    left_array[m + 1] = INT_MAX;
    right_array[n + 1] = INT_MAX;
    a = 0;
    b = 0;
    c = 1;
    while (a < m && b < n) {
        if (left_array[a] <= right_array[b]) {
            array[c] = left_array[a];
            a++;
        }
        else {
            array[c] = right_array[b];
            b++;
        }
        c++;
    }
    while (a < m) {
        array[c] = left_array[a];
        a++;
        c++;
    }
    while (b < n) {
        array[c] = left_array[b];
        b++;
        c++;
    }
}
}
int main(int argc, char* argv[]) {
    int A[10] = { 9,8,7,6,5,4,3,2,1,0 };
    mergeSort(A, 0, 9);
}

Body:
because c++ is very fussy, it likes to see things in the correct order or at least not be surprised by names it hasn't seen yet. You need to declare merge before you call it.

#include <iostream>
#include <limits.h>
using namespace std;
void merge(int array[], int p, int q, int r); <<<<=======
void mergeSort(int A[], int p, int r) {
 ......