问:
How do I get disk space statistics for a clustered disk
I have a working program that retrieves information of disk such as FreeSpace, TotalSpace etc from a remote server. I have a problem however that i cannot get the same statistics for all Clustered Disks configured on the server. The query only returns information for the Local Disk (Logical Disk).

I am able to get sizes for Local Disk(:C) as below :

```<code>    public List<Disk> GetEnvironmentStatistics()
    {
        var serverIP = Convert.ToString(System.Web.HttpContext.Current.Session["ServerIP"]);

        List<Disk> diskinfo = new List<Disk>();

        //Add System.Management to access these utilities
        ConnectionOptions options = new ConnectionOptions
        {

            Username = Convert.ToString(System.Web.HttpContext.Current.Session["Username"]),
            Password = Convert.ToString(System.Web.HttpContext.Current.Session["Password"]),
            Authority = Convert.ToString(System.Web.HttpContext.Current.Session["Authority"]),
        };

        //root - root of the tree, cimv2 - version
        ManagementScope scope = new ManagementScope("\\\\" + serverIP + "\\root\\CIMV2", options);
        scope.Connect();

        SelectQuery query = new SelectQuery("Select * from Win32_LogicalDisk");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
        ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementObject mo in queryCollection)
            {
                Disk disk = new Disk();
                disk.DiskName = mo["Name"].ToString();
                disk.DeviceId = mo["DeviceID"].ToString();
                disk.SystemName = mo["SystemName"].ToString();

                disk.FreeSpace = Convert.ToDecimal(mo["FreeSpace"]);
                var formattedFreeSpace = Helpers.DiskSpaceInGigabytes(disk.FreeSpace ?? 0);
                disk.FreeSpace = Decimal.Truncate(formattedFreeSpace);

                disk.TotalSpace = Convert.ToDecimal(mo["Size"]);
                var formattedTotalSpace = Helpers.DiskSpaceInGigabytes(disk.TotalSpace ?? 0);
                disk.TotalSpace = Decimal.Truncate(formattedTotalSpace);

                disk.UsedSpace = disk.TotalSpace - disk.FreeSpace;

                var HDPercentageUsed = 100 - (100 * disk.FreeSpace / disk.TotalSpace);
                disk.PercentageUsed = Convert.ToInt32(HDPercentageUsed);
                diskinfo.Add(disk);
            }

        return diskinfo;
    }
</code>```

I have logged into the server and noted the other disks appear as Clustered Disk.

I have researched a bit about the Clustered Disks  or Cluster Shared Volumes but the only guides i see include Powershell Scripting like here : ClusteredSharedVolume Disk Space.

My question - how can i write a WMI query  that also retrieves information for Clustered Disks. Precisely  how i can adapt the query in the provided link for my needs :

```<code>    $resources = Get-WmiObject -namespace root\MSCluster MSCluster_Resource -filter "Type='Physical
    Disk'"
    $resources | foreach {
       $res = $_
        $disks = $res.GetRelated("MSCluster_Disk")
$disks | foreach {
    $_.GetRelated("MSCluster_DiskPartition") |
        select @{N="Name"; E={$res.Name}}, @{N="Status"; E={$res.State}}, Path, VolumeLabel, TotalSize, FreeSpace
}
    } | ft
</code>```

答:
The solution requires invoking Powershell script in C# :

1. Add System.Management.Automation Reference

This dll enable access to Powershell utilities. The packages available on Nuget seem ahead and are not being recognized so i had to manually add the Reference by References >> Add Reference >> Browse >> C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35

Using Powershell i can get disk information for all Clustered Disks by the command :

```<code>get-WmiObject win32_logicaldisk -Computername (ComputerName or IPAddress here)
</code>```

2. Invoke this command in code
I added an extension method that checks for whether the remote host has Clustered Disks (if any) . If it indeed has , then use the Powershell script , if not then use normal WMI query :

```<code>public List<Disk> GetEnvironmentStatistics()
    {

        List<Disk> diskinfo = new List<Disk>();

        var serverIP = Convert.ToString(System.Web.HttpContext.Current.Session["ServerIP"]);
        var clusterDisksStatus = CheckForClusteredDisks(serverIP);

        if (Helpers.HasClusteredDisks(clusterDisksStatus))
        {
            string getClusterSharedVolumesStatistics = "get-WmiObject win32_logicaldisk -Computername " + serverIP + "";
            PowerShell ps = PowerShell.Create();
            ps.AddScript(getClusterSharedVolumesStatistics);
            var results = ps.Invoke();

            foreach (var psobject in results)
            {

                if (psobject != null)
                {
                    Disk clusteredDisk = new Disk();
                    clusteredDisk.DiskName = Convert.ToString(psobject.Members["DeviceID"].Value);

                    clusteredDisk.FreeSpace = Convert.ToDecimal(psobject.Members["FreeSpace"].Value);
                    var formattedFreeSpace = Helpers.DiskSpaceInGigabytes(clusteredDisk.FreeSpace ?? 0);
                    clusteredDisk.FreeSpace = Decimal.Truncate(formattedFreeSpace);

                    clusteredDisk.TotalSpace = Convert.ToDecimal(psobject.Members["Size"].Value);
                    var formattedTotalSpace = Helpers.DiskSpaceInGigabytes(clusteredDisk.TotalSpace ?? 0);
                    clusteredDisk.TotalSpace = Decimal.Truncate(formattedTotalSpace);

                    clusteredDisk.UsedSpace = clusteredDisk.TotalSpace - clusteredDisk.FreeSpace;
                    clusteredDisk.VolumeName = Convert.ToString(psobject.Members["VolumeName"].Value);

                    diskinfo.Add(clusteredDisk);
                }

            }
        }

        else
        {

            //Add System.Management to access these utilities
            ConnectionOptions options = new ConnectionOptions
            {

                Username = Convert.ToString(System.Web.HttpContext.Current.Session["Username"]),
                Password = Convert.ToString(System.Web.HttpContext.Current.Session["Password"]),
                Authority = Convert.ToString(System.Web.HttpContext.Current.Session["Authority"]),
            };

            //root - root of the tree, cimv2 - version
            ManagementScope scope = new ManagementScope("\\\\" + serverIP + "\\root\\CIMV2", options);
            scope.Connect();

            SelectQuery query = new SelectQuery("Select * from Win32_LogicalDisk");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();

            try
            {

                foreach (ManagementObject mo in queryCollection)
                {

                    Disk disk = new Disk();
                    disk.DiskName = mo["Name"].ToString();
                    disk.DeviceId = mo["DeviceID"].ToString();
                    disk.SystemName = mo["SystemName"].ToString();

                    disk.FreeSpace = Convert.ToDecimal(mo["FreeSpace"]);
                    var formattedFreeSpace = Helpers.DiskSpaceInGigabytes(disk.FreeSpace ?? 0);
                    disk.FreeSpace = Decimal.Truncate(formattedFreeSpace);

                    disk.TotalSpace = Convert.ToDecimal(mo["Size"]);
                    var formattedTotalSpace = Helpers.DiskSpaceInGigabytes(disk.TotalSpace ?? 0);
                    disk.TotalSpace = Decimal.Truncate(formattedTotalSpace);

                    disk.UsedSpace = disk.TotalSpace - disk.FreeSpace;

                    var HDPercentageUsed = 100 - (100 * disk.FreeSpace / disk.TotalSpace);
                    disk.PercentageUsed = Convert.ToInt32(HDPercentageUsed);
                    diskinfo.Add(disk);
                }
            }

            catch (DivideByZeroException ex)
            {

                ExceptionLogger.SendErrorToText(ex);
            }

        }
        return diskinfo;
    }
</code>```

And the Helper method to check :

```<code> public static bool HasClusteredDisks(int status)
    {
        int hasClusteredDisks = 1;
        if (status == hasClusteredDisks)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
</code>```

Body:
I have a working program that retrieves information of disk such as FreeSpace, TotalSpace etc from a remote server. I have a problem however that i cannot get the same statistics for all Clustered Disks configured on the server. The query only returns information for the Local Disk (Logical Disk).

I am able to get sizes for Local Disk(:C) as below :

    public List<Disk> GetEnvironmentStatistics()
    {
        var serverIP = Convert.ToString(System.Web.HttpContext.Current.Session["ServerIP"]);

        List<Disk> diskinfo = new List<Disk>();

        //Add System.Management to access these utilities
        ConnectionOptions options = new ConnectionOptions
        {

            Username = Convert.ToString(System.Web.HttpContext.Current.Session["Username"]),
            Password = Convert.ToString(System.Web.HttpContext.Current.Session["Password"]),
            Authority = Convert.ToString(System.Web.HttpContext.Current.Session["Authority"]),
        };

        //root - root of the tree, cimv2 - version
        ManagementScope scope = new ManagementScope("\\\\" + serverIP + "\\root\\CIMV2", options);
        scope.Connect();

        SelectQuery query = new SelectQuery("Select * from Win32_LogicalDisk");
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
        ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementObject mo in queryCollection)
            {
                Disk disk = new Disk();
                disk.DiskName = mo["Name"].ToString();
                disk.DeviceId = mo["DeviceID"].ToString();
                disk.SystemName = mo["SystemName"].ToString();

                disk.FreeSpace = Convert.ToDecimal(mo["FreeSpace"]);
                var formattedFreeSpace = Helpers.DiskSpaceInGigabytes(disk.FreeSpace ?? 0);
                disk.FreeSpace = Decimal.Truncate(formattedFreeSpace);

                disk.TotalSpace = Convert.ToDecimal(mo["Size"]);
                var formattedTotalSpace = Helpers.DiskSpaceInGigabytes(disk.TotalSpace ?? 0);
                disk.TotalSpace = Decimal.Truncate(formattedTotalSpace);

                disk.UsedSpace = disk.TotalSpace - disk.FreeSpace;

                var HDPercentageUsed = 100 - (100 * disk.FreeSpace / disk.TotalSpace);
                disk.PercentageUsed = Convert.ToInt32(HDPercentageUsed);
                diskinfo.Add(disk);
            }

        return diskinfo;
    }

I have logged into the server and noted the other disks appear as Clustered Disk.

I have researched a bit about the Clustered Disks  or Cluster Shared Volumes but the only guides i see include Powershell Scripting like here : ClusteredSharedVolume Disk Space.

