问:
Powershell Function with multiple parameters not accepting second pram
Trying to create a function that checks if you have a module installed along with that module being a minimum version. I have gotten it to work as a stand-alone check but when I try to make it function so that I don't have to have it repeated over and over when I have to check for multiple modules it fails the check for second input the version.</p>
```<code>#Check if Module is avaiable
Function Module-Check {
#Set Pramatators
Param(
    [Parameter(
        Mandatory=$true,
        Position=0,
        HelpMessage="Enter the Modules name has show in Powershell",
        ParameterSetName="Module Name")]
    [string]
        $ModuleName,

    [Parameter(
        Mandatory=$true,
        Position=1,
        HelpMessage="Enter the Modules Major Version Required has show in Powershell",
        ParameterSetName="Major Version")]
    [string]
        $ModuleVersion
        )

$ModuleAvaiable = Get-Module -ListAvailable | Select Name,Version | Where-Object {$_.name -eq "$ModuleName"}

if ($ModuleAvaiable.Name.Count -eq '0') {
Write-Host -ForegroundColor Red "$ModuleName Module is not available on this computer"
$InstallModule=Read-Host "Would you like to install it now (Y)es or (N)o"
    Switch -Wildcard($InstallModule)
    {
        "Y*" {$Action= Write-host "Importing $ModuleName Module"
           Install-Module -Name "$ModuleName"}
        "N*" {$Action= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on This module and will not be able to function PS will now exit"
            break
            }
        Default {$Action= Write-Host "No input selected ending script"
                break}
        }
    return $Action
}
else {
Write-Host "$ModuleName" $ModuleAvaiable.Version"is Avaiable on this computer"
$RequiredVersion = ($ModuleAvaiable.Version.Major -ge $ModuleVersion)
    if ($RequiredVersion = $true) {
    }
else {
    Write-Host -ForegroundColor Yellow "$ModuleName Module Version installed does not meet the required mimium version (version $ModuleVersion.X)"
    $UpdateModule=Read-Host "Update the Module version now (Y)es or (N)o"
        switch -Wildcard ($UpdateModule)
        {
        "Y*" {$Action2= Write-host "Update $ModuleName Module"
            update-Module -Name "$ModuleName"}
        "N*" {$Action2= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on this module and may not function properly with a lower version installed"

            }
        Default {$Action2= Write-Host "No input selected updating ALL Modules"
                foreach ($module in Get-InstalledModule) {
                    Get-InstalledModule $module.Name -AllVersions |
                    Where-Object Version -ne $module.Version |
                    Uninstall-Module
                                                            }
                }
        }
    Return $Action2

     }
  }
}

</code>```

答:
Maybe I am misreading your question but, here goes... Since you have defined your parameters with different parameter set names, they basically aren't supposed to be used together.

For instance, this simple gibberish function should demonstrate the phenomenon.

```<code>function Test-Something
{
    Param
    (
        [Parameter(ParameterSetName="Set1")][int]$P1,
        [Parameter(ParameterSetName="Set2")][int]$P2,
        [Parameter(ParameterSetName="Set1")][int]$P3
    )
}
</code>```

When running for example Test-Something -P1 1 you would be able to also use -P3, but running the same function with -P2 then -P1 and -P3 should not be exposed.

Running Get-Command Test-Something -Syntax, in this case should expose two separate alternatives, and the same should be true for your function where running Get-Command Module-Check -Syntax would expose

```<code>Module-Check [-ModuleName] <string> [<CommonParameters>]
Module-Check [-ModuleVersion] <string> [<CommonParameters>]
</code>```

Removing (or renaming them with the exact same name) ParameterSetName="Module Name" and ParameterSetName="Major Version" should fix this problem

Body:
Trying to create a function that checks if you have a module installed along with that module being a minimum version. I have gotten it to work as a stand-alone check but when I try to make it function so that I don't have to have it repeated over and over when I have to check for multiple modules it fails the check for second input the version.

#Check if Module is avaiable
Function Module-Check {
#Set Pramatators
Param(
    [Parameter(
        Mandatory=$true,
        Position=0,
        HelpMessage="Enter the Modules name has show in Powershell",
        ParameterSetName="Module Name")]
    [string]
        $ModuleName,

    [Parameter(
        Mandatory=$true,
        Position=1,
        HelpMessage="Enter the Modules Major Version Required has show in Powershell",
        ParameterSetName="Major Version")]
    [string]
        $ModuleVersion
        )

$ModuleAvaiable = Get-Module -ListAvailable | Select Name,Version | Where-Object {$_.name -eq "$ModuleName"}

if ($ModuleAvaiable.Name.Count -eq '0') {
Write-Host -ForegroundColor Red "$ModuleName Module is not available on this computer"
$InstallModule=Read-Host "Would you like to install it now (Y)es or (N)o"
    Switch -Wildcard($InstallModule)
    {
        "Y*" {$Action= Write-host "Importing $ModuleName Module"
           Install-Module -Name "$ModuleName"}
        "N*" {$Action= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on This module and will not be able to function PS will now exit"
            break
            }
        Default {$Action= Write-Host "No input selected ending script"
                break}
        }
    return $Action
}
else {
Write-Host "$ModuleName" $ModuleAvaiable.Version"is Avaiable on this computer"
$RequiredVersion = ($ModuleAvaiable.Version.Major -ge $ModuleVersion)
    if ($RequiredVersion = $true) {
    }
else {
    Write-Host -ForegroundColor Yellow "$ModuleName Module Version installed does not meet the required mimium version (version $ModuleVersion.X)"
    $UpdateModule=Read-Host "Update the Module version now (Y)es or (N)o"
        switch -Wildcard ($UpdateModule)
        {
        "Y*" {$Action2= Write-host "Update $ModuleName Module"
            update-Module -Name "$ModuleName"}
        "N*" {$Action2= Write-host -ForegroundColor Yellow "Functions in the Powershell rely on this module and may not function properly with a lower version installed"

            }
        Default {$Action2= Write-Host "No input selected updating ALL Modules"
                foreach ($module in Get-InstalledModule) {
                    Get-InstalledModule $module.Name -AllVersions |
                    Where-Object Version -ne $module.Version |
                    Uninstall-Module
                                                            }
                }
        }
    Return $Action2

     }
  }
}

Body:
Maybe I am misreading your question but, here goes... Since you have defined your parameters with different parameter set names, they basically aren't supposed to be used together.

For instance, this simple gibberish function should demonstrate the phenomenon.

function Test-Something
{
    Param
    (
        [Parameter(ParameterSetName="Set1")][int]$P1,
        [Parameter(ParameterSetName="Set2")][int]$P2,
        [Parameter(ParameterSetName="Set1")][int]$P3
    )
}

When running for example Test-Something -P1 1 you would be able to also use -P3, but running the same function with -P2 then -P1 and -P3 should not be exposed.

Running Get-Command Test-Something -Syntax, in this case should expose two separate alternatives, and the same should be true for your function where running Get-Command Module-Check -Syntax would expose

Module-Check [-ModuleName] <string> [<CommonParameters>]
Module-Check [-ModuleVersion] <string> [<CommonParameters>]

Removing (or renaming them with the exact same name) ParameterSetName="Module Name" and ParameterSetName="Major Version" should fix this problem


来源: stackexchange

问:
Config::LoadFile: Found incorrect option 'My.Conf' in config file
I'm working on a new conf My.Conf and I get these 2 errors, one on the very start of the worldserver:

```<code>azerothcore-wotlk/cmake-build-relwithdebinfo/src/server/worldserver/worldserver
> Config::LoadFile: Found incorrect option 'My.Conf' in config file 'azerothcore-wotlk/env/dist/etc/worldserver.conf'. Skip
</code>```

the other one later on when it stops running:

```<code>> Config: Missing property Rate.MissChanceMultiplier.TargetCreature in all config files, at least the .dist file must contain: "My.Conf = 1"
</code>```

This seems crazy as they are one the opposite of the other.

答:
The problem was that the config was present in worldserver.conf but not in worldserver.conf.dist.

Just make sure your config is present on both files.

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a new conf My.Conf and I get these 2 errors, one on the very start of the worldserver:

azerothcore-wotlk/cmake-build-relwithdebinfo/src/server/worldserver/worldserver
> Config::LoadFile: Found incorrect option 'My.Conf' in config file 'azerothcore-wotlk/env/dist/etc/worldserver.conf'. Skip

the other one later on when it stops running:

> Config: Missing property Rate.MissChanceMultiplier.TargetCreature in all config files, at least the .dist file must contain: "My.Conf = 1"

This seems crazy as they are one the opposite of the other.


问:
Spacing issue with image placed in table - HTML and CSS
I'm building a table for my website, and I'm trying to place a logo inside of a data cell. The issue is that whenever I add the picture, the margins go really weird and I can't figure out why spacing is added. I tried to remove the padding and margins on the image, and the cell itself, but nothing fixes it.

Before image:

After image:

HTML:

```<code><table class="table">
            <thead class="tablehead">
                <tr>
                    <th>Language</th>
                    <th>Year Initiated</th>
                    <th>Projects</th>
                </tr>
            </thead>
            <tbody class="tablebody">
                <tr>
                    <td><img src = "images/Java_Logo.png" class="tableimage"></td>
                    <td>2015</td>
                    <td>ENTER LINK</td>
                </tr>
                <tr>
                    <td>C#</td>
                    <td>2016</td>
                    <td>ENTER LINK</td>
                </tr>
                <tr>
                    <td>Python</td>
                    <td>2018</td>
                    <td>ENTER LINK</td>
                </tr>
                <tr>
                    <td>HTML and CSS</td>
                    <td>2018</td>
                    <td>ENTER LINK</td>
                </tr>
            </tbody>
        </table>
</code>```

CSS:

```<code>    .table{

    margin: auto;

}

.tablehead{

    font-family: permanent marker;
    font-size: 24px;

}

.tablebody{

    font-family: body;
    font-size: 20px;

}

.tableimage{

    width: 15%;
    padding:0px;
    margin: 0px;

}

th, td{

    border-bottom: 1px rgb(146, 40, 40) solid;
    padding: 10px;
    margin: 0;

}
</code>```

