问:
Var type string and not int
Why is the var type still str in Case 1?. Shouldn't it be int?
In Case 2 when I'm not using the function it changes to int.

```<code>#CASE 1
num1=str()

def suma():

    num1=int(7)

suma()

print(type(num1)) # <class 'str'>

#CASE 2
num1=str()
num1=7

print(type(num1)) # <class 'int'>
</code>```

答: This is about scoping. Dynamic and static scoping may result different results for the same code. Python is using static scoping. For case 1, you are declaring your variable and calling a method to change its type. Then if the line you are calling num1=str() has a static depth of 0, then the line num1=int(7) has the static depth of 1 since it is called in a subprogram. Then the change in the method suma() can't affect the num1 since it declared on the lower static depth. On your case 2, both of them have the same static depth then num1 will change its type.

Title: Var type string and not int

Body:
Why is the var type still str in Case 1?. Shouldn't it be int?
In Case 2 when I'm not using the function it changes to int.

#CASE 1
num1=str()

def suma():

    num1=int(7)

suma()

print(type(num1)) # <class 'str'>

#CASE 2
num1=str()
num1=7

print(type(num1)) # <class 'int'>


来源: stackexchange

问:
Why callbacks function are not fired?
I have this function that indicates if geolocation is enabled on the broweser:

function geolocationInfo() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    }
    else {
        return "Geolocation not works in this browser";
    }
}

  function success(position) {
        var crd = position.coords;

        console.log('Ваше текущее метоположение:');
        console.log(`Широта: ${crd.latitude}`);
        console.log(`Долгота: ${crd.longitude}`);
        console.log(`Плюс-минус ${crd.accuracy} метров.`);
    }

    function error(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                return "Geolocation disabled";
            case error.POSITION_UNAVAILABLE:
                return "GeoLocation is not available";
            case error.TIMEOUT:
                return "Time is ends";
            case error.UNKNOWN_ERROR:
                return "error.";
        }
    }
```

The problem is callback functions are not fired.

Any idea why callbacks(success and errors) are not fired?

答:
In case if you try to use your code inside the chrome's console, and you run your function

```<code>geolocationInfo()
</code>```

Then check the pop-up window with permissions in your browser, as the user has to allow the web-page to see the location

ContentLicense: CC BY-SA 4.0

Title: Why callbacks function are not fired?

Body:
I have this function that indicates if geolocation is enabled on the broweser:

function geolocationInfo() {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    }
    else {
        return "Geolocation not works in this browser";
    }
}

  function success(position) {
        var crd = position.coords;

        console.log('Ваше текущее метоположение:');
        console.log(`Широта: ${crd.latitude}`);
        console.log(`Долгота: ${crd.longitude}`);
        console.log(`Плюс-минус ${crd.accuracy} метров.`);
    }

    function error(error) {
        switch (error.code) {
            case error.PERMISSION_DENIED:
                return "Geolocation disabled";
            case error.POSITION_UNAVAILABLE:
                return "GeoLocation is not available";
            case error.TIMEOUT:
                return "Time is ends";
            case error.UNKNOWN_ERROR:
                return "error.";
        }
    }

The problem is callback functions are not fired.

Any idea why callbacks(success and errors) are not fired?

Body:
In case if you try to use your code inside the chrome's console, and you run your function

geolocationInfo()

Then check the pop-up window with permissions in your browser, as the user has to allow the web-page to see the location


问:
Typescript: how do you create a Copy of a type but change the property typeings
I want to create 2 types for an object. A type for the object itself and a type for the validation errors. These two types will have the same property names but the properties will have different typings.

```<code>type Person = {
  name: string,
  age: number,
  married: boolean
}

type PersonValidationError = {
  name?: string,
  age?: string,
  married?: string
}

</code>```

After a user fills out a form constructing a Person object I want to then run it through some validation and if there are errors I want to create the error object which will have error messages in the respective property. Is there a way I can tie the PersonValidationError to the Person type itself so that when i add more properties to Person I dont need to worry about them getting out of sync.

My first thought was to use keyof

```<code>type PersonValidationError = {
  [prop: keyof Person]: string
}
</code>```

But this is not valid and keyof cant be used in a index signature to my understanding.

Also I know the PersonValidationError has all its properties marked as optional but its fine if I cant change the requirement of the props because I could always wrap it in a Partial<>

答:
Use a mapped type; it looks similar to an index signature but it uses the in keyword:

```<code>type PersonValidationError = { [K in keyof Person]?: string }
</code>```

The ? makes the properties optional.  Hope that helps; good luck!

Playground link to code

Body:
I want to create 2 types for an object. A type for the object itself and a type for the validation errors. These two types will have the same property names but the properties will have different typings.

type Person = {
  name: string,
  age: number,
  married: boolean
}

type PersonValidationError = {
  name?: string,
  age?: string,
  married?: string
}

After a user fills out a form constructing a Person object I want to then run it through some validation and if there are errors I want to create the error object which will have error messages in the respective property. Is there a way I can tie the PersonValidationError to the Person type itself so that when i add more properties to Person I dont need to worry about them getting out of sync.

My first thought was to use keyof

type PersonValidationError = {
  [prop: keyof Person]: string
}

But this is not valid and keyof cant be used in a index signature to my understanding.

Also I know the PersonValidationError has all its properties marked as optional but its fine if I cant change the requirement of the props because I could always wrap it in a Partial<>

Body:
Use a mapped type; it looks similar to an index signature but it uses the in keyword:

type PersonValidationError = { [K in keyof Person]?: string }

The ? makes the properties optional.  Hope that helps; good luck!

Playground link to code


问:
IMDB API - Retrieve all movies from a list?
I would like to know if there is a way to retrieve all the movies from a list (this one for example : https://www.imdb.com/list/ls052535080/) via an API ?

I see nothing for this kind of use.

Thanks for your help !

答:
IMDB does not have any API as such.
This could help (web scraping) --</p>

```<code>import requests
import browsercookie
import bs4
url = 'https://www.imdb.com/user/ur<user_id>/lists?ref_=nv_usr_lst_3'
cj = browsercookie.chrome()
res = requests.get(url, cookies=cj)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "html.parser")
</code>```

Body:
IMDB does not have any API as such.
This could help (web scraping) --

import requests
import browsercookie
import bs4
url = 'https://www.imdb.com/user/ur<user_id>/lists?ref_=nv_usr_lst_3'
cj = browsercookie.chrome()
res = requests.get(url, cookies=cj)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, "html.parser")


问:
R flexdashboard with shiny - Sidebar
I'm trying to create a flexdashboard using r with a similar format to this page.

I used a flexdashboard with Shiny.

```<code>---
title: "title"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(lubridate)
library(viridis)
library(plotly)
library(tidytext)
library(readr)
library(tidyverse)
```

```{r global, include=FALSE}
# read global data
```

```{r wrangling-data}
```

Sidebar {.sidebar}
=====================================

```{r}
# shiny inputs defined here
```

Introduction
=====================================

### Intro

```{r}
```

Data
=====================================

```{r}
```

Conclusion
=====================================

```{r}
```
</code>```

This results in the menu items still showing on the top navigation bar.

However, I want to move the navigation babe onto the left side, like this and also include accordion sub-menus on the menu items.

答:
You have to add a level (just a sequence of dashes --). Try this code:

```<code>---
title: "title"
output:
    flexdashboard::flex_dashboard:
    orientation: columns
vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(lubridate)
library(viridis)
library(plotly)
library(tidytext)
library(readr)
library(tidyverse)
```

```{r global, include=FALSE}
# read global data
```

```{r wrangling-data}
```

Sidebar {.sidebar}
=====================================

```{r}
# shiny inputs defined here

```
Some text added

-------------------------------------

Introduction
=====================================

### Intro

```{r}
```

Data
=====================================

```{r}
```

Conclusion
=====================================

```{r}
```
</code>```

Hope it helps.

Title: R flexdashboard with shiny - Sidebar

Body:
I'm trying to create a flexdashboard using r with a similar format to this page.

I used a flexdashboard with Shiny.

---
title: "title"
output:
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(lubridate)
library(viridis)
library(plotly)
library(tidytext)
library(readr)
library(tidyverse)
```

```{r global, include=FALSE}
# read global data
```

```{r wrangling-data}
```

Sidebar {.sidebar}
=====================================

```{r}
# shiny inputs defined here
```

Introduction
=====================================

### Intro

```{r}
```

Data
=====================================

```{r}
```

Conclusion
=====================================

```{r}
```

This results in the menu items still showing on the top navigation bar.

However, I want to move the navigation babe onto the left side, like this and also include accordion sub-menus on the menu items.

Body:
You have to add a level (just a sequence of dashes --). Try this code:

---
title: "title"
output:
    flexdashboard::flex_dashboard:
    orientation: columns
vertical_layout: fill
runtime: shiny
---

```{r setup, include=FALSE}
library(flexdashboard)
library(lubridate)
library(viridis)
library(plotly)
library(tidytext)
library(readr)
library(tidyverse)
```

```{r global, include=FALSE}
# read global data
```

```{r wrangling-data}
```

Sidebar {.sidebar}
=====================================

```{r}
# shiny inputs defined here

```
Some text added

-------------------------------------

Introduction
=====================================

### Intro

```{r}
```

Data
=====================================

```{r}
```

Conclusion
=====================================

```{r}
```

Hope it helps.


问:
Azure Data Factory webhook execution times out instead of relaying errors
I've attempted to set up a simple webhook execution in Azure Data Factory (v2), calling a simple (parameter-less) webhook for an Azure Automation Runbook I set up.

From the Azure Portal, I can see that the webhook is being executed and my runbook is being run, so far so good. The runbook is (currently) returning an error within 1 minute of execution - but that's fine, I also want to test failure scenarios.

Problem:
Data Factory doesn't seem to be 'seeing' the error result and spins until the timeout (10 minutes) elapses. When I kick off a debug run of the pipeline, I get the same - a timeout and no error result.

Update: I've fixed the runbook and it's now completing successfully, but Data Factory is still timing out and is not seeing the success response either.

Here is a screenshot of the setup:

And here is the portal confirming that the webhook is being run by azure data factory, and is completing in under a minute:

WEBHOOKDATA JSON is:

```<code>{"WebhookName":"Start CAMS VM","RequestBody":"{\r\n \"callBackUri\": \"https://dpeastus.svc.datafactory.azure.com/dataplane/workflow/callback/f7c...df2?callbackUrl=AAEAFF...0927&shouldReportToMonitoring=True&activityType=WebHook\"\r\n}","RequestHeader":{"Connection":"Keep-Alive","Expect":"100-continue","Host":"eab...ddc.webhook.eus2.azure-automation.net","x-ms-request-id":"7b4...2eb"}}
</code>```

So as far as I can tell, things should be in place to pick up on the result (success of failure). Hopefully someone who's done this before knows what I'm missing.

Thanks!