My question - how can i write a WMI query  that also retrieves information for Clustered Disks. Precisely  how i can adapt the query in the provided link for my needs :

    $resources = Get-WmiObject -namespace root\MSCluster MSCluster_Resource -filter "Type='Physical
    Disk'"
    $resources | foreach {
       $res = $_
        $disks = $res.GetRelated("MSCluster_Disk")
$disks | foreach {
    $_.GetRelated("MSCluster_DiskPartition") |
        select @{N="Name"; E={$res.Name}}, @{N="Status"; E={$res.State}}, Path, VolumeLabel, TotalSize, FreeSpace
}
    } | ft

Body:
The solution requires invoking Powershell script in C# :

1. Add System.Management.Automation Reference

This dll enable access to Powershell utilities. The packages available on Nuget seem ahead and are not being recognized so i had to manually add the Reference by References >> Add Reference >> Browse >> C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35

Using Powershell i can get disk information for all Clustered Disks by the command :

get-WmiObject win32_logicaldisk -Computername (ComputerName or IPAddress here)

2. Invoke this command in code
I added an extension method that checks for whether the remote host has Clustered Disks (if any) . If it indeed has , then use the Powershell script , if not then use normal WMI query :

public List<Disk> GetEnvironmentStatistics()
    {

        List<Disk> diskinfo = new List<Disk>();

        var serverIP = Convert.ToString(System.Web.HttpContext.Current.Session["ServerIP"]);
        var clusterDisksStatus = CheckForClusteredDisks(serverIP);

        if (Helpers.HasClusteredDisks(clusterDisksStatus))
        {
            string getClusterSharedVolumesStatistics = "get-WmiObject win32_logicaldisk -Computername " + serverIP + "";
            PowerShell ps = PowerShell.Create();
            ps.AddScript(getClusterSharedVolumesStatistics);
            var results = ps.Invoke();

            foreach (var psobject in results)
            {

                if (psobject != null)
                {
                    Disk clusteredDisk = new Disk();
                    clusteredDisk.DiskName = Convert.ToString(psobject.Members["DeviceID"].Value);

                    clusteredDisk.FreeSpace = Convert.ToDecimal(psobject.Members["FreeSpace"].Value);
                    var formattedFreeSpace = Helpers.DiskSpaceInGigabytes(clusteredDisk.FreeSpace ?? 0);
                    clusteredDisk.FreeSpace = Decimal.Truncate(formattedFreeSpace);

                    clusteredDisk.TotalSpace = Convert.ToDecimal(psobject.Members["Size"].Value);
                    var formattedTotalSpace = Helpers.DiskSpaceInGigabytes(clusteredDisk.TotalSpace ?? 0);
                    clusteredDisk.TotalSpace = Decimal.Truncate(formattedTotalSpace);

                    clusteredDisk.UsedSpace = clusteredDisk.TotalSpace - clusteredDisk.FreeSpace;
                    clusteredDisk.VolumeName = Convert.ToString(psobject.Members["VolumeName"].Value);

                    diskinfo.Add(clusteredDisk);
                }

            }
        }

        else
        {

            //Add System.Management to access these utilities
            ConnectionOptions options = new ConnectionOptions
            {

                Username = Convert.ToString(System.Web.HttpContext.Current.Session["Username"]),
                Password = Convert.ToString(System.Web.HttpContext.Current.Session["Password"]),
                Authority = Convert.ToString(System.Web.HttpContext.Current.Session["Authority"]),
            };

            //root - root of the tree, cimv2 - version
            ManagementScope scope = new ManagementScope("\\\\" + serverIP + "\\root\\CIMV2", options);
            scope.Connect();

            SelectQuery query = new SelectQuery("Select * from Win32_LogicalDisk");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
            ManagementObjectCollection queryCollection = searcher.Get();

            try
            {

                foreach (ManagementObject mo in queryCollection)
                {

                    Disk disk = new Disk();
                    disk.DiskName = mo["Name"].ToString();
                    disk.DeviceId = mo["DeviceID"].ToString();
                    disk.SystemName = mo["SystemName"].ToString();

                    disk.FreeSpace = Convert.ToDecimal(mo["FreeSpace"]);
                    var formattedFreeSpace = Helpers.DiskSpaceInGigabytes(disk.FreeSpace ?? 0);
                    disk.FreeSpace = Decimal.Truncate(formattedFreeSpace);

                    disk.TotalSpace = Convert.ToDecimal(mo["Size"]);
                    var formattedTotalSpace = Helpers.DiskSpaceInGigabytes(disk.TotalSpace ?? 0);
                    disk.TotalSpace = Decimal.Truncate(formattedTotalSpace);

                    disk.UsedSpace = disk.TotalSpace - disk.FreeSpace;

                    var HDPercentageUsed = 100 - (100 * disk.FreeSpace / disk.TotalSpace);
                    disk.PercentageUsed = Convert.ToInt32(HDPercentageUsed);
                    diskinfo.Add(disk);
                }
            }

            catch (DivideByZeroException ex)
            {

                ExceptionLogger.SendErrorToText(ex);
            }

        }
        return diskinfo;
    }

And the Helper method to check :

 public static bool HasClusteredDisks(int status)
    {
        int hasClusteredDisks = 1;
        if (status == hasClusteredDisks)
        {
            return true;
        }
        else
        {
            return false;
        }
    }


来源: stackexchange

问:
How do I split a string by a whitespace after a bracket and keep the bracket in the same line
I have an array of strings that look like the following:

```<code>const stringArray = [
    'string1[1] string2[2] string3[3] [4 5]',
    'string6[6] string7[7] string8[8] [9 10]'
];
</code>```

I want to be able to separate each string into four rows (in this case, because there are 4 columns). So the array would end up like:

```<code>const splittedArray = [
    [
        'string1[1]',
        'string2[2]',
        'string3[3]',
        '[4 5]'
    ],
    [
        'string6[6]',
        'string7[7]',
        'string8[8]',
        '[9 10]'
    ]
]
</code>```

I've been searching and trying regex even though I am not a fan of it as it is unreadable, but it does not seem to be working.

Whenever I try /(?=\])\s/g it does not separate the string, whenever I try /(?=\])\s*/ it separates the string and keeps both the ] and the whitespace, but does so in the next line (and well, keeps the whitespace).

I can't seem to find a way to do what I want, but perhaps I'm just miss understanding something. Perhaps there is a simpler way to do this. Splitting after the ] without needing to check for a space would be ideal but I would still have the problem of keeping the bracket and not splitting an extra time on that last ] hence why I'm trying this solution.

Here is a little code snipper with what I have and what it returns:

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/(?=\])\s/g));

console.log(splittedStringArray);

const anotherSplittedStringArray = stringArray.map(string => string.split(/(?=\])\s*/g));

console.log(anotherSplittedStringArray);

const splittedByBrackets = stringArray.map(string => string.split(/(?=\])/));

// The same as the previous one
console.log(splittedByBrackets);```

For my case, the answer was: /\w*\[.*?\]/g (with match instead of split) by Thomas. From what I understood:

The \w* matches any word (0 or more times)

The \[ matches the [ after a word (or no word, above condition)

The .*? matches any character excluding line breaks (0 or more times) lazyly, I believe the ? is to tell to stop matching on the first character(s) otherwise it would search the whole string.

The \] matches the ] after what is after the other bracket (which is the above condition).

The /g flag makes it so it searched for more than one occurrence.

答:
You could take a positive lookbehind for a closing bracket.

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/(?<=\])\s/g));

console.log(splittedStringArray);```

ContentLicense: CC BY-SA 4.0

Body:
I have an array of strings that look like the following:

const stringArray = [
    'string1[1] string2[2] string3[3] [4 5]',
    'string6[6] string7[7] string8[8] [9 10]'
];

I want to be able to separate each string into four rows (in this case, because there are 4 columns). So the array would end up like:

const splittedArray = [
    [
        'string1[1]',
        'string2[2]',
        'string3[3]',
        '[4 5]'
    ],
    [
        'string6[6]',
        'string7[7]',
        'string8[8]',
        '[9 10]'
    ]
]

I've been searching and trying regex even though I am not a fan of it as it is unreadable, but it does not seem to be working.

Whenever I try /(?=\])\s/g it does not separate the string, whenever I try /(?=\])\s*/ it separates the string and keeps both the ] and the whitespace, but does so in the next line (and well, keeps the whitespace).

I can't seem to find a way to do what I want, but perhaps I'm just miss understanding something. Perhaps there is a simpler way to do this. Splitting after the ] without needing to check for a space would be ideal but I would still have the problem of keeping the bracket and not splitting an extra time on that last ] hence why I'm trying this solution.

Here is a little code snipper with what I have and what it returns:

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/(?=\])\s/g));

console.log(splittedStringArray);

const anotherSplittedStringArray = stringArray.map(string => string.split(/(?=\])\s*/g));

console.log(anotherSplittedStringArray);

const splittedByBrackets = stringArray.map(string => string.split(/(?=\])/));

// The same as the previous one
console.log(splittedByBrackets);

For my case, the answer was: /\w*\[.*?\]/g (with match instead of split) by Thomas. From what I understood:

The \w* matches any word (0 or more times)

The \[ matches the [ after a word (or no word, above condition)

The .*? matches any character excluding line breaks (0 or more times) lazyly, I believe the ? is to tell to stop matching on the first character(s) otherwise it would search the whole string.

The \] matches the ] after what is after the other bracket (which is the above condition).

The /g flag makes it so it searched for more than one occurrence.


问:
Can I add [FromBody] parameter with backward compatibility?
I have endpoint which doesn't have [FromBody] parameter:

```<code>    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish()
    {
        <do some stuff>
        return Ok();
    }
</code>```

But now I need to add [FromBody] parameter in the way that old code is still able to use this endpoint without parameter:

```<code>    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish([FromBody] PublishRequest request)
    {
        <do some stuff>
        return Ok();
    }
</code>```

But if I add it in this way and try to call this endpoint with empty body, i got 415 (Unsupported Media Type) response back.

I want to make this change backward compatible. So it should be possible to use this endpoint without request body and content-type header. Is is possible?

答:
It seems that optional FromBody parameters are not supported ATM, but in this github issue was posted a possible workaround:

```<code>public class SomeClassModelBinder : IModelBinder
{
    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var stream = bindingContext.HttpContext.Request.Body;
        string body;
        using (var reader = new StreamReader(stream))
        {
            body = await reader.ReadToEndAsync();
        }
        var someClass = JsonConvert.DeserializeObject<SomeClass>(body);

        bindingContext.Result = ModelBindingResult.Success(someClass);
    }
}

[FromBody, ModelBinder(BinderType = typeof(SomeClassModelBinder))] SomeClass request,
</code>```