I've also already tried multiple different images, so this does not seem to be the issue. I'd like all three columns to take up 1/3 of the space each.

答:
The table must some other css affecting it. When I put your code into JSFiddle, it seems to work the way you want. See example: https://jsfiddle.net/ruben/xg2joc1y/5/

You could try adding some css to your image:

```<code>.table img {
  display: inline;
}
</code>```

Body:
I'm building a table for my website, and I'm trying to place a logo inside of a data cell. The issue is that whenever I add the picture, the margins go really weird and I can't figure out why spacing is added. I tried to remove the padding and margins on the image, and the cell itself, but nothing fixes it.

Before image:

After image:

HTML:

                    Language
                    Year Initiated
                    Projects

                    2015
                    ENTER LINK

                    C#
                    2016
                    ENTER LINK

                    Python
                    2018
                    ENTER LINK

                    HTML and CSS
                    2018
                    ENTER LINK

CSS:

    .table{

    margin: auto;

}

.tablehead{

    font-family: permanent marker;
    font-size: 24px;

}

.tablebody{

    font-family: body;
    font-size: 20px;

}

.tableimage{

    width: 15%;
    padding:0px;
    margin: 0px;

}

th, td{

    border-bottom: 1px rgb(146, 40, 40) solid;
    padding: 10px;
    margin: 0;

}

I've also already tried multiple different images, so this does not seem to be the issue. I'd like all three columns to take up 1/3 of the space each.

Body:
The table must some other css affecting it. When I put your code into JSFiddle, it seems to work the way you want. See example: https://jsfiddle.net/ruben/xg2joc1y/5/

You could try adding some css to your image:

.table img {
  display: inline;
}


问:
dict object has no attribute
In frontend I use vue js , using axios I sent data to backend.But after clicking submit button I got this error: dict object has no attribute 'invoice_products'.

From frontend using axios:

```<code>        this.$http.post('http://127.0.0.1:8000/api/createTest', {
            invoice_products: this.invoice_products
        })
</code>```

This is my json input data

```<code>{"invoice_products":[{"name":"fgf","price":"56"}]}
</code>```

views.py:

```<code>@api_view(['POST'])
def createTest(request):
    serializer = TestSerializer(data=request.data.invoice_products)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)
</code>```

Error:
dict object has no attribute 'invoice_products'

答:
request.data is a dict. So you access its info with request.data[yourkey] not request.data.yourkey

@api_view(['POST'])
def createTest(request):
    serializer = TestSerializer(data=request.data['invoice_products'])
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

```

Depending of what you serializer looks like, you may need to add many=true option to TestSerializer

Title: dict object has no attribute

Body:
In frontend I use vue js , using axios I sent data to backend.But after clicking submit button I got this error: dict object has no attribute 'invoice_products'.

From frontend using axios:

        this.$http.post('http://127.0.0.1:8000/api/createTest', {
            invoice_products: this.invoice_products
        })

This is my json input data

{"invoice_products":[{"name":"fgf","price":"56"}]}

views.py:

@api_view(['POST'])
def createTest(request):
    serializer = TestSerializer(data=request.data.invoice_products)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

Error:
dict object has no attribute 'invoice_products'

Body:
request.data is a dict. So you access its info with request.data[yourkey] not request.data.yourkey

@api_view(['POST'])
def createTest(request):
    serializer = TestSerializer(data=request.data['invoice_products'])
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

Depending of what you serializer looks like, you may need to add many=true option to TestSerializer


问:
How to combine several iterators to one?
Can I return several iterators like one? For example in iterator() method maybe I can combine iterators like one?

```<code>import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Addresses implements Iterable<Address> {
    private final Address main;
    private final List<Address> additional;
    private final List<Address> verified;

    public Addresses(Address main, List<Address> additional, List<Address> verified) {
        this.main = main;
        this.additional = additional;
        this.verified = verified;
    }

    public Address getMain() {
        return main;
    }

    public List<Address> getAdditional() {
        return additional;
    }

    public List<Address> getVerified() {
        return verified;
    }

    @Override
    public Iterator<Address> iterator() {
        // return 3 iterators main and additional and verified like one?
        return additional.iterator() + verified.iterator() + Collections.singletonList(main).iterator();
    }

}
</code>```

I just need to iterate through all items in both lists and the main address in one cycle but have them separated.  For example, I am going to use it like this

```<code>User user = ...
Addresses addresses = new Addresses(user.getMainAddress(), user.getAdditionalAddressess(), user.getVerifiedAddressess());
//iterate through addresses and change some fields an each address
user.setMain(addresses.getMain());
user.setAdditional(addresses.getAdditional());
user.setVerified(addresses.getVerified());
</code>```

答: Guava has Iterators.concat, have a look. the link contains all your answers probably.</p>

Body:
Can I return several iterators like one? For example in iterator() method maybe I can combine iterators like one?

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Addresses implements Iterable<Address> {
    private final Address main;
    private final List<Address> additional;
    private final List<Address> verified;

    public Addresses(Address main, List<Address> additional, List<Address> verified) {
        this.main = main;
        this.additional = additional;
        this.verified = verified;
    }

    public Address getMain() {
        return main;
    }

    public List<Address> getAdditional() {
        return additional;
    }

    public List<Address> getVerified() {
        return verified;
    }

    @Override
    public Iterator<Address> iterator() {
        // return 3 iterators main and additional and verified like one?
        return additional.iterator() + verified.iterator() + Collections.singletonList(main).iterator();
    }

}

I just need to iterate through all items in both lists and the main address in one cycle but have them separated.  For example, I am going to use it like this

User user = ...
Addresses addresses = new Addresses(user.getMainAddress(), user.getAdditionalAddressess(), user.getVerifiedAddressess());
//iterate through addresses and change some fields an each address
user.setMain(addresses.getMain());
user.setAdditional(addresses.getAdditional());
user.setVerified(addresses.getVerified());


问:
replace json key with another json value using node js / javascript
```<code>testDetails.map(function(data){

let JsonData={
 title: data["title"],
 url: data["url"],
 firstName: data["username"],

 work:[{workid:data["workid"].slice(","), workname: "tester"}],
 employee: [{employee_id: data["employee_id"].slice(","), employee_desk:"custom"}]
}
})
</code>```

so my above json output look like this

```<code>{
 "title":"01"
 "url":"employe@url.com",
 "firstName":"employee name",
 "work":[{"workid":"9371", "workname": "tester"}],
 "employee":[{"employee_id":"weh34",employee_desk:"custom"}]
}
</code>```

and another JSON object where data look like this

```<code>let data={
  "031w":"ewid3728e",
  "9371":"emp_01",
   "weh34":"work_place01"
}
</code>```

The workid and employee id with the JsonData I want to replace with the value which is present inside the data json so my data which is look like this

```<code> "work":[{"workid":"9371", "workname": "tester"}],
 "employee":[{"employee_id":"weh34",employee_desk:"custom"}]
</code>```

needed to be look like this

```<code> "work":[{"workid":"work_place01", "workname": "tester"}],
 "employee":[{"employee_id":"emp_01",employee_desk:"custom"}]
</code>```

I am trying to replace the code manually like this

```<code> work:[{workid:data.weh34, workname: "tester"}],
 employee: [{employee_id: data.9371, employee_desk:"custom"}]