答:
For those looking, I created a secondary approach to the above solution - one that executes a Runbook (with parameters) from a Webhook, rather than a invoking a nested Webhook. This has a couple of benefits:

Parameters can be passed through to the Runbook (rather than requiring parameters to be baked-into a new Webhook.

A Runbook from another Azure Automation Account / Resource Group can be invoked.

There's no need to poll the status of the job, since the Start-AzureRmAutomationRunbook commandlet has a -Wait parameter.

Here's the code:

param
(
    # Note: While "WebhookData" is the only root-level parameter (set by Azure Data Factory when it invokes this webhook)
    #       The user should ensure they provide (via the ADF request body) these additional properties required to invoke the runbook:
    #       - RunbookName
    #       - ResourceGroupName (TODO: Can fill this in by default if not provided)
    #       - AutomationAccountName (TODO: Can fill this in by default if not provided)
    #       - Parameters (A nested dict containing parameters to forward along)
    [Parameter (Mandatory = $false)]
    [object] $WebhookData
)

Import-Module -Name AzureRM.resources
Import-Module -Name AzureRM.automation

Function Get-TimeStamp {
    return "[{0:yyyy-MM-dd} {0:HH:mm:ss}]" -f (Get-Date)
}

# If ADF executed this runbook via Webhook, it should have provided a WebhookData with a request body.
if (-Not $WebhookData) {
    Write-Error "Runbook was not invoked with WebhookData. Args were: $args"
    exit 0
}
if (-Not $WebhookData.RequestBody) {
    Write-Error "WebhookData did not contain a ""RequestBody"" property. Data was: $WebhookData"
    exit 0
}
$parameters = (ConvertFrom-Json -InputObject $WebhookData.RequestBody)
# And this data should contain a JSON body containing a 'callBackUri' property.
if (-Not $parameters.callBackUri) {
    Write-Error 'WebhookData was missing the expected "callBackUri" property (which Azure Data Factory should provide automatically)'
    exit 0
}
$callbackuri = $parameters.callBackUri

# Check for required parameters, and output any errors.
$ErrorMessage = ''
$RunbookName = $parameters.RunbookName
$ResourceGroupName = $parameters.ResourceGroupName
$AutomationAccountName = $parameters.AutomationAccountName
if (-Not $RunbookName) {
    $ErrorMessage += 'WebhookData was missing the expected "RunbookName" property (which the user should have added to the body via ADF)`n'
} if (-Not $ResourceGroupName) {
    $ErrorMessage += 'WebhookData was missing the expected "ResourceGroupName" property (which the user should have added to the body via ADF)`n'
} if (-Not $AutomationAccountName) {
    $ErrorMessage += 'WebhookData was missing the expected "AutomationAccountName" property (which the user should have added to the body via ADF)`n'
} if ($ErrorMessage) {
    Write-Error $ErrorMessage
} else {
    # Set the current automation connection's authenticated account to use for future Azure Resource Manager cmdlet requests.
    # TODO: Provide the user with a way to override this if the target runbook doesn't support the AzureRunAsConnection
    $ServicePrincipalConnection = Get-AutomationConnection -Name "AzureRunAsConnection"
    Add-AzureRmAccount -ServicePrincipal `
        -TenantId $ServicePrincipalConnection.TenantId `
        -ApplicationId $ServicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $ServicePrincipalConnection.CertificateThumbprint | Write-Verbose
    Select-AzureRmSubscription -SubscriptionId $ServicePrincipalConnection.SubscriptionID | Write-Verbose

    # Prepare the properties to pass on to the next runbook - all provided properties exept the ones specific to the ADF passthrough invocation
    $RunbookParams = @{ }
    if($parameters.parameters) {
        $parameters.parameters.PSObject.Properties | Foreach { $RunbookParams[$_.Name] = $_.Value }
        Write-Output "The following parameters will be forwarded to the runbook: $($RunbookParams | ConvertTo-Json -Compress)"
    }

    # Now invoke the actual runbook desired, and wait for it to complete
    Write-Output "$(Get-TimeStamp) Invoking Runbook '$($RunbookName)' from Group '$($ResourceGroupName)' and Automation Account '$($AutomationAccountName)'"
    try {
        # Runbooks have this nice flag that let you wait on their completion (unlike webhook-invoked)
        $Result = Start-AzureRmAutomationRunbook -Wait -Name $RunbookName -AutomationAccountName $AutomationAccountName -ResourceGroupName $ResourceGroupName –Parameters $RunbookParams
    } catch {
        $ErrorMessage = ("An error occurred while invoking Start-AzAutomationRunbook - " + $_.Exception.Message)
        Write-Error -Exception $_.Exception
    }
    # Digest the result to be relayed to ADF
    if($Result) {
        Write-Output "$(Get-TimeStamp) Response: $($Result | ConvertTo-Json -Compress)"
        $OutputMessage = $Result.ToString()
    } elseif(-Not $ErrorMessage) {
        $OutputMessage = "The runbook completed without errors, but the result was null."
    }
}

# Now for the entire purpose of this runbook - relay the response to the callback uri.
# Prepare the success or error response as per specifications at https://learn.microsoft.com/en-us/azure/data-factory/control-flow-webhook-activity#additional-notes
if ($ErrorMessage) {
    $OutputJson = @{
        output = @{ message = $ErrorMessage }
        statusCode = 500
        error = @{
            ErrorCode = "Error"
            Message = $ErrorMessage
        }
    } | ConvertTo-Json -depth 2
} else {
    $OutputJson = @{
        output = @{ message = $OutputMessage }
        statusCode = 200
    } | ConvertTo-Json -depth 2
}
Write-Output "Prepared ADF callback body: $OutputJson"
# Post the response to the callback URL provided
$callbackResponse = Invoke-WebRequest -Uri $callbackuri -UseBasicParsing -Method POST -ContentType "application/json" -Body $OutputJson

Write-Output "Response was relayed to $callbackuri"
Write-Output ("ADF replied with the response: " + ($callbackResponse | ConvertTo-Json -Compress))
```

Body:
I've attempted to set up a simple webhook execution in Azure Data Factory (v2), calling a simple (parameter-less) webhook for an Azure Automation Runbook I set up.

From the Azure Portal, I can see that the webhook is being executed and my runbook is being run, so far so good. The runbook is (currently) returning an error within 1 minute of execution - but that's fine, I also want to test failure scenarios.

Problem:
Data Factory doesn't seem to be 'seeing' the error result and spins until the timeout (10 minutes) elapses. When I kick off a debug run of the pipeline, I get the same - a timeout and no error result.

Update: I've fixed the runbook and it's now completing successfully, but Data Factory is still timing out and is not seeing the success response either.

Here is a screenshot of the setup:

And here is the portal confirming that the webhook is being run by azure data factory, and is completing in under a minute:

WEBHOOKDATA JSON is:

{"WebhookName":"Start CAMS VM","RequestBody":"{\r\n \"callBackUri\": \"https://dpeastus.svc.datafactory.azure.com/dataplane/workflow/callback/f7c...df2?callbackUrl=AAEAFF...0927&shouldReportToMonitoring=True&activityType=WebHook\"\r\n}","RequestHeader":{"Connection":"Keep-Alive","Expect":"100-continue","Host":"eab...ddc.webhook.eus2.azure-automation.net","x-ms-request-id":"7b4...2eb"}}

So as far as I can tell, things should be in place to pick up on the result (success of failure). Hopefully someone who's done this before knows what I'm missing.

Thanks!


问:
When to use the Bridge pattern and how is it different from the Adapter pattern?
Has anyone ever used the Bridge pattern in a real world application? If so, how did you use it? Is it me, or is it just the Adapter pattern with a little dependency injection thrown into the mix? Does it really deserve its own pattern?</p>

答:
You're working for an insurance company where you develop a workflow application that manages different kind of tasks: accounting, contract, claims. This is the abstraction. On the implementation side, you must be able to create tasks from different sources: email, fax, e-messaging.

You begin your design with these classes:

```<code>public class Task {...}
public class AccountingTask : Task {...}
public class ContractTask : Task {...}
public class ClaimTask : Task {...}
</code>```

Now, since each sources must be handled in a specific way, you decide to specialize each task type:

```<code>public class EmailAccountingTask : AccountingTask {...}
public class FaxAccountingTask : AccountingTask {...}
public class EmessagingAccountingTask : AccountingTask {...}

public class EmailContractTask : ContractTask {...}
public class FaxContractTask : ContractTask {...}
public class EmessagingContractTask : ContractTask {...}

public class EmailClaimTask : ClaimTask {...}
public class FaxClaimTask : ClaimTask {...}
public class EmessagingClaimTask : ClaimTask {...}
</code>```

You end up with 13 classes. Adding a task type or a source type becomes challenging. Using the bridge pattern produces something easier to maintain by decoupling the task (the abstraction) from the source (which is an implementation concern):

```<code>// Source
public class Source {
   public string GetSender();
   public string GetMessage();
   public string GetContractReference();
   (...)
}

public class EmailSource : Source {...}
public class FaxSource : Source {...}
public class EmessagingSource : Source {...}

// Task
public class Task {
   public Task(Source source);
   (...)
}
public class AccountingTask : Task {...}
public class ContractTask : Task {...}
public class ClaimTask : Task {...}
</code>```

Adding a task type or a source is now much more easier.

Note: Most developers would not create the 13 classes hierarchy upfront to handle this problem. However, in real life, you might not know in advance the number of source and task types ; if you have only one source and two task types, you would probably not decouple Task from Source. Then, the overall complexity grows as new sources and task types are added. At some point, you will refactor and, most often, end up with a bridge-like solution.

OwnerDisplayName: Charles Graham

Body:
You're working for an insurance company where you develop a workflow application that manages different kind of tasks: accounting, contract, claims. This is the abstraction. On the implementation side, you must be able to create tasks from different sources: email, fax, e-messaging.

You begin your design with these classes:

public class Task {...}
public class AccountingTask : Task {...}
public class ContractTask : Task {...}
public class ClaimTask : Task {...}

Now, since each sources must be handled in a specific way, you decide to specialize each task type:

public class EmailAccountingTask : AccountingTask {...}
public class FaxAccountingTask : AccountingTask {...}
public class EmessagingAccountingTask : AccountingTask {...}

public class EmailContractTask : ContractTask {...}
public class FaxContractTask : ContractTask {...}
public class EmessagingContractTask : ContractTask {...}

public class EmailClaimTask : ClaimTask {...}
public class FaxClaimTask : ClaimTask {...}
public class EmessagingClaimTask : ClaimTask {...}

You end up with 13 classes. Adding a task type or a source type becomes challenging. Using the bridge pattern produces something easier to maintain by decoupling the task (the abstraction) from the source (which is an implementation concern):

// Source
public class Source {
   public string GetSender();
   public string GetMessage();
   public string GetContractReference();
   (...)
}

public class EmailSource : Source {...}
public class FaxSource : Source {...}
public class EmessagingSource : Source {...}

// Task
public class Task {
   public Task(Source source);
   (...)
}
public class AccountingTask : Task {...}
public class ContractTask : Task {...}
public class ClaimTask : Task {...}

Adding a task type or a source is now much more easier.

Note: Most developers would not create the 13 classes hierarchy upfront to handle this problem. However, in real life, you might not know in advance the number of source and task types ; if you have only one source and two task types, you would probably not decouple Task from Source. Then, the overall complexity grows as new sources and task types are added. At some point, you will refactor and, most often, end up with a bridge-like solution.


问:
Only get unique values as json response from database
I have a database and understand in sql I can get unique values via:
Select DISTINCT name, industry from database;
however when I access it via local host and look at the json response i get duplicate values from different times.

code in VSCODE:

```<code>  req.db.from('database').select("name","symbol")
    .then((rows) => {
      res.json({ "Error": false, "Message": "Success", "Database": rows })
    })
    .catch((err) => {
      console.log(err);
      res.json({ "Error": true, "Message": "Error in MYSQL query" })
    })
});
</code>```

what do I need to alter to only receive the name and symbol of each response once and not for every single entry of that object in the database?

答: ah simply .distinct. didn't work earlier for some reason but is working now. rookie :')</p>

Body:
I have a database and understand in sql I can get unique values via:
Select DISTINCT name, industry from database;
however when I access it via local host and look at the json response i get duplicate values from different times.

code in VSCODE:

  req.db.from('database').select("name","symbol")
    .then((rows) => {
      res.json({ "Error": false, "Message": "Success", "Database": rows })
    })
    .catch((err) => {
      console.log(err);
      res.json({ "Error": true, "Message": "Error in MYSQL query" })
    })
});

what do I need to alter to only receive the name and symbol of each response once and not for every single entry of that object in the database?


问:
Azure DevOps Pipeline not finding edmx resources
I have a .Net Core 3.1 MSTest project that calls a separate class library that connects to my database, which was done database-first so I have a .edmx file. It all runs fine locally, but when I push it out to my Azure DevOps Pipeline I start getting a Unable to load the specified metadata resource. exception. I've tested this out by putting in a bit of code to print out all the resources in the assembly

```<code>var resources = (Assembly with EDMX).Assembly.GetManifestResourceNames();
System.Console.WriteLine("There are " + resources.Length + " resources in the assembly");
foreach (var resource in resources)
{
    System.Console.WriteLine(resource);
}
</code>```

The result on my local computer prints out what I expect

```<code>There are 3 resources in the assembly
Model.csdl
Model.msl
Model.ssdl
</code>```

However, the same run on my Pipeline shows 0 resources

```<code>There are 0 resources in the assembly
</code>```

My build process locally and on my pipeline are the exact same

```<code>task: PowerShell@2
inputs:
targetType: 'inline'
script: |
  & "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\msbuild.exe" $(Build.SourcesDirectory)\MyProject\MyProject.sln
  dir $(Build.SourcesDirectory)\MyProject -include ('*.csdl', '*.msl', '*.ssdl') -recurse
  & "C:\hostedtoolcache\windows\dotnet\dotnet.exe" test $(Build.SourcesDirectory)\MyProject\Project.Tests\Project.Tests.csproj