Body:
I have endpoint which doesn't have [FromBody] parameter:

    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish()
    {
        <do some stuff>
        return Ok();
    }

But now I need to add [FromBody] parameter in the way that old code is still able to use this endpoint without parameter:

    [HttpPost("{id:int}/publish")]
    public async Task<IActionResult> Publish([FromBody] PublishRequest request)
    {
        <do some stuff>
        return Ok();
    }

But if I add it in this way and try to call this endpoint with empty body, i got 415 (Unsupported Media Type) response back.

I want to make this change backward compatible. So it should be possible to use this endpoint without request body and content-type header. Is is possible?

Body:
It seems that optional FromBody parameters are not supported ATM, but in this github issue was posted a possible workaround:

public class SomeClassModelBinder : IModelBinder
{
    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var stream = bindingContext.HttpContext.Request.Body;
        string body;
        using (var reader = new StreamReader(stream))
        {
            body = await reader.ReadToEndAsync();
        }
        var someClass = JsonConvert.DeserializeObject<SomeClass>(body);

        bindingContext.Result = ModelBindingResult.Success(someClass);
    }
}

[FromBody, ModelBinder(BinderType = typeof(SomeClassModelBinder))] SomeClass request,


问:
CompareValidator does not allow thousands separator - is this a bug or by design?
Minimal, Complete, and Verifiable example (Framework 3.5):

```<code><%@ Page Language="C#" Culture="en-US" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="txt" runat="server" />
        <asp:CompareValidator runat="server" ControlToValidate="txt" Operator="DataTypeCheck" Type="Double" Text="This is not a double." />
        <asp:Button runat="server" Text="Do Postback" />
    </form>
</body>
</html>
</code>```

Enter 1,234.0 in the text box and hit TAB.

Expected result: Nothing.

Actual result: This is not a double.

Why do I expect the comparison to succeed: Because the documentation says: "Validation fails if the value cannot be converted to the specified data type.", but Convert.ToDouble("1,234.0", CultureInfo.GetCultureInfo("en-US")) succeeds.

My question:

Is this a bug (which I should report to Microsoft Connect) or did I miss some part of the documentation where it says that CompareValidator uses different conversion rules than the remainder of the .NET framework?

答:
Is this a bug (which I should report to Microsoft Connect) or did I miss some part of the documentation where it says that CompareValidator uses different conversion rules than the remainder of the .NET framework?

Neither. I assume that this is a deliberate, but underdocumented feature.

Why do I assume that? Because of the reference source of BaseCompareValidator.Convert: Type="Integer" validations are performed by simply trying Int32.Parse, but double validations explicitly match against some regular expression, which includes the decimal separator but not the thousands separator. Something similar is done for validating decimals (but including the thousands separator, or, more precisely, the "group separator"). So, it's apparently not an oversight (since they explicitly allowed the thousands separator for currency values).

Why did they do all that extra work instead of just checking for the result of double.TryParse? I can only speculate, by the following reasons would make sense:

CompareValidator has been around since .NET 1, but, if I recall correctly, TryParse was added only later. Maybe they wanted to avoid the overhead of calling Parse and catching the exception.

For a developer, it's obvious that 1e10 and NaN are valid doubles, but not to most end-users. Thus, it makes sense to exclude them.

That still does not explain why they deliberately avoided the thousands separator, but, from the limited information available, this is the best I could get...

ContentLicense: CC BY-SA 3.0

Body:
Minimal, Complete, and Verifiable example (Framework 3.5):

<%@ Page Language="C#" Culture="en-US" %>

<!DOCTYPE html>

    <form id="form1" runat="server">
        <asp:TextBox ID="txt" runat="server" />
        <asp:CompareValidator runat="server" ControlToValidate="txt" Operator="DataTypeCheck" Type="Double" Text="This is not a double." />
        <asp:Button runat="server" Text="Do Postback" />
    </form>

Enter 1,234.0 in the text box and hit TAB.

Expected result: Nothing.

Actual result: This is not a double.

Why do I expect the comparison to succeed: Because the documentation says: "Validation fails if the value cannot be converted to the specified data type.", but Convert.ToDouble("1,234.0", CultureInfo.GetCultureInfo("en-US")) succeeds.

My question:

Is this a bug (which I should report to Microsoft Connect) or did I miss some part of the documentation where it says that CompareValidator uses different conversion rules than the remainder of the .NET framework?


问:
how to handle alerts in android using appium
How do I handle alerts in an Android web application using Appium server (1.0.1) and the Android SDK?

The below code is not working on android:

```<code>driver.switchTo().accept().alert();
</code>```

Error message:

```<code>> -modal window does not get closed
</code>```

答:
// first check alert is present or not

```<code>public boolean isAlertPresent() {
    try {
        mobDriver.switchTo().alert();
        log.info("ALERT IS PRESENT !! ");
        return true;
    } catch (Exception e) {
        log.info("ALERT IS NOT PRESENT !! ");
        return false;
    }
}

public void mobileAlertHandle() {
    if (isAlertPresent()) {
        Alert alert = mobDriver.switchTo().alert();
        alert.accept();
   }
}
</code>```

if this does not work then inspect your element and try with id or name

ex: mobDriver.findElementById("android:id/button2").click()

Body:
How do I handle alerts in an Android web application using Appium server (1.0.1) and the Android SDK?

The below code is not working on android:

driver.switchTo().accept().alert();

Error message:

> -modal window does not get closed

Body:
// first check alert is present or not

public boolean isAlertPresent() {
    try {
        mobDriver.switchTo().alert();
        log.info("ALERT IS PRESENT !! ");
        return true;
    } catch (Exception e) {
        log.info("ALERT IS NOT PRESENT !! ");
        return false;
    }
}

public void mobileAlertHandle() {
    if (isAlertPresent()) {
        Alert alert = mobDriver.switchTo().alert();
        alert.accept();
   }
}

if this does not work then inspect your element and try with id or name

ex: mobDriver.findElementById("android:id/button2").click()


问:
How to view a simple create-react-app component offline?
Specifically, I have a very simple calculator component. No databases involved, just simple computations done client-side.

I want to use this component on an old laptop that cannot connect to the internet.

What is the best way to go about this?

答: React doesnt require internet if database is not used. Just build project, and send index.html to any device you want</p>


问:
Postgresql : "OR" does'nt work like I want
I've got some problem with my request :

This request work :

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac
WHERE o.id_organisation = a.id_organisation
AND ac.id_organisation = o.id_organisation
AND ac.id_device = :idd ;
</code>```

This request work :

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Louer l
WHERE o.id_organisation = a.id_organisation
AND l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE;
</code>```

But when I put an "OR" between the both requests, it doesn't work :

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac, Louer l

WHERE o.id_organisation = a.id_organisation

AND (ac.id_organisation = o.id_organisation
AND ac.id_device = :idd)

OR (l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE);
</code>```

I've tried to put parentheses, but the request still doesn't work.

Do you have any idea ?

答:
I think you intend:

```<code>SELECT o.nom, a.url, a.apikey
FROM Organisation o JOIN
     API a
     ON o.id_organisation = a.id_organisation
WHERE EXISTS (SELECT 1
              FROM Acheter ac
              WHERE ac.id_organisation = o.id_organisation AND
                    ac.id_device = :idd
             ) OR
      EXISTS (SELECT 1
              FROM louer l
              WHERE l.id_device = :idd AND
                    l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE
            );
</code>```

Note the use of proper, explicit, standard, readable JOIN syntax.  Never use commas in the FROM clause.

Body:
I've got some problem with my request :

This request work :

SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac
WHERE o.id_organisation = a.id_organisation
AND ac.id_organisation = o.id_organisation
AND ac.id_device = :idd ;

This request work :

SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Louer l
WHERE o.id_organisation = a.id_organisation
AND l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE;

But when I put an "OR" between the both requests, it doesn't work :

SELECT o.nom, a.url, a.apikey
FROM Organisation o, API a, Acheter ac, Louer l

WHERE o.id_organisation = a.id_organisation

AND (ac.id_organisation = o.id_organisation
AND ac.id_device = :idd)

OR (l.id_organisation = o.id_organisation
AND l.id_device = :idd
AND l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE);

I've tried to put parentheses, but the request still doesn't work.

Do you have any idea ?

Body:
I think you intend:

SELECT o.nom, a.url, a.apikey
FROM Organisation o JOIN
     API a
     ON o.id_organisation = a.id_organisation
WHERE EXISTS (SELECT 1
              FROM Acheter ac
              WHERE ac.id_organisation = o.id_organisation AND
                    ac.id_device = :idd
             ) OR
      EXISTS (SELECT 1
              FROM louer l
              WHERE l.id_device = :idd AND
                    l.dateLocation + l.dureeLocation * interval '1 day' < CURRENT_DATE
            );

Note the use of proper, explicit, standard, readable JOIN syntax.  Never use commas in the FROM clause.


问:
Can Pandas DataFrame.sort_index() performance be improved on sorted data?
Is there any way to improve the performance of DataFrame.sort_index() when the data is already sorted by the columns that are used for the index? On a dataset with 40 mio records, sort_index() takes 3.25 mins for me, independent on whether the data is sorted already or not.

If there is no intended way high level way to do it, is there maybe a low level way of changing the DataFrame state to sorted by index without actually sorting it?

答:
If I understood you correctly, you can verify that the index is sorted prior to actually sorting it with DataFrame.index.is_monotonic_increasing, which should be faster. So you could do something like:

```<code>if not df.index.is_monotonic_increasing:
    df = df.sort_index()
