text:
Q: Azure DSC Extension. HKLM:\SOFTWARE\Microsoft\PowerShell\3\DSC doesn't exist I'm trying to create an Azure RM Template with SQL Server 2016 AlwaysOn Avaiability Group by using this base template http://4c74356b41.com/post5775
The template I linked is too complex for me. I just need to create 2 VMs and 1 Storage Account and apply proper DSC to the VMs. I'm getting the following error while applying configuration sql-primary and configuration sql-secondary to the both VMs:
Cannot find path 'HKLM:\\SOFTWARE\\Microsoft\\PowerShell\\3\\DSC' because it does not exist.
A duplicate resource identifier '[xSQLServerLogin]sqlLogintestdomain\\testadmin' was found while processing the specification for node 'localhost'.
Change the name of this resource so that it is unique within the node specification.

This is the DSC configuration taken from the blog post and that I'm trying to apply:
configuration sql-primary {
    Param (
        # Get deployment details
        [Parameter(Mandatory)]
        [String]$deploymentPrefix,
        [Parameter(Mandatory)]
        [String]$DomainName,
        [String]$DomainNetbiosName = (Get-NetBIOSName -DomainName $DomainName),

        # Credentials
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]$Admincreds,
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]$SQLServiceCreds,
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]$WitnessAccount,

        # Listener Configuration
        [Parameter(Mandatory)]
        [String]$SqlAlwaysOnAvailabilityGroupListenerIp,

        # Minor things
        [String]$bacpacUri = "https://github.com/AvyanConsultingCorp/pci-paas-webapp-ase-sqldb-appgateway-keyvault-oms/raw/master/artifacts/ContosoPayments.bacpac",
        [UInt32]$DatabaseEnginePort = 1433,
        [UInt32]$DatabaseMirrorPort = 5022
    )

    Import-DscResource -ModuleName PSDesiredStateConfiguration, xPSDesiredStateConfiguration, xComputerManagement, xNetworking, xActiveDirectory, xFailOverCluster, xSQLServer, xDatabase, xSmbShare
    [System.Management.Automation.PSCredential]$DomainCreds = New-Object System.Management.Automation.PSCredential ("${DomainNetbiosName}\$($Admincreds.UserName)", $Admincreds.Password)
    [System.Management.Automation.PSCredential]$DomainFQDNCreds = New-Object System.Management.Automation.PSCredential ("${DomainName}\$($Admincreds.UserName)", $Admincreds.Password)
    [System.Management.Automation.PSCredential]$SQLCreds = New-Object System.Management.Automation.PSCredential ("${DomainNetbiosName}\$($SQLServiceCreds.UserName)", $SQLServiceCreds.Password)

    # Prepare for configuration
    Enable-CredSSPNTLM -DomainName $DomainName
    $features = @("Failover-Clustering", "RSAT-Clustering-Mgmt", "RSAT-Clustering-PowerShell", "RSAT-AD-PowerShell")
    $ports = @(59999, $DatabaseEnginePort, $DatabaseMirrorPort)
    WaitForSqlSetup

    Node localhost {
        LocalConfigurationManager {
            ConfigurationMode  = "ApplyOnly"
            RebootNodeIfNeeded = $true
        }

        User DisableLocalAdmin {
            Disabled = $true
            UserName = $Admincreds.UserName

            Ensure = "Present"
        }
        WindowsFeatureSet Prereqs {
            IncludeAllSubFeature = $true
            Name                 = $features

            Ensure               = "Present"
        }
        File SetupFolder {
            DestinationPath = "C:\setup"
            Type            = "Directory"

            Ensure          = "Present"
        }
        xSmbShare MySMBShare {
            Name       = "Setup"
            Path       = "C:\Setup"
            FullAccess = "Everyone"

            DependsOn  = "[File]SetupFolder"
            Ensure     = "Present"
        }
        xRemoteFile FileDownload {
            DestinationPath = "C:\setup\ContosoPayments.bacpac"
            MatchSource     = $true
            Uri             = $bacpacUri

            DependsOn       = "[File]SetupFolder"
        }
        foreach ($port in $ports) {
            xFirewall "rule-$port" {
                Access       = "Allow"
                Description  = "Inbound rule for SQL Server to allow $port TCP traffic."
                Direction    = "Inbound"
                DisplayGroup = "SQL Server"
                DisplayName  = "SQL Server $port (TCP-In)"
                Name         = "SQL-Server-$port-TCP-In"
                LocalPort    = $port -as [String]
                Protocol     = "TCP"
                State        = "Enabled"

                Ensure       = "Present"
            }
        }

        xWaitForADDomain DscForestWait {
            DomainName           = $DomainName
            DomainUserCredential = $DomainCreds
            RetryCount           = $RetryCount
            RetryIntervalSec     = $RetryIntervalSec

            DependsOn            = "[WindowsFeatureSet]Prereqs"
        }
        xComputer DomainJoin {
            Name       = $env:COMPUTERNAME
            DomainName = $DomainName
            Credential = $DomainCreds

            DependsOn  = "[xWaitForADDomain]DscForestWait"
        }

        xSQLServerServiceAccount "sqlServiceDomainAccount" {
            SQLServer       = $env:COMPUTERNAME
            SQLInstanceName = "MSSQLSERVER"
            ServiceType     = "DatabaseEngine"
            ServiceAccount  = $SQLCreds
            RestartService  = $true
        }
        Script setSpn {
            GetScript            = "@{Ensure = `"set spn for sql service`"}"
            TestScript           = { $false }
            SetScript            = ( {
                    Invoke-Expression "setspn -D MSSQLSvc/{0}.{1}:1433 {0}$"
                    Invoke-Expression "setspn -D MSSQLSvc/{0}.{1} {0}$"
                    Invoke-Expression "setspn -S MSSQLSvc/{0}.{1}:1433 {2}"
                    Invoke-Expression "setspn -S MSSQLSvc/{0}.{1} {2}"
                } -f $env:COMPUTERNAME, $DomainName, $SQLServiceCreds.UserName )

            PsDscRunAsCredential = $DomainCreds
        }
        xCluster FailoverCluster {
            DomainAdministratorCredential = $DomainCreds
            Name                          = "${deploymentPrefix}-sql-cls"
            StaticIPAddress               = "${SqlAlwaysOnAvailabilityGroupListenerIp}0"

            PsDscRunAsCredential          = $DomainCreds
        }
        Script CloudWitness {
            SetScript            = ( {
                    Set-ClusterQuorum -CloudWitness -AccountName "{0}" -AccessKey "{1}"
                } -f $WitnessAccount.UserName, $WitnessAccount.GetNetworkCredential().Password )
            TestScript           = "(Get-ClusterQuorum).QuorumResource.Name -eq `"Cloud Witness`""
            GetScript            = "@{Ensure = if ((Get-ClusterQuorum).QuorumResource.Name -eq `"Cloud Witness`") {`"Present`"} else {`"Absent`"}}"

            DependsOn            = "[xCluster]FailoverCluster"
            PsDscRunAsCredential = $DomainCreds
        }
        foreach ($user in @($DomainCreds.UserName, $SQLCreds.UserName, "NT SERVICE\ClusSvc")) {
            xSQLServerLogin "sqlLogin$user" {
                LoginType       = "WindowsUser"
                Name            = $user
                SQLInstanceName = "MSSQLSERVER"
                SQLServer       = $env:COMPUTERNAME

                Ensure          = "Present"
            }
        }
        xSQLServerRole sqlAdmins {
            MembersToInclude = @($DomainCreds.UserName, $SQLCreds.UserName)
            ServerRoleName   = "sysadmin"
            SQLInstanceName  = "MSSQLSERVER"
            SQLServer        = $env:COMPUTERNAME

            DependsOn        = "[xComputer]DomainJoin"
            Ensure           = "Present"
        }
        foreach ($user in @("NT AUTHORITY\SYSTEM", "NT SERVICE\ClusSvc")) {
            xSQLServerPermission "sqlPermission-$user" {
                InstanceName = "MSSQLSERVER"
                NodeName     = $env:COMPUTERNAME
                Permission   = @("AlterAnyAvailabilityGroup", "ViewServerState", "ConnectSQL")
                Principal    = $user

                Ensure       = "Present"
            }
        }

        xSQLServerMaxDop DegreeOfParallelism {
            DynamicAlloc    = $false
            MaxDop          = 1
            SQLServer       = $env:COMPUTERNAME
            SQLInstanceName = "MSSQLSERVER"

            Ensure          = "Present"
        }
        xSQLServerAlwaysOnService enableHadr {
            SQLServer       = $env:computername
            SQLInstanceName = "MSSQLSERVER"

            DependsOn       = "[xCluster]FailoverCluster"
            Ensure          = "Present"
        }
        xSQLServerEndpoint endpointHadr {
            EndPointName    = "${deploymentPrefix}-sql-endpoint"
            Port            = $DatabaseMirrorPort
            SQLInstanceName = "MSSQLSERVER"
            SQLServer       = $env:computername

            DependsOn       = "[xSQLServerAlwaysOnService]enableHadr"
            Ensure          = "Present"
        }
        xSQLServerEndpointPermission endpointPermission {
            InstanceName = "MSSQLSERVER"
            NodeName     = $env:computername
            Name         = "${deploymentPrefix}-sql-endpoint"
            Principal    = $SQLCreds.UserName
            Permission   = "CONNECT"

            DependsOn    = "[xSQLServerEndpoint]endpointHadr"
            Ensure       = "Present"
        }
        xSQLServerEndpointState endpointStart {
            InstanceName = "MSSQLSERVER"
            NodeName     = $env:computername
            Name         = "${deploymentPrefix}-sql-endpoint"
            State        = "Started"

            DependsOn    = "[xSQLServerEndpoint]endpointHadr"
        }

        xSQLServerAlwaysOnAvailabilityGroup AvailabilityGroup {
            AvailabilityMode     = "SynchronousCommit"
            Name                 = "${deploymentPrefix}-sql-ag"
            SQLServer            = $env:computername
            SQLInstanceName      = "MSSQLSERVER"

            DependsOn            = @("[xSQLServerEndpointState]endpointStart", "[xCluster]FailoverCluster", "[Script]setSpn")
            Ensure               = "Present"
            PsDscRunAsCredential = $SQLCreds
        }
        xSQLServerAvailabilityGroupListener AvailabilityGroupListener {
            AvailabilityGroup    = "${deploymentPrefix}-sql-ag"
            IpAddress            = "$SqlAlwaysOnAvailabilityGroupListenerIp/255.255.255.0"
            InstanceName         = "MSSQLSERVER"
            NodeName             = $env:COMPUTERNAME
            Name                 = "${deploymentPrefix}-sql-ag"
            Port                 = 59999

            DependsOn            = "[xSQLServerAlwaysOnAvailabilityGroup]AvailabilityGroup"
            Ensure               = "Present"
            PsDscRunAsCredential = $DomainCreds
        }

        xDatabase DeployBacPac {
            Credentials      = $DomainCreds
            BacPacPath       = "C:\setup\ContosoPayments.bacpac"
            DatabaseName     = "ContosoClinic"
            SqlServer        = $env:COMPUTERNAME
            SqlServerVersion = "2016-SP1"

            DependsOn        = @( "[xSQLServerAlwaysOnAvailabilityGroup]AvailabilityGroup", "[xRemoteFile]FileDownload" )
            Ensure           = "Present"
        }
        xSQLServerAlwaysOnAvailabilityGroupDatabaseMembership DatabaseToAlwaysOn {
            AvailabilityGroupName = "${deploymentPrefix}-sql-ag"
            BackupPath            = "\\${deploymentPrefix}-sql-0\setup\"
            DatabaseName          = "ContosoClinic"
            SQLServer             = $env:COMPUTERNAME
            SQLInstanceName       = "MSSQLSERVER"

            DependsOn             = @("[xDatabase]DeployBacPac", "[xSQLServerAlwaysOnAvailabilityGroup]AvailabilityGroup" )
            Ensure                = "Present"
            PsDscRunAsCredential  = $SQLCreds
        }
    }
}