</code>```

Just to make sure the resources actually exist on my Azure Build agent I've added that 2nd powershell command to find my .csdl, .msl, and .ssdl files, and sure enough they do exist

```<code>Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        5/30/2020   3:54 PM          30772 Model.csdl
-a----        5/30/2020   3:54 PM          10993 Model.msl
-a----        5/30/2020   3:54 PM          23351 Model.ssdl
</code>```

These files are located in $(Build.SourcesDirectory)\MyProject\Project.Models\obj\Debug\edmxResourcesToEmbed

And the property looks to be correctly set in my .csproj

```<code>  <ItemGroup>
      <EntityDeploy Include="ProjectModels.edmx">
          <Generator>EntityModelCodeGenerator</Generator>
          <LastGenOutput>ProjectModels.Designer.cs</LastGenOutput>
      </EntityDeploy>
  </ItemGroup>
</code>```

I don't use .edmx database designs often, so I'm unfamiliar on how it is suppose to handle the resources, are they suppose to get compiled into the assembly, or are they just loaded at runtime? My build process both locally and in my Pipeline both show:

```<code>Skipping target "EntityDeployNonEmbeddedResources" because it has no outputs.
EntityDeployEmbeddedResources:
Processing 1 EDMX files.
Starting to process input file 'ProjectModels.edmx'.
Finished processing input file 'ProjectModels.edmx'.
Finished processing 1 EDMX files.
</code>```

Not sure what that indicates, but since it occurs on both I'm assuming its not part of the issue. The only other difference that I can think of is my Azure Pipeline uses Visual Studio 2019 Enterprise, while my local build uses Visual Studio 2019 Community.

Any ideas on what I can do to get these resources to load on my Pipeline build?

答:
Azure DevOps Pipeline not finding edmx resources

This issue should comes from the dotnet test.

AFAIK, dotnet cli does not support embed edmx resources. These types of files are supported in MSBuild props/targets that don't ship in the CLI and only ship in full framework VS.

You could check this ticket for some more details.

And the remaining work for this is already tracked at dotnet/ef6#231.

Hope this helps.

Body:
I have a .Net Core 3.1 MSTest project that calls a separate class library that connects to my database, which was done database-first so I have a .edmx file. It all runs fine locally, but when I push it out to my Azure DevOps Pipeline I start getting a Unable to load the specified metadata resource. exception. I've tested this out by putting in a bit of code to print out all the resources in the assembly

var resources = (Assembly with EDMX).Assembly.GetManifestResourceNames();
System.Console.WriteLine("There are " + resources.Length + " resources in the assembly");
foreach (var resource in resources)
{
    System.Console.WriteLine(resource);
}

The result on my local computer prints out what I expect

There are 3 resources in the assembly
Model.csdl
Model.msl
Model.ssdl

However, the same run on my Pipeline shows 0 resources

There are 0 resources in the assembly

My build process locally and on my pipeline are the exact same

task: PowerShell@2
inputs:
targetType: 'inline'
script: |
  & "C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\msbuild.exe" $(Build.SourcesDirectory)\MyProject\MyProject.sln
  dir $(Build.SourcesDirectory)\MyProject -include ('*.csdl', '*.msl', '*.ssdl') -recurse
  & "C:\hostedtoolcache\windows\dotnet\dotnet.exe" test $(Build.SourcesDirectory)\MyProject\Project.Tests\Project.Tests.csproj

Just to make sure the resources actually exist on my Azure Build agent I've added that 2nd powershell command to find my .csdl, .msl, and .ssdl files, and sure enough they do exist

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        5/30/2020   3:54 PM          30772 Model.csdl
-a----        5/30/2020   3:54 PM          10993 Model.msl
-a----        5/30/2020   3:54 PM          23351 Model.ssdl

These files are located in $(Build.SourcesDirectory)\MyProject\Project.Models\obj\Debug\edmxResourcesToEmbed

And the property looks to be correctly set in my .csproj

  <ItemGroup>
      <EntityDeploy Include="ProjectModels.edmx">
          <Generator>EntityModelCodeGenerator</Generator>
          <LastGenOutput>ProjectModels.Designer.cs</LastGenOutput>
      </EntityDeploy>
  </ItemGroup>

I don't use .edmx database designs often, so I'm unfamiliar on how it is suppose to handle the resources, are they suppose to get compiled into the assembly, or are they just loaded at runtime? My build process both locally and in my Pipeline both show:

Skipping target "EntityDeployNonEmbeddedResources" because it has no outputs.
EntityDeployEmbeddedResources:
Processing 1 EDMX files.
Starting to process input file 'ProjectModels.edmx'.
Finished processing input file 'ProjectModels.edmx'.
Finished processing 1 EDMX files.

Not sure what that indicates, but since it occurs on both I'm assuming its not part of the issue. The only other difference that I can think of is my Azure Pipeline uses Visual Studio 2019 Enterprise, while my local build uses Visual Studio 2019 Community.

Any ideas on what I can do to get these resources to load on my Pipeline build?


问:
showdown extend flowchart.js integrate
showdown is used to convert markdown editor on my blog website, however it doesn't support flowchart which i need. Reading the extension showdown extension, i write a extions for showdown like the follow:

let showdown = require("showdown");
let jQuery = require("jquery");
let flowchart = require("flowchart.js");

function decodeLang(text) {
    return text
      .replace(/¨D/g, '$')
      .replace(/¨T/g, '¨')
      .trim();
}

let flowchartExt = function () {
    let matches = [];
    jQuery(document.head).append('');
    return [{
        type: 'lang',
        filter: function (text, converter, options) {
            return text.replace(/```\s*flow\s*\n+(((?!```)[^])+)\n+```/gm, function (wholeMatch, match) {
                matches.push(decodeLang(match));
                return '%flowchart_placeholder' + _.size(matches) + '%';
            });
        }
    }, {
        type: 'output',
        filter: function (text, converter, options) {
            if (!_.isEmpty(matches)) {
                let jqCanvas = jQuery('<div id="__canvas">').css({
                    position: 'absolute',
                    top: '-1000px',
                    left: '-1000px'
                }).appendTo(document.body);

                let chart = null;
                _.forEach(matches, function (match, i) {
                    let pattern = '%flowchart_placeholder' + (i + 1) + '%';
                    text = text.replace(new RegExp(pattern, 'g'), function () {
                        if (match) {
                            if (chart) {
                                chart.clean();
                            }
                            try {
                                chart = flowchart.parse(match);
                                chart.drawSVG('__canvas');
                                return '<flow-container>' + jqCanvas.html() + '</flow-container>';
                            } catch (e) {
                                console.log(e);
                            }
                        }
                        return match;
                    });
                });

                matches = [];
                jqCanvas.remove();
            }

            return text;
        }
    }]
};
showdown.extension('flowchart', flowchartExt);

export {showdown};</code>```

Now, i instance it's converter to convert the flowchart syntax

import {showdown} from '../_wraps/markdown';

let converter = new showdown.Converter({tables: true});

makeHtml(markdown) {
    return converter.makeHtml(markdown);
}```
</div>
</div>
</p>

<p>flowchart syntax like the following:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>```flow
st=>start: Start
op=>operation: Your Operation
cond=>condition: Yes or No?
e=>end
st->op->cond
cond(yes)->e
cond(no)->op
```</code>```

However it not works! Any suggestion?

答:
Sorry to forget to register the extension to the showdown.Converter, i thought showdown will register it to the Converter defaultly as i register it to the showdown object.

let converter = new showdown.Converter({tables: true, extensions: ['flowchart']});```

Title: showdown extend flowchart.js integrate

Body:
showdown is used to convert markdown editor on my blog website, however it doesn't support flowchart which i need. Reading the extension showdown extension, i write a extions for showdown like the follow:

let showdown = require("showdown");
let jQuery = require("jquery");
let flowchart = require("flowchart.js");

function decodeLang(text) {
    return text
      .replace(/¨D/g, '$')
      .replace(/¨T/g, '¨')
      .trim();
}

let flowchartExt = function () {
    let matches = [];
    jQuery(document.head).append('');
    return [{
        type: 'lang',
        filter: function (text, converter, options) {
            return text.replace(/```\s*flow\s*\n+(((?!```)[^])+)\n+```/gm, function (wholeMatch, match) {
                matches.push(decodeLang(match));
                return '%flowchart_placeholder' + _.size(matches) + '%';
            });
        }
    }, {
        type: 'output',
        filter: function (text, converter, options) {
            if (!_.isEmpty(matches)) {
                let jqCanvas = jQuery('<div id="__canvas">').css({
                    position: 'absolute',
                    top: '-1000px',
                    left: '-1000px'
                }).appendTo(document.body);

                let chart = null;
                _.forEach(matches, function (match, i) {
                    let pattern = '%flowchart_placeholder' + (i + 1) + '%';
                    text = text.replace(new RegExp(pattern, 'g'), function () {
                        if (match) {
                            if (chart) {
                                chart.clean();
                            }
                            try {
                                chart = flowchart.parse(match);
                                chart.drawSVG('__canvas');
                                return '<flow-container>' + jqCanvas.html() + '</flow-container>';
                            } catch (e) {
                                console.log(e);
                            }
                        }
                        return match;
                    });
                });

                matches = [];
                jqCanvas.remove();
            }

            return text;
        }
    }]
};
showdown.extension('flowchart', flowchartExt);

export {showdown};</code></pre>
</div>
</div>
</p>

<p>Now, i instance it's converter to convert the flowchart syntax</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import {showdown} from '../_wraps/markdown';

let converter = new showdown.Converter({tables: true});

makeHtml(markdown) {
    return converter.makeHtml(markdown);
}</code></pre>
</div>
</div>
</p>

<p>flowchart syntax like the following:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>```flow
st=>start: Start
op=>operation: Your Operation
cond=>condition: Yes or No?
e=>end
st->op->cond
cond(yes)->e
cond(no)->op
```

However it not works! Any suggestion?


问:
PowerShell: Add every sub-directory to path
On Windows 10 and via PowerShell, how do you add every sub-directory to the PATH variable?

I fine some method for Linux (e.g., this one), and "adapting" them to PowerShell, I came across the following.

```<code>'$env:PATH = $env:PATH + (find C:\Users\appveyor\ -type d -printf "\";%pbuild\\"")'
</code>```

This throws The filename, directory name, or volume label syntax is incorrect.

A bit more context: I am running this on appveyor, and trying to add every path under appveyor (simplified for clarity) such as C:\Users\appveyor\*\build\ to path.

答:
```<code>$env:PATH =
    @($env:PATH) +
    [string]::join(
        ";",
        (Get-ChildItem -LiteralPath "[PATH TO SEARCH]" -Directory -Recurse).fullname
    )
</code>```

This based on @briantist's suggestion; the main difference is in the join syntax.

To get this work on appveyor, do the following:

```<code>{ps:
    "$env:PATH =
         @($env:PATH) + [string]::join(
             \";\",
             (Get-ChildItem -LiteralPath \"[PATH TO SEARCH]\" -Directory -Recurse).fullname
    )"
}
</code>```

Body:
On Windows 10 and via PowerShell, how do you add every sub-directory to the PATH variable?

I fine some method for Linux (e.g., this one), and "adapting" them to PowerShell, I came across the following.

'$env:PATH = $env:PATH + (find C:\Users\appveyor\ -type d -printf "\";%pbuild\\"")'

This throws The filename, directory name, or volume label syntax is incorrect.

A bit more context: I am running this on appveyor, and trying to add every path under appveyor (simplified for clarity) such as C:\Users\appveyor\*\build\ to path.

Body:
$env:PATH =
    @($env:PATH) +
    [string]::join(
        ";",
        (Get-ChildItem -LiteralPath "[PATH TO SEARCH]" -Directory -Recurse).fullname
    )

This based on @briantist's suggestion; the main difference is in the join syntax.

To get this work on appveyor, do the following:

{ps:
    "$env:PATH =
         @($env:PATH) + [string]::join(
             \";\",
             (Get-ChildItem -LiteralPath \"[PATH TO SEARCH]\" -Directory -Recurse).fullname
    )"
}


问:
Snowflake: why query is retried twice during resource contention
Snowflake query running on a medium warehouse is re-ran twice during resource contention. Can someone share any reference on how snowflake fails and then retries the execution of the same query. What is the advantage we are gaining with this approach?

Step 1
Step 2
Step 1002
Step 2002

答:
As it has been explained to us by support: When a query fails due to internal errors, snowflake retries the query but on the prior software stack versions. To see if the failure is part of a recent update on their side. </p>

<p>You do get the joy of paying for both runs. If there is happening a lot, you should open a support case as there is a repeating bug that should be addressed or worked around. Under some situations we have had the long dead time (the failure case) refunded. </p>

Body:
As it has been explained to us by support: When a query fails due to internal errors, snowflake retries the query but on the prior software stack versions. To see if the failure is part of a recent update on their side.

You do get the joy of paying for both runs. If there is happening a lot, you should open a support case as there is a repeating bug that should be addressed or worked around. Under some situations we have had the long dead time (the failure case) refunded.


问:
How to display different comment sets for a commenting component? (VueJS, Firebase)
I'm trying to create a social media app with comments on each post.

I can display comments, but each post displays the same set of comments.

I'm struggling to figure out how I can display different sets of comments on each post.

Would really appreciate help!

Github code here

答:
I see the problem you have here: you should add some method of separation between comments on different posts.

Example:

Without separation:

A user > Nice post

User 2 > This is a cool post

The 3rd > Wow, cool!

A user > Nice post

User 5 > This is a cool post

The 6th > Wow, cool!

A user > Nice post

User 8 > This is a cool post

The 9th > Wow, cool!

With separation:

Post 1 > A user > Nice post

Post 3 > User 2 > This is a cool post

Post 2 > The 3rd > Wow, cool!

Post 3 > A user > Nice post

Post 1 > User 5 > This is a cool post

Post 2 > The 6th > Wow, cool!

Post 2 > A user > Nice post

Post 1 > User 8 > This is a cool post

Post 3 > The 9th > Wow, cool!

How to fix:

Add a match for a post id, and add the post ids to each post.

And change the script in CommentForm.vue with this:

export default {
  data() {
    return {
      username: null,
      comment: null,
      post: null,
    };
  },
  name: "CommentForm",
  methods: {
    onPost() {
      let commentContent = {
        name: this.username,
        comment: this.comment,
        post: this.post
      };
      this.$emit("comment-posted", commentContent),
        (this.username = null),
        (this.comment = null),
        (this.post = null);
    },
  },
};
```


问:
In Azure SQL Server can the AD Admin which is also a Service Principal run a query on the master database?
Given:

An Azure SQL Server - MyAzureSqlServer

A Service Principal - MyServicePrincipal

The Service Principal is configured as the AD Admin of the Azure SQL Server. (Azure Portal and Az Powershell module do not allow it, but Azure CLI and the REST API do)

I have Powershell code that runs SELECT 1 on the given database in the aforementioned Azure SQL Server:

```<code>param($db)

$AzContext = Get-AzContext               # Assume this returns the Az Context for MyServicePrincipal
$TenantId = $AzContext.Tenant.Id
$ClientId = $AzContext.Account.Id
$SubscriptionId = $AzContext.Subscription.Id
$ClientSecret = $AzContext.Account.ExtendedProperties.ServicePrincipalSecret

$token = Get-AzureAuthenticationToken -TenantID $TenantId -ClientID $ClientId -ClientSecret $ClientSecret -ResourceAppIDUri "https://database.windows.net/"

Invoke-SqlQueryThruAdoNet -ConnectionString "Server=MyAzureSqlServer.database.windows.net;database=$db" -AccessToken $token -Query "SELECT 1"
</code>```

Where Get-AzureAuthenticationToken is:

```<code>function Get-AzureAuthenticationToken(
    [Parameter(Mandatory)][String]$TenantID,
    [Parameter(Mandatory)][String]$ClientID,
    [Parameter(Mandatory)][String]$ClientSecret,
    [Parameter(Mandatory)][String]$ResourceAppIDUri)
{
    $tokenResponse = Invoke-RestMethod -Method Post -UseBasicParsing `
        -Uri "https://login.windows.net/$TenantID/oauth2/token" `
        -Body @{
        resource      = $ResourceAppIDUri
        client_id     = $ClientID
        grant_type    = 'client_credentials'
        client_secret = $ClientSecret
    } -ContentType 'application/x-www-form-urlencoded'

    Write-Verbose "Access token type is $($tokenResponse.token_type), expires $($tokenResponse.expires_on)"
    $tokenResponse.access_token
}
</code>```

And Invoke-SqlQueryThruAdoNet is:

```<code>function Invoke-SqlQueryThruAdoNet(
    [parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$ConnectionString,
    [parameter(Mandatory=$true)]
    [string]$Query,
    $QueryTimeout = 30,
    [string]$AccessToken
)
{
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    try
    {
        $SqlConnection.ConnectionString = $ConnectionString
        if ($AccessToken)
        {
            $SqlConnection.AccessToken = $AccessToken
        }
        $SqlConnection.Open()

        $SqlCmd.CommandTimeout = $QueryTimeout
        $SqlCmd.CommandText = $Query
        $SqlCmd.Connection = $SqlConnection

        $DataSet = New-Object System.Data.DataSet
        $SqlAdapter.SelectCommand = $SqlCmd
        [void]$SqlAdapter.Fill($DataSet)

        $res = $null
        if ($DataSet.Tables.Count)
        {
            $res = $DataSet.Tables[$DataSet.Tables.Count - 1]
        }
        $res
    }
    finally
    {
        $SqlAdapter.Dispose()
        $SqlCmd.Dispose()
        $SqlConnection.Dispose()
    }
}
</code>```

And it works fine on any database, except on the master, for which I get:

[MyAzureSqlServer.database.windows.net\master] Login failed for user '4...1@2...b'. (SqlError 18456, LineNumber = 65536, ClientConnectionId = b8f4f657-2772-4306-b222-4533013227d1)

where 4...1 is the client Id of MyServicePrincipal and 2...b is our Azure AD Tenant Id.

So I know the access token is OK, because I can run queries on other databases. It is specifically the master that is problematic. Is there a solution for that? Of course, it must work with the Service Principal being the AD Admin.

EDIT 1

As I have mentioned there are 2 ways to configure a Service Principal to be the AD Admin:

Using Azure CLI. It is actually straightforward:

```<code>az sql server ad-admin create --resource-group {YourAzureSqlResourceGroupName} `
        --server-name {YourAzureSqlServerName} `
        --display-name {ADAdminName} `
        --object-id {ServicePrincipalObjectId}
</code>```

The {ADAdminName} can be whatever, but we pass the display name of the Service Principal.

Now while this works, we abandoned Azure CLI in favour of Az Powershell, because the latter does not persist Service Principal credentials on disk in clear text. However, Az Powershell's function Set-AzSqlServerActiveDirectoryAdministrator does not accept a Service Principal. Yet the Azure REST API does allow it, hence we have the following custom PS function doing the job:

```<code>function Set-MyAzSqlServerActiveDirectoryAdministrator
{
    [CmdLetBinding(DefaultParameterSetName = 'NoObjectId')]
    param(
        [Parameter(Mandatory, Position = 0)][string]$ResourceGroupName,
        [Parameter(Mandatory, Position = 1)][string]$ServerName,
        [Parameter(ParameterSetName = 'ObjectId', Mandatory)][ValidateNotNullOrEmpty()]$ObjectId,
        [Parameter(ParameterSetName = 'ObjectId', Mandatory)][ValidateNotNullOrEmpty()]$DisplayName
    )

    $AzContext = Get-AzContext
    if (!$AzContext)
    {
        throw "No Az context is found."
    }
    $TenantId = $AzContext.Tenant.Id
    $ClientId = $AzContext.Account.Id
    $SubscriptionId = $AzContext.Subscription.Id
    $ClientSecret = $AzContext.Account.ExtendedProperties.ServicePrincipalSecret

    if ($PsCmdlet.ParameterSetName -eq 'NoObjectId')
    {
        $sp = Get-AzADServicePrincipal -ApplicationId $ClientId
        $DisplayName = $sp.DisplayName
        $ObjectId = $sp.Id
    }

    $path = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.Sql/servers/$ServerName/administrators/activeDirectory"
    $apiUrl = "https://management.azure.com${path}?api-version=2014-04-01"
    $jsonBody = @{
        id         = $path
        name       = 'activeDirectory'
        properties = @{
            administratorType = 'ActiveDirectory'
            login             = $DisplayName
            sid               = $ObjectId
            tenantId          = $TenantId
        }
    } | ConvertTo-Json -Depth 99
    $token = Get-AzureAuthenticationToken -TenantID $TenantId -ClientID $ClientId -ClientSecret $ClientSecret -ResourceAppIDUri "https://management.core.windows.net/"
    $headers = @{
        "Authorization" = "Bearer $token"
        "Content-Type"  = "application/json"
    }
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    Invoke-RestMethod $apiUrl -Method Put -Headers $headers -Body $jsonBody
}
</code>```

It uses the already familiar (see above) function Get-AzureAuthenticationToken. For our needs it sets the currently logged in Service Principal as the AD admin.

答:
According to my test, when we directly set Azure service principal as Azure SQL AD admin, it will cause some problems. We cannot log in master database with the service pricipal. Because Azure AD administrator login should be an Azure AD user or an Azure AD group. For more details, please refer to the document

So if you want to set Azure service principal as Azure SQL AD admin, we need to create an Azure AD security group, add service principal as the group's member the set the Azure AD group as Azure SQL AD admin.

For example

Configure Azure AD admin

```<code>Connect-AzAccount

$group=New-AzADGroup -DisplayName SQLADADmin -MailNickname SQLADADmin

$sp=Get-AzADServicePrincipal -DisplayName "TodoListService-OBO-sample-v2"

Add-AzADGroupMember -MemberObjectId $sp.Id -TargetGroupObjectId $group.id

$sp=Get-AzADServicePrincipal -DisplayName "<your sq name>"

Remove-AzSqlServerActiveDirectoryAdministrator -ResourceGroupName "<>" -ServerName "<>" -force

Set-AzSqlServerActiveDirectoryAdministrator -ResourceGroupName "<>" -ServerName "<>" -DisplayName $group.DisplayName -ObjectId $group.id
</code>```

query

```<code>$appId = "<your sp app id>"
$password = "<your sp password>"
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($appId, $secpasswd)
Connect-AzAccount -ServicePrincipal -Credential $mycreds -Tenant "<your AD tenant id>"
#get token
$context =Get-AzContext
$dexResourceUrl='https://database.windows.net/'
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account,
                                $context.Environment,
                                $context.Tenant.Id.ToString(),
                                 $null,
                                 [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never,
                                 $null, $dexResourceUrl).AccessToken

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$ConnectionString="Data Source=testsql08.database.windows.net; Initial Catalog=master;"

# query the current database name
$Query="SELECT DB_NAME()"

    try
    {
        $SqlConnection.ConnectionString = $ConnectionString
        if ($token)
        {
            $SqlConnection.AccessToken = $token
        }
        $SqlConnection.Open()

        $SqlCmd.CommandText = $Query
        $SqlCmd.Connection = $SqlConnection

        $DataSet = New-Object System.Data.DataSet
        $SqlAdapter.SelectCommand = $SqlCmd
        [void]$SqlAdapter.Fill($DataSet)

        $res = $null
        if ($DataSet.Tables.Count)
        {
            $res = $DataSet.Tables[$DataSet.Tables.Count - 1]
        }
         $res
    }
    finally
    {
        $SqlAdapter.Dispose()
        $SqlCmd.Dispose()
        $SqlConnection.Dispose()
    }

</code>```

Body:
Given:

An Azure SQL Server - MyAzureSqlServer

A Service Principal - MyServicePrincipal

The Service Principal is configured as the AD Admin of the Azure SQL Server. (Azure Portal and Az Powershell module do not allow it, but Azure CLI and the REST API do)

I have Powershell code that runs SELECT 1 on the given database in the aforementioned Azure SQL Server:

param($db)

$AzContext = Get-AzContext               # Assume this returns the Az Context for MyServicePrincipal
$TenantId = $AzContext.Tenant.Id
$ClientId = $AzContext.Account.Id
$SubscriptionId = $AzContext.Subscription.Id
$ClientSecret = $AzContext.Account.ExtendedProperties.ServicePrincipalSecret

$token = Get-AzureAuthenticationToken -TenantID $TenantId -ClientID $ClientId -ClientSecret $ClientSecret -ResourceAppIDUri "https://database.windows.net/"

Invoke-SqlQueryThruAdoNet -ConnectionString "Server=MyAzureSqlServer.database.windows.net;database=$db" -AccessToken $token -Query "SELECT 1"

Where Get-AzureAuthenticationToken is:

function Get-AzureAuthenticationToken(
    [Parameter(Mandatory)][String]$TenantID,
    [Parameter(Mandatory)][String]$ClientID,
    [Parameter(Mandatory)][String]$ClientSecret,
    [Parameter(Mandatory)][String]$ResourceAppIDUri)
{
    $tokenResponse = Invoke-RestMethod -Method Post -UseBasicParsing `
        -Uri "https://login.windows.net/$TenantID/oauth2/token" `
        -Body @{
        resource      = $ResourceAppIDUri
        client_id     = $ClientID
        grant_type    = 'client_credentials'
        client_secret = $ClientSecret
    } -ContentType 'application/x-www-form-urlencoded'

    Write-Verbose "Access token type is $($tokenResponse.token_type), expires $($tokenResponse.expires_on)"
    $tokenResponse.access_token
}

And Invoke-SqlQueryThruAdoNet is:

function Invoke-SqlQueryThruAdoNet(
    [parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$ConnectionString,
    [parameter(Mandatory=$true)]
    [string]$Query,
    $QueryTimeout = 30,
    [string]$AccessToken
)
{
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
    $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
    try
    {
        $SqlConnection.ConnectionString = $ConnectionString
        if ($AccessToken)
        {
            $SqlConnection.AccessToken = $AccessToken
        }
        $SqlConnection.Open()

        $SqlCmd.CommandTimeout = $QueryTimeout
        $SqlCmd.CommandText = $Query
        $SqlCmd.Connection = $SqlConnection

        $DataSet = New-Object System.Data.DataSet
        $SqlAdapter.SelectCommand = $SqlCmd
        [void]$SqlAdapter.Fill($DataSet)

        $res = $null
        if ($DataSet.Tables.Count)
        {
            $res = $DataSet.Tables[$DataSet.Tables.Count - 1]
        }
        $res
    }
    finally
    {
        $SqlAdapter.Dispose()
        $SqlCmd.Dispose()
        $SqlConnection.Dispose()
    }
}

And it works fine on any database, except on the master, for which I get:

[MyAzureSqlServer.database.windows.net\master] Login failed for user '4...1@2...b'. (SqlError 18456, LineNumber = 65536, ClientConnectionId = b8f4f657-2772-4306-b222-4533013227d1)

where 4...1 is the client Id of MyServicePrincipal and 2...b is our Azure AD Tenant Id.

So I know the access token is OK, because I can run queries on other databases. It is specifically the master that is problematic. Is there a solution for that? Of course, it must work with the Service Principal being the AD Admin.

EDIT 1

As I have mentioned there are 2 ways to configure a Service Principal to be the AD Admin:

Using Azure CLI. It is actually straightforward:

az sql server ad-admin create --resource-group {YourAzureSqlResourceGroupName} `
        --server-name {YourAzureSqlServerName} `
        --display-name {ADAdminName} `
        --object-id {ServicePrincipalObjectId}

The {ADAdminName} can be whatever, but we pass the display name of the Service Principal.

Now while this works, we abandoned Azure CLI in favour of Az Powershell, because the latter does not persist Service Principal credentials on disk in clear text. However, Az Powershell's function Set-AzSqlServerActiveDirectoryAdministrator does not accept a Service Principal. Yet the Azure REST API does allow it, hence we have the following custom PS function doing the job:

function Set-MyAzSqlServerActiveDirectoryAdministrator
{
    [CmdLetBinding(DefaultParameterSetName = 'NoObjectId')]
    param(
        [Parameter(Mandatory, Position = 0)][string]$ResourceGroupName,
        [Parameter(Mandatory, Position = 1)][string]$ServerName,
        [Parameter(ParameterSetName = 'ObjectId', Mandatory)][ValidateNotNullOrEmpty()]$ObjectId,
        [Parameter(ParameterSetName = 'ObjectId', Mandatory)][ValidateNotNullOrEmpty()]$DisplayName
    )

    $AzContext = Get-AzContext
    if (!$AzContext)
    {
        throw "No Az context is found."
    }
    $TenantId = $AzContext.Tenant.Id
    $ClientId = $AzContext.Account.Id
    $SubscriptionId = $AzContext.Subscription.Id
    $ClientSecret = $AzContext.Account.ExtendedProperties.ServicePrincipalSecret

    if ($PsCmdlet.ParameterSetName -eq 'NoObjectId')
    {
        $sp = Get-AzADServicePrincipal -ApplicationId $ClientId
        $DisplayName = $sp.DisplayName
        $ObjectId = $sp.Id
    }

    $path = "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.Sql/servers/$ServerName/administrators/activeDirectory"
    $apiUrl = "https://management.azure.com${path}?api-version=2014-04-01"
    $jsonBody = @{
        id         = $path
        name       = 'activeDirectory'
        properties = @{
            administratorType = 'ActiveDirectory'
            login             = $DisplayName
            sid               = $ObjectId
            tenantId          = $TenantId
        }
    } | ConvertTo-Json -Depth 99
    $token = Get-AzureAuthenticationToken -TenantID $TenantId -ClientID $ClientId -ClientSecret $ClientSecret -ResourceAppIDUri "https://management.core.windows.net/"
    $headers = @{
        "Authorization" = "Bearer $token"
        "Content-Type"  = "application/json"
    }
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    Invoke-RestMethod $apiUrl -Method Put -Headers $headers -Body $jsonBody
}

It uses the already familiar (see above) function Get-AzureAuthenticationToken. For our needs it sets the currently logged in Service Principal as the AD admin.

Body:
According to my test, when we directly set Azure service principal as Azure SQL AD admin, it will cause some problems. We cannot log in master database with the service pricipal. Because Azure AD administrator login should be an Azure AD user or an Azure AD group. For more details, please refer to the document

So if you want to set Azure service principal as Azure SQL AD admin, we need to create an Azure AD security group, add service principal as the group's member the set the Azure AD group as Azure SQL AD admin.

For example

Configure Azure AD admin

Connect-AzAccount

$group=New-AzADGroup -DisplayName SQLADADmin -MailNickname SQLADADmin

$sp=Get-AzADServicePrincipal -DisplayName "TodoListService-OBO-sample-v2"

Add-AzADGroupMember -MemberObjectId $sp.Id -TargetGroupObjectId $group.id

$sp=Get-AzADServicePrincipal -DisplayName "<your sq name>"

Remove-AzSqlServerActiveDirectoryAdministrator -ResourceGroupName "<>" -ServerName "<>" -force

Set-AzSqlServerActiveDirectoryAdministrator -ResourceGroupName "<>" -ServerName "<>" -DisplayName $group.DisplayName -ObjectId $group.id

query

$appId = "<your sp app id>"
$password = "<your sp password>"
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($appId, $secpasswd)
Connect-AzAccount -ServicePrincipal -Credential $mycreds -Tenant "<your AD tenant id>"
#get token
$context =Get-AzContext
$dexResourceUrl='https://database.windows.net/'
$token = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account,
                                $context.Environment,
                                $context.Tenant.Id.ToString(),
                                 $null,
                                 [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never,
                                 $null, $dexResourceUrl).AccessToken

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$ConnectionString="Data Source=testsql08.database.windows.net; Initial Catalog=master;"

# query the current database name
$Query="SELECT DB_NAME()"

    try
    {
        $SqlConnection.ConnectionString = $ConnectionString
        if ($token)
        {
            $SqlConnection.AccessToken = $token
        }
        $SqlConnection.Open()

        $SqlCmd.CommandText = $Query
        $SqlCmd.Connection = $SqlConnection

        $DataSet = New-Object System.Data.DataSet
        $SqlAdapter.SelectCommand = $SqlCmd
        [void]$SqlAdapter.Fill($DataSet)

        $res = $null
        if ($DataSet.Tables.Count)
        {
            $res = $DataSet.Tables[$DataSet.Tables.Count - 1]
        }
         $res
    }
    finally
    {
        $SqlAdapter.Dispose()
        $SqlCmd.Dispose()
        $SqlConnection.Dispose()
    }


问:
Display :before element on a flex container in ie11
I have a flex container with a couple of children that I need to have a before element on. The before element displays if the parent container is display: block but not if it's display: flex ! is there a workaround for this?

:before doesn't work, but child container styling is fine:

```<code><div class="parent">
  <div></div>
  <div></div>
</div>

<style lang="scss">
.parent {
  display: flex;
  justify-content: space-between;
  position: relative;

  &:before {
    content: '';
    position: absolute;
    top: -20px;
    height: 20px;
    width: 100%;
    background: linear-gradient(180deg, transparent, $gray);
  }
}
</style>
</code>```

:before works, but breaks my child element styling:

```<code><div class="parent">
  <div></div>
  <div></div>
</div>

<style lang="scss">
.parent {
  display: block;
  position: relative;

  &:before {
    content: '';
    position: absolute;
    top: -20px;
    height: 20px;
    width: 100%;
    background: linear-gradient(180deg, transparent, $gray);
  }
}
</style>
</code>```

答:
Try to add margin-right:auto; CSS style for the first div element in the parent container.

Code as below (you could change the CSS style to SCSS style):

```<code><div class="parent">
    <div style="background-color:coral;">content 1</div>
    <div style="background-color:pink;">content 2</div>
</div>

<style >
    .parent {
        display: flex;
        display: -ms-flexbox;
        justify-content: space-between;
        position: relative;
    }

        .parent::before {
            content: "";
            position: absolute;
            top: -20px;
            height: 20px;
            width: 100%;
            background: linear-gradient(180deg , red, yellow);
            background-color: aqua;
        }

        .parent div:first-child {
            margin-right:auto;
        }
        .parent div {
            width: 70px;
            height: 70px;
            display: block;
        }
</style>
</code>```

The result in IE11 browser like this:

Body:
I have a flex container with a couple of children that I need to have a before element on. The before element displays if the parent container is display: block but not if it's display: flex ! is there a workaround for this?

:before doesn't work, but child container styling is fine:

:before works, but breaks my child element styling:

Body:
Try to add margin-right:auto; CSS style for the first div element in the parent container.

Code as below (you could change the CSS style to SCSS style):

<div class="parent">
    <div style="background-color:coral;">content 1</div>
    <div style="background-color:pink;">content 2</div>
</div>

<style >
    .parent {
        display: flex;
        display: -ms-flexbox;
        justify-content: space-between;
        position: relative;
    }

        .parent::before {
            content: "";
            position: absolute;
            top: -20px;
            height: 20px;
            width: 100%;
            background: linear-gradient(180deg , red, yellow);
            background-color: aqua;
        }

        .parent div:first-child {
            margin-right:auto;
        }
        .parent div {
            width: 70px;
            height: 70px;
            display: block;
        }
</style>

The result in IE11 browser like this:


问:
Error: filtered policies are not supported by this adapter
This TypeORMAdapter (https://github.com/node-casbin/typeorm-adapter) supports FilteredAdapter however not sure why I'm getting below error : -

```<code>Error: filtered policies are not supported by this adapter
message:"filtered policies are not supported by this adapter"
stack:"Error: filtered policies are not supported by this adapter
    at Enforcer.<anonymous> (/var/task/node_modules/casbin/lib/coreEnforcer.js:159:23)
    at Generator.next (<anonymous>)
    at /var/task/node_modules/casbin/lib/coreEnforcer.js:21:71
    at new Promise (<anonymous>)
    at /var/task/node_modules/casbin/lib/coreEnforcer.js:17:12
    at Enforcer.loadFilteredPolicy (/var/task/node_modules/casbin/lib/coreEnforcer.js:153:16)
    at /var/task/src/loadPermissions.js:35:24
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Runtime.handler (/var/task/index.js:15:22)"
__proto__:Object {constructor: , name: "Error", message: "", …}
</code>```

Below is my code: -

```<code>'use-strict';
const { newEnforcer } = require('casbin');
const TypeORMAdapter = require('typeorm-adapter');
const { updateCache } = require('./cache-manager/cacheService');
const MODEL = process.env.MODEL || './enforcer/casbin_conf/model.conf';
const { join } = require('path');

module.exports.loadPermissions = async (event, context, callback, logger) => {
    let key = null;
    if (event.queryStringParameters && event.queryStringParameters.key) {
        console.log("Received key: " + event.queryStringParameters.key);
        key = event.queryStringParameters.key;
    }
    const a = await TypeORMAdapter.default.newAdapter({
        type: 'mysql',
        host: '192.168.1.5',
        port: 3306,
        username: 'root',
        password: '',
        database: 'casbin',
    });
    //a.enabledFiltered(true);

    const e = await newEnforcer(join(__dirname, MODEL), a);
    // Load the filtered policy from DB.
    const fp = await e.loadFilteredPolicy({
        'ptype': 'p',
        'v0': 'alice'
    });
    const policies = { "v0": "p", "v1": "admin", "v2": "/*", "v3": "GET" }; //temp code only
    return await updateCache(key, policies, logger);
};
</code>```

I get error whenever I call this method loadFilteredPolicy(). Secondly, I would like to know why the method loadFilteredPolicy(filter) is getting called which is there on CoreEnforcer class. I want to invoke the loadFilteredPolicy(model, filter) which is there on TypeORMAdapter.

Please assist me here.

Thank you

答:
That adapter doesn't support the "filtered policy" feature. It's an optional feature. See: https://casbin.org/docs/en/policy-subset-loading

You can raise a GitHub issue in that adapter's repo. In the issue, you can ask for help to support that feature. PR is also welcomed.

Body:
This TypeORMAdapter (https://github.com/node-casbin/typeorm-adapter) supports FilteredAdapter however not sure why I'm getting below error : -

Error: filtered policies are not supported by this adapter
message:"filtered policies are not supported by this adapter"
stack:"Error: filtered policies are not supported by this adapter
    at Enforcer.<anonymous> (/var/task/node_modules/casbin/lib/coreEnforcer.js:159:23)
    at Generator.next (<anonymous>)
    at /var/task/node_modules/casbin/lib/coreEnforcer.js:21:71
    at new Promise (<anonymous>)
    at /var/task/node_modules/casbin/lib/coreEnforcer.js:17:12
    at Enforcer.loadFilteredPolicy (/var/task/node_modules/casbin/lib/coreEnforcer.js:153:16)
    at /var/task/src/loadPermissions.js:35:24
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Runtime.handler (/var/task/index.js:15:22)"
__proto__:Object {constructor: , name: "Error", message: "", …}

Below is my code: -

'use-strict';
const { newEnforcer } = require('casbin');
const TypeORMAdapter = require('typeorm-adapter');
const { updateCache } = require('./cache-manager/cacheService');
const MODEL = process.env.MODEL || './enforcer/casbin_conf/model.conf';
const { join } = require('path');

module.exports.loadPermissions = async (event, context, callback, logger) => {
    let key = null;
    if (event.queryStringParameters && event.queryStringParameters.key) {
        console.log("Received key: " + event.queryStringParameters.key);
        key = event.queryStringParameters.key;
    }
    const a = await TypeORMAdapter.default.newAdapter({
        type: 'mysql',
        host: '192.168.1.5',
        port: 3306,
        username: 'root',
        password: '',
        database: 'casbin',
    });
    //a.enabledFiltered(true);

    const e = await newEnforcer(join(__dirname, MODEL), a);
    // Load the filtered policy from DB.
    const fp = await e.loadFilteredPolicy({
        'ptype': 'p',
        'v0': 'alice'
    });
    const policies = { "v0": "p", "v1": "admin", "v2": "/*", "v3": "GET" }; //temp code only
    return await updateCache(key, policies, logger);
};

I get error whenever I call this method loadFilteredPolicy(). Secondly, I would like to know why the method loadFilteredPolicy(filter) is getting called which is there on CoreEnforcer class. I want to invoke the loadFilteredPolicy(model, filter) which is there on TypeORMAdapter.

Please assist me here.

Thank you


问:
zip a list with space delimited into tuple
I have a dataframe df with a column called columnList as str.

```<code>"1 2,7 8,10 7"
</code>```

Then I converted them to a list as shown :

```<code>[1 2,7 8,10 7]
</code>```

I want to convert the value inside list to tuple :

```<code>[(1,2),(7,8),(10,7)]
</code>```

Current code :

```<code>temp = df['columnList'].str.split(',')
result = list(zip(temp[::2], temp[1::2]))
print(result)
</code>```

I'm getting empty list.

df looks like this :

```<code>column1    columnList
  YY      1 2,7 8,10 7
</code>```

Name: df, dtype: object

答:
You don't need to use zip here, just iterate over the list, split each element and store it as a tuple.

```<code>l = [ '1 2', '7 8', '10 7']
[tuple(int(i) for i in numbers.split()) for numbers in l]

#[(1, 2), (7, 8), (10, 7)]
</code>```

Body:
I have a dataframe df with a column called columnList as str.

"1 2,7 8,10 7"

Then I converted them to a list as shown :

[1 2,7 8,10 7]

I want to convert the value inside list to tuple :

[(1,2),(7,8),(10,7)]

Current code :

temp = df['columnList'].str.split(',')
result = list(zip(temp[::2], temp[1::2]))
print(result)

I'm getting empty list.

df looks like this :

column1    columnList
  YY      1 2,7 8,10 7

Name: df, dtype: object

Body:
You don't need to use zip here, just iterate over the list, split each element and store it as a tuple.

l = [ '1 2', '7 8', '10 7']
[tuple(int(i) for i in numbers.split()) for numbers in l]

#[(1, 2), (7, 8), (10, 7)]


问:
load favicon.ico from referenced project does not work (_host.cshtml)
load favicon.ico from referenced project does not work (_host.cshtml)

loading of scripts and css files of referenced projects works, but not for the favicon. it's located in the wwwroot of referenced project.

neither work

```<code><image href="_content/Common.Server.UI/favicon.ico" rel="stylesheet" />
</code>```

```<code><link href="_content/Common.Server.UI/favicon.ico" rel="stylesheet" />
</code>```

What am I doing wrong?

Thw browser says 404 for the favicon.

答:
rel "Specifies the relationship between the current document and the linked document". The relationship attribute should be "icon" not stylesheet which is used for .css files.

<link rel="icon" type="image/png" href="images/icon.png">
```

or type ico for .ico files ect.

Body:
load favicon.ico from referenced project does not work (_host.cshtml)

loading of scripts and css files of referenced projects works, but not for the favicon. it's located in the wwwroot of referenced project.

neither work

<image href="_content/Common.Server.UI/favicon.ico" rel="stylesheet" />

<link href="_content/Common.Server.UI/favicon.ico" rel="stylesheet" />

What am I doing wrong?

Thw browser says 404 for the favicon.

Body:
rel "Specifies the relationship between the current document and the linked document". The relationship attribute should be "icon" not stylesheet which is used for .css files.

<link rel="icon" type="image/png" href="images/icon.png">

or type ico for .ico files ect.


问:
Disable/Remove floating label hint text in TextInputLayout XML
This may seem counter-intuitive but is there a way to disable or remove the floating label hint in TextInputLayout? The reason I want to use TextInputLayout instead of just an EditText is for the counter that TextInputLayout provides.

Here is what I have so far:

```<code><android.support.design.widget.TextInputLayout
            android:id="@+id/textContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            app:counterEnabled="true"
            app:counterMaxLength="100">

            <EditText
                android:id="@+id/myEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="top|left"
                android:inputType="textMultiLine|textCapSentences"
                android:maxLength="100"
                android:scrollbars="vertical"
                android:hint="This is my cool hint"/>

        </android.support.design.widget.TextInputLayout>
</code>```

答:
If someone have problems like me:

The label make the text padding show wrong then do this:

```<code><com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:paddingTop="@dimen/default_padding"
                    android:paddingBottom="@dimen/default_padding"
                    android:layout_height="wrap_content"
                    android:hint="@string/search_hint" />
</code>```

Add padding top and padding bottom to the TextInputEditText that will fix the problem

ContentLicense: CC BY-SA 3.0

Body:
This may seem counter-intuitive but is there a way to disable or remove the floating label hint in TextInputLayout? The reason I want to use TextInputLayout instead of just an EditText is for the counter that TextInputLayout provides.

Here is what I have so far:

<android.support.design.widget.TextInputLayout
            android:id="@+id/textContainer"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scrollbars="vertical"
            app:counterEnabled="true"
            app:counterMaxLength="100">

            <EditText
                android:id="@+id/myEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="top|left"
                android:inputType="textMultiLine|textCapSentences"
                android:maxLength="100"
                android:scrollbars="vertical"
                android:hint="This is my cool hint"/>

        </android.support.design.widget.TextInputLayout>

Body:
If someone have problems like me:

The label make the text padding show wrong then do this:

<com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:paddingTop="@dimen/default_padding"
                    android:paddingBottom="@dimen/default_padding"
                    android:layout_height="wrap_content"
                    android:hint="@string/search_hint" />

Add padding top and padding bottom to the TextInputEditText that will fix the problem


问:
How can I group the number of values into columns based on month in sql
I have a data set like

```<code>Code Date
123  21-Jan-2000
234  23-Feb-1999
123  19-Jan-2001
</code>```

and I would like to query the table to display the data like this:

```<code>Code Total (All months) Jan Feb ... Dec
123    2                 1   1
234    1                 0   1
</code>```

I really have no idea how to start this. Any hints or help is greatly appreciated.

答:
You want to use PIVOT. From the official documentation:

```<code>select * from (
   select times_purchased, state_code
   from customers t
)
pivot
(
   count(state_code)
   for state_code in ('NY','CT','NJ','FL','MO')
)
order by times_purchased
</code>```

So in your case, the following query:

```<code>select * from (
    select code, datepart(month, date) as month
      from #data
) as data
pivot
(
    count(code)
     for month in ('1','2','3','4','5','6','7','8','9','10','11','12')
)
</code>```

Body:
I have a data set like

Code Date
123  21-Jan-2000
234  23-Feb-1999
123  19-Jan-2001

and I would like to query the table to display the data like this:

Code Total (All months) Jan Feb ... Dec
123    2                 1   1
234    1                 0   1

I really have no idea how to start this. Any hints or help is greatly appreciated.

Body:
You want to use PIVOT. From the official documentation:

select * from (
   select times_purchased, state_code
   from customers t
)
pivot
(
   count(state_code)
   for state_code in ('NY','CT','NJ','FL','MO')
)
order by times_purchased

So in your case, the following query:

select * from (
    select code, datepart(month, date) as month
      from #data
) as data
pivot
(
    count(code)
     for month in ('1','2','3','4','5','6','7','8','9','10','11','12')
)


问:
How to persist enum const in ormlite as a interface type?
I have one enum, which implements an interface. The purpose of this interface is only to create a bound between multiples enums, so that I can later implements a plugin system. (This post may clear the thing a little bit.)

My library enum lloks like this :

public interface Resource extends Displayable<Resource> {

    // all the methods that implements my enum
    // Displayable is just an interface that I need in my game
    // Just doesn't consider it, it can't interfer
}
```

<p>And an exemple of an enum that implements this interface :</p>

<pre class="lang-java prettyprint-override"><code>public enum LibraryEnum implements Resource {
    // static final fields

    // fields and resources

    // all implemented methods
}
</code>```

The thing is that I want to store this as an interface, to enable a sort of enum inheritance, because I'm about to create a plugin system. Any dev would just have to implements this unique interface to add resources in the game. But I don't know how he (or she) would name it (there might be some doubles).

I have a class with the associated field, as shown here :

@DatabaseTable(tableName = "packs")
public class Pack implements Displayable<Pack> {

    @DatabaseField(columnName = "id", generatedId = true)
    private Long packId;

    // Here it is
    @DatabaseField
    private Resource resource;
    // Is there any annotation arguments to add ?

    @DatabaseField
    private int quantity;

    // Some other fiels
    // Then constructors and methods
}
```

I've read the docs a little bit, and it say to create a custom implementation of the DataPersister interface. So I began to do it, but there is so many methods to implement (20?), that I don't know where to began and where to end. Maybe it's the wrong way to do it?
The docs shows an exemple where are the methods aren't even there, and for the type that already exists in java (Date & DateTime).

How can I achieve this? Or is this even possible? If not, is there anyway to do what I want anyway (store unknown const enum fields in the database)?

答:
I've read the docs a little bit, and it say to create a custom implementation of the DataPersister interface. So I began to do it, but there is so many methods to implement (20?), that I don't know where to began and where to end.

First off you should consider RTFM on custom persisters.  I've spent a good bit of time on the ORMLite docs.

The right thing to do is to extend a currently implemented persister from ORMLite.  For example, you could extend the BaseEnumType if you are persisting an enum.  If none of the persisters work then you should extend the generic BaseDataType.

With BaseDataType, all you need to implement is:

```<code>public Object parseDefaultString(FieldType fieldType, String defaultStr);

public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos);
</code>```

Although not required, you probably also want to override:

```<code>public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos)
</code>```

Typically you'd want to override a couple other methods to tweak the behavior of your custom persister.

Body:
I have one enum, which implements an interface. The purpose of this interface is only to create a bound between multiples enums, so that I can later implements a plugin system. (This post may clear the thing a little bit.)

My library enum lloks like this :

public interface Resource extends Displayable<Resource> {

    // all the methods that implements my enum
    // Displayable is just an interface that I need in my game
    // Just doesn't consider it, it can't interfer
}

And an exemple of an enum that implements this interface :

public enum LibraryEnum implements Resource {
    // static final fields

    // fields and resources

    // all implemented methods
}

The thing is that I want to store this as an interface, to enable a sort of enum inheritance, because I'm about to create a plugin system. Any dev would just have to implements this unique interface to add resources in the game. But I don't know how he (or she) would name it (there might be some doubles).

I have a class with the associated field, as shown here :

@DatabaseTable(tableName = "packs")
public class Pack implements Displayable<Pack> {

    @DatabaseField(columnName = "id", generatedId = true)
    private Long packId;

    // Here it is
    @DatabaseField
    private Resource resource;
    // Is there any annotation arguments to add ?

    @DatabaseField
    private int quantity;

    // Some other fiels
    // Then constructors and methods
}

I've read the docs a little bit, and it say to create a custom implementation of the DataPersister interface. So I began to do it, but there is so many methods to implement (20?), that I don't know where to began and where to end. Maybe it's the wrong way to do it?
The docs shows an exemple where are the methods aren't even there, and for the type that already exists in java (Date & DateTime).

How can I achieve this? Or is this even possible? If not, is there anyway to do what I want anyway (store unknown const enum fields in the database)?

Body:
I've read the docs a little bit, and it say to create a custom implementation of the DataPersister interface. So I began to do it, but there is so many methods to implement (20?), that I don't know where to began and where to end.

First off you should consider RTFM on custom persisters.  I've spent a good bit of time on the ORMLite docs.

The right thing to do is to extend a currently implemented persister from ORMLite.  For example, you could extend the BaseEnumType if you are persisting an enum.  If none of the persisters work then you should extend the generic BaseDataType.

With BaseDataType, all you need to implement is:

public Object parseDefaultString(FieldType fieldType, String defaultStr);

public Object resultToSqlArg(FieldType fieldType, DatabaseResults results, int columnPos);

Although not required, you probably also want to override:

public Object sqlArgToJava(FieldType fieldType, Object sqlArg, int columnPos)

Typically you'd want to override a couple other methods to tweak the behavior of your custom persister.


问:
Change appended td by condition inside loop
I am appending rows and columns to a table using javascript. But I need one of the classname inside the td to somethings else based on the condition inside a `$.post() response.

I did this:

```<code>let arr = ['Hermione', 'Ron', 'Harry']

arr.forEach(d=>{
    $('#the_table>tbody').append(`
                <tr id='tr_${d}'>
                    <td'>${d}</td>
                    <td><i id='change' class='no'></i></td>
                </tr>
            `);
});

const myfunc = () => {
$.post(api, json_object,
    function(data, status) {
        if (data.value === 'started') {
        setTimeout(myfunc, 5000);
    } else {
        $('#change').removeClass('no').addClass('yes');
        }
}, 'json');
            }
myfunc();
</code>```

When I do this, it is only changing the value for the first value (Hermione). But in the console.log, I can see that the data.value is not started so it should've changed to yes.

Hoe can I change it to yes for each of the rows once the condition has been passed

答:
Can you provide JSfiddle or any online code setup to debug more? I could see there is first  element is having a single quote that is not being ignored.
${d} should be like this ${d}

Thanks

Body:
I am appending rows and columns to a table using javascript. But I need one of the classname inside the td to somethings else based on the condition inside a `$.post() response.

I did this:

let arr = ['Hermione', 'Ron', 'Harry']

arr.forEach(d=>{
    $('#the_table>tbody').append(`

                    ${d}

            `);
});

const myfunc = () => {
$.post(api, json_object,
    function(data, status) {
        if (data.value === 'started') {
        setTimeout(myfunc, 5000);
    } else {
        $('#change').removeClass('no').addClass('yes');
        }
}, 'json');
            }
myfunc();

When I do this, it is only changing the value for the first value (Hermione). But in the console.log, I can see that the data.value is not started so it should've changed to yes.

Hoe can I change it to yes for each of the rows once the condition has been passed


问:
Pipeline Level Access Control for Service Connection in Azure DevOps - Classic Editor Pipelines
I have a SSH service connection created in Azure DevOps. My account has  enabled 'New service connections experience' preview feature and able to see new security features for service connections. It appears that we can enable security so that certain YAML pipeline(s) are able to use service connection.However, I do not see similar feature for Classic Editor pipeline.Can I get some suggestions on how I can achieve something similar for Classic Editor?

Example : Below details are under same ADO organization and project with same level of user(user/admin/reader) level access

Service Connection name : test-ssh-connection
Classic Editor Pipelines Created:
1) pipeline1 - this can use service connection
2) pipeline2 - we want to restrict service connection so that this pipeline is not able to use service connection.

答:
It appears that we can enable security so that certain YAML
pipeline(s) are able to use service connection.However, I do not see
similar feature for Classic Editor pipeline.Can I get some suggestions
on how I can achieve something similar for Classic Editor?

Sorry but a similar experience for Classic pipeline is not supported for now. Just as the document states, pipeline permissions are only for Yaml pipelines while user permissions are for Classic pipelines.

For Classic pipelines, if the account someone uses to sign in Web portal doesn't have the user permission, then the pipeline created by him can't access the service connection:

Though what you want is not supported, I agree with you that it would be better if the pipeline permissions feature can support Classic pipelines. So my suggestion is to add your request for this feature on our UserVoice site. Thank you for helping us build a better Azure DevOps!


问:
Vue JS "PROP MUTATING" for Upload Image
first sorry for my bad English.

I have one component, this component only working for upload image.

I'm running this component to 2 form. First add form, second edit form. Edit modal open and send to props Image URL.

This..

```<code><ua-single-upload :propsImage="editSingleImage" @uploadImage="addSingleImage = $event"></ua-single-upload>
</code>```

This is so good working. Image:

If I'm reload new photo, working and console give this error: "[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "propsImage""

AND...

This component not working with ADD FORM. I select image, not showing not uploading...
Please help me friends..

I want to be able to add a new image and update the existing one with a component.

This is my Component Codes...

```<code><template>
   <div class="singleImageUpdate p-4">
      <div class="p-4">
         <h4>Kapak Fotoğrafı Seçiniz</h4>
      </div>
      <div class="p-4">
         <input
            type="file"
            name="fileUrl"
            id="file"
            ref="fileInput"
            @change="onFileChange" />

          <label for="file">Yeni Fotoğraf Ekle</label>

          <button
            class="ml-4"
            type="button"
            v-if="this.propsImage != null"
            @click="onFileDelete"> Fotoğrafı Kaldır </button>

          <button
           class="ml-4"
           type="button"
           v-else
           disabled
           @click="onFileDelete"> Fotoğrafı Kaldır </button>
        </div>

        <div class="p-4 mt-4">
          <small v-if="this.propsImage">
              Fotoğraf kırpılmamaktadır, görüntü temsilidir.
          </small>
          <img
             class="mt-4 shadow-lg"
             v-if="this.propsImage"
             :src="propsImage" />
        </div>
      </div>
</template>

<script>
  export default{
    data(){
      return{}
    },
    props: {
      propsImage: String
    },
    methods: {
          onFileChange(event) {
            const file = event.target.files[0];
            this.propsImage = URL.createObjectURL(file);
            this.$emit("updateSingleImage", 1);
            this.$emit("uploadImage",event.target.files[0]);
          },
          onFileDelete() {
            this.propsImage = "";
            const input = this.$refs.fileInput;
            input.type = "text";
            input.type = "file";
            this.$emit("updateSingleImage", 0);
            this.$emit("uploadImage", null);
          },
        }
      }
</code>```

答:
Id say the warning is pretty descriptive, you are mutating the property directly which is a bad practice, since the parent might change the prop value and will therefore overwrite it.

What you should do instead is perhaps:

Create a reactive property inside the data function and use the prop as an initial value:

```<code>props: {
  propsImage:string
},
data(){
  return {
    image: this.propsImage
  }
}
</code>```

or if you want to update image whenever propsImage changes:

```<code>watch: {
  propsImage(newValue){
    this.image = newValue
  }
}
</code>```

or If you want to update the prop in the parent component emit the event

```<code>computed: {
  image: {
    get(){
      return this.propsImage
    },
    set(newValue)
    {
      this.$emit('update:props-image',newValue)
    }
  }
}
</code>```

and change the property inside the template of the parent component to <my-component :props-image.sync="myValue" />

Also there is no this context bound to the vue instance in the template is there?

Title: Vue JS "PROP MUTATING" for Upload Image

Body:
first sorry for my bad English.

I have one component, this component only working for upload image.

I'm running this component to 2 form. First add form, second edit form. Edit modal open and send to props Image URL.

This..

<ua-single-upload :propsImage="editSingleImage" @uploadImage="addSingleImage = $event"></ua-single-upload>

This is so good working. Image:

If I'm reload new photo, working and console give this error: "[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "propsImage""

AND...

This component not working with ADD FORM. I select image, not showing not uploading...
Please help me friends..

I want to be able to add a new image and update the existing one with a component.

This is my Component Codes...

<template>

Kapak Fotoğrafı Seçiniz

         <input
            type="file"
            name="fileUrl"
            id="file"
            ref="fileInput"
            @change="onFileChange" />

          Yeni Fotoğraf Ekle

          <button
            class="ml-4"
            type="button"
            v-if="this.propsImage != null"
            @click="onFileDelete"> Fotoğrafı Kaldır </button>

          <button
           class="ml-4"
           type="button"
           v-else
           disabled
           @click="onFileDelete"> Fotoğrafı Kaldır </button>

              Fotoğraf kırpılmamaktadır, görüntü temsilidir.

</template>

Body:
Id say the warning is pretty descriptive, you are mutating the property directly which is a bad practice, since the parent might change the prop value and will therefore overwrite it.

What you should do instead is perhaps:

Create a reactive property inside the data function and use the prop as an initial value:

props: {
  propsImage:string
},
data(){
  return {
    image: this.propsImage
  }
}

or if you want to update image whenever propsImage changes:

watch: {
  propsImage(newValue){
    this.image = newValue
  }
}

or If you want to update the prop in the parent component emit the event

computed: {
  image: {
    get(){
      return this.propsImage
    },
    set(newValue)
    {
      this.$emit('update:props-image',newValue)
    }
  }
}

and change the property inside the template of the parent component to <my-component :props-image.sync="myValue" />

Also there is no this context bound to the vue instance in the template is there?


问:
How do I continue looping, even through an error? Python
I have two conditions in my story using the question that I made to ask the users.

The first condition is true and second condition is false. In the first condition, if it's true, I want the program to finish. In the second condition, if it's false, I want to loop back to the question that I asked.

I have the following code, but so far it will loop back if the first is true and the second is false.

Any ideas?

invalid = ValueError

def age():
  user_input = input("Enter your Age")
  try:
    val = int(user_input)
    print("Input is an integer number. Number = ", val)
  except ValueError:
    print("No.. input is not a number. It's a string")

while invalid:
  age()
```

答:
I'd make things easier and just use a boolean as your continuation flag, rather than the ValueError:

```<code>ask_again = True
def age():
  user_input = input("Enter your Age")
  try:
    val = int(user_input)
    print("Input is an integer number. Number = ", val)
    ask_again = False
  except ValueError:
    print("No.. input is not a number. It's a string")

while ask_again:
  age()
</code>```

Does that look like what you want? Happy Coding!

Body:
I'd make things easier and just use a boolean as your continuation flag, rather than the ValueError:

ask_again = True
def age():
  user_input = input("Enter your Age")
  try:
    val = int(user_input)
    print("Input is an integer number. Number = ", val)
    ask_again = False
  except ValueError:
    print("No.. input is not a number. It's a string")

while ask_again:
  age()

Does that look like what you want? Happy Coding!