</code>```

Body:
If I understood you correctly, you can verify that the index is sorted prior to actually sorting it with DataFrame.index.is_monotonic_increasing, which should be faster. So you could do something like:

if not df.index.is_monotonic_increasing:
    df = df.sort_index()


问:
Problem while initializing the repo [Errno 13] Permission denied
I have a problem. I tried initial repo (https://github.com/AOSPA/manifest -b quartz), but I can't because I have a error:

Traceback (most recent call last):
  File "/home/wojciech/WORKSPACE/.repo/repo/main.py", line 49, in
    import event_log
  File "/home/wojciech/WORKSPACE/.repo/repo/event_log.py", line 167, in
    _EVENT_ID = multiprocessing.Value('i', 1)
  File "/snap/git-repo/18/usr/lib/python2.7/multiprocessing/init.py", line 253, in Value
    return Value(typecode_or_type, *args, **kwds)
  File "/snap/git-repo/18/usr/lib/python2.7/multiprocessing/sharedctypes.py", line 108, in Value
    lock = RLock()
  File "/snap/git-repo/18/usr/lib/python2.7/multiprocessing/init.py", line 183, in RLock
    return RLock()
  File "/snap/git-repo/18/usr/lib/python2.7/multiprocessing/synchronize.py", line 172, in init
    SemLock.init(self, RECURSIVE_MUTEX, 1, 1)
  File "/snap/git-repo/18/usr/lib/python2.7/multiprocessing/synchronize.py", line 75, in init
    sl = self._semlock = _multiprocessing.SemLock(kind, value, maxvalue)
OSError: [Errno 13] Permission denied

Thanks for help

答:
To be honest, most of my "permission denied" errors are resolved by running cmd as administrator. Try right click on cmd and choose "Run as administrator". If you're trying to create repo through IDE, try running it as administrator as well :)

On Linux, as you are on, add sudo  at the start of the command.


问:
R shiny conditionPanel same filter on multiple pages
I'm building an R shiny app with some filters that I want to apply on different pages and I want some of these filters to create extra inputs. I've been using conditionalPanel to show/hide the extra inputs but I'm having a problem with hiding the extra inputs when you go onto a different page.

In the example below if you select an age range, this age range is selected on all pages. If you select 60+ you get an additional input for gender and when you select a gender and change page this is applied on all the other pages. But, if you then select a different age range on a different page the gender conditionalPanel isn't hidden until you click on a different page. If I change the || to && in the condition statement it solves the problem I get another problem where the conditional panel doesn't show until you click on a different page.

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)

agePanelUI <- function(id) {
  ns <- NS(id)

  fluidRow(
    column(width = 9,
           uiOutput(ns("select_age")))
  )
}

agePanel <- function(input, output, session, x) {
  output$select_age <- renderUI({
    input$resetInput
    radioGroupButtons(
      inputId = paste0(x, "age_choice"),
      choices = c('0-18', '19-34', "35-59", "60+"),
      selected =  '0-18')
  })
}

filterPanelUI <- function(id) {
  ns <- NS(id)
  fluidRow(
    column(width = 9,
           uiOutput(ns('select_gender'))))
}

filterPanel <- function(input, output, session, x) {
  output$select_gender <- renderUI({
    input$resetInput
    pickerInput(
      inputId = paste0(x, "gender_choice"),
      choices = c('F', 'M'),
      options = list(`actions-box` = TRUE,`selected-text-format` = "count > 3"),
      multiple = TRUE
    )
  })
}

ui <- dashboardPage(

  header = dashboardHeader(
    title = "testing",
    titleWidth = 250),

  dashboardSidebar(

    width = 250,
    sidebarMenu(
      id = "menu",
      menuItem("Information", tabName = "info"),
      menuItem("page 1", tabName = "page1"),
      menuItem("page 2", tabName = "page2"),
      menuItem("page 3", tabName = "page3"))),
  dashboardBody(
    tabItems(tabItem("info"),
    tabItem(tabName = "page1",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_11"),

                conditionalPanel(
                  condition = "input.first_age_choice == '60+' || input.second_age_choice == '60+' || input.third_age_choice == '60+'",
                  filterPanelUI(id = "id_1")))),
    tabItem(tabName = "page2",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_12"),

                conditionalPanel(
                  condition = "input.first_age_choice == '60+' || input.second_age_choice == '60+' || input.third_age_choice == '60+'",
                  filterPanelUI(id = "id_2"))
            )),
    tabItem(tabName = "page3",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_13"),

                conditionalPanel(
                  condition = "input.first_age_choice == '60+' || input.second_age_choice == '60+' || input.third_age_choice == '60+'",
                  filterPanelUI(id = "id_3"))
            )))))

server <- function(input, output, session) {

  callModule(module = filterPanel, id = "id_1", x = "first_")
  callModule(module = filterPanel, id = "id_2", x = "second_")
  callModule(module = filterPanel, id = "id_3", x = "third_")

  callModule(module = agePanel, id = "id_11", x = "first_")
  callModule(module = agePanel, id = "id_12", x = "second_")
  callModule(module = agePanel, id = "id_13", x = "third_")

  tab_select <- reactiveValues()

  observe({
    if (input$menu == "page1") {
      tab_select$gender <- input$first_gender_choice
      tab_select$age <- input$first_age_choice
    } else if(input$menu == "page2") {
      tab_select$gender <- input$second_gender_choice
      tab_select$age <- input$second_age_choice
    } else if(input$menu == "page3") {
      tab_select$gender <- input$third_gender_choice
      tab_select$age <- input$third_age_choice
    }
  })

  observeEvent(input$menu, {
    updatePickerInput(session, inputId = "first_gender_choice", selected = tab_select$gender)
    updatePickerInput(session, inputId = "second_gender_choice", selected = tab_select$gender)
    updatePickerInput(session, inputId = "third_gender_choice", selected = tab_select$gender)
    updateRadioGroupButtons(session, inputId = "first_age_choice", selected = tab_select$age)
    updateRadioGroupButtons(session, inputId = "second_age_choice", selected = tab_select$age)
    updateRadioGroupButtons(session, inputId = "third_age_choice", selected = tab_select$age)
  })
}

shinyApp(ui, server)

</code>```

答:
I managed to work this out with a bit more logic in the conditionPanel condition:</p>

```<code>tabItem(tabName = "page1",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_11"),

                conditionalPanel(
                  condition = "(input.menu == 'page1' && input.first_age_choice == '60+') || (input.menu != 'page1' && (input.second_age_choice == '60+' || input.third_age_choice == '60+'))",
                  filterPanelUI(id = "id_1")))),
    tabItem(tabName = "page2",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_12"),

                conditionalPanel(
                  condition = "(input.menu == 'page2' && input.second_age_choice == '60+') || (input.menu != 'page2' && (input.first_age_choice == '60+' || input.third_age_choice == '60+'))",
                  filterPanelUI(id = "id_2"))
            )),
    tabItem(tabName = "page3",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_13"),

                conditionalPanel(
                  condition = "(input.menu == 'page3' && input.third_age_choice == '60+') || (input.menu != 'page3' && (input.second_age_choice == '60+' || input.first_age_choice == '60+'))",
                  filterPanelUI(id = "id_3"))
            )))))
</code>```

Body:
I'm building an R shiny app with some filters that I want to apply on different pages and I want some of these filters to create extra inputs. I've been using conditionalPanel to show/hide the extra inputs but I'm having a problem with hiding the extra inputs when you go onto a different page.

In the example below if you select an age range, this age range is selected on all pages. If you select 60+ you get an additional input for gender and when you select a gender and change page this is applied on all the other pages. But, if you then select a different age range on a different page the gender conditionalPanel isn't hidden until you click on a different page. If I change the || to && in the condition statement it solves the problem I get another problem where the conditional panel doesn't show until you click on a different page.

library(shiny)
library(shinydashboard)
library(shinyWidgets)

agePanelUI <- function(id) {
  ns <- NS(id)

  fluidRow(
    column(width = 9,
           uiOutput(ns("select_age")))
  )
}

agePanel <- function(input, output, session, x) {
  output$select_age <- renderUI({
    input$resetInput
    radioGroupButtons(
      inputId = paste0(x, "age_choice"),
      choices = c('0-18', '19-34', "35-59", "60+"),
      selected =  '0-18')
  })
}

filterPanelUI <- function(id) {
  ns <- NS(id)
  fluidRow(
    column(width = 9,
           uiOutput(ns('select_gender'))))
}

filterPanel <- function(input, output, session, x) {
  output$select_gender <- renderUI({
    input$resetInput
    pickerInput(
      inputId = paste0(x, "gender_choice"),
      choices = c('F', 'M'),
      options = list(`actions-box` = TRUE,`selected-text-format` = "count > 3"),
      multiple = TRUE
    )
  })
}

ui <- dashboardPage(

  header = dashboardHeader(
    title = "testing",
    titleWidth = 250),

  dashboardSidebar(

    width = 250,
    sidebarMenu(
      id = "menu",
      menuItem("Information", tabName = "info"),
      menuItem("page 1", tabName = "page1"),
      menuItem("page 2", tabName = "page2"),
      menuItem("page 3", tabName = "page3"))),
  dashboardBody(
    tabItems(tabItem("info"),
    tabItem(tabName = "page1",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_11"),

                conditionalPanel(
                  condition = "input.first_age_choice == '60+' || input.second_age_choice == '60+' || input.third_age_choice == '60+'",
                  filterPanelUI(id = "id_1")))),
    tabItem(tabName = "page2",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_12"),

                conditionalPanel(
                  condition = "input.first_age_choice == '60+' || input.second_age_choice == '60+' || input.third_age_choice == '60+'",
                  filterPanelUI(id = "id_2"))
            )),
    tabItem(tabName = "page3",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_13"),

                conditionalPanel(
                  condition = "input.first_age_choice == '60+' || input.second_age_choice == '60+' || input.third_age_choice == '60+'",
                  filterPanelUI(id = "id_3"))
            )))))

server <- function(input, output, session) {

  callModule(module = filterPanel, id = "id_1", x = "first_")
  callModule(module = filterPanel, id = "id_2", x = "second_")
  callModule(module = filterPanel, id = "id_3", x = "third_")

  callModule(module = agePanel, id = "id_11", x = "first_")
  callModule(module = agePanel, id = "id_12", x = "second_")
  callModule(module = agePanel, id = "id_13", x = "third_")

  tab_select <- reactiveValues()

  observe({
    if (input$menu == "page1") {
      tab_select$gender <- input$first_gender_choice
      tab_select$age <- input$first_age_choice
    } else if(input$menu == "page2") {
      tab_select$gender <- input$second_gender_choice
      tab_select$age <- input$second_age_choice
    } else if(input$menu == "page3") {
      tab_select$gender <- input$third_gender_choice
      tab_select$age <- input$third_age_choice
    }
  })

  observeEvent(input$menu, {
    updatePickerInput(session, inputId = "first_gender_choice", selected = tab_select$gender)
    updatePickerInput(session, inputId = "second_gender_choice", selected = tab_select$gender)
    updatePickerInput(session, inputId = "third_gender_choice", selected = tab_select$gender)
    updateRadioGroupButtons(session, inputId = "first_age_choice", selected = tab_select$age)
    updateRadioGroupButtons(session, inputId = "second_age_choice", selected = tab_select$age)
    updateRadioGroupButtons(session, inputId = "third_age_choice", selected = tab_select$age)
  })
}