configuration sql-secondary {
    Param (
        # Get deployment details
        [Parameter(Mandatory)]
        [String]$deploymentPrefix,
        [Parameter(Mandatory)]
        [String]$DomainName,
        [String]$DomainNetbiosName = (Get-NetBIOSName -DomainName $DomainName),

        # Credentials
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]$Admincreds,
        [Parameter(Mandatory)]
        [System.Management.Automation.PSCredential]$SQLServicecreds,

        # Minor things
        [string]$clusterIp,
        [UInt32]$DatabaseEnginePort = 1433,
        [UInt32]$DatabaseMirrorPort = 5022
    )

    Import-DscResource -ModuleName PSDesiredStateConfiguration, xComputerManagement, xNetworking, xActiveDirectory, xFailoverCluster, xSQLServer
    [System.Management.Automation.PSCredential]$DomainCreds = New-Object System.Management.Automation.PSCredential ("${DomainNetbiosName}\$($Admincreds.UserName)", $Admincreds.Password)
    [System.Management.Automation.PSCredential]$DomainFQDNCreds = New-Object System.Management.Automation.PSCredential ("${DomainName}\$($Admincreds.UserName)", $Admincreds.Password)
    [System.Management.Automation.PSCredential]$SQLCreds = New-Object System.Management.Automation.PSCredential ("${DomainNetbiosName}\$($SQLServicecreds.UserName)", $SQLServicecreds.Password)

    # Prepare for configuration
    $features = @("Failover-Clustering", "RSAT-Clustering-Mgmt", "RSAT-Clustering-PowerShell", "RSAT-AD-PowerShell")
    $ports = @(59999, $DatabaseEnginePort, $DatabaseMirrorPort)
    WaitForSqlSetup

    Node localhost {
        LocalConfigurationManager {
            ConfigurationMode  = "ApplyOnly"
            RebootNodeIfNeeded = $true
        }

        User DisableLocalAdmin {
            Disabled = $true
            UserName = $Admincreds.UserName

            Ensure = "Present"
        }
        WindowsFeatureSet Prereqs {
            Name                 = $features
            IncludeAllSubFeature = $true

            Ensure               = "Present"
        }
        foreach ($port in $ports) {
            xFirewall "rule-$port" {
                Access       = "Allow"
                Description  = "Inbound rule for SQL Server to allow $port TCP traffic."
                Direction    = "Inbound"
                DisplayName  = "SQL Server $port (TCP-In)"
                DisplayGroup = "SQL Server"
                Name         = "SQL-Server-$port-TCP-In"
                LocalPort    = $port -as [String]
                Protocol     = "TCP"
                State        = "Enabled"

                Ensure       = "Present"
            }
        }
        xWaitForADDomain DscForestWait {
            DomainName           = $DomainName
            DomainUserCredential = $DomainCreds
            RetryCount           = $RetryCount
            RetryIntervalSec     = $RetryIntervalSec

            DependsOn            = "[WindowsFeatureSet]Prereqs"
        }
        xComputer DomainJoin {
            Name       = $env:COMPUTERNAME
            DomainName = $DomainName
            Credential = $DomainCreds

            DependsOn  = "[xWaitForADDomain]DscForestWait"
        }

        xSQLServerServiceAccount "sqlServiceDomainAccount" {
            SQLServer       = $env:COMPUTERNAME
            SQLInstanceName = "MSSQLSERVER"
            ServiceType     = "DatabaseEngine"
            ServiceAccount  = $SQLCreds
            RestartService  = $true
        }
        Script setSpn {
            GetScript            = "@{Ensure = `"set spn for sql service`"}"
            TestScript           = { $false }
            SetScript            = ( {
                    Invoke-Expression "setspn -D MSSQLSvc/{0}.{1}:1433 {0}$"
                    Invoke-Expression "setspn -D MSSQLSvc/{0}.{1} {0}$"
                    Invoke-Expression "setspn -S MSSQLSvc/{0}.{1}:1433 {2}"
                    Invoke-Expression "setspn -S MSSQLSvc/{0}.{1} {2}"
                } -f $env:COMPUTERNAME, $DomainName, $SQLServiceCreds.UserName)

            PsDscRunAsCredential = $DomainCreds
        }
        foreach ($user in @($DomainCreds.UserName, $SQLCreds.UserName, "NT SERVICE\ClusSvc")) {
            xSQLServerLogin "sqlLogin$user" {
                Name            = $user
                LoginType       = "WindowsUser"
                SQLInstanceName = "MSSQLSERVER"
                SQLServer       = $env:COMPUTERNAME

                Ensure          = "Present"
            }
        }
        xSQLServerRole sqlAdmins {
            MembersToInclude = @($DomainCreds.UserName, $SQLCreds.UserName)
            ServerRoleName   = "sysadmin"
            SQLInstanceName  = "MSSQLSERVER"
            SQLServer        = $env:COMPUTERNAME

            DependsOn        = "[xComputer]DomainJoin"
            Ensure           = "Present"
        }
        foreach ($user in @("NT AUTHORITY\SYSTEM", "NT SERVICE\ClusSvc")) {
            xSQLServerPermission "sqlPermission-$user" {
                InstanceName = "MSSQLSERVER"
                NodeName     = $env:COMPUTERNAME
                Permission   = @("AlterAnyAvailabilityGroup", "ViewServerState", "ConnectSQL")
                Principal    = $user

                Ensure       = "Present"
            }
        }
        xSQLServerMaxDop DegreeOfParallelism {
            DynamicAlloc    = $false
            MaxDop          = 1
            SQLServer       = $env:COMPUTERNAME
            SQLInstanceName = "MSSQLSERVER"

            Ensure          = "Present"
        }

        xWaitForCluster waitForCluster {
            Name                 = "${deploymentPrefix}-sql-cls"
            RetryIntervalSec     = $RetryIntervalSec
            RetryCount           = $RetryCount

            PsDscRunAsCredential = $DomainCreds
        }
        script joinCluster {
            GetScript            = "@{Ensure = `"join node to cluster with script resource, as cluster resource doesn't work in Azure`"}"
            TestScript           = "( Get-ClusterNode -Cluster {0} | Select-Object -ExpandProperty Name ) -contains `"{1}`"" -f $clusterIp, $env:COMPUTERNAME
            SetScript            = "Add-ClusterNode -Name {0} -NoStorage -Cluster {1}" -f $env:COMPUTERNAME, $clusterIp

            DependsOn = "[xWaitForCluster]waitForCluster"
            PsDscRunAsCredential = $DomainCreds
        }

        xSQLServerAlwaysOnService enableHadr {
            SQLServer       = $env:computername
            SQLInstanceName = "MSSQLSERVER"

            DependsOn       = "[Script]joinCluster"
            Ensure          = "Present"
        }
        xSQLServerEndpoint endpointHadr {
            EndPointName    = "${deploymentPrefix}-sql-endpoint"
            Port            = $DatabaseMirrorPort
            SQLInstanceName = "MSSQLSERVER"
            SQLServer       = $env:computername

            DependsOn       = "[xSQLServerAlwaysOnService]enableHadr"
            Ensure          = "Present"
        }
        xSQLServerEndpointPermission endpointPermission {
            InstanceName = "MSSQLSERVER"
            NodeName     = $env:computername
            Name         = "${deploymentPrefix}-sql-endpoint"
            Principal    = $SQLCreds.UserName
            Permission   = "CONNECT"

            DependsOn    = "[xSQLServerEndpoint]endpointHadr"
            Ensure       = "Present"
        }
        xSQLServerEndpointState endpointStart {
            InstanceName = "MSSQLSERVER"
            NodeName     = $env:computername
            Name         = "${deploymentPrefix}-sql-endpoint"
            State        = "Started"

            DependsOn    = "[xSQLServerEndpoint]endpointHadr"
        }

        xWaitForAvailabilityGroup waitforAG {
            Name                 = "${deploymentPrefix}-sql-ag"
            RetryIntervalSec     = $RetryIntervalSec
            RetryCount           = $RetryCount

            DependsOn            = @("[xSQLServerEndpointState]endpointStart", "[Script]joinCluster", "[Script]setSpn")
            PsDscRunAsCredential = $DomainCreds
        }
        xSQLServerAlwaysOnAvailabilityGroupReplica AddReplica {
            AvailabilityGroupName         = "${deploymentPrefix}-sql-ag"
            AvailabilityMode              = "SynchronousCommit"
            Name                          = $env:COMPUTERNAME
            PrimaryReplicaSQLServer       = "${deploymentPrefix}-sql-0"
            PrimaryReplicaSQLInstanceName = "MSSQLSERVER"
            SQLInstanceName               = "MSSQLSERVER"
            SQLServer                     = $env:COMPUTERNAME

            DependsOn                     = "[xWaitForAvailabilityGroup]waitforAG"
            Ensure                        = "Present"
            PsDscRunAsCredential          = $SQLCreds
        }
    }
}

function WaitForSqlSetup {
    while ($true) {
        try {
            Get-ScheduledTaskInfo "\ConfigureSqlImageTasks\RunConfigureImage" -ErrorAction Stop
            Start-Sleep -Seconds 5
        }
        catch {
            break
        }
    }
}

function Get-NetBIOSName {
    [OutputType([string])]
    param(
        [string]$DomainName
    )

    if ($DomainName.Contains(".")) {
        $length = $DomainName.IndexOf(".")
        if ( $length -ge 16) {
            $length = 15
        }
        return $DomainName.Substring(0, $length)
    }
    else {
        if ($DomainName.Length -gt 15) {
            return $DomainName.Substring(0, 15)
        }
        else {
            return $DomainName
        }
    }
}

function Enable-CredSSPNTLM {
    param(
        [Parameter(Mandatory = $true)]
        [string]$DomainName
    )

    # This is needed for the case where NTLM authentication is used

    Write-Verbose "STARTED:Setting up CredSSP for NTLM"

    Enable-WSManCredSSP -Role client -DelegateComputer localhost, *.$DomainName -Force -ErrorAction SilentlyContinue
    Enable-WSManCredSSP -Role server -Force -ErrorAction SilentlyContinue

    if (-not (Test-Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation -ErrorAction SilentlyContinue)) {
        New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows -Name "\CredentialsDelegation" -ErrorAction SilentlyContinue
    }

    if ( -not (Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation -Name "AllowFreshCredentialsWhenNTLMOnly" -ErrorAction SilentlyContinue)) {
        New-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation -Name "AllowFreshCredentialsWhenNTLMOnly" -value "1" -PropertyType dword -ErrorAction SilentlyContinue
    }

    if (-not (Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation -Name "ConcatenateDefaults_AllowFreshNTLMOnly" -ErrorAction SilentlyContinue)) {
        New-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation -Name "ConcatenateDefaults_AllowFreshNTLMOnly" -value "1" -PropertyType dword -ErrorAction SilentlyContinue
    }

    if (-not (Test-Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -ErrorAction SilentlyContinue)) {
        New-Item -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation -Name "AllowFreshCredentialsWhenNTLMOnly" -ErrorAction SilentlyContinue
    }

    if (-not (Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -Name "1" -ErrorAction SilentlyContinue)) {
        New-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -Name "1" -value "wsman/$env:COMPUTERNAME" -PropertyType string -ErrorAction SilentlyContinue
    }

    if (-not (Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -Name "2" -ErrorAction SilentlyContinue)) {
        New-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -Name "2" -value "wsman/localhost" -PropertyType string -ErrorAction SilentlyContinue
    }

    if (-not (Get-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -Name "3" -ErrorAction SilentlyContinue)) {
        New-ItemProperty HKLM:\SOFTWARE\Policies\Microsoft\Windows\CredentialsDelegation\AllowFreshCredentialsWhenNTLMOnly -Name "3" -value "wsman/*.$DomainName" -PropertyType string -ErrorAction SilentlyContinue
    }

    Write-Verbose "DONE:Setting up CredSSP for NTLM"
}

[Int]$RetryCount = 100
[Int]$RetryIntervalSec = 15

# $cd = @{
#     AllNodes = @(
#         @{
#             NodeName                    = "localhost"
#             PSDscAllowDomainUser        = $true
#             PSDscAllowPlainTextPassword = $true
#         }
#     )
# }

And this is the exact ARM Template I'm deploying
https://pastebin.com/d52BpEFM

A: Just to sum up a bunch of points here:

*

*domain and sql accounts should be different

*sql cluster ip address should be in one of the cluster networks

*you need to precreate the dns name record for the load balancer (due to how i'm doing everything in parallel i've decided to put that functionallity into the domain provisioning dsc configurations)

*to check deployment you can use always on dashboard

Cannot find path 'HKLM:\SOFTWARE\Microsoft\PowerShell\3\DSC'
because it does not exist.

Seems to be a general error being thrown when something goes wrong (at least I could never find a pattern why it appeared), so its safe to disregard that error, it will be gone when you fix the real error (in my experience).
SQL provisioning fails (sometimes) with weird errors (usually dns\timing related). I'm not sure how this would behave in an environment where domain is precreated in advance. it might be less fragile overall. In my latest commit (at the time of writing) I believe I've addressed some of the stability issues, and I'm quite sure with domain, storage for backups, keyvault precreated those issues shouldn't be present at all.


text:
Q: Fortify Source Analyzer and Apache Lenya I am trying to use Fortify Source Code Analyzer for a research project at my school to test the security for open source Java web applications. I am currently working on Apache Lenya. I am working with the last stable release (Lenya v2.0.2).
Inside the root directory there is a file named build.sh. This file is called to build Lenya using the version of Ant that ships with the release (in the tools/bin folder). I can build Lenya just fine when I run ./build.sh. So, it would be assumed that running the following command in Fortify would work :
sourceanalyzer -b lenya -Xmx1200M touchless ./build.sh

However, when I try and run:
sourceanayzer -b lenya -Xmx1200M -scan -f lenya.fpr

I get:

build id Lenya not found.

I looked at the buid.sh file and noticed that it was just resetting the current ant home, classpath, and ant options variables, running the ant build command, and resetting the values back to their defaults. So I reset all of the variables manually (without the script) instead of running the script and ran:
sourceanalyzer -b lenya -Xmx1200M touchless tools/bin/ant -logger org.apache.tools.ant.NoBannerLogger

Then I ran :
sourceanalyzer -b lenya -Xmx1200M -scan -f lenya.fpr

but I got the same error. I'm not sure if this is because I am doing something wrong or if it is something that Fortify is not doing correctly. Any insight will be great.

A: I'm not sure whether you have access to the Fortify documentation, but that will definitely help. You should refer to the SCA User's Guide to understand how to use the sourceanalyzer executable.
To cut things short, there are two ways of getting the FPR file:

*

*(The long way) Write a script to translate and analyse the source code by providing the path of the source code and the classpath to the sourceanalyzer executable.

*(The short way) Use the SCACompiler instead of javac as the compiler. You'll need to modify the build script for this.

I prefer the former due to its customizability when handling large code bases.
PS: Which version of Fortify is this?

A: Don't use the touchless command, that is for C/C++ Integration. Since Lenya is written in Java, you're better off with other commands. Try this for your first translation step (run from your base lenya dir):
sourceanalyzer -b lenya -Xmx1200M -source 1.5 -cp "**/*.jar" "**/*"

A: The command you used actually could work with Java builds, except that it has some limitations.  Using the touchless build wrapper creates a number of compiler wrappers, e.g. for javac, and puts the wrappers at the front of the PATH environment variable.
If your build.sh script contains fully qualified references to javac, for example /usr/java/bin/javac, then the touchless build integration will not work.
user233276's instructions are the most broadly useful.  If you want to experiment with Fortify SCA build integration, I would suggest the technique would be to modify build.sh (see http://svn.apache.org/viewvc/lenya/trunk/build.sh?view=markup&pathrev=400414) and change line 43 from:
"$ANT_HOME/bin/ant" -logger org.apache.tools.ant.NoBannerLogger -emacs $@

to:
sourceanalyzer -b Lenya "$ANT_HOME/bin/ant" -logger org.apache.tools.ant.NoBannerLogger -emacs $@

See the Fortify SCA User Guide for the three types of ant integration:

*

*Override the build.compiler property:
ant -lib sourceanalyzer.jar {Fortify ant options} {ant options}

*Shortcut to the above:
sourceanalyzer -b {Fortify options} ant {ant options}

*Or, if you make a custom build.xml as shown in the appendix:
ant -lib sourceanalyzer.jar {ant options}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Publishing resource files of ASP.NET MVC application on Azure I'm working on a web application in C# with the ASP.NET MVC 5 framework. I publish my work on Azure and everything seems te work fine. Except when I Change something in one of my Resources Files (strings). I can see the changes locally, but not on Azure. Adding new strings works fine.
Any ideas?
Thanks in advance!

A: Looks like your publish settings aren't removing or updating the resource files.  Try this:
Clean Windows Azure Website


text:
Q: put dynamic value in $_POST I want to use a code like
foreach($_POST[cat_id] as $key=>$val){
                if($val){
                $arr[cat_id] = $val;
                $arr[porder] = $_POST['".$val."'];
                $arr[store_user_id] =$_SESSION[uid];
                }
            }

but $_POST['".$val."'] will not cover any value but in my loop put the name dynamically can any one help me I want to show value of $_POST['".$val."'] which comes dynamically. I also use $_POST['<?=$val?>'] but it does not work.. please help...

A: Just use $_POST[$val] in place of $_POST['".$val."']

A: have you tried this way:
$arr[cat_id] = $_POST[$val]

?


text:
Q: Minimal polynomial equals characteristic polynomial of nilpotent endomorphism
Let $F$ be a field, $A : V \to V$ a nilpotent endomorphism in a finite
dimensional vector space. Proof, that the Minimal Polynomial $m_A$
equals the characteristic polynomial $f_A$ if and only if for each
factorization $f_A (x) = p(x)q(x)$, $Im(p(A)) = Ker(q(A))$.

I am stuck with both directions. I know, that the minimal polynomial of A must be $x^k$ for a $k$, so each factorization must be $x^i \cdot x^{k-i}$. I would appreciate hints as well as a solution.

A: As you note, because $A$ is nilpotent, the characteristic polynomial is $f_A(x)=x^n$ with $n=\dim(V)$ (assuming your characteristic polynomials are monic; otherwise, it is $(-1)^nx^n$). THe minimal polynomial is $m_A(x) = x^k$, with $1\leq k\leq n$.
Express $f_A(x) = m_A(x)x^{n-k}$. Then $\mathrm{Im}(m_A(A))=\mathrm{ker}(A^{n-k})$. But $m_A(A)$ is the zero linear transformation, so the image is trivial. Thus, $\mathrm{ker}(A^{n-k})$ is trivial, so $A^{n-k}$ is one-to-one. This is impossible if $n-k\gt 0$ (since $A$, being nilpotent, has nontrivial kernel), thus $n-k=0$ and hence $m_A(x)=f_A(x)$.
Conversely, suppose that $m_A(x)=f_A(x)$. Let $\beta=\{v_1,ldots,v_n\}$ be a Jordan canonical basis for $A$; that is, $A(v_m) = v_{m-1}$ if $m=2,\ldots,n$, and $A(v_1)=\mathbf{0}$. Then it is easy to verify that $\mathrm{Im}(A^r) = \mathrm{span}(v_1,\ldots,v_{n-r})$, and $\mathrm{ker}(A^s) = \mathrm{span}(v_1,\ldots,v_s)$. Thus, if $f_A(x) = x^rx^{n-r}$, we have
$$\mathrm{Im}(A^r) = \mathrm{span}(v_1,\ldots,v_{n-r}) = \mathrm{ker}(A^{n-r}),$$
as required.

Related, this question characterizing the (finite dimensional) linear operators for which the minimal and characteristic polynomials agree.


text:
Q: Server side (or clientside??) solution to prevent multiple ajax requests across sessions? I had a quick question. I have a login on my site (using Auth0 + Firebase). The site is using Ember JS. When you login, you have a dashboard, and when you click on the "Display" button, it shows a live feed pulling from Twitter's API and Instagram's API using AJAX requests. However, if you open the same page on multiple screens with the same user, it makes double the ajax requests, or triple depending on the amount of screens it's on. Is there any way to make this server side? Have it make the requests once on the server and then just fetch it from there live?
Ideally, I would like for people to login across multiple computers, click their "display button", and be projected the same stream. I figure this would need to be server side, i'm just at a loss of where to even start. I essentially just want to prevent 15 simultaneous ajax requests across sessions, and just have them fetch the 1. Is this even possible?
Thanks for the help is advance!


text:
Q: Validate JSON Web Token in .NET Core without usage of try/catch I'm currently trying to validate a JWT in the manner that was suggested in the following answer
Here the code sample
try
{
 tokenHandler.ValidateToken(token, validationParameters, out validatedToken);
}
catch (Exception e)
{
 log(e.ToString()); //something else happened
 throw;
}

Is there a better way to achieve something like this without the try/catch clause? To me it seems to be quite the messy solution, especially when hooking this function up to a controller.
Thanks!

A: The wonderful thing about Net Core is that this is built in. You actually dont need to validate the tokens yourself. If the token is invalid, a response is automatically fired back to client for you. IF however, you do feel the need to dive in and manually validate - you can do this: https://www.jerriepelser.com/blog/manually-validating-rs256-jwt-dotnet/
Ok, so i've dug out some code from the bowels of one of my projects.. Basically it lets me hook into the events that occur when a token is validated and assign my own even handlers to various points.
I believe this is what you are looking for.
Add this code to your IServiceCollection registrations:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddCustomJwtBearer(options =>
        {
            options.TokenValidationParameters = tokenParams;
            options.Events = ConfigureJwtEvents(tokenConfiguration);
        });

And this code into a STATIC class somewhere so you can call it as an extension method:
public static void AddCustomJwtBearer(this AuthenticationBuilder builder, Action<JwtBearerOptions> options)
    {
        builder.Services.TryAddEnumerable(ServiceDescriptor.Singleton<IPostConfigureOptions<JwtBearerOptions>, JwtBearerPostConfigureOptions>());
        builder.AddScheme<JwtBearerOptions, JwtBearerHandler>("Bearer", null, options);
    }

/// <summary>
/// Returns a configured <see cref="JwtBearerEvents"/>
/// </summary>
/// <param name="tokenConfiguration">Token Configuration</param>
/// <returns><see cref="JwtBearerEvents"/></returns>
private static JwtBearerEvents ConfigureJwtEvents(TokenConfiguration tokenConfiguration)
{
    var bearerEvents = new JwtBearerEvents
    {
        OnAuthenticationFailed = context =>
        {
            if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
            {
                context.Response.Headers.Add("Token-Expired", "true");
            }

         return Task.CompletedTask;
        }
    };

    // Authentication Failed Method
    bearerEvents.OnAuthenticationFailed = [YOUR-EVENT-HANDLER]

    // Challenge Raised Event
    bearerEvents.OnChallenge = [YOUR-EVENT-HANDLER]

    // Message Received Event
    bearerEvents.OnMessageReceived = [YOUR-EVENT-HANDLER]

    // Token Validated Event
    bearerEvents.OnTokenValidated = [YOUR-EVENT-HANDLER]

    return bearerEvents;
}

Where it says: [YOUR-EVENT-HANDLER] .. You can add in your own event handler methods and they will fire if/when each of those events happens.


text:
Q: Measuring Diode "Pushback" Voltage I was recently learning about how a diode works, and I understand how a diode, in it's natural state, develops a sort of "pushback" voltage that pushes against any voltage that is applied, effectively lowering the energy of any electrons that pass (forward voltage). This part makes pretty good sense to me.
However, I fail to understand how to measure this "pushback voltage." Using a multi meter, I tried the setting which I use to measure the voltage out of a battery (200 mV setting), and I noticed that I got different values when testing my small LED's: 3.4 for the Red Led, nothing for the Blue Led, and 9.8 for the green LED. I'm not sure what's going on here. I expected the 3.4 Voltage drop to be normal, but the other LED's don't seem correct. And how can a multi meter even measure the forward voltage of a diode? As in, wouldn't any electrons that had the potential energy to cross against the induced electric field have already made the jump from the n-junction to the p-junction? Any ideas?

A: None of those values make sense.  Red is usually around 1.8V, green is a little over 2 V.
You can't measure the forward voltage of an LED with just a voltmeter.  You have to connect your LED to a current source and measure the voltage across the diode when current is flowing through it.
Many multimeters have a diode test function that does exactly what I've described - it pushes a low current through the diode and measures the voltage across it.

Whatever you were measuring, it wasn't the forward voltage of the LED.  On the 200mV scale, your numbers would be millivolts, not volts as you wrote.
I expect you were getting a tiny little bit of current from the light hitting the LED.  That could be enough for your meter to register a few millivolts.

A: If anyone else comes across this question and still has confusion after reading the chosen answer, check out this answer: https://physics.stackexchange.com/questions/108314/why-isnt-there-a-potential-difference-across-a-disconnected-diode


text:
Q: How to subclass custom JFX components with FXML correctly? I would like to subclass custom JFX components to change/extend their behavior. As a real world example, I would like to extend a data viewer component with editing functionality.
Consider the following very minimal scenario.
Using the class Super works perfectly.
But when instantiating the subclass Sub (in a FXML-file) the FXMLLoader does not inject the @FXML field label anymore.
Therefore calling initialize leads to a NullPointerException when accessing the field with value null. I suppose FXMLLoader somehow needs the information to also initialize the Super sub-object of Sub using Super.fxml.
Please note that the method initialize gets automatically called by FXMLLoader after injection.
I'm aware that nesting the super component inside the sub component should work fine, but I would still like to know if this is possible using inheritance.
Widening the visibility of label to protected did obviously not solve this problem. Defining an extension point in fx:root in combination with @DefaultProperty (this solution has been proposed here) has worked neither.
I appreciate any help.
fxml/Super.fxml
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.*?>

<fx:root xmlns:fx="http://javafx.com/fxml/1" type="HBox">
    <Label fx:id="label"/>
</fx:root>

Super.java
import java.io.IOException;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;

public class Super extends HBox {

    @FXML
    protected Label label;

    public Super() {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/" + getClass().getSimpleName() + ".fxml"));
        fxmlLoader.setRoot(this);
        fxmlLoader.setController(this);

        try {
            fxmlLoader.load();
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }

    public void initialize() {
        label.setText("Super");
    }
}

fxml/Sub.fxml
<?import test.Super?>

<fx:root xmlns:fx="http://javafx.com/fxml/1" type="Super"></fx:root>

Sub.java
public class Sub extends Super {
    public Sub() {
        super();
    }
}

UPDATE
Like in this question the way to go seems to be to call the FXMLLoader for each level of inheritance (which has a FXML-file attached). The problem comes down to injecting @FXML-annotated fields being connected to calling initialize afterwards. Meaning, if we want the fields to become injected, initialize gets called afterwards for each single load. But when initialize gets overridden by each subclass the most specific implementation gets called n times (where n is the number of inheritance levels).
Something like
public void initialize() {
    if (getClass() == THISCLASS) {
        realInitialize();
    }
}

would [Update]not[/Update] solve this problem, but appears like a hack to me.
Consider this demo code by @mrak, which shows the loading on each inheritance level. When we implement initialize methods in both levels the problem described above occurs.

Here a more complete minimal working example based on mraks code.
Super.java
package test;

import java.io.IOException;
import java.net.URL;

import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;

public class Super extends HBox {

    @FXML
    private Label label;

    public Super() {
        super();
        loadFxml(Super.class.getResource("/fxml/Super.fxml"), this, Super.class);
    }

    public void initialize() {
        label.setText("initialized");
    }

    protected static void loadFxml(URL fxmlFile, Object rootController, Class<?> clazz) {
        FXMLLoader loader = new FXMLLoader(fxmlFile);
        if (clazz == rootController.getClass()) { // PROBLEM
            loader.setController(rootController);
        }
        loader.setRoot(rootController);
        try {
            loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Sub.java
package test;

import javafx.fxml.FXML;
import javafx.scene.control.Button;

public class Sub extends Super {

    @FXML
    private Button button;

    public Sub() {
        super();
        loadFxml(Sub.class.getResource("/fxml/Sub.fxml"), this, Sub.class);
    }

    @Override
    public void initialize() {
        super.initialize();
        button.setText("initialized");
    }

}

Super.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.HBox?>
<?import javafx.scene.control.*?>

<fx:root xmlns:fx="http://javafx.com/fxml/1" type="HBox">
    <Label fx:id="label" text="not initialized"/>
</fx:root>

Sub.fxml
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.*?>
<?import test.Super?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.Button?>

<fx:root xmlns:fx="http://javafx.com/fxml/1" type="Super">
    <Button fx:id="button" text="not initialized"/>
</fx:root>

See the commented line in Super.loadFxml. Using this condition leads to the injection of only the @FXML entries in the leaf. But initialize gets called only once. Not using this condition leads to (theoretically) the injection of all @FXML entries. But initialize takes place after every load, hence NullPointerExceptions occur on each non-leaf initialization.
The problem can be fixed when not using initialize at all and calling some init function myself. But again, this appears very hacky to me.

A: It doesn't look like you are defining a label in Sub.xml, which could be why nothing is being injected into the label field. Try updating Sub.xml to contain the following:
<?import Super?>

<fx:root xmlns:fx="http://javafx.com/fxml/1" type="Super">
    <Label fx:id="label"/>
</fx:root>

Does that work?
The problem is that the call to getClass() in Super returns Sub.class when you are instantiating a Sub. So it loads Sub.xml, which I guess is not what you want (it seems like you're trying to load both Super.xml and Sub.xml). You might be able to do that by explicitly loading Super.xml in the Super constructor AND explicitly loading Sub.xml in the Sub constructor.

A: I think I see the problem. If you don't call setController() in Super(), there is no place to inject label, so the field remains null. If you do call setController() in super, then Sub's implementation of initialize() is called twice - once by the call to load() in Super() and again by the call to load() in Sub.
In theory, this should work as long as you guard against NPEs in Sub. If Sub#initialize() is called and button is still null, you know that you're being initialized for Super and you should delegate to super.initialize(). When button is non-null, you wouldn't call super.

A: I know this post is a bit old but I ran into the same problem and finally found a solution for correctly initializing parents/children when inheriting and having injections and properties in both child and parent. Here is the simple architecture that I am using:
public class Parent extends HBox {

    @FXML
    private Label labelThatIsInBothFXMLs;

    public Parent() {
        this(true);
    }

    protected Parent(boolean doLoadFxml) {
        if (doLoadFxml) {
            loadFxml(Parent.class.getResource(...));
        }
    }

    protected void loadFxml(URL fxmlFile) {
        FXMLLoader loader .... //Load the file
    }

    @Initialize
    protected void initialize() {
        // Do parent initialization.
        labelThatIsInBothFXMLs.setText("Works!");
    }

}

public class Child extends Parent {

    @FXML
    private Label labelOnlyInChildFXML;

    public Child() {
        super(false);
        loadFxml(Child.class.getResource(...));
    }

    @Override
    protected void initialize() {
        super.initialize();
        // Do child initialization.
        labelOnlyInChildFXML.setText("Works here too!");
    }
}

The important part to notice is that the lowest level child is the one that calls the fxml load. This is so that all levels of constructors are ran before the fxml load starts injecting data using reflection. If a parent loads the fxml the child have yet to create the class properties causing the reflection injection to fail. This is true for properties set in the FXML as well.

A: There is a simple way for Flipbed's answer
public class Super extends HBox {

@FXML
private Label label;

public Super() {
    super();
    if(getClass() == Super.class)
        loadFxml(Super.class.getResource("/fxml/Super.fxml"), this, Super.class);
}

Thats all you need


text:
Q: composer and amazon php sdk I am trying to follow the instructions here on downloading the amazon-php-sdk. In the last step it says To use it, just add the following line to your code's bootstrap process.
require '/path/to/sdk/vendor/autoload.php';

What is my code's bootstrap process in this case?

A: Well, once you have added dependencies to composer.json and update/install the vendors, you are ready to use them.
Because, Symfony2 bootstrap uses composer autoload already.

To ensure optimal flexibility and code reuse, Symfony2 applications
  leverage a variety of classes and 3rd party components. But loading
  all of these classes from separate files on each request can result in
  some overhead. To reduce this overhead, the Symfony2 Standard Edition
  provides a script to generate a so-called bootstrap file, consisting
  of multiple classes definitions in a single file. By including this
  file (which contains a copy of many of the core classes), Symfony no
  longer needs to include any of the source files containing those
  classes. This will reduce disc IO quite a bit.

FYI: use-bootstrap-files


text:
Q: Loopback 4 controller Omit
I'm giving my first steps in Loopback 4, and I've been trying to follow the tutorial that they have to generate a new REST Api.
The thing is that after creating my model, database and repository, I started to develop my controller class and encountered a piece of code that nowhere in the documentation we have a mention to it.
I have it signaled below:
async createTodo(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(Todo, {title: 'NewTodo', exclude: ['id']}),
        },
      },
    })
 todo: **Omit<Todo, 'id'>,** <----------
  ): Promise<Todo> {
    ...
    return this.todoRepository.create(todo);
  }

My question is: For what this omit is for? I've tried to remove it from the code, and the result is the same as the one that I have without it.
Also, in that post request, I'd like to hide the id property from the object, when I receive the answer. How can I do that just for this request' response?
Thanks in advance!

A: This is more Typescript thing than Loopback.
Loopback uses Typescript so you usually define types and interfaces. For controller request body, you need to define interface.

Omit<T,K>
Constructs a type by picking all properties from T and then removing K.

Here, I assume you have set id property to auto generate or generate by yourself. And id property is not a user input. Your front-end does not send id value. Then You need to create an interface with all properties of TodoModel except id. Now you can create new record with the received object.
You can read more on Typescript utilities here
In addition, Loopaback4 uses DataObject<Model> to convert model into interface.


text:
Q: Comparing two DataFrames for partial row equality and output equal rows into a new DataFrame? I have two existing DataFrames which I have named death and air:
County,Death Rate
Autauga,859
Baldwin,976

County,AQI
Baldwin,51
Clay,45

These datasets were taken from different sources and are of different lengths, the same counties do not appear in each DataFrame.
When values for County match I need to create a third DataFrame with only columns AQI and Death Rate.
Here is what I started with (death is the larger df):
import pandas as pd

death = pd.read_csv('SimpleDeath1.csv')
air = pd.read_csv('simpleAir.csv')

data = pd.DataFrame(columns= ['AQI', 'Death Rate'], index=None)

for i in range (0, death.size):
    if death['County'] == air['County']:
        data.append({'AQI' : air['AQI'], 'Death Rate' : death['Death Rate']})

This outputs the following error:
ValueError: Can only compare identically-labeled Series objects

Which has been extensively asked about and discussed on SO. There are actually 382 questions returned when searching SO for this specific error, and while I haven't yet read them all, I have read enough to doubt the efficiency of my initial approach to this problem.
Some highlights from what I've read thus far.
Can anyone with fresh eyes help me to understand a better way of approaching this problem?
Some things I have tried:

*

*Changing comparison:
if death['County'].equals(air['County')]:
Doesn't throw an error, but my new DataFrame is empty

*Converting DataFrame values to strings:
if death['County'].str() == air['County'].str()):
data.append({'AQI' : air['AQI'], 'Death Rate' : death['Death Rate']})
Throws:
TypeError: 'StringMethods' object is not callable

Any help using DataFrames or another strategy would be greatly appreciated!

A: In this case, you can use the merge function from pandas:
import pandas as pd

death = {'County': ['Autauga', 'Baldwin'], 'Death Rate': [859, 976]}
air = {'County': ['Baldwin', 'Clay'], 'AQI': [51, 45]}

death = pd.DataFrame(death)
air = pd.DataFrame(air)

merged = death.merge(air, how='inner', on='County')
merged

This yields:
County  Death Rate  AQI
0   Baldwin 976 51

on='County' defines the column that contains the keys used in the merging operation.
how='inner' tells the code to select only keys that are present in both data frames based on the column 'County' as defined above.
You can then use the drop function from pandas to remove the unwanted 'County' column afterwards.

A: import pandas as pd

death = pd.DataFrame({'County': ['county1', 'county2', 'county3'], 'Deaths': [1,2,3]})
County  Deaths
0   county1 1
1   county2 2
2   county3 3

air = pd.DataFrame({'County': ['county2', 'county3', 'county4'], 'AQI': [21,32,43]})
County  AQI
0   county2 21
1   county3 32
2   county4 43

merged = pd.merge(death, air)
County  Deaths  AQI
0   county2 2   21
1   county3 3   32


text:
Q: how to select a specific entry from a JSON object string: {"foo1":"1123","foo2":"332","foo3":"23-SEP-15"}

Hi Guys,
Im attempting to retrieve the value of foo3 from a string (so need the date part of the string). Ive tried parsing this with JSON but seems to throw up a lot of difficulties in my program if the date string is in the incorrect format (which is a possibility).
Was thinking it might be easier to put this into an array and then search the array for date matches?
Or would it be easier just to search the actual string itself for the date (or i guess any string after foo3: and enclosed in " ".
My regex is extremely poor so im really struggling to do this method myself. Any advice on which technique would be best would be really appreciated

A: To retrieve the value of foo3, you can just use JSON.Parse with a callback function that will only return the value of foo3 if it is present.
Here is a working snippet:

var text = '{"foo1":"1123","foo2":"332","foo3":"23-SEP-15"}';
JSON.parse(text, function(k,v){
  if (k === 'foo3') {
    document.write(v);
  }
  return v;
});

Here, in function(k,v), k stands for the key and v stands for the value.
You can find more working examples of how to parse JSON with JavaScript at the provided MDN link above.


text: Q: What does double colon [::] inside the third bracket mean? I have seen some programs in python has [::] in the code. But I can't understand why to use and when to use this. Could you please provide some description in a simple language? Thanks in advance.


text:
Q: Problems compiling arXiv LaTeX source files I use LaTeX to write papers. I'm using TeXworks/MiKTeX on a Windows XP computer. When I write the LaTeX code, I can compile it without any problems using "pdfLaTeX+MakeIndex+BibTeX".
But if I download LaTeX source code from arXiv and I try to compile it using "pdfLaTeX+MakeIndex+BibTeX" it won't work. I get the error "! Undefined control sequence".
However, I don't have any problems compiling LaTeX source code from arXiv if I use "pdfLaTeX" instead of "pdfLaTeX+MakeIndex+BibTeX".
Why is this happening? What's the difference between "pdfLaTeX+MakeIndex+BibTeX" and "pdfLaTeX"?
The reason why I ask these questions is that I'd like to make some minor changes to one of my arXiv papers, so I will download the LaTeX source code and make the changes there. I guess I'll have to use "pdfLaTeX" to compile the source code, but I want to make sure that no unwanted changes are made in the paper.
LaTeX source files downloaded from arXiv don't seem to have .tex extension. They seem to be of a different type (I guess this is due to arXiv processing), but anyway I can open them without any problems using TeXworks.

A: Try adding the .tex extension back on to the file.
I'm not sure why arXiv would remove it,
  but many editors will assume that it's there
  when running compile sequences.
To see what I mean, compare the compilation for pdfLaTeX and BibTeX:
$ pdflatex myfile.tex
$ bibtex myfile

Note that bibtex doesn't need the file extension
  since it also looks at the files generated by the LaTeX run.
Editors like TeXworks (and others, no doubt) will run these sequences for you automatically, but this requires that it knows where the extension is so that it can remove it.
When there is no extension to remove, ambiguities will arise:
$ pdflatex myfile
$ bibtex myfile

It's likely that one of these programs picked up on the 'wrong' myfile,
  causing the error that you saw.
(For example, take a look inside the aux file; running pdflatex directly on this file would certainly throw an error.)


text:
Q: Use Function Keys as Keyboard Shortcut I have a Macbook Pro 13" with Retina Display running OS X Mavericks 10.9.4
I use Code Editors like PHPStorm which Require me to use the Function Keys as Keyboard Shortcuts like Command+F6.
But F6 just increases my backlighting.
I want the function Keys to do this special stuff when used alone and behave as normal Function keys when I add something before it like Cmd.
For example :
F11 should decrease volume,
but Cmd+F11 should be a shortcut

A: I think you got two options:

*

*Enable function keys to work like normal keys and to activate their special functions – like increasing volume etc. – when pressing fn beforehand.

*

*Open System Preferences

*Select preference pane Keyboard

*Select Keyboard tab

*Activate option Use all F1, F2, etc, keys as standard function keys

Image taken from OSXDaily.com

*Set custom app shortcuts for your programs that need function keys in their shortcuts.

*

*Open System Preferences

*Select preference pane Keyboard

*Select Shortcuts tab

*Select group App Shortcuts

*Press + and add your needed shortcuts – those already existent in the editor. Just select the corresponding app, insert the shortcut name (name in the menu connected to the shortcut) and enter shortcut already set by the program.

Image taken from Geeksays.com


text:
Q: flush_rewrite_rules not working on plugin deactivation, invalid URLs not showing 404 i'm just about to release a community plug-in and have a few last anoying issues.
First, whenever i visit a page that would not be valid for the plugin, www.mydomain.com/forms/tester it will take me to a different page. What should happen, is the plugin code try and use the path 'tester', find there is no such file, and then return a page not found error.
Second, i am using AskApache RewriteRules viewer plugin to see my rules, and can see that even though i have deactivated my plug-in, rewrite rules remain 'index.php?formid=$matches[1]'. I cant understand as i am flushing rewrite rules on plugin deactivation, and i know the function is being called. This gives the same affect as above, with incorrect URLs not going to 404 but instead going to other pages.
Is there anyway to fix this, so that if a wrong page is visited, 404 are thrown?
Code is currently hosted here: . http://www.unifiedmicrosystems.com/products-and-services/software-development/wordpress/jformer-for-wordpress/.
I am just waiting for wordpress.org access to upload the source there for general use. I have tried to copy a cut down version with relevant parts below.
Many thanks in advance,
Chris
class JFormerForWP
{
static $errors = false; /* for debugging */
static $pluginPath;
static $pluginUrl;

public static function makeFormFactory($id,$class)
{
    $classPath = self::$pluginPath . "/forms/{$class}.php";
    require_once $classPath;
}

/* called each request */
public static function init()
{
    self::$pluginPath = dirname(__FILE__);  // Set Plugin Path
    self::$pluginUrl = WP_PLUGIN_URL . '/jformer-for-wp/'; // Set Plugin URL

    self::addRewriteRules();
    add_filter( 'query_vars', array(__CLASS__, 'addQueryVars'));
    add_action( 'template_redirect', array(__CLASS__, 'formDisplay'));

    add_action('wp_print_styles', array(__CLASS__, 'styles'));
    add_action('wp_print_scripts', array(__CLASS__, 'scripts') );
    add_shortcode('jformer', array(__CLASS__, 'shortcodeHandler'));

    add_action('wp_ajax_nopriv_jFormerForWp', array(__CLASS__, 'ajaxHandler'));
    add_action('wp_ajax_jFormerForWp', array(__CLASS__, 'ajaxHandler'));
    self::$errors = new WP_Error();
}

public static function ajaxHandler()
{
    $formID = $_POST['jFormerId'];
    echo self::getForm($formID);
}

public static function shortcodeHandler($atts, $content)
{
    extract( shortcode_atts( array(
    'id' => '0',
    'class' => '',
    'text' => ''
    ), $atts ) );

    // echo 'dumping shortcode values. content: ' . $content . ', id: ' . $id . ', class: ' . $class . '
';

    $options = self::getOptions();
    $permastructString = $options['url_string'];
}

public static function getOptions()
{
    $options = get_option('jformer_options',array('url_string' => 'forms'));
    return $options;
}

public static function addRewriteRules()
{
    $options = self::getOptions();
    add_rewrite_rule( $options['url_string'] . '/?([^/]*)','index.php?formid=$matches[1]', 'top' );
}

public static function addQueryVars($vars)
{
    $vars[] = 'formid';
    return $vars;
}

public static function formDisplay()
{
}

public static function activate()
{
    if (version_compare(PHP_VERSION, '5', '<'))
    {
        deactivate_plugins(basename(__FILE__));
    }

    self::addRewriteRules();
    flush_rewrite_rules(true);
}

public static function deactivate()
{

    delete_option('jformer_options');
    //$wp_rewrite->flush_rules(true);
    flush_rewrite_rules(true);
}

public static function addAdminPage()
{
    add_options_page( 'jFormer', 'jFormer Plugin', 'manage_options', 'jFormerForWP', array( __CLASS__ , 'displayAdminPageHtml' ));
}

public static function adminInit()
{
    register_setting( 'jformer_options', 'jformer_options', array(__CLASS__,'validateOptions') );
    add_settings_section('jformer_main', 'jFormer Settings', array(__CLASS__,'sectionText'), 'jformer_main_options');
    add_settings_field('jformer_url_string', 'Rewrite String', array(__CLASS__,'displayUrlStringSetting'), 'jformer_main_options', 'jformer_main');
    add_action('admin_notices', array(__CLASS__,'displayAdminNotices'));
}

public static function sectionText()
{
    echo '
Main description
';
}

public static function displayUrlStringSetting()
{
    $options = self::getOptions();
    echo "<input id='jformer_url_string' name='jformer_options[url_string]' size='40' type='text' value='{$options['url_string']}' />";
}

public static function validateOptions($input)
{
    $input['url_string'] = trim($input['url_string']);

    if(!preg_match('/^[a-z0-9]{1,}$/i', $input['url_string']))
    {
        add_settings_error('jFormerForWP', 'url_string_error', 'Invalid URL string, please fix ensure string consists of alphanumeric characters only and is at least 1 character long', 'error' );
    }
    else
    {
        // add_settings_error('jFormerForWP', 'url_string_updated', 'String updated', 'updated' );
        $validatedOptions['url_string'] = $input['url_string'];
    }

    return $validatedOptions;
}

public static function registerAdminSettings()
{
        register_setting('JFormerForWPSettings', 'JFormerForWPSettings_option1');

}

public static function displayAdminPageHtml()
{
    ?>

jFormer for WordPress Plugin Options

        Options relating to the Custom Plugin.
        <form action="options.php" method="post">
            <?php
            settings_fields('jformer_options'); ?>
            <?php do_settings_sections('jformer_main_options'); ?>
            <input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
        </form>

    <?php
}

function showMessage($message, $msgclass = 'updated')
{
    echo "
$message
";
}

public static function insertSettingsLink($links)
{
    $settings_link = ''.__('Settings','JFormerForWP').'';
     array_unshift( $links, $settings_link );
     return $links;
}

public static function styles()
{
    wp_enqueue_style('jformer', self::$pluginUrl. 'css/style.css');
}

public static function scripts()
{
    wp_enqueue_script('jformer', self::$pluginUrl . 'jFormer/jFormer.js',array('jquery'));
}
}

register_activation_hook(__FILE__, array('JFormerForWP','activate'));
register_deactivation_hook(__FILE__, array('JFormerForWP','deactivate'));
add_action('init', 'JFormerForWP::init');
add_action('admin_init', 'JFormerForWP::adminInit');
add_action('admin_menu', 'JFormerForWP::addAdminPage');
?>

A: I got around this niggling issue with something like the following:
function my_plugin_deactivate() {
  global $wp_rewrite;
  unset($wp_rewrite->non_wp_rules['my-rewrite-match']);
  flush_rewrite_rules();
}

Note that 'my-rewrite-match' is the original string you passed into add_rewrite_rule, not the regex it is internally mapped to.

A: Have you tried delete_option('rewrite_rules'); on deactivate? I came across the following when investigating this problem and it did the trick for me:

Typically you register post types on init. Some time after that, you
  get the deactivation action. A responsible plugin would remove its
  rewrite rules by flushing. However, it can't undo the registration, so
  the flush doesn't remove the plugin's rewrites.
The hacky workaround I've used is to just delete the rewrite_rules
  option on deactivation. They will be generated again when they are
  needed, so the only noticeable effect is that the next site view may
  take a bit longer.

Have a look at http://core.trac.wordpress.org/ticket/14761#comment:12 for a discussion on this topic.

A: doing something similar.... creating a portfolio post type plugin and am stuck in the same place.  activation seems to be ok.  deactivation just redirects to the homepage.  what i'd like is for the URL to remain the same but to generate a 404, so you know it is a broken link.  i know it is unlikely that a portfolio post type would be deactivated, but well it just seems like due diligence.
about the only source i've found on the subject:
http://shibashake.com/wordpress-theme/how-to-flush-permalink-rules-with-flush_rules
not quite doing it for me.  i've also tried:
update_option('rewrite_rules');
flush_rewrite_rules();

on deactivate, but it isn't quite right either.


text:
Q: How to modify the cell dimensions in tikzcd? Code:
\[
\begin{tikzcd}[cells={nodes={draw=gray}}]
    \text{Math is excellent!} \ar[r, rightarrow] \ar[d, leftarrow]
        & \text{w} \ar[d, rightarrow]\\
    \text{w} \ar[u, rightarrow] \ar[r, leftarrow]
        & \text{Pythagoreans killed someone!}
\end{tikzcd}
\]

Output:

Requirement: I am trying to achieve something like this:

*

*I know that Case 1 is not possible since the columns (and rows) are formed by centering the cells.

*So I try to implement Case 2 which does seem achievable. In particular, I am trying to do this:

*

*Make the width of the cells in a column equal.

*Then somehow write on that cell at a specific place. (Left aligned on the top right, and right aligned on the bottom left.)

Note: I deliberately write "at a specific place", and not just the special cases of left and right alignments.
Can this be done? (I thought of using \phantom. But that obviously gives crude results in this case.)
I know that how to modify the arrow anchor points so it is not a problem.

A: Just to let you know how to do this in plain TikZ, even if this is not what you're asking for:

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{positioning, arrows.meta}

\begin{document}

    \begin{tikzpicture}[
            node distance = 2cm and 5cm,
            every node/.style = {
                rectangle,
                draw,
                inner sep = 5pt,
                minimum size = 1cm},
            > = {Straight Barb}
            ]
        \node[left] (A) {Math is excellent!};
        \node[right, right= of A] (B) {w};
        \node[below = of A.east, anchor = east] (C) {w};
        \node[below = of B.west, anchor = west] (D) {Pythagoreans kill someone!};

        \path[->]
            (A) edge (B)
            (B.south) edge (D.north-|B)
            (D) edge (C)
            (C.north) edge (A.south-|C);
    \end{tikzpicture}

\end{document}

There are better ways to do this (but more complex), so I just wrote a simple code.

A: Here is a tikz-cd solution. The idea is to use \fcolorbox to draw the boxes around the text, and \llap and \rlap to control the arrow placement. Box color is controlled globally with \cdboxcolor, set to gray.
Define new commands \leftbox, \rightbox and \cdbox:
\leftbox{<dim>}{<text>} places <text> in a box that is shifted left so the tikzcd arrow is aimed as if the box had width <dim> instead of its actual width. \rightbox is defined analogously. \cdbox{<text>} does not shift.

\documentclass{article}

\usepackage{tikz-cd,amsmath}

\newcommand{\cdboxcolor}{gray}
\newcommand{\leftbox}[2]{\hspace{#1}\llap{\fcolorbox{\cdboxcolor}{white}{#2}}}
\newcommand{\rightbox}[2]{\rlap{\fcolorbox{\cdboxcolor}{white}{#2}}\hspace{#1}}
\newcommand{\cdbox}[1]{\fcolorbox{\cdboxcolor}{white}{#1}}

\begin{document}

\[
\begin{tikzcd}[cells={nodes={inner sep=0pt}}]
    \leftbox{1cm}{Math is excellent!} \ar[r, rightarrow] \ar[d, leftarrow]
        & \cdbox{w} \ar[d, rightarrow]\\
    \cdbox{w} \ar[u, rightarrow] \ar[r, leftarrow]
        & \rightbox{1cm}{Pythagoreans killed someone!}
\end{tikzcd}
\]

\end{document}

A: I'm not quite sure what you mean by

Note: I deliberately write "at a specific place", and not just the special cases of left and right alignments.

What other kind of alignments are there?
Case 1
Case 1 is actually the easiest.

*

*I know that Case 1 is not possible since the columns (and rows) are formed by centering the cells.

No, they aren't. They are aligned by their coordinate systems.
The rows align by y = 0 and the columns align by x = 0.
(Though, they are some pitfalls.)
Since every node is placed by default at (0, 0) you can just change its anchor.
By default, all nodes in a matrix of math nodes are placed at their base anchor.
This means the columns are horizontally centered and the rows are aligned by their baseline. By changing this to base west or base east we can enforce left or right alignment.
In the second diagram I've added some xshifting that changes the position "at a specifical place".
I'm using my ext.paths.ortho library which provides handy styles following question and answer to "Tikz: purely vertical arrow from nodeA.south to nodeB.north".
The shortcut *| stands for only vertical second and |* stands for only vertical first.
Code
\documentclass[varwidth]{standalone}
\usepackage{tikz-cd}
\tikzset{strut without depth/.style={text depth=+0pt, text height=+\ht\strutbox}}
\tikzcdset{
  column align/.is choice,
  @column align/.style n args={2}{column align/#1/.style={anchor={#2}}},
  @column align/.list={{left}{base west},{right}{base east},{center}{base}},
  colspec/.style={
    /utils/exec=\def\pgfmathresult{0},
    /utils/temp/.code={%
      \edef\pgfmathresult{\pgfinteval{\pgfmathresult+1}}%
      \pgfkeysalso{/tikz/column \pgfmathresult/.append style={
                     /tikz/commutative diagrams/column align/##1}}},
    /utils/temp/.list={#1}}}

\usetikzlibrary{ext.paths.ortho}
\begin{document}
\[
\begin{tikzcd}[
  cells={strut without depth, nodes={draw=gray}},
  math mode=false,
  /tikz/ortho/install shortcuts,
  colspec={right, left},
]
  Math is excellent!           \ar[r, rightarrow]
                               \ar[d, *|, leftarrow]
& w                            \ar[d, |*, rightarrow] \\
  w                            \ar[r, leftarrow]
& Pythagoreans killed someone!
\end{tikzcd}
\]
\[
\begin{tikzcd}[
  cells={strut without depth, nodes={draw=gray}},
  math mode=false,
  /tikz/ortho/install shortcuts,
  colspec={right, left},
]
  Math is excellent!           \ar[r, rightarrow]
                               \ar[d, *|, leftarrow]
& |[xshift=1cm]|   w           \ar[d, |*, rightarrow] \\
  |[xshift=-.5cm]| w           \ar[r, leftarrow]
& Pythagoreans killed someone!
\end{tikzcd}
\]
\end{document}

Output

Case 2
Again, with purely left, right and center alignment, this is possible.
This is basically the same as case 1 just with a fitted node around the actual contant which uses my ext.node-families library.
I've added a third and centered column to highlight why from' and/or to' is necessary to switch between the smaller nodes and the bigger drawn ones.
We could even invert that toggle (by naming the inner nodes with a ' and the drawn nodes without one).
This uses a custom fit key (that also only scans one node) because TikZ-CD uses a special asymmetrical rectangle shape.
For other alignments than left/right/center, i.e. as above with xshift, an adjustment to the fit key is necessary.
We could also do something like I did in my answer for "Make two nodes occupy the space of one node" where you can just go haywire with your placement and place a subnode inside it and have it act almost like a proper node.
Code
\documentclass[varwidth]{standalone}
\usepackage{tikz-cd}
\tikzcdset{
  @column align/.style n args={4}{
    column align/#1/.style={
      anchor={#2}, /tikz/commutative diagrams/@make box of column/.style={
        anchor={#3}, at={(\tikzlastnode.#4)}}}},
  column align/.is choice,
  @column align/.list={
    {left}  {base west}{real west}  {real west},
    {right} {base east}{real east}  {real east},
    {center}{base}     {real center}{real center}},
  colspec/.style={
    /utils/exec=\def\pgfmathresult{0},
    /utils/temp/.code={%
      \edef\pgfmathresult{\pgfinteval{\pgfmathresult+1}}%
      \pgfkeysalso{/tikz/column \pgfmathresult/.append style={
                     /tikz/commutative diagrams/column align/##1}}},
    /utils/temp/.list={#1}},
  make box of column/.style={
    inner sep=+0pt, outer sep=+0pt, minimum size=+0pt,
    commutative diagrams/fit=\tikzlastnode,name=\tikzlastnode',
    node family/width=\tikzmatrixname-\the\pgfmatrixcurrentcolumn,
    commutative diagrams/@make box of column,
    append after command={(\tikzlastnode.south west) edge[
      commutative diagrams/column box/.try,to path={
        ([xshift=+.5\pgflinewidth,yshift=+.5\pgflinewidth]\tikztostart)
        rectangle([xshift=+-.5\pgflinewidth,yshift=+-.5\pgflinewidth]%
          \tikztotarget)}](\tikzlastnode.north east)}},
  make column box/.style={
    append after command={
      [every node/.code=]node[commutative diagrams/make box of column]{}}}}
\makeatletter
\tikzcdset{
  fit/.code={% tikz-cd uses an asymmetrical rectangle …
    \pgf@process{\pgfpointdiff{\pgfpointanchor{\tikz@pp@name{#1}}{west}}
                              {\pgfpointanchor{\tikz@pp@name{#1}}{east}}}%
    \pgfkeysalso{/tikz/text width/.expanded=+\the\pgf@x}%
    \pgf@process{\pgfpointdiff{\pgfpointanchor{\tikz@pp@name{#1}}{base}}
                              {\pgfpointanchor{\tikz@pp@name{#1}}{north}}}%
    \pgfkeysalso{/tikz/text height/.expanded=+\the\pgf@y}%
    \pgf@process{\pgfpointdiff{\pgfpointanchor{\tikz@pp@name{#1}}{south}}
                              {\pgfpointanchor{\tikz@pp@name{#1}}{base}}}%
    \pgfkeysalso{/tikz/text depth/.expanded=+\the\pgf@y}},
  from'/.code=\edef\tikzcd@ar@start{\tikzcd@ar@start'},
  to'/.code=\edef\tikzcd@ar@target{\tikzcd@ar@target'}}
\makeatother
\usetikzlibrary{ext.paths.ortho,ext.node-families,fit}
\begin{document}
\[
\begin{tikzcd}[
  cells={
    text depth=+0pt, text height=+.7em,% \strut without depth
    nodes={commutative diagrams/make column box}},
  math mode=false,
  /tikz/ortho/install shortcuts,
  colspec={right, left, center}
]
  Math is excellent!
    \ar[r, rightarrow]
    \ar[d, *|, leftarrow]
& w \ar[d, |*, rightarrow] \rar[from', to']
& Foo \\
  w \ar[r, leftarrow]
& Pythagoreans killed someone!
& Baaaaaaaaaar
\end{tikzcd}
\]
\end{document}

Output

A: Who told you Case 1 is not possible?
Of course, it is, with tikz-cd, without using hacking!
You may 1) use \tikztostart (starting point) and \tikztotarget (ending point); or 2) name a node; and then use them in to path or from.
Here are some examples:
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz-cd}

\begin{document}
Solution with node names and \verb|from|/\verb|to|:
\[
\begin{tikzcd}[
    cells={nodes={draw=gray}},
    /tikz/column 1/.append style={nodes={anchor=base east}},
    /tikz/column 2/.append style={nodes={anchor=base west}}
    ]
    |[alias=mathis]|\text{Math is excellent!}\ar[r]\ar[d, leftarrow, from={mathis.south -| secondw}] &
      |[alias=firstw]|\text{w}\ar[d, to={Pytha.north -| firstw}]\\
    |[alias=secondw]|\text{w}\ar[r, leftarrow] &
      |[alias=Pytha]|\text{Pythagoreans killed someone!}
\end{tikzcd}
\]

Solution with node names and \verb|to path|:
\[
\begin{tikzcd}[
    cells={nodes={draw=gray}},
    /tikz/column 1/.append style={nodes={anchor=base east}},
    /tikz/column 2/.append style={nodes={anchor=base west}}
    ]
    |[alias=mathis]|\text{Math is excellent!}\ar[r]\ar[d, leftarrow, to path={(mathis.south -| secondw) -- (secondw)}] &
      |[alias=firstw]|\text{w}\ar[d, to path={ -- (Pytha.north -| firstw)}]\\
    |[alias=secondw]|\text{w}\ar[r, leftarrow] &
      |[alias=Pytha]|\text{Pythagoreans killed someone!}
\end{tikzcd}
\]

Solution with \verb|\tikztostart|, \verb|\tikztotarget| and \verb|to path|:
\[
\begin{tikzcd}[
    cells={nodes={draw=gray}},
    /tikz/column 1/.append style={nodes={anchor=base east}},
    /tikz/column 2/.append style={nodes={anchor=base west}}
    ]
    \text{Math is excellent!}\ar[r]\ar[d, leftarrow, to path={(\tikztostart.south -| \tikztotarget) -- (\tikztotarget)}] &
      \text{w}\ar[d, to path={-- (\tikztotarget.north -| \tikztostart)}]\\
    \text{w}\ar[r, leftarrow] & \text{Pythagoreans killed someone!}
    \end{tikzcd}
\]

Mixed:
\[
\begin{tikzcd}[
    cells={nodes={draw=gray}},
    /tikz/column 1/.append style={nodes={anchor=base east}},
    /tikz/column 2/.append style={nodes={anchor=base west}}
    ]
    |[alias=first]|\text{Math is excellent!}\ar[r]\ar[d, leftarrow, from={first.south -| second}] &
      \text{w}\ar[d, to path={-- (\tikztotarget.north -| \tikztostart)}]\\
    |[alias=second]|\text{w}\ar[r, leftarrow] & \text{Pythagoreans killed someone!}
\end{tikzcd}
\]
\end{document}

Look at Section 2.4 here, for more info: https://tug.org/TUGboat/tb43-1/tb133duck-tikz-cd.pdf.


text:
Q: I want to know Complete project line of code in TFS project collection Team,
Could you please help on the advise.
I want to know how to calculate the line of code for my TFS project collection. I need for entire instance to calculate the line of code.
Please advise. Thank you

A: Note: I'm assuming you're using TFVC, not Git.
You should be able to get this from the data warehouse (Tfs_Warehouse) assuming you have Reporting Services configured.
There is a Code Churn table. I believe you should be able to sum the NetLinesAdded field to get the total number of lines of code.
The Analysis Cube has a Total Lines field, as well.
However, you can also get this information from your file system with PowerShell, for example:
(gci -Path 'C:\Users\Daniel\Source\Repos\' -rec -Include '*.cs' | select-string .).Count

This comes with the caveat that "lines of code" is, in almost every single case, a totally meaningless, worthless number.


text:
Q: Query for all users except for users with an ID in this collection I'm trying to find all users except for users with an id that is a member of an array exclude_ids
Here's what I have:
User.where("id != ?", exclude_ids)

This only works when exclude_ids has only 1 element. If it has more than one element, I get
this error:
ActiveRecord::StatementInvalid: SQLite3::SQLException: near ",": syntax error: SELECT     "users".* FROM       "users" WHERE     (id != 1,2)

I'd appreciate any help.

A: I havent used Rails 3 but its unsafe to use User.where("id in #{exclude_ids} ?").
On Rails 2.x you do it as follows
User.find(:all, :conditions => ["id NOT IN (?)", [1,2,3]])

Rails 3.x docs http://railsapi.com/doc/rails-v3.0.0.beta.3/classes/ActiveRecord/Base.html

A: User.where('id NOT IN (:ids)', ids: exclude_ids)  # SQL does the filtering

or
User.select { |u| exclude_ids.exclude? u.id }  # Ruby does the filtering

A: i  am not confirm but you can Try this
User.where("id not in #{exclude_ids} ?")


text:
Q: Gmail Api returns error 503 service unavailable I got this this code that gets email from my account. This works on one of our automation process. But using another account im getting a service unavailable error
    private static GmailService GetGmailService()
    {
        string credPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        UserCredential credential;
        using (var stream =
            new FileStream(Path.Combine(credPath, "credentials.json"), FileMode.Open, FileAccess.Read))
        {
            var path = System.Environment.GetFolderPath(
              System.Environment.SpecialFolder.Personal);
            var credPath2 = Path.Combine(path, ".credentials/gmail-dotnet-quickstart.json");

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath2, true)).Result;
        }

        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,

        });
        return service;
    }

    public static string GetRegistrationLink(string devEmail, string toEmail, string subjectSearch = "", string keywords = "")
    {
        var url = string.Empty;
        var service = GetGmailService();
        var inboxlistRequest = service.Users.Messages.List(devEmail);
        inboxlistRequest.LabelIds = "INBOX";

        var query = @"in:unread in:inbox subject:Reset your CS Professional Suite Web account password";
        //@"in:unread ";
        //if (!string.IsNullOrEmpty(subjectSearch))
        //    query += $"subject:{subjectSearch} ";
        //if (!string.IsNullOrEmpty(toEmail))
        //    query += $"to:{toEmail} ";
        //if (!string.IsNullOrEmpty(keywords))
        //    query += $@"{keywords}";

        //inboxlistRequest.Q = query;
        inboxlistRequest.IncludeSpamTrash = false;

        //get our emails
        var emailListResponse = inboxlistRequest.Execute();
        if (emailListResponse != null && emailListResponse.Messages != null)
        {
            //loop through each email and get what fields you want...
            foreach (var email in emailListResponse.Messages)
            {
                var emailInfoRequest = service.Users.Messages.Get(devEmail, email.Id);
                var emailInfoResponse = emailInfoRequest.Execute();
                if (emailInfoResponse == null) continue;
                var from = "";
                var date = "";
                foreach (var mParts in emailInfoResponse.Payload.Headers)
                {
                    switch (mParts.Name)
                    {
                        case "Date":
                            date = mParts.Value;
                            break;
                        case "From":
                            @from = mParts.Value;
                            break;

                    }

                    if (date == "" || @from == "") continue;
                    var messageBodyParts = emailInfoResponse.Payload?.Parts?.SelectMany(a => a.Parts).ToList();
                    if (messageBodyParts == null) continue;
                    foreach (var p in messageBodyParts)
                    {
                        if (p.MimeType != "text/html") continue;
                        byte[] data = FromBase64ForUrlString(p.Body.Data);
                        var decodedString = Encoding.UTF8.GetString(data);
                        url = Regex.Match(decodedString, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value;
                    }
                }
            }

        }
        return url;
    }

The api has been enabled and the credentials has been included on the project but it is returning the 503 service not available error. But when i run the same code on a console, it works fine with the same credentials.json


text:
Q: Django throwing a ValueError: source code string cannot contain null bytes The whole error is quite huge :
Traceback (most recent call last):

 File "C:\Users\FiercePC\IdeaProjects\RadioShazam\server\ServerDjango\manage.py", line 22, in <module>
    main()
  File "C:\Users\FiercePC\IdeaProjects\RadioShazam\server\ServerDjango\manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 257, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 39, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 3, in <module>
    from django.core.management.commands.runserver import (
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 10, in <module>
    from django.core.servers.basehttp import (
  File "C:\Users\FiercePC\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\servers\basehttp.py", line 14, in <module>
    from wsgiref import simple_server
ValueError: source code string cannot contain null bytes`

I just generated the project and didn't do almost anything. The program works on my computer but not on my friend's. We have the same versions of python/django etc.