</code>```

but data["workid"].slice(",") and data["employee_id"].slice(",") always get changed so I want to match both the json and fetch the value and place it in my JsonData

答:
Just use the value you got from testDetails as the index in the data object to get the corresponding value.

You need to use a different variable from data as the parameter to the mapping function so you can refer to the external variable data. I changed it to d below.

```<code>testDetails.map(d => ({
  title: d["title"],
  url: d["url"],
  firstName: d["username"],
  work: [{
    workid: data[d["workid"].slice(",")],
    workname: "tester"
  }],
  employee: [{
    employee_id: data[d["employee_id"].slice(",")],
    employee_desk: "custom"
  }]
}));
</code>```

Body:
testDetails.map(function(data){

let JsonData={
 title: data["title"],
 url: data["url"],
 firstName: data["username"],

 work:[{workid:data["workid"].slice(","), workname: "tester"}],
 employee: [{employee_id: data["employee_id"].slice(","), employee_desk:"custom"}]
}
})

so my above json output look like this

{
 "title":"01"
 "url":"employe@url.com",
 "firstName":"employee name",
 "work":[{"workid":"9371", "workname": "tester"}],
 "employee":[{"employee_id":"weh34",employee_desk:"custom"}]
}

and another JSON object where data look like this

let data={
  "031w":"ewid3728e",
  "9371":"emp_01",
   "weh34":"work_place01"
}

The workid and employee id with the JsonData I want to replace with the value which is present inside the data json so my data which is look like this

 "work":[{"workid":"9371", "workname": "tester"}],
 "employee":[{"employee_id":"weh34",employee_desk:"custom"}]

needed to be look like this

 "work":[{"workid":"work_place01", "workname": "tester"}],
 "employee":[{"employee_id":"emp_01",employee_desk:"custom"}]

I am trying to replace the code manually like this

 work:[{workid:data.weh34, workname: "tester"}],
 employee: [{employee_id: data.9371, employee_desk:"custom"}]

but data["workid"].slice(",") and data["employee_id"].slice(",") always get changed so I want to match both the json and fetch the value and place it in my JsonData

Body:
Just use the value you got from testDetails as the index in the data object to get the corresponding value.

You need to use a different variable from data as the parameter to the mapping function so you can refer to the external variable data. I changed it to d below.

testDetails.map(d => ({
  title: d["title"],
  url: d["url"],
  firstName: d["username"],
  work: [{
    workid: data[d["workid"].slice(",")],
    workname: "tester"
  }],
  employee: [{
    employee_id: data[d["employee_id"].slice(",")],
    employee_desk: "custom"
  }]
}));


问:
Could track mdm ios/android device/user profiles restrictions?
I have a mobile app in ios and android platforms. Our some customers are distributing it in mdm(many even use airwatch). Airwatch has some restriction payloads like: "Allow use of camera", "Allow screen capture", "Allow Biometric ID modification" etc.(these are ios/android device/user profiles restrictions) I want to take action in my mobile apps according to these payloads. For example there is an upload option with camera. I want to that if "Allow use of camera" is set as false, I want to not showing camera option.

Could track these payloads form ios and android apps? If yes, how to make it?

Thanks in advance.

答:
Take a look at android.content.RestrictionsManager.
getApplicationRestrictions() will return a Bundle of restrictions.

RestrictionsManager


问:
PHP Session Cookie Not Stored in XAMPP
For some reason the php session cookie file is not being stored on XAMPP in the default tmp directory, and I ran a search of the entire XAMPP for the session_id() and there are no results. Any ideas??

There is one file "sess_6mkb82rg31nmgjmf7i3ee7mjif" but it doesn't appear to be in the same format as a client-side cookie and is not the correct session id. The correct one is statically across multiple page loads "u8c6ldb8dcpddr55d542vodtpr". There are database queries coded into the file I found. I'm not sure what this may be. However it is in the correct directory where sessions are stored because there is a file called why.tmp and it says do not delete the session files.

What I am trying to do is find the session file and copy the contents to a new file with a new id because I've seen that creating a new id every page load is recommended on stackoverflow to reduce the risks of hacks by session fixation.

I am sure that the code doesn't change the session id after I get it from the virtual server because I am only at the point of getting the contents of the old session file so far.

I have built a successfully running framework that has no problems with sessions other than me finding the session file. It must be stored outside of the XAMPP directory or the data is saved within another file.

Thanks for your time!

答:
Unfortunately this is normal for simulated services like Xampp and others users like me is currently having that problem if do you need more information Check de OficialXamppForum that talks about to create a $_COOKIE (for any propourse) after to use the method setcookie($NameCookie,$Content,time()+$Seconds); the LocalServer correctly assign the Cookie, but!, later if I going to refresh the page pressing F5, the cookie will be erased, now, I recommend you press the button (i) near the link in your browser and check if the info and expiration date are correctly like this image:

Later, if any information is correctly trust me the cookie was set correctly, that "XamppIssue" is not happen only on PHP-Cookies, also occur with the method $_SERVER['HTTP_CLIENT_IP' that is assumed to allows to read the private ip user ex: (XXX.XXX.XXX.XXX), but! in XamppServer was loaded like this "::1::" or "1" or "::1" or ":1:" or ":1" and can check this discussion here in StackOverFlow when the people says that the method was applied correctly but because is a LocalHost has those limitations at time to executing PHP .

Finally if you want to check DEFINITELY!! if your PHP  runs correctly use a host like 000WebHost or Azure to discard any problems.

Have a nice day :D :D .

ContentLicense: CC BY-SA 3.0

Title: PHP Session Cookie Not Stored in XAMPP


问:
Execute a query string as part of a hard-coded statement
I have a very long stored procedure that runs a select statement. The statement I would like to add at the end would work in a query string. Is it possible to execute a query string as part of a hard-coded statement in SQL Server?</p>
```<code>SELECT *
FROM INV_DATA
WHERE 1 = 1
  AND MY_ID =

SET @SQL = @SQL + ' SELECT id FROM people WHERE id =
    CASE WHEN NOT EXISTS (SELECT ... WHERE storeID = (CASE WHEN ...@ACT_METHOD = ...)) AND ...'
</code>```

答:
SQL Server has a built-in stored procedure that runs queries into string variables, sp_executesql.

Here's an exemple:

```<code>DECLARE @IntVariable INT;
DECLARE @SQLString NVARCHAR(500);
DECLARE @ParmDefinition NVARCHAR(500);

/* Build the SQL string one time.*/
SET @SQLString =
     N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
       FROM AdventureWorks2012.HumanResources.Employee
       WHERE BusinessEntityID = @BusinessEntityID';
SET @ParmDefinition = N'@BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
                      @BusinessEntityID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
                      @BusinessEntityID = @IntVariable;
</code>```

SQL Server sp_executesql documentation

Body:
I have a very long stored procedure that runs a select statement. The statement I would like to add at the end would work in a query string. Is it possible to execute a query string as part of a hard-coded statement in SQL Server?

SELECT *
FROM INV_DATA
WHERE 1 = 1
  AND MY_ID =

SET @SQL = @SQL + ' SELECT id FROM people WHERE id =
    CASE WHEN NOT EXISTS (SELECT ... WHERE storeID = (CASE WHEN ...@ACT_METHOD = ...)) AND ...'

Body:
SQL Server has a built-in stored procedure that runs queries into string variables, sp_executesql.

Here's an exemple:

DECLARE @IntVariable INT;
DECLARE @SQLString NVARCHAR(500);
DECLARE @ParmDefinition NVARCHAR(500);

/* Build the SQL string one time.*/
SET @SQLString =
     N'SELECT BusinessEntityID, NationalIDNumber, JobTitle, LoginID
       FROM AdventureWorks2012.HumanResources.Employee
       WHERE BusinessEntityID = @BusinessEntityID';
SET @ParmDefinition = N'@BusinessEntityID tinyint';
/* Execute the string with the first parameter value. */
SET @IntVariable = 197;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
                      @BusinessEntityID = @IntVariable;
/* Execute the same string with the second parameter value. */
SET @IntVariable = 109;
EXECUTE sp_executesql @SQLString, @ParmDefinition,
                      @BusinessEntityID = @IntVariable;

SQL Server sp_executesql documentation


问:
I want to let my Discord Bot send images/gifs
I've been trying every bit of code I find that might work but either the command doesn't load (it says the bot is typing and then stops) or just the bot itself doesn't work. I'm using Python.</p>

答:
Alternatively, you can use URLs for images/gifs by adding the link as a standard message to be sent by your bot.

```<code>async def _cowgif(self, ctx):
    await ctx.send("http://imgur.com/gallery/YiMUiop")
</code>```

Note that this is an asynchronous request.

Body:
Alternatively, you can use URLs for images/gifs by adding the link as a standard message to be sent by your bot.

async def _cowgif(self, ctx):
    await ctx.send("http://imgur.com/gallery/YiMUiop")

Note that this is an asynchronous request.


问:
Yarn throws an error while trying to build electron app
When I try to create an electron app via yarn create electron-app "my-app", it throws an error saying

```<code>'C:\Users\Lincoln' is not recognized as an internal or external command,
operable program or batch file.
error Command failed.
Exit code: 1
Command: C:\Users\Lincoln Muller\AppData\Local\Yarn\bin\create-electron-app
Arguments: my-app
Directory: C:\Users\Lincoln Muller
Output:
</code>```

What should I do? I'm new to Yarn, and NPM worked fine. This also only happens on Windows, when I use my iMac on Monterey or my Linux laptop the command runs fine.

答:
It seems that Yarn assumes it can run the program create-electron-app without considering spaces in the file path. Unfortunately, this does not work and only the part up to the first space is considered a program to run, hence you get the error message that C:\Users\Lincoln is not a valid command.

The problem is discussed in this Yarn issue. The key idea in the workarounds is to accept Yarn's behavior and give it a file path that doesn't contain spaces. There are two concrete ideas:

Option A - Use directory name abbreviation to skip the space

```<code>yarn config set cache-folder "C:\Users\Lincol~1\AppData\Local\Yarn\Cache"
yarn config set prefix "C:\Users\Lincol~1\AppData\Local\Yarn"
</code>```

For this to work, make sure to take 6 characters from the actual directory name and then append ~1. If the space happens to occur within the first 6 characters, this approach will not work for you.

Option B - Make another user folder, skipping the space (using junction)

```<code>mklink /J "C:\Users\Lincoln-Muller" "C:\Users\Lincoln Muller"
yarn config set cache-folder "C:\Users\Lincoln-Muller\AppData\Local\Yarn\Cache"
yarn config set prefix "C:\Users\Lincoln-Muller\AppData\Local\Yarn"
</code>```

A junction allows two directory names to point at the same file system structure. That means that there are two ways to address the same directory. Their contents cannot diverge because they are the same directory.

Body:
When I try to create an electron app via yarn create electron-app "my-app", it throws an error saying

'C:\Users\Lincoln' is not recognized as an internal or external command,
operable program or batch file.
error Command failed.
Exit code: 1
Command: C:\Users\Lincoln Muller\AppData\Local\Yarn\bin\create-electron-app
Arguments: my-app
Directory: C:\Users\Lincoln Muller
Output:

What should I do? I'm new to Yarn, and NPM worked fine. This also only happens on Windows, when I use my iMac on Monterey or my Linux laptop the command runs fine.

Body:
It seems that Yarn assumes it can run the program create-electron-app without considering spaces in the file path. Unfortunately, this does not work and only the part up to the first space is considered a program to run, hence you get the error message that C:\Users\Lincoln is not a valid command.

The problem is discussed in this Yarn issue. The key idea in the workarounds is to accept Yarn's behavior and give it a file path that doesn't contain spaces. There are two concrete ideas:

Option A - Use directory name abbreviation to skip the space

yarn config set cache-folder "C:\Users\Lincol~1\AppData\Local\Yarn\Cache"
yarn config set prefix "C:\Users\Lincol~1\AppData\Local\Yarn"

For this to work, make sure to take 6 characters from the actual directory name and then append ~1. If the space happens to occur within the first 6 characters, this approach will not work for you.

Option B - Make another user folder, skipping the space (using junction)

mklink /J "C:\Users\Lincoln-Muller" "C:\Users\Lincoln Muller"
yarn config set cache-folder "C:\Users\Lincoln-Muller\AppData\Local\Yarn\Cache"
yarn config set prefix "C:\Users\Lincoln-Muller\AppData\Local\Yarn"

A junction allows two directory names to point at the same file system structure. That means that there are two ways to address the same directory. Their contents cannot diverge because they are the same directory.


问:
Why is there an empty line after every record when writing a CSV file?
I have some lists and want to write them in a CSV file.
Every list has 9200 items.

And every list must be a column in a CSV file.

I write this code:

```<code>file_path = os.path.join(os.path.realpath(folder_name), 'file_wanted.csv')
file_list = [list_1, list_2, list_3, list_4, list_5, list_6, list_7, list_8]
exported = zip_longest(*file_list)