shinyApp(ui, server)

Body:
I managed to work this out with a bit more logic in the conditionPanel condition:

tabItem(tabName = "page1",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_11"),

                conditionalPanel(
                  condition = "(input.menu == 'page1' && input.first_age_choice == '60+') || (input.menu != 'page1' && (input.second_age_choice == '60+' || input.third_age_choice == '60+'))",
                  filterPanelUI(id = "id_1")))),
    tabItem(tabName = "page2",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_12"),

                conditionalPanel(
                  condition = "(input.menu == 'page2' && input.second_age_choice == '60+') || (input.menu != 'page2' && (input.first_age_choice == '60+' || input.third_age_choice == '60+'))",
                  filterPanelUI(id = "id_2"))
            )),
    tabItem(tabName = "page3",
            box(width = 12, status = "primary", solidHeader = TRUE,
                fluidRow(
                  column(width = 9, h4("Selection"))),

                agePanelUI(id = "id_13"),

                conditionalPanel(
                  condition = "(input.menu == 'page3' && input.third_age_choice == '60+') || (input.menu != 'page3' && (input.second_age_choice == '60+' || input.first_age_choice == '60+'))",
                  filterPanelUI(id = "id_3"))
            )))))


问:
Create multiple y axis chart epplus c#
I want to have the following multi y-axis chart while exporting to excel:

I tried some examples from the internet but no luck.
I am using the following code for the this:

```<code>ExcelChart chart = workSheet.Drawings.AddChart("chtLine", eChartType.LineMarkers);
var serie1 = chart.Series.Add(workSheet.Cells["D2:D7"], workSheet.Cells["A2:A7"]);
var chartType2 = chart.PlotArea.ChartTypes.Add(eChartType.ColumnClustered);
var serie2 = chartType2.Series.Add(workSheet.Cells["B2:B7"], workSheet.Cells["A2:A7"]);

chart.SetPosition(0, 0, 8, 0);
chart.SetSize(500, 300);
</code>```

But this code is creating a single y-axis only.
Please help me on this.

答:
It get resolved.
I simply added the following line of code:</p>

```<code>chart.UseSecondaryAxis = true;
</code>```

Title: Create multiple y axis chart epplus c#

Body:
I want to have the following multi y-axis chart while exporting to excel:

I tried some examples from the internet but no luck.
I am using the following code for the this:

ExcelChart chart = workSheet.Drawings.AddChart("chtLine", eChartType.LineMarkers);
var serie1 = chart.Series.Add(workSheet.Cells["D2:D7"], workSheet.Cells["A2:A7"]);
var chartType2 = chart.PlotArea.ChartTypes.Add(eChartType.ColumnClustered);
var serie2 = chartType2.Series.Add(workSheet.Cells["B2:B7"], workSheet.Cells["A2:A7"]);

chart.SetPosition(0, 0, 8, 0);
chart.SetSize(500, 300);

But this code is creating a single y-axis only.
Please help me on this.

Body:
It get resolved.
I simply added the following line of code:

chart.UseSecondaryAxis = true;


问:
Email verification without having a FirebaseUser
I'm trying to send a verification email without having a firebaseUser, is it possible ?
I know i can do it with user.sendEmailVerification() method but can i do it just by giving an email from a textfield ?</p>

答:
Based on what I knew and what I've read from the documentation, it looks like it's not possible to do this. A Firebase user, a.k.a an user authenticated within Firebase platform is required if you want to send email verification that uses Firebase Email Vetification service.

Well, do not lose hope since there are plenty workarounds to do this. What I would do to achieve this is to use Firebase Cloud Functions to create serverless API platform. I connect Firebase Cloud Functions with Firebase Admin SDK (which also has access to other Firebase services if I am not mistaken).

I send an email using some kind of email service providers such as SendGrid to designated email address (which the app got from user's inputted email) and provide a link to verify there (in the e-mail that sent to designated email address). Then, in the cloud functions, you leverage Firebase Admin SDK to change verification status.

This approach is flexible though, as it can be used to verify a user not only with Firebase Authentication.

Hope it helps. If it's not clear for you, just comment.
Happy coding.

EDIT: After thoroughly read your question again, I realized that my answer is not fully correct. Somehow you still need a specific user to be added within Firebase Authentication database, which you would not want to do manually and let your app do so instead. Perhaps you can use Firebase Admin SDK in this matter. You can read official Firebase documentation for more information regarding Admin SDK.


问:
dicionary filled with dataframes restructuring
I am trying to restructure a dictionary which is filled with multiple dataframes. I have found a solution, but as I am new to Python, it is a rather primitive one. Because my solution is very slow when I increase the number of dataframes inside my dictionary, I wanted to ask if anyone know how to improve my existing code or knows an alternative solution:

I have a dictionary which is made up of three df's with info about a country. To give an example:

```<code># example dictionary filled with dataframes
import pandas as pd
import numpy as np

dic_old={}

countries = ['USA', 'China', 'India']
col = ['factor 1','factor 2','factor 3']
ind = pd.DatetimeIndex(start ='2019-01-10', freq ='m',  periods = 5)

df1=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)
df2=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)
df3=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)

dic_old['USA']=df1
dic_old['China']=df2
dic_old['India']=df3
</code>```

Now I would like to restructure this dictionary. Instead of having 3 dataframes with the information of each separate country, I would now like to have a dataframe for each date with the info of all countries. So my dictionary would change from 3 dataframes with 5 rows à 3 columns, to a new dictionary with 5 dataframes and 3 rows à 3 columns. I managed to do this with the following code:

```<code>dates = ind.tolist()
factors = dic_old['USA'].columns
dic_new = {}

# Create empty dataframes with desired column headers and index
for d in dates:
    dic_new[d.strftime('%Y-%m')] = pd.DataFrame(index=countries, columns = factors) #

# fill empty dataframes with info from dic_old
for y in dates:
    for e in countries:
        dic_new[y.strftime('%Y-%m')].loc[e] = dic_old[e].loc[y]
</code>```

Now if I increase the number of dataframes (lets say I add more countries and more dates), then my piece of code becomes very slow. This is probably no surprise considering that I use 3 for loops which are known to be rather slow. Does anyone know how I could make my code run faster or does anyone see an alternative to solving my problem?

thanks in advance, any help appreciated

答:
I think you should change the design of your program.
Why not having only one DataFrame instead?

Take a look to the append method (docs) or the concat method (docs).

If you want to replicate data fast, use merge method (docs) with two dataframes (i.e. dates and factors) using a dummy key (i.e. df["key"]=0) to perform a cartesian product.

Body:
I am trying to restructure a dictionary which is filled with multiple dataframes. I have found a solution, but as I am new to Python, it is a rather primitive one. Because my solution is very slow when I increase the number of dataframes inside my dictionary, I wanted to ask if anyone know how to improve my existing code or knows an alternative solution:

I have a dictionary which is made up of three df's with info about a country. To give an example:

# example dictionary filled with dataframes
import pandas as pd
import numpy as np

dic_old={}

countries = ['USA', 'China', 'India']
col = ['factor 1','factor 2','factor 3']
ind = pd.DatetimeIndex(start ='2019-01-10', freq ='m',  periods = 5)

df1=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)
df2=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)
df3=pd.DataFrame(np.random.rand(5,3),columns=col, index = ind)

dic_old['USA']=df1
dic_old['China']=df2
dic_old['India']=df3

Now I would like to restructure this dictionary. Instead of having 3 dataframes with the information of each separate country, I would now like to have a dataframe for each date with the info of all countries. So my dictionary would change from 3 dataframes with 5 rows à 3 columns, to a new dictionary with 5 dataframes and 3 rows à 3 columns. I managed to do this with the following code:

dates = ind.tolist()
factors = dic_old['USA'].columns
dic_new = {}

# Create empty dataframes with desired column headers and index
for d in dates:
    dic_new[d.strftime('%Y-%m')] = pd.DataFrame(index=countries, columns = factors) #

# fill empty dataframes with info from dic_old
for y in dates:
    for e in countries:
        dic_new[y.strftime('%Y-%m')].loc[e] = dic_old[e].loc[y]

Now if I increase the number of dataframes (lets say I add more countries and more dates), then my piece of code becomes very slow. This is probably no surprise considering that I use 3 for loops which are known to be rather slow. Does anyone know how I could make my code run faster or does anyone see an alternative to solving my problem?

thanks in advance, any help appreciated


问:
C++ for loop too slow
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

```<code>static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}
</code>```

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.

答: Probably the code that capture a new frame is called after patestCallback ends, if you aren't able to meet your deadlines it means your CPU isn't powerful enough (=processing is too complex). This is not an explanation (of why) but a solutions that should work if you would have had more than one Core in your CPU (sometimes it works even if you have one Core), you could create a thread that process the audio, the callback should only copy (or change a pointer) to audio to be processed, which enables your main thread (audio capturing thread) to not wait too long.</p>

Title: C++ for loop too slow

Body:
I'm trying to make an audio application with PortAudio. My callback function has been very slow and it has been creating constant underruns. I removed everything in the callback one by one until I found the issue: the for loop. I removed everything so that the only thing happening in the callback function is the for loop and it is still causing underruns. I know it is the for loop because when I reduce the number of iterations, the underruns go away.

static int patestCallback(const void *inputBuffer, void *outputBuffer,
                      unsigned long framesPerBuffer,
                      const PaStreamCallbackTimeInfo *timeInfo,
                      PaStreamCallbackFlags statusFlags, void *userData)
{
    int x = 0;
    for (int jj = 0; jj < 10000; jj++)
    {
        x++; // for testing, not actually used
    };
    return paContinue;
}

Here is my full code for testing: https://gist.github.com/johnroper100/b87641f5609dbb49bc3c1121b1f4daf1

Not really necessary for this question, but I did the same callback in the python equivalent (sounddevice) and there are no issues.


问:
how to read the response from a web site?
I have a website url which gives corresponding city names by taking zip code as input parameter. Now I want to know how to read the response from the site.

This is the link I am using http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680

答:
The simplest way it to use the light-weight WebClient classes in System.Net namespace. The following example code will just download the entire response as a string:

```<code>using (WebClient wc = new WebClient())
{
   string response = wc.DownloadString("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680");
}
</code>```

However, if you require more control over the response and request process then you can use the more heavy-weight HttpWebRequest Class. For instance, you may want to deal with different status codes or headers. There's an example of using HttpWebRequest this in the article How to use HttpWebRequest and HttpWebResponse in .NET on CodeProject.

Body:
The simplest way it to use the light-weight WebClient classes in System.Net namespace. The following example code will just download the entire response as a string:

using (WebClient wc = new WebClient())
{
   string response = wc.DownloadString("http://zipinfo.com/cgi-local/zipsrch.exe?zip=60680");
}

However, if you require more control over the response and request process then you can use the more heavy-weight HttpWebRequest Class. For instance, you may want to deal with different status codes or headers. There's an example of using HttpWebRequest this in the article How to use HttpWebRequest and HttpWebResponse in .NET on CodeProject.


问:
How add button in label?
I need to add a button at the end of the text to trigger an alert. The text can be in several lines  How can I do that?

it should look like this

答:
You can use NSTextAttachment to add image at the end of text.

```<code>let fullString = NSMutableAttributedString(string: "Text")

// Create our NSTextAttachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "awesomeIcon.png")

// Wrap the attachment in its own attributed string so we can append it
let imageString = NSAttributedString(attachment: imageAttachment)

// Add the NSTextAttachment
fullString.append(imageString)

// Draw the result in a label
yourLabel.attributedText = fullString
</code>```

and then add UITapGestureRecognizer to trigger action after tap.

```<code>let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(showAlert(tapGesture:)))
yourLabel.addGestureRecognizer(tapGesture)

@objc func showAlert(tapGesture: UITapGestureRecognizer){
    // Show alert
}
</code>```

Title: How add button in label?

Body:
You can use NSTextAttachment to add image at the end of text.

let fullString = NSMutableAttributedString(string: "Text")

// Create our NSTextAttachment
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(named: "awesomeIcon.png")

// Wrap the attachment in its own attributed string so we can append it
let imageString = NSAttributedString(attachment: imageAttachment)

// Add the NSTextAttachment
fullString.append(imageString)

// Draw the result in a label
yourLabel.attributedText = fullString

and then add UITapGestureRecognizer to trigger action after tap.

let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(showAlert(tapGesture:)))
yourLabel.addGestureRecognizer(tapGesture)

@objc func showAlert(tapGesture: UITapGestureRecognizer){
    // Show alert
}


问:
Position of DialogFragment in Android
I have a DialogFragment to show a View like a Popup screen.
The Window appears always in the middle of the screen.
Is there a way to set the position of the DialogFragment window?
I have looked in to the source code but couldn't find anything yet.

答:
In case somebody would like to bring the dialog to the screen's bottom, and make it full width, here is my solution:</p>

```<code>    @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // the content
    final RelativeLayout root = new RelativeLayout(getActivity());
    root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    // creating the fullscreen dialog
    final Dialog dialog = new Dialog(getActivity());
    Window dialogWindow = dialog.getWindow();

    dialog.setContentView(root);
    dialogWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

    WindowManager.LayoutParams params = dialogWindow.getAttributes();

    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;

    dialogWindow.setAttributes(params);
    dialogWindow.setGravity(Gravity.BOTTOM);

    return dialog;
}
</code>```

Title: Position of DialogFragment in Android

Body:
In case somebody would like to bring the dialog to the screen's bottom, and make it full width, here is my solution:

    @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    // the content
    final RelativeLayout root = new RelativeLayout(getActivity());
    root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

    // creating the fullscreen dialog
    final Dialog dialog = new Dialog(getActivity());
    Window dialogWindow = dialog.getWindow();

    dialog.setContentView(root);
    dialogWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));

    WindowManager.LayoutParams params = dialogWindow.getAttributes();

    params.width = ViewGroup.LayoutParams.MATCH_PARENT;
    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;

    dialogWindow.setAttributes(params);
    dialogWindow.setGravity(Gravity.BOTTOM);

    return dialog;
}


问:
Where is the WPF Numeric UpDown control?
Getting into the first serious WPF project.  It seems like there are a lot of basic controls flat out missing.  Specifically, I am looking for the Numeric UpDown control.  Was there an out of band release that I missed?  Really don't feel like writing my own control.

I do not want to use the WindowsFormHost and plop a WinForm ctl on it.  I want it to be fully WPF without any legacy junk.

Thanks

答:
Go to NugetPackage manager of you project-> Browse and search for mahApps.Metro -> install package into you project. You will see Reference added: MahApps.Metro.
Then in you XAML code add:

"xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"

Where you want to use your object add:

```<code><mah:NumericUpDown x:Name="NumericUpDown" ... />
</code>```

Enjoy the full extensibility of the object (Bindings, triggers and so on...).

ContentLicense: CC BY-SA 2.5

Body:
Go to NugetPackage manager of you project-> Browse and search for mahApps.Metro -> install package into you project. You will see Reference added: MahApps.Metro.
Then in you XAML code add:

"xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"

Where you want to use your object add:

<mah:NumericUpDown x:Name="NumericUpDown" ... />

Enjoy the full extensibility of the object (Bindings, triggers and so on...).


问:
Suppress fixed effects coefficients in R
is there a way to suppress the coefficients for fixed effects in a linear model when using the summary() function (e.g. the equivalent of the absorb() function in stata). For example, I would like to have the summary function output just the intercept and x rather than the coefficients and standard errors for the factors as well:

```<code>frame <- data.frame(x = rnorm(100), y = rnorm(100), z = rep(c("A", "B", "C", "D"),25))
summary(lm(y~x + as.factor(z), data = frame))

Call:
lm(formula = y ~ x + as.factor(z), data = frame)

Residuals:
Min      1Q  Median      3Q     Max
-2.2417 -0.6407  0.1783  0.5789  2.4347

Coefficients:
          Estimate Std. Error t value Pr(>|t|)
(Intercept)   -0.25829    0.19196  -1.346   0.1816
 x              0.09983    0.09788   1.020   0.3104
</code>```

...

Thanks.

答:
I can highly recommend the stargazer package:

```<code>frame <- data.frame(x = rnorm(100), y = rnorm(100), z = rep(c("A", "B", "C", "D"),25))
summary(lm(y~x + as.factor(z), data = frame))
model <- lm(y~x + as.factor(z), data = frame)
library(stargazer)
stargazer(model, type="text")
stargazer(model, omit = "z", type="text")
</code>```

Body:
is there a way to suppress the coefficients for fixed effects in a linear model when using the summary() function (e.g. the equivalent of the absorb() function in stata). For example, I would like to have the summary function output just the intercept and x rather than the coefficients and standard errors for the factors as well:

frame <- data.frame(x = rnorm(100), y = rnorm(100), z = rep(c("A", "B", "C", "D"),25))
summary(lm(y~x + as.factor(z), data = frame))

Call:
lm(formula = y ~ x + as.factor(z), data = frame)

Residuals:
Min      1Q  Median      3Q     Max
-2.2417 -0.6407  0.1783  0.5789  2.4347

Coefficients:
          Estimate Std. Error t value Pr(>|t|)
(Intercept)   -0.25829    0.19196  -1.346   0.1816
 x              0.09983    0.09788   1.020   0.3104

...

Thanks.

Body:
I can highly recommend the stargazer package:

frame <- data.frame(x = rnorm(100), y = rnorm(100), z = rep(c("A", "B", "C", "D"),25))
summary(lm(y~x + as.factor(z), data = frame))
model <- lm(y~x + as.factor(z), data = frame)
library(stargazer)
stargazer(model, type="text")
stargazer(model, omit = "z", type="text")


问:
python:find a ascending/decreasing elements in a list without using loop
Suppose I have a list, I need to find two lists in list 'a', in a increasing/decreasing order, respectively.

```<code>a=[4,2,6,5,2,6,9,7,10,1,2,1]
</code>```

The output should be a list :

```<code>b=[4,6,9,10] # in an ascending order
</code>```

and

```<code>c=[4,2,1] # in a decreasing order , c[-1] is the first '1' in list a, c[1] is the first '2' in list a.
</code>```

Is there a possible way to do it without using loop (I have solved it using a loop)? As a have a large dataset, using loop would be slow. So I am looking for a faster way if possible. Thanks a lot.

答:
Could you precise your problem :

Do you want to find the longest ascending/decreasing sub list ? In this case your problem has something to do with dynamic programming, and I think you'll need more than one loop...

If you don't want your sub-lists to be maximal, maybe you can set a limit on the length of your lists b and c to do it faster.

If you have other hypothesis on your list, for instance, you know its max and its min, you can stop your calcul when you reach the max (only if you want your lists to be strictly decreasing/ascending).

I hope it is usefull for you :)

Body:
Suppose I have a list, I need to find two lists in list 'a', in a increasing/decreasing order, respectively.

a=[4,2,6,5,2,6,9,7,10,1,2,1]

The output should be a list :

b=[4,6,9,10] # in an ascending order

and

c=[4,2,1] # in a decreasing order , c[-1] is the first '1' in list a, c[1] is the first '2' in list a.

Is there a possible way to do it without using loop (I have solved it using a loop)? As a have a large dataset, using loop would be slow. So I am looking for a faster way if possible. Thanks a lot.


问:
HTML/CSS buttons work but don't show any effect unless page is refreshed
This is the first time I'm asking around here. Hopefully you guys can help me.

For a client I'm creating a website for a bar/restaurant. A part of the page setup for the menu card. I created 3 buttons underneath to switch between diner, lunch and drinks. Whenever I hit one of the buttons I see the link change. The weird part; I can't figure out why the image doesn't change. If I refresh the page (the changed links let's say) it shows the image it's supposed to show.

I guess my question is. How can I make sure that the image changes with the button press without having to reload the page.

HTML

```<code>    <span id="menu1"></span>
    <span id="menu2"></span>
    <span id="menu3"></span>

    <div class="image-container">
        <img src="img/menu1.jpg" class="slider-image">
        <img src="img/menu2.jpg" class="slider-image">
        <img src="img/menu3.jpg" class="slider-image">
    </div>

    <div class="button-container">
      <a href="#menu1" class="slider-button"></a>
      <a href="#menu2" class="slider-button"></a>
      <a href="#menu3" class="slider-button"></a>
    </div>
</div>
</code>```

CSS

```<code>.slide-container {
  width: 495px;
  height: 750px;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  text-align: center;
  margin-bottom: 30px;
  margin-top: 30px;
}

.image-container {
  width: 1485px;
  height: 700px;
  position: relative;

}

.slider-image {
  float: left;
  margin: 0px;
  padding: 0px;
  max-width: 495px;
}

.button-container {
  margin-top: 10px;
  position: relative;
}

.slider-button {
  display: inline-block;
  height: 10px;
  width: 10px;
  border-radius: 5px;
  background-color: black;
}

#menu1:target ~ .image-container {
  margin: 0px;
  margin-top: 5%;
}

#menu2:target ~ .image-container {
  left: -495px;
  margin-top: 5%;
}

#menu3:target ~ .image-container {
  left: -990px;
  margin-top: 5%;
}
</code>```