with open(file_path, "w+", errors="ignore") as file:
    write = csv.writer(file)
    write.writerow(["list_1", "list_2", "list_3", "list_4", "list_5", "list_6", "list_7", "list_8"])
    write.writerows(exported)
</code>```

But I have the file like that

Is there a better way to write the code so that the extra line doesn't bloom for me after every record

答:
Pandas is your friend.</p>
```<code>import numpy as np, pandas as pd, os
from itertools import zip_longest

file_path = os.path.join(os.path.realpath(folder_name))
exported = list(zip_longest(list_1, list_2, list_3, list_4,
                            list_5, list_6, list_7, list_8, fillvalue=np.nan))

df = pd.DataFrame(exported)
df.to_csv(file_path, index=False)
</code>```

Body:
I have some lists and want to write them in a CSV file.
Every list has 9200 items.

And every list must be a column in a CSV file.

I write this code:

file_path = os.path.join(os.path.realpath(folder_name), 'file_wanted.csv')
file_list = [list_1, list_2, list_3, list_4, list_5, list_6, list_7, list_8]
exported = zip_longest(*file_list)

with open(file_path, "w+", errors="ignore") as file:
    write = csv.writer(file)
    write.writerow(["list_1", "list_2", "list_3", "list_4", "list_5", "list_6", "list_7", "list_8"])
    write.writerows(exported)

But I have the file like that

Is there a better way to write the code so that the extra line doesn't bloom for me after every record

Body:
Pandas is your friend.

import numpy as np, pandas as pd, os
from itertools import zip_longest

file_path = os.path.join(os.path.realpath(folder_name))
exported = list(zip_longest(list_1, list_2, list_3, list_4,
                            list_5, list_6, list_7, list_8, fillvalue=np.nan))

df = pd.DataFrame(exported)
df.to_csv(file_path, index=False)


问:
Finding Geo Locations for ipv4 and ipv6 using BigQuery and MaxMind GeoIP
I'm trying to match users to their geo locations using their IPs.

IPs is a mix of ipv4, ipv6 and some rows with invalid entries.

I'm using GeoLite2-City-Blocks-IPv4 (know I will have to use a different file for ipv6, if anybody knows which one is the correct one, much appreciated) and GeoLite2-City-Locations-en. So basically, one file has the IP blocks and their location codes and the other one have the actual locations for those codes.

I used instructions from this article by Felipe Hoffa https://towardsdatascience.com/geolocation-with-bigquery-de-identify-76-million-ip-addresses-in-20-seconds-e9e652480bd2 to match my IPs with the IPs in the blocks file.

The problem is I get an error when trying to use the NET.SAFE_IP_FROM_STRING(ip_address) & NET.IP_NET_MASK(4,mask) functions. The error is:

Bitwise binary operator for BYTES requires equal length of the inputs. Got 16 bytes on the left hand side and 4 bytes on the right hand side.

So I tried to ensure IPs are valid before passing them to the function using regex. This works for ipv4. I've now figured out regex to match ipv6 as well, and from my checks, it seems accurate. However I still get the error. I can't figure out why and how to fix my query to get the correct result.

See whole query below:

```<code>(
    SELECT
      *,
      NET.SAFE_IP_FROM_STRING(ip_address) & NET.IP_NET_MASK(4,
        mask) network_bin
    FROM (
      SELECT
        * EXCEPT (is_valid)
      FROM (
        SELECT
          *,
          CASE
            WHEN (REGEXP_CONTAINS(ip_address, r'\A[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7}\z') OR (NOT REGEXP_CONTAINS(ip_address, r'\A(.*?[a-f0-9](:|\z)){8}') AND REGEXP_CONTAINS(ip_address, r'\A([a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,6})?::([a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,6})?\z')) OR REGEXP_CONTAINS(ip_address, r'\A[a-f0-9]{1,4}(:[a-f0-9]{1,4}){5}:(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}\z') OR (NOT REGEXP_CONTAINS(ip_address, r'\A(.*?[a-f0-9]:){6}') AND REGEXP_CONTAINS(ip_address, r'\A([a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,4})?::([a-f0-9]{1,4}:){0,5}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}\z')) ) THEN TRUE
            WHEN REGEXP_CONTAINS(ip_address, r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") THEN TRUE
          ELSE
          FALSE
        END
          AS is_valid
        FROM (
          SELECT
            user,
            ip_address,
            date
          FROM
            `project.dataset.table`)
      WHERE
        is_valid IS TRUE),
      UNNEST(GENERATE_ARRAY(9,32)) mask)
</code>```

答:
There is same answer as for this question
How to improve performance of GeoIP query in BigQuery?

WITH test_data AS (
    SELECT '2a02:2f0c:570c:fe00:1db7:21c4:21fa:f89' AS ip UNION ALL
    SELECT '79.114.150.111' AS ip
)
-- replace the input_data with your data
, ipv4 AS (
    SELECT DISTINCT ip, NET.SAFE_IP_FROM_STRING(ip) AS ip_bytes
    FROM test_data
    WHERE BYTE_LENGTH(NET.SAFE_IP_FROM_STRING(ip)) = 4
), ipv4d AS (
    SELECT ip, city_name, country_name, latitude, longitude
    FROM (
        SELECT ip, ip_bytes & NET.IP_NET_MASK(4, mask) network_bin, mask
        FROM ipv4, UNNEST(GENERATE_ARRAY(8,32)) mask
    )
    JOIN `demo_bq_dataset.geoip_city_v4`
    USING (network_bin, mask)
), ipv6 AS (
    SELECT DISTINCT ip, NET.SAFE_IP_FROM_STRING(ip) AS ip_bytes
    FROM test_data
    WHERE BYTE_LENGTH(NET.SAFE_IP_FROM_STRING(ip)) = 16
), ipv6d AS (
    SELECT ip, city_name, country_name, latitude, longitude
    FROM (
        SELECT  ip, ip_bytes & NET.IP_NET_MASK(16, mask) network_bin, mask
        FROM ipv6, UNNEST(GENERATE_ARRAY(19,64)) mask
    )
    JOIN `demo_bq_dataset.geoip_city_v6`
    USING (network_bin, mask)
)
SELECT * FROM ipv4d
UNION ALL
SELECT * FROM ipv6d
```

In order to get the geoip_city_v4 and geoip_city_v6 you need to download the geoip database from https://maxmind.com/

You can follow this tutorial in to update and prepare you dataset https://hodo.dev/posts/post37-gcp-bigquery-geoip/.

Body:
I'm trying to match users to their geo locations using their IPs.

IPs is a mix of ipv4, ipv6 and some rows with invalid entries.

I'm using GeoLite2-City-Blocks-IPv4 (know I will have to use a different file for ipv6, if anybody knows which one is the correct one, much appreciated) and GeoLite2-City-Locations-en. So basically, one file has the IP blocks and their location codes and the other one have the actual locations for those codes.

I used instructions from this article by Felipe Hoffa https://towardsdatascience.com/geolocation-with-bigquery-de-identify-76-million-ip-addresses-in-20-seconds-e9e652480bd2 to match my IPs with the IPs in the blocks file.

The problem is I get an error when trying to use the NET.SAFE_IP_FROM_STRING(ip_address) & NET.IP_NET_MASK(4,mask) functions. The error is:

Bitwise binary operator for BYTES requires equal length of the inputs. Got 16 bytes on the left hand side and 4 bytes on the right hand side.

So I tried to ensure IPs are valid before passing them to the function using regex. This works for ipv4. I've now figured out regex to match ipv6 as well, and from my checks, it seems accurate. However I still get the error. I can't figure out why and how to fix my query to get the correct result.

See whole query below:

(
    SELECT
      *,
      NET.SAFE_IP_FROM_STRING(ip_address) & NET.IP_NET_MASK(4,
        mask) network_bin
    FROM (
      SELECT
        * EXCEPT (is_valid)
      FROM (
        SELECT
          *,
          CASE
            WHEN (REGEXP_CONTAINS(ip_address, r'\A[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7}\z') OR (NOT REGEXP_CONTAINS(ip_address, r'\A(.*?[a-f0-9](:|\z)){8}') AND REGEXP_CONTAINS(ip_address, r'\A([a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,6})?::([a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,6})?\z')) OR REGEXP_CONTAINS(ip_address, r'\A[a-f0-9]{1,4}(:[a-f0-9]{1,4}){5}:(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}\z') OR (NOT REGEXP_CONTAINS(ip_address, r'\A(.*?[a-f0-9]:){6}') AND REGEXP_CONTAINS(ip_address, r'\A([a-f0-9]{1,4}(:[a-f0-9]{1,4}){0,4})?::([a-f0-9]{1,4}:){0,5}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}\z')) ) THEN TRUE
            WHEN REGEXP_CONTAINS(ip_address, r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") THEN TRUE
          ELSE
          FALSE
        END
          AS is_valid
        FROM (
          SELECT
            user,
            ip_address,
            date
          FROM
            `project.dataset.table`)
      WHERE
        is_valid IS TRUE),
      UNNEST(GENERATE_ARRAY(9,32)) mask)

Body:
There is same answer as for this question
How to improve performance of GeoIP query in BigQuery?

WITH test_data AS (
    SELECT '2a02:2f0c:570c:fe00:1db7:21c4:21fa:f89' AS ip UNION ALL
    SELECT '79.114.150.111' AS ip
)
-- replace the input_data with your data
, ipv4 AS (
    SELECT DISTINCT ip, NET.SAFE_IP_FROM_STRING(ip) AS ip_bytes
    FROM test_data
    WHERE BYTE_LENGTH(NET.SAFE_IP_FROM_STRING(ip)) = 4
), ipv4d AS (
    SELECT ip, city_name, country_name, latitude, longitude
    FROM (
        SELECT ip, ip_bytes & NET.IP_NET_MASK(4, mask) network_bin, mask
        FROM ipv4, UNNEST(GENERATE_ARRAY(8,32)) mask
    )
    JOIN `demo_bq_dataset.geoip_city_v4`
    USING (network_bin, mask)
), ipv6 AS (
    SELECT DISTINCT ip, NET.SAFE_IP_FROM_STRING(ip) AS ip_bytes
    FROM test_data
    WHERE BYTE_LENGTH(NET.SAFE_IP_FROM_STRING(ip)) = 16
), ipv6d AS (
    SELECT ip, city_name, country_name, latitude, longitude
    FROM (
        SELECT  ip, ip_bytes & NET.IP_NET_MASK(16, mask) network_bin, mask
        FROM ipv6, UNNEST(GENERATE_ARRAY(19,64)) mask
    )
    JOIN `demo_bq_dataset.geoip_city_v6`
    USING (network_bin, mask)
)
SELECT * FROM ipv4d
UNION ALL
SELECT * FROM ipv6d

In order to get the geoip_city_v4 and geoip_city_v6 you need to download the geoip database from https://maxmind.com/

You can follow this tutorial in to update and prepare you dataset https://hodo.dev/posts/post37-gcp-bigquery-geoip/.


问:
R : How to iterate sum across multiple columns?
I am trying to iterate/loop a sum across multiple non-consecutive columns. My objective is to compute the subscale score of multiple questionnaires measured repeatedly across time.

Dataset for one questionnaire of x items and n time-points:

```<code>df <- tibble(
  ID = 1:5,
  itemA_1 = sample(100, 5, TRUE),
  itemB_1 = sample(100, 5, TRUE),
  itemC_1 = sample(100, 5, TRUE),
  itemD_1 = sample(100, 5, TRUE),
  itemx_1 = sample(100, 5, TRUE),
  itemA_3 = sample(100, 5, TRUE),
  itemB_3 = sample(100, 5, TRUE),
  itemC_3 = sample(100, 5, TRUE),
  itemD_3 = sample(100, 5, TRUE),
  itemx_3 = sample(100, 5, TRUE),
  itemA_n = sample(100, 5, TRUE),
  itemB_n = sample(100, 5, TRUE),
  itemC_n = sample(100, 5, TRUE),
  itemD_n = sample(100, 5, TRUE),
  itemx_n = sample(100, 5, TRUE),
)
</code>```

The sum for one specific time point works just fine:

```<code>df %>% mutate(total_1 = sum(c(itemA_1, itemC_1, itemD_1))
</code>```

This loop does not work:

```<code>for (i in c(1, 3, n)) {
    df %>% mutate(total_i = sum(c(itemA_i, itemC_i, itemD_i))
    }
</code>```

What am I doing wrong?

答:
Here's a base R option without pivoting, where we first select the columns that we want to sum, then get the unique suffix names, then we can use rowSums to get the sum of each group (i.e., each unique suffix). Then, I update the column names, and then merge with the original dataframe.

```<code>df_sum <- df[, grepl( "ID|itemA|itemC|itemD", names(df))]

suffixes <- unique(sub("^[^_]*_", "", colnames(df_sum)))

df2 <- sapply(suffixes, function(x) rowSums(df_sum[,endsWith(colnames(df_sum), x)]))
colnames(df2)[-1] <- paste("total", colnames(df2)[-1], sep = "_")
merge(x = df, y = df2, by = "ID", all.x = TRUE)
</code>```

Output

```<code>  ID itemA_1 itemB_1 itemC_1 itemD_1 itemx_1 itemA_3 itemB_3 itemC_3 itemD_3 itemx_3 itemA_n itemB_n itemC_n itemD_n itemx_n total_1 total_3 total_n
1  1      92      84      31      74      77      26      71      92      59      70      47      54       7       6      95     197     177      60
2  2      49       6      40       6      94      61      69      58      49      62      66      13      94      52      23      95     168     212
3  3      67      69      34      56      44      94      69       1      52      96      62      64      34      78      67     157     147     174
4  4      86      33      85      87      30      33      26      15      70      97      34      36      74      58      87     258     118     166
5  5      49      25      23      56      63       4      84      35      92      34      33      62      95      77      50     128     131     205
</code>```

Data

```<code>df <- structure(list(ID = 1:5, itemA_1 = c(92L, 49L, 67L, 86L, 49L),
    itemB_1 = c(84L, 6L, 69L, 33L, 25L), itemC_1 = c(31L, 40L,
    34L, 85L, 23L), itemD_1 = c(74L, 6L, 56L, 87L, 56L), itemx_1 = c(77L,
    94L, 44L, 30L, 63L), itemA_3 = c(26L, 61L, 94L, 33L, 4L),
    itemB_3 = c(71L, 69L, 69L, 26L, 84L), itemC_3 = c(92L, 58L,
    1L, 15L, 35L), itemD_3 = c(59L, 49L, 52L, 70L, 92L), itemx_3 = c(70L,
    62L, 96L, 97L, 34L), itemA_n = c(47L, 66L, 62L, 34L, 33L),
    itemB_n = c(54L, 13L, 64L, 36L, 62L), itemC_n = c(7L, 94L,
    34L, 74L, 95L), itemD_n = c(6L, 52L, 78L, 58L, 77L), itemx_n = c(95L,
    23L, 67L, 87L, 50L)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -5L))
</code>```

Benchmark

```<code>df1 <- df
df2 <- df

bm <- microbenchmark::microbenchmark(akrun_tidyverse = {df %>%
                                       pivot_longer(cols =-ID, names_to = c("item", ".value"), names_sep = "_") %>%
                                       filter(item %in% c("itemA", "itemC", "itemD")) %>%
                                       group_by(ID) %>%
                                       summarise(across(where(is.numeric), sum, na.rm = TRUE,
                                                        .names = "total_{.col}")) %>%
                                       left_join(df, .)},
                                     akrun_loop = {for (i in c(1, 3, 'n')) {
                                       df1 <- df1 %>%
                                         mutate(!! str_c("total_", i) :=
                                                  rowSums(across(all_of(str_c(c("itemA_", "itemC_", "itemD_"), i)))))
                                     }},
                                     andrew_baseR = {df_sum <- df2[, grepl( "ID|itemA|itemC|itemD", names(df2))];
                                     suffixes <- unique(sub("^[^_]*_", "", colnames(df_sum)));
                                     df3 <- sapply(suffixes, function(x) rowSums(df_sum[,endsWith(colnames(df_sum), x)]));
                                     colnames(df3)[-1] <- paste("total", colnames(df3)[-1], sep = "_");
                                     merge(x = df, y = df3, by = "ID", all.x = TRUE)},
                                     times = 1000)

autoplot(bm)
</code>```

Body:
I am trying to iterate/loop a sum across multiple non-consecutive columns. My objective is to compute the subscale score of multiple questionnaires measured repeatedly across time.

Dataset for one questionnaire of x items and n time-points:

df <- tibble(
  ID = 1:5,
  itemA_1 = sample(100, 5, TRUE),
  itemB_1 = sample(100, 5, TRUE),
  itemC_1 = sample(100, 5, TRUE),
  itemD_1 = sample(100, 5, TRUE),
  itemx_1 = sample(100, 5, TRUE),
  itemA_3 = sample(100, 5, TRUE),
  itemB_3 = sample(100, 5, TRUE),
  itemC_3 = sample(100, 5, TRUE),
  itemD_3 = sample(100, 5, TRUE),
  itemx_3 = sample(100, 5, TRUE),
  itemA_n = sample(100, 5, TRUE),
  itemB_n = sample(100, 5, TRUE),
  itemC_n = sample(100, 5, TRUE),
  itemD_n = sample(100, 5, TRUE),
  itemx_n = sample(100, 5, TRUE),
)

The sum for one specific time point works just fine:

df %>% mutate(total_1 = sum(c(itemA_1, itemC_1, itemD_1))

This loop does not work:

for (i in c(1, 3, n)) {
    df %>% mutate(total_i = sum(c(itemA_i, itemC_i, itemD_i))
    }

What am I doing wrong?

Body:
Here's a base R option without pivoting, where we first select the columns that we want to sum, then get the unique suffix names, then we can use rowSums to get the sum of each group (i.e., each unique suffix). Then, I update the column names, and then merge with the original dataframe.

df_sum <- df[, grepl( "ID|itemA|itemC|itemD", names(df))]

suffixes <- unique(sub("^[^_]*_", "", colnames(df_sum)))

df2 <- sapply(suffixes, function(x) rowSums(df_sum[,endsWith(colnames(df_sum), x)]))
colnames(df2)[-1] <- paste("total", colnames(df2)[-1], sep = "_")
merge(x = df, y = df2, by = "ID", all.x = TRUE)

Output

  ID itemA_1 itemB_1 itemC_1 itemD_1 itemx_1 itemA_3 itemB_3 itemC_3 itemD_3 itemx_3 itemA_n itemB_n itemC_n itemD_n itemx_n total_1 total_3 total_n
1  1      92      84      31      74      77      26      71      92      59      70      47      54       7       6      95     197     177      60
2  2      49       6      40       6      94      61      69      58      49      62      66      13      94      52      23      95     168     212
3  3      67      69      34      56      44      94      69       1      52      96      62      64      34      78      67     157     147     174
4  4      86      33      85      87      30      33      26      15      70      97      34      36      74      58      87     258     118     166
5  5      49      25      23      56      63       4      84      35      92      34      33      62      95      77      50     128     131     205

Data

df <- structure(list(ID = 1:5, itemA_1 = c(92L, 49L, 67L, 86L, 49L),
    itemB_1 = c(84L, 6L, 69L, 33L, 25L), itemC_1 = c(31L, 40L,
    34L, 85L, 23L), itemD_1 = c(74L, 6L, 56L, 87L, 56L), itemx_1 = c(77L,
    94L, 44L, 30L, 63L), itemA_3 = c(26L, 61L, 94L, 33L, 4L),
    itemB_3 = c(71L, 69L, 69L, 26L, 84L), itemC_3 = c(92L, 58L,
    1L, 15L, 35L), itemD_3 = c(59L, 49L, 52L, 70L, 92L), itemx_3 = c(70L,
    62L, 96L, 97L, 34L), itemA_n = c(47L, 66L, 62L, 34L, 33L),
    itemB_n = c(54L, 13L, 64L, 36L, 62L), itemC_n = c(7L, 94L,
    34L, 74L, 95L), itemD_n = c(6L, 52L, 78L, 58L, 77L), itemx_n = c(95L,
    23L, 67L, 87L, 50L)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -5L))

Benchmark

df1 <- df
df2 <- df

bm <- microbenchmark::microbenchmark(akrun_tidyverse = {df %>%
                                       pivot_longer(cols =-ID, names_to = c("item", ".value"), names_sep = "_") %>%
                                       filter(item %in% c("itemA", "itemC", "itemD")) %>%
                                       group_by(ID) %>%
                                       summarise(across(where(is.numeric), sum, na.rm = TRUE,
                                                        .names = "total_{.col}")) %>%
                                       left_join(df, .)},
                                     akrun_loop = {for (i in c(1, 3, 'n')) {
                                       df1 <- df1 %>%
                                         mutate(!! str_c("total_", i) :=
                                                  rowSums(across(all_of(str_c(c("itemA_", "itemC_", "itemD_"), i)))))
                                     }},
                                     andrew_baseR = {df_sum <- df2[, grepl( "ID|itemA|itemC|itemD", names(df2))];
                                     suffixes <- unique(sub("^[^_]*_", "", colnames(df_sum)));
                                     df3 <- sapply(suffixes, function(x) rowSums(df_sum[,endsWith(colnames(df_sum), x)]));
                                     colnames(df3)[-1] <- paste("total", colnames(df3)[-1], sep = "_");
                                     merge(x = df, y = df3, by = "ID", all.x = TRUE)},
                                     times = 1000)

autoplot(bm)


问:
MvcSiteMapProvider -- Children of dynamic nodes don't show up in breadcrumbs or sitemap
I am trying to develop of sitemap for my site that maintains URL parameters when it needs to. I'm using MvcSiteMapProvider and trying to use dynamic nodes to preserve the route data for various nodes. However, the problem I'm having is with the children of dynamic nodes. When I nest a node within a dynamic node in my sitemap file, it doesn't show up on the sitemap generated using Html.MvcSiteMap().SiteMap(), and when I navigate to the page, I lose all of the breadcrumbs BEFORE the dynamic node.

For example, if my dynamic node is called "Person Details", the breadcrumb looks like this on the Person Details page:

```<code>Home > People > Person Details
</code>```

But as soon as I navigate further into the page, say "Contact Person", the breadcrumb looks like this:

```<code>Person Details > Contact Person
</code>```

without the first two paths. Also if I try to navigate back to Person Details, none of the url parameters are maintained (e.g. instead of going to http://localhost:55555/Home/People/PersonDetails?id=12, it goes to http://localhost:55555/Home/People/PersonDetails).

When I try to display the whole sitemap by using Html.MvcSiteMap().SiteMap(), it outputs the correct hierarchy up until the dynamic node. The sitemap lists a unique node for each "Person" node found in the dynamic node provider, but does not display any of the children of the dynamic node.

My sitemap looks something like this (abbreviated):

```<code><?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0" enableLocalization="true">
  <mvcSiteMapNode title="Home"  controller="Home" action="Index">
    <mvcSiteMapNode title="People" controller="Information" action="People">
      <mvcSiteMapNode title="Person Details" controller="Information" action="PersonDetails" dynamicNodeProvider="MySite.Code.PersonDetailsDynamicNodeProvider, MySite">
        <mvcSiteMapNode title="Contact Person" controller="Information" action="Contact" />
      </mvcSiteMapNode>
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>
</code>```

And my dynamic node provider looks like this:

```<code>public class PersonDetailsDynamicNodeProvider : DynamicNodeProviderBase
{
    List<Person> people = proxy.GetPeople();

    public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
    {
        var nodes = new List<DynamicNode>();

        foreach (var person in people)
        {
            DynamicNode node = new DynamicNode();
            node.RouteValues.Add("id", person.ID);

            nodes.Add(node);
        }

        return nodes;
    }

    static private PersonServiceClient proxy = new PersonServiceClient();
}
</code>```

Is there anything I am missing? I get the feeling I've just left something out, but I'm very new to web development and really am just stabbing in the dark at this point.

答:
You don't need a dynamic node provider.

```<code><mvcSiteMapNode title="Person Details" controller="Information" action="PersonDetails" preservedRouteParameters="id">
  <mvcSiteMapNode title="Contact Person" controller="Information" action="Contact" />
</mvcSiteMapNode>
</code>```

works fine for what you're doing.

Body:
I am trying to develop of sitemap for my site that maintains URL parameters when it needs to. I'm using MvcSiteMapProvider and trying to use dynamic nodes to preserve the route data for various nodes. However, the problem I'm having is with the children of dynamic nodes. When I nest a node within a dynamic node in my sitemap file, it doesn't show up on the sitemap generated using Html.MvcSiteMap().SiteMap(), and when I navigate to the page, I lose all of the breadcrumbs BEFORE the dynamic node.

For example, if my dynamic node is called "Person Details", the breadcrumb looks like this on the Person Details page:

Home > People > Person Details

But as soon as I navigate further into the page, say "Contact Person", the breadcrumb looks like this:

Person Details > Contact Person

without the first two paths. Also if I try to navigate back to Person Details, none of the url parameters are maintained (e.g. instead of going to http://localhost:55555/Home/People/PersonDetails?id=12, it goes to http://localhost:55555/Home/People/PersonDetails).

When I try to display the whole sitemap by using Html.MvcSiteMap().SiteMap(), it outputs the correct hierarchy up until the dynamic node. The sitemap lists a unique node for each "Person" node found in the dynamic node provider, but does not display any of the children of the dynamic node.

My sitemap looks something like this (abbreviated):

<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0" enableLocalization="true">
  <mvcSiteMapNode title="Home"  controller="Home" action="Index">
    <mvcSiteMapNode title="People" controller="Information" action="People">
      <mvcSiteMapNode title="Person Details" controller="Information" action="PersonDetails" dynamicNodeProvider="MySite.Code.PersonDetailsDynamicNodeProvider, MySite">
        <mvcSiteMapNode title="Contact Person" controller="Information" action="Contact" />
      </mvcSiteMapNode>
    </mvcSiteMapNode>
  </mvcSiteMapNode>
</mvcSiteMap>

And my dynamic node provider looks like this:

public class PersonDetailsDynamicNodeProvider : DynamicNodeProviderBase
{
    List<Person> people = proxy.GetPeople();

    public override IEnumerable<DynamicNode> GetDynamicNodeCollection()
    {
        var nodes = new List<DynamicNode>();

        foreach (var person in people)
        {
            DynamicNode node = new DynamicNode();
            node.RouteValues.Add("id", person.ID);

            nodes.Add(node);
        }

        return nodes;
    }

    static private PersonServiceClient proxy = new PersonServiceClient();
}

Is there anything I am missing? I get the feeling I've just left something out, but I'm very new to web development and really am just stabbing in the dark at this point.

Body:
You don't need a dynamic node provider.

<mvcSiteMapNode title="Person Details" controller="Information" action="PersonDetails" preservedRouteParameters="id">
  <mvcSiteMapNode title="Contact Person" controller="Information" action="Contact" />
</mvcSiteMapNode>

works fine for what you're doing.


问:
problem with Flutter SDK location after install with ubuntu snap
I installed flutter SDK using ubuntu "snap" by running:

$ sudo snap install flutter --classic

and when i want to add PATH of flutter sdk to android studio
i have a seroius problem !!

recently i searched flutter sdk paths and i saw some guys said , if you installed it with snap,
this is sdk path:

/home/user_name/snap/flutter/common/flutter

then I checked this path and i saw in common directory i have a zip file and there is no flutter directory , i tried to unzip that file but it gives error and cannot unzip it.

please help me , please ....

答:
Download the last version of Flutter manually

Delete all files located in this path:

/home/user_name/snap/flutter/common/flutter
3. Extract all files from the downloaded .tar.xz to the flutter folder


问:
Are column headers essential in an accessible role="grid" setup?
goal: accessibility

target screen readers: JAWS and NVDA

I am adding role="grid" to a list of items. Each row in the grid contains some grid cells representing the item name, description, etc. I cannot change the markup to use a table so this is why I am using role="grid".

My question first question:

Within the context I am working, it is easier for me to add a visually hidden header to each grid cell rather than adding a separate row  to the grid with column headers for each column.  Is it ok to label each grid cell with a header rather than creating a row of column headers (role="columnheader")? How will this affect the level of accessibility for screen readers? Do users always expect a grid to have column headers?

My second question:

I want to include some content which is not located within the container I have marked with role="grid" as a grid row. Is it possible to associate content outside the grid container with the grid as a grid row?

NOTE: Keep in mind that altering the markup is not an option so suggestions such as "build it as a table" will not help here.

Thank you!

答:
I cannot change the markup to use a table so this is why I am using role="grid".

If you can specify role="grid" in your code then it seems like you could specify role="table".  Is there a reason that's not possible?  The reason I ask is because grids should be reserved for when the actual cell contents can be edited, kind of like a spreadsheet.  The fact that a cell has an interactive element in it does not mean it should be a grid.  So my first recommendation is to use role="table".

However, grids are recommended when you have a group of things where you can navigate to each "thing" using the arrow keys.

I'm guessing you already read the spec for grids.

it is easier for me to add a visually hidden header to each grid cell rather than adding a separate row to the grid with column headers for each column. Is it ok to label each grid cell with a header rather than creating a row of column headers

While you could do that, you'll miss out on some of the benefits of real column and row headers.  With a basic
, it's very helpful for assistive technology users, such as screen readers, to have both  and .  The latter is often overlooked.

Picture yourself in the middle of a big table.  Lots of rows and columns.  You know the current value of the cell in the table because the screen reader just announced it.  Now you want to navigate down one cell.  If you don't have a row header, then you will not hear any context for the next cell value.  If you want to navigate left or right one cell, if you don't have a column header, then you will not hear any context for the next cell value.

If you hard code the column header as a visually hidden element, then you will always hear that column header announced for the cell even if you are navigating vertically down a column.  That would be unexpected behavior for a screen reader user.  The column header should only be announced if you navigate horizontally across a row, not vertically down a column.  When you navigate vertically, the row headers should be announced.

I'm not trying to be harsh here but I think you need to go back to your statement:

it is easier for me

and decide if the ease of coding is more important than the end user experience.

If there's a technology reason you can't have column and row headers, because the library you're using doesn't allow it or some other reason, then as a last resort, you can try coding around it with visually hidden element but I would not recommend that as a first choice.

I want to include some content which is not located within the container I have marked with role="grid" as a grid row.

That's a little trickier.  The aria-owns attribute is exactly what you need but it's typically used when a child element can't be owned by the parent via normal DOM nesting. In your case, it sounds like most of the elements are nested according to the DOM but you'll also have something outside the DOM.

The tricky part is when you mix the two.  As documented in the spec:

If an element has both aria-owns and DOM children then the order of the child elements with respect to the parent/child relationship is the DOM children first, then the elements referenced in aria-owns.

So you might get some funky reading order if the literal DOM children are announced first and then the aria-owns children are announced second.  Definitely worth a bit of testing.  You might have to put an ID on every row, including the content outside the table, then use all of those IDs in aria-owns of the table even those most of the rows are "naturally" owned by the table because of the DOM.

Body:
I cannot change the markup to use a table so this is why I am using role="grid".

If you can specify role="grid" in your code then it seems like you could specify role="table".  Is there a reason that's not possible?  The reason I ask is because grids should be reserved for when the actual cell contents can be edited, kind of like a spreadsheet.  The fact that a cell has an interactive element in it does not mean it should be a grid.  So my first recommendation is to use role="table".

However, grids are recommended when you have a group of things where you can navigate to each "thing" using the arrow keys.

I'm guessing you already read the spec for grids.

it is easier for me to add a visually hidden header to each grid cell rather than adding a separate row to the grid with column headers for each column. Is it ok to label each grid cell with a header rather than creating a row of column headers

While you could do that, you'll miss out on some of the benefits of real column and row headers.  With a basic <table>, it's very helpful for assistive technology users, such as screen readers, to have both <th scope="col"> and <th scope="row">.  The latter is often overlooked.

Picture yourself in the middle of a big table.  Lots of rows and columns.  You know the current value of the cell in the table because the screen reader just announced it.  Now you want to navigate down one cell.  If you don't have a row header, then you will not hear any context for the next cell value.  If you want to navigate left or right one cell, if you don't have a column header, then you will not hear any context for the next cell value.

If you hard code the column header as a visually hidden element, then you will always hear that column header announced for the cell even if you are navigating vertically down a column.  That would be unexpected behavior for a screen reader user.  The column header should only be announced if you navigate horizontally across a row, not vertically down a column.  When you navigate vertically, the row headers should be announced.

I'm not trying to be harsh here but I think you need to go back to your statement:

it is easier for me

and decide if the ease of coding is more important than the end user experience.

If there's a technology reason you can't have column and row headers, because the library you're using doesn't allow it or some other reason, then as a last resort, you can try coding around it with visually hidden element but I would not recommend that as a first choice.

I want to include some content which is not located within the container I have marked with role="grid" as a grid row.

That's a little trickier.  The aria-owns attribute is exactly what you need but it's typically used when a child element can't be owned by the parent via normal DOM nesting. In your case, it sounds like most of the elements are nested according to the DOM but you'll also have something outside the DOM.

The tricky part is when you mix the two.  As documented in the spec:

If an element has both aria-owns and DOM children then the order of the child elements with respect to the parent/child relationship is the DOM children first, then the elements referenced in aria-owns.

So you might get some funky reading order if the literal DOM children are announced first and then the aria-owns children are announced second.  Definitely worth a bit of testing.  You might have to put an ID on every row, including the content outside the table, then use all of those IDs in aria-owns of the table even those most of the rows are "naturally" owned by the table because of the DOM.


问:
CRA error. Html Webpack Plugin: Error: Child compilation failed:
I create a default react app with npx create-react-app app-name --template typescript but my app isn't working. Error:

```<code>Html Webpack Plugin:
  Error: Child compilation failed:
  Module build failed (from ../../../#Node/authorization/6. crypto-converter/node_modules/html-webpack-pl  ugin/lib/loader.js):
  Error: Cannot find module 'C:\#Node\authorization\6. crypto-converter\node_modules\html-webpack-plugin\  lib\loader.js'
  Require stack:
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack-manifest-plugin\dist\index.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\config\webpack.config.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\scripts\start.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:1005:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at loadLoader (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.  js:19:17)
      at iteratePitchingLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib  \LoaderRunner.js:182:2)
      at runLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunne  r.js:397:2)
      at NormalModule._doBuild (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Normal  Module.js:812:3)
      at NormalModule.build (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalMod  ule.js:956:15)
      at C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Compilation.js:1367:12
  ModuleBuildError: Module build failed (from ../../../#Node/authorization/6. crypto-converter/node_modul  es/html-webpack-plugin/lib/loader.js):
  Error: Cannot find module 'C:\#Node\authorization\6. crypto-converter\node_modules\html-webpack-plugin\  lib\loader.js'
  Require stack:
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack-manifest-plugin\dist\index.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\config\webpack.config.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\scripts\start.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:1005:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at loadLoader (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.  js:19:17)
      at iteratePitchingLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib  \LoaderRunner.js:182:2)
      at runLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunne  r.js:397:2)
      at NormalModule._doBuild (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Normal  Module.js:812:3)
      at NormalModule.build (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalMod  ule.js:956:15)
      at C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Compilation.js:1367:12
      at processResult (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.j  s:751:19)
      at C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.js:853:5
      at C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js:399:11
      at C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js:185:11
      at loadLoader (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.  js:33:11)
      at iteratePitchingLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib  \LoaderRunner.js:182:2)
      at runLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunne  r.js:397:2)
...`
</code>```

Before that I see warning:

(node:2720) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:2720) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
```

I tried:

Create new app

Create app in other directories

Delete node.js

Install other versions of node.js (16.14.0, 17.4.0, 16.13.2 - active)

答: Solution: install react-scripts@4.0.3. If you know how to fix problem with react-script@5.0.0 write please.

Body:
I create a default react app with npx create-react-app app-name --template typescript but my app isn't working. Error:

Html Webpack Plugin:
  Error: Child compilation failed:
  Module build failed (from ../../../#Node/authorization/6. crypto-converter/node_modules/html-webpack-pl  ugin/lib/loader.js):
  Error: Cannot find module 'C:\#Node\authorization\6. crypto-converter\node_modules\html-webpack-plugin\  lib\loader.js'
  Require stack:
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack-manifest-plugin\dist\index.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\config\webpack.config.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\scripts\start.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:1005:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at loadLoader (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.  js:19:17)
      at iteratePitchingLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib  \LoaderRunner.js:182:2)
      at runLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunne  r.js:397:2)
      at NormalModule._doBuild (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Normal  Module.js:812:3)
      at NormalModule.build (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalMod  ule.js:956:15)
      at C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Compilation.js:1367:12
  ModuleBuildError: Module build failed (from ../../../#Node/authorization/6. crypto-converter/node_modul  es/html-webpack-plugin/lib/loader.js):
  Error: Cannot find module 'C:\#Node\authorization\6. crypto-converter\node_modules\html-webpack-plugin\  lib\loader.js'
  Require stack:
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\webpack-manifest-plugin\dist\index.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\config\webpack.config.js
  - C:\#Node\authorization\6. crypto-converter\node_modules\react-scripts\scripts\start.js
      at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
      at Function.Module._load (node:internal/modules/cjs/loader:778:27)
      at Module.require (node:internal/modules/cjs/loader:1005:19)
      at require (node:internal/modules/cjs/helpers:102:18)
      at loadLoader (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.  js:19:17)
      at iteratePitchingLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib  \LoaderRunner.js:182:2)
      at runLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunne  r.js:397:2)
      at NormalModule._doBuild (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Normal  Module.js:812:3)
      at NormalModule.build (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalMod  ule.js:956:15)
      at C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\Compilation.js:1367:12
      at processResult (C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.j  s:751:19)
      at C:\#Node\authorization\6. crypto-converter\node_modules\webpack\lib\NormalModule.js:853:5
      at C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js:399:11
      at C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunner.js:185:11
      at loadLoader (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\loadLoader.  js:33:11)
      at iteratePitchingLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib  \LoaderRunner.js:182:2)
      at runLoaders (C:\#Node\authorization\6. crypto-converter\node_modules\loader-runner\lib\LoaderRunne  r.js:397:2)
...`

Before that I see warning:

(node:2720) [DEP_WEBPACK_DEV_SERVER_ON_AFTER_SETUP_MIDDLEWARE] DeprecationWarning: 'onAfterSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:2720) [DEP_WEBPACK_DEV_SERVER_ON_BEFORE_SETUP_MIDDLEWARE] DeprecationWarning: 'onBeforeSetupMiddleware' option is deprecated. Please use the 'setupMiddlewares' option.

I tried:

Create new app

Create app in other directories

Delete node.js

Install other versions of node.js (16.14.0, 17.4.0, 16.13.2 - active)


问:
Android Library publishing fails after recommended AGP update to 7.1.1/Gradle 7.2
My build is failing after performing the upgrade to AGP 7.1.1 and performing the automated upgrade steps from Android Studio in a library project.

I am following the following guide: https://developer.android.com/studio/build/maven-publish-plugin

We've been using this for quite awhile without issue.

After performing the automated steps from the IDE, I now get the following error:

```<code>A problem occurred configuring project ':some-lib'.
> Could not find method publications() for arguments [build_546b384slk3v64hu8jsdnbywh$_run_closure1$_closure5$_closure9$_closure10@333a4a39] on object of type com.android.build.gradle.internal.dsl.LibraryPublishingImpl$AgpDecorated.
</code>```

My build.gradle file looks like so:

```<code>android {
 ...

     afterEvaluate {
        publishing {

            publications {
                mavenAar(MavenPublication) {
                    from components.release
                }
            }

            repositories {
                maven {
                    url artifact_repo_url
                    credentials {
                        ...
                    }
                }
            }
        }
    }
}
</code>```

My gradle-wrapper.properties looks like so:

```<code>distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

</code>```

Any suggestions for how to fix this?

答:
The answer to my question is shown here:
https://developer.android.com/reference/tools/gradle-api/7.1/com/android/build/api/dsl/LibraryPublishing

The afterEvaluate{ publishing {} }
section should be outside of the android {} block and in its own afterEvaluate {}

We also need to add a publishing {} section in the android block that specifies the variant/s to publish.

For me the result looked something like this:

```<code>android {
    publishing {
        singleVariant("release")
    }
}

afterEvaluate {
    publishing {
        publications {
            release(MavenPublication) {
                from components.release
                // ......
            }
        }
    }
}

</code>```

Body:
My build is failing after performing the upgrade to AGP 7.1.1 and performing the automated upgrade steps from Android Studio in a library project.

I am following the following guide: https://developer.android.com/studio/build/maven-publish-plugin

We've been using this for quite awhile without issue.

After performing the automated steps from the IDE, I now get the following error:

A problem occurred configuring project ':some-lib'.
> Could not find method publications() for arguments [build_546b384slk3v64hu8jsdnbywh$_run_closure1$_closure5$_closure9$_closure10@333a4a39] on object of type com.android.build.gradle.internal.dsl.LibraryPublishingImpl$AgpDecorated.

My build.gradle file looks like so:

android {
 ...

     afterEvaluate {
        publishing {

            publications {
                mavenAar(MavenPublication) {
                    from components.release
                }
            }

            repositories {
                maven {
                    url artifact_repo_url
                    credentials {
                        ...
                    }
                }
            }
        }
    }
}

My gradle-wrapper.properties looks like so:

distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME

Any suggestions for how to fix this?

Body:
The answer to my question is shown here:
https://developer.android.com/reference/tools/gradle-api/7.1/com/android/build/api/dsl/LibraryPublishing

The afterEvaluate{ publishing {} }
section should be outside of the android {} block and in its own afterEvaluate {}

We also need to add a publishing {} section in the android block that specifies the variant/s to publish.

For me the result looked something like this:

android {
    publishing {
        singleVariant("release")
    }
}

afterEvaluate {
    publishing {
        publications {
            release(MavenPublication) {
                from components.release
                // ......
            }
        }
    }
}


问:
matplotlib triplot and tricontourf
I'm attempting to plot a 2D dataset having unstructured coordinates in matplotlib using tricontourf. I'm able to generate a plot of the 'mesh' with triplot, however when I use the same Triangulation object for tricontourf, I get an error (see below). What am I missing? Example:

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

def lower(x):
    return 2 + 1*x

def upper(x):
    return 60 + 4*x

ni = 10
nj = 12

x = np.linspace(1,15,ni)

## make a trapezoid
xy = np.zeros((ni,nj,2),dtype=np.float32)
for i in range(len(x)):
    y = np.linspace(lower(x[i]),upper(x[i]),nj)
    xy[i,:,0] = x[i]
    xy[i,:,1] = y

## add noise
xy += -0.1 + 0.2*np.random.rand(ni,nj,2)

## make tris 'indices list'
xi, yi    = np.meshgrid(range(ni), range(nj), indexing='xy')
inds_list = np.stack((xi,yi), axis=2)
inds_list = np.reshape(inds_list, (ni*nj,2), order='C')
inds_list = np.ravel_multi_index((inds_list[:,0],inds_list[:,1]), (ni,nj), order='C')
inds_list = np.reshape(inds_list, (ni,nj), order='F')

tris = np.zeros((2*(ni-1)*(nj-1),3), dtype=np.int64)
ci=0
for i in range(ni-1):
    for j in range(nj-1):
        tris[ci,0] = inds_list[i+1, j+1]
        tris[ci,1] = inds_list[i,   j+1]
        tris[ci,2] = inds_list[i,   j  ]
        ci+=1
        tris[ci,0] = inds_list[i,   j  ]
        tris[ci,1] = inds_list[i+1, j  ]
        tris[ci,2] = inds_list[i+1, j+1]
        ci+=1

triangulation = mpl.tri.Triangulation(x=xy[:,:,0].ravel(), y=xy[:,:,1].ravel(), triangles=tris)

fig1 = plt.figure(figsize=(4, 4/(16/9)), dpi=300)
ax1 = plt.gca()
ax1.triplot(triangulation, lw=0.5)
#ax1.tricontourf(triangulation)
fig1.tight_layout(pad=0.25)
plt.show()
</code>```

...produces

however, uncommenting the line with ax1.tricontourf

throws the error:

```<code>Traceback (most recent call last):
  File "test.py", line 54, in <module>
    ax1.tricontourf(triangulation)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 307, in tricontourf
    return TriContourSet(ax, *args, **kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 29, in __init__
    super().__init__(ax, *args, **kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\contour.py", line 812, in __init__
    kwargs = self._process_args(*args, **kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 45, in _process_args
    tri, z = self._contour_args(args, kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 60, in _contour_args
    z = np.ma.asarray(args[0])
IndexError: list index out of range
</code>```

I am using:

Python version: 3.8.9

matplotlib version: 3.5.1

答:
I would say you need to provide the array of values to contour, e.g.:

x= xy[:,:,0].ravel()
z= np.random.rand(x.shape[0])
ax1.tricontourf(triangulation, z)
```

Title: matplotlib triplot and tricontourf

Body:
I'm attempting to plot a 2D dataset having unstructured coordinates in matplotlib using tricontourf. I'm able to generate a plot of the 'mesh' with triplot, however when I use the same Triangulation object for tricontourf, I get an error (see below). What am I missing? Example:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

def lower(x):
    return 2 + 1*x

def upper(x):
    return 60 + 4*x

ni = 10
nj = 12

x = np.linspace(1,15,ni)

## make a trapezoid
xy = np.zeros((ni,nj,2),dtype=np.float32)
for i in range(len(x)):
    y = np.linspace(lower(x[i]),upper(x[i]),nj)
    xy[i,:,0] = x[i]
    xy[i,:,1] = y

## add noise
xy += -0.1 + 0.2*np.random.rand(ni,nj,2)

## make tris 'indices list'
xi, yi    = np.meshgrid(range(ni), range(nj), indexing='xy')
inds_list = np.stack((xi,yi), axis=2)
inds_list = np.reshape(inds_list, (ni*nj,2), order='C')
inds_list = np.ravel_multi_index((inds_list[:,0],inds_list[:,1]), (ni,nj), order='C')
inds_list = np.reshape(inds_list, (ni,nj), order='F')

tris = np.zeros((2*(ni-1)*(nj-1),3), dtype=np.int64)
ci=0
for i in range(ni-1):
    for j in range(nj-1):
        tris[ci,0] = inds_list[i+1, j+1]
        tris[ci,1] = inds_list[i,   j+1]
        tris[ci,2] = inds_list[i,   j  ]
        ci+=1
        tris[ci,0] = inds_list[i,   j  ]
        tris[ci,1] = inds_list[i+1, j  ]
        tris[ci,2] = inds_list[i+1, j+1]
        ci+=1

triangulation = mpl.tri.Triangulation(x=xy[:,:,0].ravel(), y=xy[:,:,1].ravel(), triangles=tris)

fig1 = plt.figure(figsize=(4, 4/(16/9)), dpi=300)
ax1 = plt.gca()
ax1.triplot(triangulation, lw=0.5)
#ax1.tricontourf(triangulation)
fig1.tight_layout(pad=0.25)
plt.show()

...produces

however, uncommenting the line with ax1.tricontourf

throws the error:

Traceback (most recent call last):
  File "test.py", line 54, in <module>
    ax1.tricontourf(triangulation)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 307, in tricontourf
    return TriContourSet(ax, *args, **kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 29, in __init__
    super().__init__(ax, *args, **kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\contour.py", line 812, in __init__
    kwargs = self._process_args(*args, **kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 45, in _process_args
    tri, z = self._contour_args(args, kwargs)
  File "C:\Users\steve\AppData\Roaming\Python\Python38\site-packages\matplotlib\tri\tricontour.py", line 60, in _contour_args
    z = np.ma.asarray(args[0])
IndexError: list index out of range

I am using:

Python version: 3.8.9

matplotlib version: 3.5.1


问:
How can I access child object property in Compas Search framework?
I have following code (in grails and Searchable Plugin aka Compass):

```<code>class Topic {

  String name;
  static searchable = true;
}

class Question extends BaseEntity {
  String question;

  static searchable = true;
  static hasMany = [
      topics: Topic
  ]
}
</code>```

How can I search Question with specific topic id?

Something like Question.search("topics#id:12") or Question.search("topics.id:12") dosnt work.

答:
Chage your searchable block in Question so it looks like this:

```<code>static searchable = {
    topics component: true
}
</code>```

and in Topic if you dont want Topics returned as root search elements

```<code>static searchable = [
    root: false
]
</code>```

Fire up grails and add a few items, then download Luke from http://www.getopt.org/luke/
and open the index for your Question domain object which will be at ~/.grails/projects/projName/searchable-index/'env'/index/question

If you check the documents tab you will see the terms embedded in the index which will be something like $/Question/topics

This should give you the path to put in your Question.search, something like:

Question.search('$/Question/topics/id:1')

ContentLicense: CC BY-SA 2.5

Body:
I have following code (in grails and Searchable Plugin aka Compass):

class Topic {

  String name;
  static searchable = true;
}

class Question extends BaseEntity {
  String question;

  static searchable = true;
  static hasMany = [
      topics: Topic
  ]
}

How can I search Question with specific topic id?

Something like Question.search("topics#id:12") or Question.search("topics.id:12") dosnt work.

Body:
Chage your searchable block in Question so it looks like this:

static searchable = {
    topics component: true
}

and in Topic if you dont want Topics returned as root search elements

static searchable = [
    root: false
]

Fire up grails and add a few items, then download Luke from http://www.getopt.org/luke/
and open the index for your Question domain object which will be at ~/.grails/projects/projName/searchable-index/'env'/index/question

If you check the documents tab you will see the terms embedded in the index which will be something like $/Question/topics

This should give you the path to put in your Question.search, something like:

Question.search('$/Question/topics/id:1')