If anyone has any idea and could help. I thank you!

答:
See following code snippet, you need add id to an element and specify that id in anchor tag so that browser will scroll page up to that content on clicking the anchor.

#section1,
#section2,
#section3,
#section4 {
  height: 400px;
  border-bottom: 1px solid #999;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Section 1
Section 2
Section 3
Section 4
<div id="container">
  <div id="section1">SECTION 1</div>
  <div id="section2">SECTION 2</div>
  <div id="section3">SECTION 3</div>
  <div id="section4">SECTION 4</div>
</div></code>```

Body:
This is the first time I'm asking around here. Hopefully you guys can help me.

For a client I'm creating a website for a bar/restaurant. A part of the page setup for the menu card. I created 3 buttons underneath to switch between diner, lunch and drinks. Whenever I hit one of the buttons I see the link change. The weird part; I can't figure out why the image doesn't change. If I refresh the page (the changed links let's say) it shows the image it's supposed to show.

I guess my question is. How can I make sure that the image changes with the button press without having to reload the page.

HTML

CSS

.slide-container {
  width: 495px;
  height: 750px;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  text-align: center;
  margin-bottom: 30px;
  margin-top: 30px;
}

.image-container {
  width: 1485px;
  height: 700px;
  position: relative;

}

.slider-image {
  float: left;
  margin: 0px;
  padding: 0px;
  max-width: 495px;
}

.button-container {
  margin-top: 10px;
  position: relative;
}

.slider-button {
  display: inline-block;
  height: 10px;
  width: 10px;
  border-radius: 5px;
  background-color: black;
}

#menu1:target ~ .image-container {
  margin: 0px;
  margin-top: 5%;
}

#menu2:target ~ .image-container {
  left: -495px;
  margin-top: 5%;
}

#menu3:target ~ .image-container {
  left: -990px;
  margin-top: 5%;
}

If anyone has any idea and could help. I thank you!

Body:
See following code snippet, you need add id to an element and specify that id in anchor tag so that browser will scroll page up to that content on clicking the anchor.

#section1,
#section2,
#section3,
#section4 {
  height: 400px;
  border-bottom: 1px solid #999;
}

<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
<a href="#section4">Section 4</a>
<div id="container">
  <div id="section1">SECTION 1</div>
  <div id="section2">SECTION 2</div>
  <div id="section3">SECTION 3</div>
  <div id="section4">SECTION 4</div>
</div>


问:
Wildcard file ignore is not working in .talismanrc
I have these files in project root

test.sql and test1.sql

.talismanrc

```<code>fileignoreconfig:
- filename: '*.sql'
  checksum: 29a138ee50018bdc968f352d2a69fa09e17de38fcc400630bb04dd7019e768be
# - filename: abc.sql
#   checksum: e12b607678a6b1821eca6e49f36588d8e89f8e6ed0f8a6abc6ef53b394bdc06b
# - filename: abc1.sql
#   checksum: cdca6d4d3d4c094fbdaeae9b6202fcf39be192454616e1e7d5b6fc2c60d25887

</code>```

.pre-commit-config

```<code># See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
-   repo: https://github.com/thoughtworks/talisman
    rev: v1.2.0
    hooks:
    # either `commit` or `push` support
    -   id: talisman-commit
    # -   id: talisman-push
</code>```

I am trying to write ignore rule for .sql file so that I don't need multiple entries in .talismanrc.
This is how I generated checksum for '*.sql'
talisman --checksum="*.sql"
When I try with two different rules it's working but wildcard rule is not working.
Am I missing something?

答:
I was missing ignore_detectors. After generating checksum using talisman --checksum="*.sql" I got the following

```<code>fileignoreconfig:
- filename: '*.sql'
  checksum: 29a148ff50018bdc968f352d2a69fa09e17de38fcc400630bb04dd7019e768be
</code>```

and I added ignore_detectors.
The final .talismanrc files look like this

```<code>fileignoreconfig:
- filename: '*.sql'
  checksum: 29a138ee50018bdc968f352d2a69fa09e17de38fcc400630bb04dd7019e768be
  ignore_detectors: [filename]
</code>```

Body:
I have these files in project root

test.sql and test1.sql

.talismanrc

fileignoreconfig:
- filename: '*.sql'
  checksum: 29a138ee50018bdc968f352d2a69fa09e17de38fcc400630bb04dd7019e768be
# - filename: abc.sql
#   checksum: e12b607678a6b1821eca6e49f36588d8e89f8e6ed0f8a6abc6ef53b394bdc06b
# - filename: abc1.sql
#   checksum: cdca6d4d3d4c094fbdaeae9b6202fcf39be192454616e1e7d5b6fc2c60d25887

.pre-commit-config

# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
-   repo: https://github.com/thoughtworks/talisman
    rev: v1.2.0
    hooks:
    # either `commit` or `push` support
    -   id: talisman-commit
    # -   id: talisman-push

I am trying to write ignore rule for .sql file so that I don't need multiple entries in .talismanrc.
This is how I generated checksum for '*.sql'
talisman --checksum="*.sql"
When I try with two different rules it's working but wildcard rule is not working.
Am I missing something?

Body:
I was missing ignore_detectors. After generating checksum using talisman --checksum="*.sql" I got the following

fileignoreconfig:
- filename: '*.sql'
  checksum: 29a148ff50018bdc968f352d2a69fa09e17de38fcc400630bb04dd7019e768be

and I added ignore_detectors.
The final .talismanrc files look like this

fileignoreconfig:
- filename: '*.sql'
  checksum: 29a138ee50018bdc968f352d2a69fa09e17de38fcc400630bb04dd7019e768be
  ignore_detectors: [filename]


问:
Property 'reduce' does not exist on type 'IComponent'
How do I get rid of the error Property 'reduce' does not exist on type 'IComponent' on my method. Initially, components had an any type, so it worked fine. But now that I am strongly typing all my methods ad variables I am seeing issues.

```<code>  static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.map((obj) =>
      obj.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      ),
    );
  }
</code>```

My interface is as follows:

```<code>export interface IComponent
  extends IComponentDetail {
}
</code>```

答:
```<code>  return components.map((obj) =>
      obj.reduce(
      //...
</code>```

obj here is not an array anymore so you can't use reduce function. Not really sure what your function does, maybe remove the map function and replace it with the reduce instead.

Body:
How do I get rid of the error Property 'reduce' does not exist on type 'IComponent' on my method. Initially, components had an any type, so it worked fine. But now that I am strongly typing all my methods ad variables I am seeing issues.

  static addPlaceholdersOnMultiplePages(components: IComponent[]): IComponent[] {
    return components.map((obj) =>
      obj.reduce(
        (r, a) =>
          r.concat(a, {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          }),
        [
          {
            componentIndex: null,
            componentName: ActiveComponentsPartialSelector.Placeholder,
            componentId: `${ActiveComponents.Placeholder}-${UtilService.generateRandomString(8)}`,
            timestamp: new Date().getTime(),
          },
        ],
      ),
    );
  }

My interface is as follows:

export interface IComponent
  extends IComponentDetail {
}

Body:
  return components.map((obj) =>
      obj.reduce(
      //...

obj here is not an array anymore so you can't use reduce function. Not really sure what your function does, maybe remove the map function and replace it with the reduce instead.


问:
Rails simpleform pre data
How do I make a simple form association have pre data when editing?

My form:

```<code><h1>Editing kategori</h1>
<%= simple_form_for(@konkurrancer, :url => {:action => 'update', :id => @konkurrancer.id }) do |f| %>
    <%= f.association :kategoris  %>
    <%= f.button :submit, :value => 'Edit konkurrence' %>
<% end %>
</code>```

答:
Your best bet is to do something like this in your controller:

```<code>def edit
  @konkurrancer = Konkurrancer.new(:title => "hello wurld", :description => "blah blah blah", :nuclear_level => 10)
end
</code>```

Then your form should automatically populate these values as "pre data".

Title: Rails simpleform pre data

Body:
How do I make a simple form association have pre data when editing?

My form:

Editing kategori

<%= simple_form_for(@konkurrancer, :url => {:action => 'update', :id => @konkurrancer.id }) do |f| %>
    <%= f.association :kategoris  %>
    <%= f.button :submit, :value => 'Edit konkurrence' %>
<% end %>

Body:
Your best bet is to do something like this in your controller:

def edit
  @konkurrancer = Konkurrancer.new(:title => "hello wurld", :description => "blah blah blah", :nuclear_level => 10)
end

Then your form should automatically populate these values as "pre data".


问:
How to convert a tensor of booleans to ints in PyTorch?
Suppose, we have a tensor

```<code>t = torch.tensor([True, False, True, False])
</code>```

How do we convert it to an integer tensor with values [1, 0, 1, 0]?

答:
The solution is just a single line of code.

To convert a tensor t with values [True, False, True, False] to an integer tensor, just do the following.

```<code>t = torch.tensor([True, False, True, False])
t_integer = t.long()
print(t_integer)
[1, 0, 1, 0]
</code>```

Body:
Suppose, we have a tensor

t = torch.tensor([True, False, True, False])

How do we convert it to an integer tensor with values [1, 0, 1, 0]?

Body:
The solution is just a single line of code.

To convert a tensor t with values [True, False, True, False] to an integer tensor, just do the following.

t = torch.tensor([True, False, True, False])
t_integer = t.long()
print(t_integer)
[1, 0, 1, 0]


问:
Simple code program to print ASCII of a string (per characters) not working with input cases
So i have created a simple program to print ASCII codes of a string per characters, in this case i must use input case(T) to toggle on how much string that i want to print to ASCII.
There are 2 problems:
The first problem is it wont read all of my input case and only read the last case of string (it was supposed to print every ASCII code of every string). The second problem is i must use "-" symbol between every ASCII but it ended up in the end of every ASCII code that is printed.
What is wrong and what should i do in this case? I am still not very fond of C Programming so i couldn't seem to find any solution for this. Here is the the code:

```<code>#include<stdio.h>
#include<stdlib.h>

int main()
{
int T;
char t[1000];
scanf("%d", &T);
for(int i = 0; i < T; i++)
{
    scanf("%s", t);
    fflush(stdin);
}

for(int i = 0; i < T; i++)
{
    printf("Case %d:\n", i+1);
    for(int j = 0; t[j] != '\0'; j++)
    {
        printf("%d-", t[j]);
    }
    printf("\n");
}

return 0;
}
</code>```

And here is the result of the program when run:

```<code>2
ABCDEF
GHIJKL
Case 1:
71-72-73-74-75-76-
Case 2:
71-72-73-74-75-76-

--------------------------------
Process exited after 9.87 seconds with return value 0
Press any key to continue . . .
</code>```

答:
The second inner for loop must be inside the first for loop.

Also the call of the function fflush

```<code>fflush(stdin);
</code>```

has undefined behavior.

The body of the function main can look like

```<code>size_t n;
char s[1000];

scanf( "%zu", &n );

for ( size_t i = 0; i < n; i++ )
{
    scanf( "%s", s );

    printf( "Case %zu:\n", i+1 );

    for ( size_t j = 0; s[j] != '\0'; j++ )
    {
        if ( j != 0 ) putchar( '-' );
        printf( "%d", s[j] );
    }
    printf("\n");
}
</code>```

Body:
So i have created a simple program to print ASCII codes of a string per characters, in this case i must use input case(T) to toggle on how much string that i want to print to ASCII.
There are 2 problems:
The first problem is it wont read all of my input case and only read the last case of string (it was supposed to print every ASCII code of every string). The second problem is i must use "-" symbol between every ASCII but it ended up in the end of every ASCII code that is printed.
What is wrong and what should i do in this case? I am still not very fond of C Programming so i couldn't seem to find any solution for this. Here is the the code:

#include<stdio.h>
#include<stdlib.h>

int main()
{
int T;
char t[1000];
scanf("%d", &T);
for(int i = 0; i < T; i++)
{
    scanf("%s", t);
    fflush(stdin);
}

for(int i = 0; i < T; i++)
{
    printf("Case %d:\n", i+1);
    for(int j = 0; t[j] != '\0'; j++)
    {
        printf("%d-", t[j]);
    }
    printf("\n");
}

return 0;
}

And here is the result of the program when run:

2
ABCDEF
GHIJKL
Case 1:
71-72-73-74-75-76-
Case 2:
71-72-73-74-75-76-

--------------------------------
Process exited after 9.87 seconds with return value 0
Press any key to continue . . .

Body:
The second inner for loop must be inside the first for loop.

Also the call of the function fflush

fflush(stdin);

has undefined behavior.

The body of the function main can look like

size_t n;
char s[1000];

scanf( "%zu", &n );

for ( size_t i = 0; i < n; i++ )
{
    scanf( "%s", s );

    printf( "Case %zu:\n", i+1 );

    for ( size_t j = 0; s[j] != '\0'; j++ )
    {
        if ( j != 0 ) putchar( '-' );
        printf( "%d", s[j] );
    }
    printf("\n");
}


问:
How to change the value of outside variable from inside the method
I am trying to change the value of a variable "memes"
in a function called "joke". Joke function should change the value of memes to 1313, but it does not and when the print(str(memes)) is triggered the value of "memes" variable is still 0.

```<code>class Bruhmoment:
    memes = 0
    def __init__(self, name):
        self.name=name
    global memes
    def joke(self):
        memes=1313
        print(str(memes))
</code>```

答:
If you're looking for a class variable (as opposed to an instance variable), you need to do things different:</p>

```<code>class Bruhmoment:
    memes = 0
    def __init__(self, name):
       self.name = name
    def joke(self):
       Bruhmoment.memes = 1313
       return Bruhmoment.memes

b = Bruhmoment('xxx')
b.joke()
=> 1313
</code>```

Body:
I am trying to change the value of a variable "memes"
in a function called "joke". Joke function should change the value of memes to 1313, but it does not and when the print(str(memes)) is triggered the value of "memes" variable is still 0.

class Bruhmoment:
    memes = 0
    def __init__(self, name):
        self.name=name
    global memes
    def joke(self):
        memes=1313
        print(str(memes))

Body:
If you're looking for a class variable (as opposed to an instance variable), you need to do things different:

class Bruhmoment:
    memes = 0
    def __init__(self, name):
       self.name = name
    def joke(self):
       Bruhmoment.memes = 1313
       return Bruhmoment.memes

b = Bruhmoment('xxx')
b.joke()
=> 1313


问:
How do I split a string by a whitespace after a bracket and keep the bracket in the same line
I have an array of strings that look like the following:

```<code>const stringArray = [
    'string1[1] string2[2] string3[3] [4 5]',
    'string6[6] string7[7] string8[8] [9 10]'
];
</code>```

I want to be able to separate each string into four rows (in this case, because there are 4 columns). So the array would end up like:

```<code>const splittedArray = [
    [
        'string1[1]',
        'string2[2]',
        'string3[3]',
        '[4 5]'
    ],
    [
        'string6[6]',
        'string7[7]',
        'string8[8]',
        '[9 10]'
    ]
]
</code>```

I've been searching and trying regex even though I am not a fan of it as it is unreadable, but it does not seem to be working.

Whenever I try /(?=\])\s/g it does not separate the string, whenever I try /(?=\])\s*/ it separates the string and keeps both the ] and the whitespace, but does so in the next line (and well, keeps the whitespace).

I can't seem to find a way to do what I want, but perhaps I'm just miss understanding something. Perhaps there is a simpler way to do this. Splitting after the ] without needing to check for a space would be ideal but I would still have the problem of keeping the bracket and not splitting an extra time on that last ] hence why I'm trying this solution.

Here is a little code snipper with what I have and what it returns:

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/(?=\])\s/g));

console.log(splittedStringArray);

const anotherSplittedStringArray = stringArray.map(string => string.split(/(?=\])\s*/g));

console.log(anotherSplittedStringArray);

const splittedByBrackets = stringArray.map(string => string.split(/(?=\])/));

// The same as the previous one
console.log(splittedByBrackets);```

For my case, the answer was: /\w*\[.*?\]/g (with match instead of split) by Thomas. From what I understood:

The \w* matches any word (0 or more times)

The \[ matches the [ after a word (or no word, above condition)

The .*? matches any character excluding line breaks (0 or more times) lazyly, I believe the ? is to tell to stop matching on the first character(s) otherwise it would search the whole string.

The \] matches the ] after what is after the other bracket (which is the above condition).

The /g flag makes it so it searched for more than one occurrence.

答:
Using Negative Lookahead

```<code>\s(?![^\[]*\])
</code>```

Regex Demo

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/\s(?![^\[]*\])/g));

console.log(splittedStringArray);```

Body:
I have an array of strings that look like the following:

const stringArray = [
    'string1[1] string2[2] string3[3] [4 5]',
    'string6[6] string7[7] string8[8] [9 10]'
];

I want to be able to separate each string into four rows (in this case, because there are 4 columns). So the array would end up like:

const splittedArray = [
    [
        'string1[1]',
        'string2[2]',
        'string3[3]',
        '[4 5]'
    ],
    [
        'string6[6]',
        'string7[7]',
        'string8[8]',
        '[9 10]'
    ]
]

I've been searching and trying regex even though I am not a fan of it as it is unreadable, but it does not seem to be working.

Whenever I try /(?=\])\s/g it does not separate the string, whenever I try /(?=\])\s*/ it separates the string and keeps both the ] and the whitespace, but does so in the next line (and well, keeps the whitespace).

I can't seem to find a way to do what I want, but perhaps I'm just miss understanding something. Perhaps there is a simpler way to do this. Splitting after the ] without needing to check for a space would be ideal but I would still have the problem of keeping the bracket and not splitting an extra time on that last ] hence why I'm trying this solution.

Here is a little code snipper with what I have and what it returns:

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/(?=\])\s/g));

console.log(splittedStringArray);

const anotherSplittedStringArray = stringArray.map(string => string.split(/(?=\])\s*/g));

console.log(anotherSplittedStringArray);

const splittedByBrackets = stringArray.map(string => string.split(/(?=\])/));

// The same as the previous one
console.log(splittedByBrackets);

For my case, the answer was: /\w*\[.*?\]/g (with match instead of split) by Thomas. From what I understood:

The \w* matches any word (0 or more times)

The \[ matches the [ after a word (or no word, above condition)

The .*? matches any character excluding line breaks (0 or more times) lazyly, I believe the ? is to tell to stop matching on the first character(s) otherwise it would search the whole string.

The \] matches the ] after what is after the other bracket (which is the above condition).

The /g flag makes it so it searched for more than one occurrence.

Body:
Using Negative Lookahead

\s(?![^\[]*\])

Regex Demo

const stringArray = [
  'string1[1] string2[2] string3[3] [4 5]',
  'string6[6] string7[7] string8[8] [9 10]'
];

const splittedStringArray = stringArray.map(string => string.split(/\s(?![^\[]*\])/g));

console.log(splittedStringArray);


问:
How to run intellij's cucumber-java plugin locally
I am using Intellij cucumber-java plugin. After updating to cucumber-jvm 3, it fails to navigate to step definitions from feature files since I am using new argument placeholders now (e.g., "I have {int} cukes in my {string}" instead of "^I have (\d+) cukes in my (.*?)$").

I would like to tweak cucumber-java plugin but I don't really get it how to build and run intellij's plugin locally. I cloned the plugins from https://github.com/JetBrains/intellij-plugins, cloned intellij community edition and set up plugin devKit. At this point I don't see how to build and run cucumber-java plugin locally. I tried to create a new plugin to extend cucumber-java but there is no extension points in cucumber-java.

Is it dead-end or am I missing something really obvious?

答:
I know it is old question, but mby someone will find this answer usefull.

Not long ago I actually managed to tweak the cucumber plugin (gherkin) for intelliJ, so mby same way will work for cucumber-java plugin.

I had a problem with very complex step definitions, when I used many optional regexps.
eg. If I had something like this in my stepdef "(| using user \"([^\"])\" and password \"([^\"])\")" then autocompletion was failing and showed just param for the rest of the step, but nvm why I needed to "repair" the plugin - this is what I've done to make it work for me:

I converted the plugin from devkit way to gradle based plugin, this article was very usefull for me: adding-gradle-support-to-an-existing-devkit-based-intellij-platform-plugin

I got rid of all compilation issues, I had to change one class from kotlin to java, and fix some issues with properties.

After that I was able to build the plugin and simply install compiled jar by hand in intelliJ, what I have never achived is to debug the plugin.