问:
How to compare nested dicts
```<code>a_standard = {
    'section1': {
        'category1': 1,
        'category2': 2
    },
    'section2': {
        'category1': 1,
        'category2': 2
    }

}

a_new = {
    'section1': {
        'category1': 1,
        'category2': 2
    },
    'section2': {
        'category1': 1,
        'category2': 3
    }

}
</code>```

I want to find the difference between a_standard and a_new which is in a_new[section2][category2] difference in value being 2 and 3

Should I convert each to a set and then do difference or loop and compare the dict?

答:
There is a library called deepdiff that has a lot of options, but I find it to be somewhat unintuitive.

Here's a recursive function that I often use to compute diffs during my unit tests. This goes a bit beyond what the question asks, because I take care of the case of lists being nested as well. I hope you'll find it useful.

Function definition:

from copy import deepcopy

def deep_diff(x, y, parent_key=None, exclude_keys=[], epsilon_keys=[]):
    """
    Take the deep diff of JSON-like dictionaries

    No warranties when keys, or values are None

    """
    EPSILON = 0.5
    rho = 1 - EPSILON

    if x == y:
        return None

    if parent_key in epsilon_keys:
        xfl, yfl = float_or_None(x), float_or_None(y)
        if xfl and yfl and xfl * yfl >= 0 and rho * xfl <= yfl and rho * yfl <= xfl:
            return None

    if type(x) != type(y) or type(x) not in [list, dict]:
        return x, y

    if type(x) == dict:
        d = {}
        for k in x.keys() ^ y.keys():
            if k in exclude_keys:
                continue
            if k in x:
                d[k] = (deepcopy(x[k]), None)
            else:
                d[k] = (None, deepcopy(y[k]))

        for k in x.keys() & y.keys():
            if k in exclude_keys:
                continue

            next_d = deep_diff(x[k], y[k], parent_key=k, exclude_keys=exclude_keys, epsilon_keys=epsilon_keys)
            if next_d is None:
                continue

            d[k] = next_d

        return d if d else None

    # assume a list:
    d = [None] * max(len(x), len(y))
    flipped = False
    if len(x) > len(y):
        flipped = True
        x, y = y, x

    for i, x_val in enumerate(x):
        d[i] = deep_diff(y[i], x_val, parent_key=i, exclude_keys=exclude_keys, epsilon_keys=epsilon_keys) if flipped else deep_diff(x_val, y[i], parent_key=i, exclude_keys=exclude_keys, epsilon_keys=epsilon_keys)

    for i in range(len(x), len(y)):
        d[i] = (y[i], None) if flipped else (None, y[i])

    return None if all(map(lambda x: x is None, d)) else d

# We need this helper function as well:
def float_or_None(x):
    try:
        return float(x)
    except ValueError:
        return None
```
<p><strong>Usage</strong>:</p>
<pre class="lang-py prettyprint-override"><code>>>> deep_diff(a_standard, a_new)

{'section2': {'category2': (2, 3)}}
</code>```

I think the output is a little more intuitive than the other answers.

In unit tests I'll so something like:

import json

diff = deep_diff(expected_out, out, exclude_keys=["flickery1", "flickery2"])
assert diff is None, json.dumps(diff, indent=2)
```

Title: How to compare nested dicts

Body:
a_standard = {
    'section1': {
        'category1': 1,
        'category2': 2
    },
    'section2': {
        'category1': 1,
        'category2': 2
    }

}

a_new = {
    'section1': {
        'category1': 1,
        'category2': 2
    },
    'section2': {
        'category1': 1,
        'category2': 3
    }

}

I want to find the difference between a_standard and a_new which is in a_new[section2][category2] difference in value being 2 and 3

Should I convert each to a set and then do difference or loop and compare the dict?

Body:
There is a library called deepdiff that has a lot of options, but I find it to be somewhat unintuitive.

Here's a recursive function that I often use to compute diffs during my unit tests. This goes a bit beyond what the question asks, because I take care of the case of lists being nested as well. I hope you'll find it useful.

Function definition:

from copy import deepcopy

def deep_diff(x, y, parent_key=None, exclude_keys=[], epsilon_keys=[]):
    """
    Take the deep diff of JSON-like dictionaries

    No warranties when keys, or values are None

    """
    EPSILON = 0.5
    rho = 1 - EPSILON

    if x == y:
        return None

    if parent_key in epsilon_keys:
        xfl, yfl = float_or_None(x), float_or_None(y)
        if xfl and yfl and xfl * yfl >= 0 and rho * xfl <= yfl and rho * yfl <= xfl:
            return None

    if type(x) != type(y) or type(x) not in [list, dict]:
        return x, y

    if type(x) == dict:
        d = {}
        for k in x.keys() ^ y.keys():
            if k in exclude_keys:
                continue
            if k in x:
                d[k] = (deepcopy(x[k]), None)
            else:
                d[k] = (None, deepcopy(y[k]))

        for k in x.keys() & y.keys():
            if k in exclude_keys:
                continue

            next_d = deep_diff(x[k], y[k], parent_key=k, exclude_keys=exclude_keys, epsilon_keys=epsilon_keys)
            if next_d is None:
                continue

            d[k] = next_d

        return d if d else None

    # assume a list:
    d = [None] * max(len(x), len(y))
    flipped = False
    if len(x) > len(y):
        flipped = True
        x, y = y, x

    for i, x_val in enumerate(x):
        d[i] = deep_diff(y[i], x_val, parent_key=i, exclude_keys=exclude_keys, epsilon_keys=epsilon_keys) if flipped else deep_diff(x_val, y[i], parent_key=i, exclude_keys=exclude_keys, epsilon_keys=epsilon_keys)

    for i in range(len(x), len(y)):
        d[i] = (y[i], None) if flipped else (None, y[i])

    return None if all(map(lambda x: x is None, d)) else d

# We need this helper function as well:
def float_or_None(x):
    try:
        return float(x)
    except ValueError:
        return None

Usage:

>>> deep_diff(a_standard, a_new)

{'section2': {'category2': (2, 3)}}

I think the output is a little more intuitive than the other answers.

In unit tests I'll so something like:

import json

diff = deep_diff(expected_out, out, exclude_keys=["flickery1", "flickery2"])
assert diff is None, json.dumps(diff, indent=2)


来源: stackexchange

问:
How to switch images on click with Visual Studio
I'm using visual studios and I want to make a sprite look like it's walking. So when I press the left arrow key the sprite moves left but I want to change the image each time I press the key so his other leg is forward and it seems like he is walking. At first, I had a gif but it doesn't have the same effect.

I'm using visual studios and only new but can't seem to find an updated answer. If there is anyways to improve my question please let me know. Thank you!

I'm Using Windows Form App (.NET Framework)

答:
what is the code to change the image

If you want to traverse through the pictures in the ImageList, you can define an field index to store the index of images.

Please refer to the following code.

```<code>int index = 0;

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Left)
    {
        if (index > imageList1.Images.Count - 1)
            index = 0;
        pictureBox1.Image = imageList1.Images[index++];
    }
}
</code>```

The test result,

ContentLicense: CC BY-SA 4.0

Body:
what is the code to change the image

If you want to traverse through the pictures in the ImageList, you can define an field index to store the index of images.

Please refer to the following code.

int index = 0;

private void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Left)
    {
        if (index > imageList1.Images.Count - 1)
            index = 0;
        pictureBox1.Image = imageList1.Images[index++];
    }
}

The test result,


问:
How to add a new key to a dictionary based on condition match of two existed dict key values in python?
I'm having a dictionary with boolean values as,

```<code>dict_prob = {'A': [True, False, True, False, True, True],
             'B': [False, False, True, False, True, False]}
</code>```

Now i would like to create a key called A_and_B and add it to either new dict or the current dict as,

```<code>out_dict_con = {'A': [True, False, True, False, True, True],
                'B': [False, False, True, False, True, False],
                'A_and_B':[False,True,True,True,True,False] }
</code>```

Basically the newly created key is a result of conjunction of A and B keys.

答:
You can zip the two lists and compare in a list comprehension:

```<code>dict_prob = {'A': [True, False, True, False, True, True],
             'B': [False, False, True, False, True, False]}

dict_prob['A_and_B'] = [a == b for a,b in zip(dict_prob['A'], dict_prob['B'])]
</code>```

dict_prob will be:

```<code>{'A': [True, False, True, False, True, True],
 'B': [False, False, True, False, True, False],
 'A_and_B': [False, True, True, True, True, False]}
</code>```

Body:
I'm having a dictionary with boolean values as,

dict_prob = {'A': [True, False, True, False, True, True],
             'B': [False, False, True, False, True, False]}

Now i would like to create a key called A_and_B and add it to either new dict or the current dict as,

out_dict_con = {'A': [True, False, True, False, True, True],
                'B': [False, False, True, False, True, False],
                'A_and_B':[False,True,True,True,True,False] }

Basically the newly created key is a result of conjunction of A and B keys.

Body:
You can zip the two lists and compare in a list comprehension:

dict_prob = {'A': [True, False, True, False, True, True],
             'B': [False, False, True, False, True, False]}

dict_prob['A_and_B'] = [a == b for a,b in zip(dict_prob['A'], dict_prob['B'])]

dict_prob will be:

{'A': [True, False, True, False, True, True],
 'B': [False, False, True, False, True, False],
 'A_and_B': [False, True, True, True, True, False]}


问:
Fetch particular string from particular block
I am new to c#. I have text file with data in it but I want to read particular block line data.

Here address can occur multiple times in text file.

```<code>Something here...
... ... ...
    interface "system"
        address 10.4.1.10/32
        no shutdown
    exit
something here...
... ... ...
    address 101.4.1.11/32
</code>```

but i want to capture within this

```<code>interface "system"
        address 10.4.1.10/32
        no shutdown
    exit
</code>```

I want to capture this ip from the block:

```<code>10.4.1.10
</code>```

I tried this code:

```<code>int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
</code>```

Expected Output:

my expected output is to capture the ip address from that block ie.10.4.1.10
that ip is inside "interface system" block.. that makes that address as unique.. as there can be many ips with keyword address. So i want to take address which is inside interface system block.

Please let me know how i can capture particular string from the block.

答:
Regular Expressions are perfectly suited to handle this type of "problem". The following console app demonstrates how to use Regex to extract the desired IP address from the targeted string block.

```<code>private static readonly string IPV4_PATTERN = "[0-9./]";
private static readonly string IPV4_IPV6_PATTERN = "[A-Z0-9:./]";

static void Main(string[] args)
{
    TestSearchFile();
}

private static string ParseIpWithRegex(string textToSearch, string startBlock, string endBlock)
{
    var pattern = $@"{startBlock}\D*\s*({IPV4_IPV6_PATTERN}+).*{endBlock}";
    var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
    if (ms.Groups.TryGetValue("1", out var g))
    {
        return g.Value;
    }
        return string.Empty;
    }

private static void TestSearchFile()
{
    var sep = Environment.NewLine;

    var ipAddress6 = "2001:db8:85a3:8d3:1319:8a2e:370:7348";
    var ipAddress4 = "10.4.1.10/32";

    var t = "Something here..." + sep;
    t += "... ... ... " + sep;
    t += "interface \"system\"" + sep;
    t += "address " + ipAddress4 + sep;
    t += "no shutdown" + sep;
    t += "exit" + sep;
    t += "something here..." + sep;
    t += "address 101.4.1.11/32" + sep;
    t += "... ... ... " + sep;

    var startBlock = "interface \"system\"";
    var endBlock = "exit";

    var ip = ParseIpWithRegex(t, startBlock, endBlock);
    Console.WriteLine($"IP: {ip}");
}
</code>```

I've included two IP address patterns IPV4_PATTERN for IPV4 only as well as IPV4_IPV6_PATTERN for both IPV4 and IPV6. Select the one you feel is most appropriate. Although the IPV4_IPV6_PATTERN would apply to both IP versions I believe it improves performance slight when the search is narrowed by using the narrowest pattern.

Don't forget to import the Regex reference:

```<code>using System.Text.RegularExpressions;
</code>```

**Code Explained**

The method "ParseIpWithRegex" uses a Regex pattern constructed by using the string that signifies the start of the targeted block and the string that signifies the end of that block. Nestled within that pattern is the regular expressions class definition that defines the IP address pattern we wish to isolate as a group.

```<code>$@"{startBlock}\D*\s*({IPV4_IPV6_PATTERN}+).*{endBlock}";
</code>```

It should be noted that the curly brackets are just for string interpolation and have (in this case) nothing to do with the actual regular expression!

After the "startBlock" we see "\D*". This means that after the "startBlock" include in the search all non-numeric characters (where the "star" indicates to expect zero to infinitely many). Then we see "\s*" which means to include all white space (including new line characters since I included RegexOptions.Singleline).

The IP address pattern is in brackets "()" which instructs Regex to create groups. In this case, behind the IP address pattern (in the above code example IPV4_IPV6_PATTERN) there is a "+" symbol. This indicates that there MUST be at least one of the characters that is in the IP address Regex class definition in order to be considered a "match".

After that we see ".*" in front of the "endBlock". This means to look for any character--including the "new line" character (zero to infinitely many) in from of the "endBlock" string.

If you have any questions, please leave a comment.

EDIT

From your button onclick method you will call SearchFileForIp. You will need to change myTextBox to match your code.

You should also decide whether you will be searching IPV4 or both IPV4 and IPV6 and select the appropriate variable IPV4_PATTERN or IPV4_IPV6_PATTERN.

```<code>private void SearchFileForIp()
{
    var fileName = "c:\\test.txt";
    using var sr = new StreamReader(fileName);
    string fileContent = sr.ReadToEnd();

    var startBlock = "interface \"system\"";
    var endBlock = "exit";

    var ip = ParseForIpRegex(fileContent, startBlock, endBlock);
    myTextBox.Text = ip; //Change this to match your code
}

private readonly string IPV4_PATTERN = "[0-9./]";
private readonly string IPV4_IPV6_PATTERN = "[A-Z0-9:./]";
private string ParseForIpRegex(string textToSearch, string startBlock, string endBlock)
{
    var pattern = $@"{startBlock}\D*\s*({IPV4_PATTERN}+).*{endBlock}";
    var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
    if(ms.Groups.Count > 0)
    {
        return ms.Groups[1].Value;
    }

    //For .Net Core apps
    //if (ms.Groups.TryGetValue("1", out var g))
    //{
    //    return g.Value;
    //}

    return string.Empty;
}
</code>```

Body:
I am new to c#. I have text file with data in it but I want to read particular block line data.

Here address can occur multiple times in text file.

Something here...
... ... ...
    interface "system"
        address 10.4.1.10/32
        no shutdown
    exit
something here...
... ... ...
    address 101.4.1.11/32

but i want to capture within this

interface "system"
        address 10.4.1.10/32
        no shutdown
    exit

I want to capture this ip from the block:

10.4.1.10

I tried this code:

int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);
   counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();

Expected Output:

my expected output is to capture the ip address from that block ie.10.4.1.10
that ip is inside "interface system" block.. that makes that address as unique.. as there can be many ips with keyword address. So i want to take address which is inside interface system block.

Please let me know how i can capture particular string from the block.

Body:
Regular Expressions are perfectly suited to handle this type of "problem". The following console app demonstrates how to use Regex to extract the desired IP address from the targeted string block.

private static readonly string IPV4_PATTERN = "[0-9./]";
private static readonly string IPV4_IPV6_PATTERN = "[A-Z0-9:./]";

static void Main(string[] args)
{
    TestSearchFile();
}

private static string ParseIpWithRegex(string textToSearch, string startBlock, string endBlock)
{
    var pattern = $@"{startBlock}\D*\s*({IPV4_IPV6_PATTERN}+).*{endBlock}";
    var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
    if (ms.Groups.TryGetValue("1", out var g))
    {
        return g.Value;
    }
        return string.Empty;
    }

private static void TestSearchFile()
{
    var sep = Environment.NewLine;

    var ipAddress6 = "2001:db8:85a3:8d3:1319:8a2e:370:7348";
    var ipAddress4 = "10.4.1.10/32";

    var t = "Something here..." + sep;
    t += "... ... ... " + sep;
    t += "interface \"system\"" + sep;
    t += "address " + ipAddress4 + sep;
    t += "no shutdown" + sep;
    t += "exit" + sep;
    t += "something here..." + sep;
    t += "address 101.4.1.11/32" + sep;
    t += "... ... ... " + sep;

    var startBlock = "interface \"system\"";
    var endBlock = "exit";

    var ip = ParseIpWithRegex(t, startBlock, endBlock);
    Console.WriteLine($"IP: {ip}");
}

I've included two IP address patterns IPV4_PATTERN for IPV4 only as well as IPV4_IPV6_PATTERN for both IPV4 and IPV6. Select the one you feel is most appropriate. Although the IPV4_IPV6_PATTERN would apply to both IP versions I believe it improves performance slight when the search is narrowed by using the narrowest pattern.

Don't forget to import the Regex reference:

using System.Text.RegularExpressions;

**Code Explained**

The method "ParseIpWithRegex" uses a Regex pattern constructed by using the string that signifies the start of the targeted block and the string that signifies the end of that block. Nestled within that pattern is the regular expressions class definition that defines the IP address pattern we wish to isolate as a group.

$@"{startBlock}\D*\s*({IPV4_IPV6_PATTERN}+).*{endBlock}";

It should be noted that the curly brackets are just for string interpolation and have (in this case) nothing to do with the actual regular expression!

After the "startBlock" we see "\D*". This means that after the "startBlock" include in the search all non-numeric characters (where the "star" indicates to expect zero to infinitely many). Then we see "\s*" which means to include all white space (including new line characters since I included RegexOptions.Singleline).

The IP address pattern is in brackets "()" which instructs Regex to create groups. In this case, behind the IP address pattern (in the above code example IPV4_IPV6_PATTERN) there is a "+" symbol. This indicates that there MUST be at least one of the characters that is in the IP address Regex class definition in order to be considered a "match".

After that we see ".*" in front of the "endBlock". This means to look for any character--including the "new line" character (zero to infinitely many) in from of the "endBlock" string.

If you have any questions, please leave a comment.

EDIT

From your button onclick method you will call SearchFileForIp. You will need to change myTextBox to match your code.

You should also decide whether you will be searching IPV4 or both IPV4 and IPV6 and select the appropriate variable IPV4_PATTERN or IPV4_IPV6_PATTERN.

private void SearchFileForIp()
{
    var fileName = "c:\\test.txt";
    using var sr = new StreamReader(fileName);
    string fileContent = sr.ReadToEnd();

    var startBlock = "interface \"system\"";
    var endBlock = "exit";

    var ip = ParseForIpRegex(fileContent, startBlock, endBlock);
    myTextBox.Text = ip; //Change this to match your code
}

private readonly string IPV4_PATTERN = "[0-9./]";
private readonly string IPV4_IPV6_PATTERN = "[A-Z0-9:./]";
private string ParseForIpRegex(string textToSearch, string startBlock, string endBlock)
{
    var pattern = $@"{startBlock}\D*\s*({IPV4_PATTERN}+).*{endBlock}";
    var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
    if(ms.Groups.Count > 0)
    {
        return ms.Groups[1].Value;
    }

    //For .Net Core apps
    //if (ms.Groups.TryGetValue("1", out var g))
    //{
    //    return g.Value;
    //}

    return string.Empty;
}


答:
This should work:</p>

```<code>dict_prob = {'A': [True, False, True, False, True, True],
             'B': [False, False, True, False, True, False]}

dict_prob['A_and_B'] = [a and b for a,b in zip(dict_prob['A'], dict_prob['B']]
</code>```

Title: How to add a new key to a dictionary based on condition match of two existed dict key values in python?

Body:
This should work:

dict_prob = {'A': [True, False, True, False, True, True],
             'B': [False, False, True, False, True, False]}

dict_prob['A_and_B'] = [a and b for a,b in zip(dict_prob['A'], dict_prob['B']]


答:
you can add to python dict objects like so

dict_prob['A_and_B'] = [not (a ^ b) for a,b in zip(dict_prob['A'], dict_prob['B']]
```

^ is the XOR operator. Inverse of XOR is bidirectional.

Body:
you can add to python dict objects like so

dict_prob['A_and_B'] = [not (a ^ b) for a,b in zip(dict_prob['A'], dict_prob['B']]

^ is the XOR operator. Inverse of XOR is bidirectional.


问:
Problems getting updated information with PHP exec()
I have simple code that uses exec() to set a variable with some system information (like current IP.) I execute the code and display the information. I change the IP address of the computer and rerun the code. I'm using unset() to clear the variable before executing the code, however, it still displays the old information. How do I obtain the current information using exec()? Thanks in advance and sorry for the noob-iness.</p>

```<code>  <button type="button" class="btn btn-info btn-lg" onclick="showip()">Get IP</button>

  <script>
  function showip(){
     <?php
        unset($return);
        unset($ip);
        exec('wget https://ipinfo.io/ip -qO -', $return);
        $ip = $return[0];
     ?>
     curip = <?php echo(json_encode($ip, JSON_HEX_TAG)); ?>;
     alert("The current IP is "+curip);
   }
  </script>
</code>```

答:
A server may have multiple IP addresses, including at least the public IP and the local(VPN) IP.
I guess the question for obtain public IP has been answered. If you want to obtain the local IP(inside the VPN) of the server. You may try use 'ip addr' like this:

```<code>function ips(){
  $ips = [];
  exec('ip addr', $lines);
  foreach($lines as $line){
    $fields = explode(" ",trim($line));
    if($fields[0] == 'inet'){
      $ip = explode("/",$fields[1])[0];
      $ifname = $fields[count($fields)-1];
      $ips[$ifname] = $ip;
    }
  }
  return $ips;
}
</code>```

This will return all local IP(v4) of each interfaces. If you want to have IPv6, just change 'inet' to 'inet6'.

Body:
I have simple code that uses exec() to set a variable with some system information (like current IP.) I execute the code and display the information. I change the IP address of the computer and rerun the code. I'm using unset() to clear the variable before executing the code, however, it still displays the old information. How do I obtain the current information using exec()? Thanks in advance and sorry for the noob-iness.

  <button type="button" class="btn btn-info btn-lg" onclick="showip()">Get IP</button>

Body:
A server may have multiple IP addresses, including at least the public IP and the local(VPN) IP.
I guess the question for obtain public IP has been answered. If you want to obtain the local IP(inside the VPN) of the server. You may try use 'ip addr' like this:

function ips(){
  $ips = [];
  exec('ip addr', $lines);
  foreach($lines as $line){
    $fields = explode(" ",trim($line));
    if($fields[0] == 'inet'){
      $ip = explode("/",$fields[1])[0];
      $ifname = $fields[count($fields)-1];
      $ips[$ifname] = $ip;
    }
  }
  return $ips;
}

This will return all local IP(v4) of each interfaces. If you want to have IPv6, just change 'inet' to 'inet6'.


问:
Editing an existing tag value on a Azure KeyVault secret version
My aim to create a new version of a particular secret in my KeyVault and copy all the tags of the current version to the new one. However while doing that, I want to change the value of one of those tags and keep the rest of them as it is.

```<code>$CurrentSecret = Get-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -IncludeVersions
$ActiveSecret = $CurrentSecret[0]

$NewSecret = New-AzServiceBusKey -Name $SecretName -ResourceGroup $ResourceGroupName -Namespace $SBNameSpace -RegenerateKey PrimaryKey

$NewSecretValue = $NewSecret.PrimaryKey

$SecureStringNewKey = ConvertTo-SecureString -String $NewSecretValue -AsPlainText -Force
$EndDate = (Get-Date).AddMonths(12)

$SecretObject = Set-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -SecretValue $SecureStringNewKey -Expires $EndDate -ContentType $ActiveSecret.ContentType -Tag $ActiveSecret.Tags

PS E:\XXX> $SecretObject.Tags

Name                           Value
----                           -----
KeyType                        Primary
SecretType                     ServiceBusKey
</code>```

I want to change the value of "KeyType" to "Secondary" and keep everything the same.

I tried the following but it overrides the value as expected :

```<code>$Tags = @{ 'KeyType' = 'Secondary'}

$New = Update-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -Expires $EndDate -ContentType $ActiveSecret.ContentType -Enable $True -Tag $Tags -PassThru

$New.Tags

Name                           Value
----                           -----
KeyType                        Secondary
</code>```

Eventually the tags in the original version would increase to around 10. I am not looking forward to a way of specifying everything in an enumerator as hardcore values in code while updating the tags.
I tried looking at $New.Tags.KeyType. (Length,Clone,GetEnumerator,GetHashCode,CompareTo,Contains,CopyTo,EndsWith,Equals)
but couldn't find a way to just update just the value of KeyType tag to 'Secondary'

答:
Well, if I understand your meaning correctly, you have already created the new version of the secret, and you want to update its Tag now, please try the command below after Set-AzKeyVaultSecret.

```<code>$sec = Get-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName
$sec.Tags.KeyType = "Secondary"
Update-AzKeyVaultSecret -VaultName $VaultName -Name $VaultName -Tag $sec.Tags
</code>```

Or you can use the command below directly, it will also work.

```<code>$SecretObject = Set-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -SecretValue $SecureStringNewKey -Expires $EndDate -ContentType $ActiveSecret.ContentType -Tag $ActiveSecret.Tags
$SecretObject.Tags.KeyType = "Secondary"
Update-AzKeyVaultSecret -VaultName $VaultName -Name mySecret123 -Tag $SecretObject.Tags
</code>```

Body:
My aim to create a new version of a particular secret in my KeyVault and copy all the tags of the current version to the new one. However while doing that, I want to change the value of one of those tags and keep the rest of them as it is.

$CurrentSecret = Get-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -IncludeVersions
$ActiveSecret = $CurrentSecret[0]

$NewSecret = New-AzServiceBusKey -Name $SecretName -ResourceGroup $ResourceGroupName -Namespace $SBNameSpace -RegenerateKey PrimaryKey

$NewSecretValue = $NewSecret.PrimaryKey

$SecureStringNewKey = ConvertTo-SecureString -String $NewSecretValue -AsPlainText -Force
$EndDate = (Get-Date).AddMonths(12)

$SecretObject = Set-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -SecretValue $SecureStringNewKey -Expires $EndDate -ContentType $ActiveSecret.ContentType -Tag $ActiveSecret.Tags

PS E:\XXX> $SecretObject.Tags

Name                           Value
----                           -----
KeyType                        Primary
SecretType                     ServiceBusKey

I want to change the value of "KeyType" to "Secondary" and keep everything the same.

I tried the following but it overrides the value as expected :

$Tags = @{ 'KeyType' = 'Secondary'}

$New = Update-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -Expires $EndDate -ContentType $ActiveSecret.ContentType -Enable $True -Tag $Tags -PassThru

$New.Tags

Name                           Value
----                           -----
KeyType                        Secondary

Eventually the tags in the original version would increase to around 10. I am not looking forward to a way of specifying everything in an enumerator as hardcore values in code while updating the tags.
I tried looking at $New.Tags.KeyType. (Length,Clone,GetEnumerator,GetHashCode,CompareTo,Contains,CopyTo,EndsWith,Equals)
but couldn't find a way to just update just the value of KeyType tag to 'Secondary'

Body:
Well, if I understand your meaning correctly, you have already created the new version of the secret, and you want to update its Tag now, please try the command below after Set-AzKeyVaultSecret.

$sec = Get-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName
$sec.Tags.KeyType = "Secondary"
Update-AzKeyVaultSecret -VaultName $VaultName -Name $VaultName -Tag $sec.Tags

Or you can use the command below directly, it will also work.

$SecretObject = Set-AzKeyVaultSecret -VaultName $VaultName -Name $SecretName -SecretValue $SecureStringNewKey -Expires $EndDate -ContentType $ActiveSecret.ContentType -Tag $ActiveSecret.Tags
$SecretObject.Tags.KeyType = "Secondary"
Update-AzKeyVaultSecret -VaultName $VaultName -Name mySecret123 -Tag $SecretObject.Tags


问:
Problem with jQuery mouseleave firing when container has select box
I have a two containers -- one is nested inside of another.  When I hover over the parent, I want the child container to appear. When I mouseout, I want the child container to fadeout. The problem I'm having is the child container has a form that contains a "select box". When the user selects the select box -- the mouseleave event is accidentally fired.

How can I stop the select box from tripping the mouseleave event?

You can see my working code here: http://jsfiddle.net/rsturim/9TZyh/3/

Here's a summary of my script:

```<code>$('#parent-container').live("mouseenter", function () {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave", function (e) {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().hide();
});
</code>```

edit: appears fine in WebKit-based browsers. Fails in Firefox and IE7-IE9.

答:
Since mouseleave and mouseenter events are non-standard you can get such lags here and there. The only method I can suggest to fix that is using some hacks. Here is http://jsfiddle.net/mPDcu/1/ improved version of you code.</p>

```<code>var selectOpened = false;
$('#select-grind-type').click(function(e){
    selectOpened = !selectOpened;
    e.stopPropagation();
});
$('body').click(function(){
    if (selectOpened) {
        selectOpened = false;
    }
})
$('#parent-container').on("mouseenter", function() {
    var $this = $(this),
        $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave", function(e) {
    if (!selectOpened) {
        var $this = $(this),
            $selectOptionsContainer = $this.find('#child-container');
        $selectOptionsContainer.stop().hide();
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a two containers -- one is nested inside of another.  When I hover over the parent, I want the child container to appear. When I mouseout, I want the child container to fadeout. The problem I'm having is the child container has a form that contains a "select box". When the user selects the select box -- the mouseleave event is accidentally fired.

How can I stop the select box from tripping the mouseleave event?

You can see my working code here: http://jsfiddle.net/rsturim/9TZyh/3/

Here's a summary of my script:

$('#parent-container').live("mouseenter", function () {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave", function (e) {
    var $this = $(this),
    $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().hide();
});

edit: appears fine in WebKit-based browsers. Fails in Firefox and IE7-IE9.

Body:
Since mouseleave and mouseenter events are non-standard you can get such lags here and there. The only method I can suggest to fix that is using some hacks. Here is http://jsfiddle.net/mPDcu/1/ improved version of you code.

var selectOpened = false;
$('#select-grind-type').click(function(e){
    selectOpened = !selectOpened;
    e.stopPropagation();
});
$('body').click(function(){
    if (selectOpened) {
        selectOpened = false;
    }
})
$('#parent-container').on("mouseenter", function() {
    var $this = $(this),
        $selectOptionsContainer = $this.find('#child-container');
    $selectOptionsContainer.stop().fadeTo('slow', 1.0);
}).live("mouseleave", function(e) {
    if (!selectOpened) {
        var $this = $(this),
            $selectOptionsContainer = $this.find('#child-container');
        $selectOptionsContainer.stop().hide();
    }
});


问:
Convert repetitive pattern into JSON file with python
Hope you are doing fine,

I have a data file(containing 1000s of a structured pattern of data), like below

```<code>PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""
</code>```

I tried to convert the datafile(partner.txt) to JSON with below code:

Created empty dictionaries dict1 and dict2

Reading the data file line by line

used this if not line.isspace() to make sure the linefeed is read is written in dictionary dict1

When linebreak(empty line appears) appended the content of dict1 to dict2 using dict2.update(dict1)

```<code>import json

dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')

        else:
            dict2.update(dict1)
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")

</code>```

But this code creates a json(test1.json) with only the single block of PARTNER

```<code>{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
}
</code>```

Expected Output
I tried looking up a lot but couldn't find a way:-

```<code>{
"data":[
{
 "PARTNER": "ABC",
 "ADDRESS1": "ABC Country INN",
 "DEPARTMENT": "ABC Department",
 "CONTACT_PERSON": "HR",
 "TELEPHONE": "+91.90.XX XX X XXX",
 "FAX": "+01.XX.XX XX XX XX",
 "EMAIL": ""
},
{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
},
{
 "PARTNER": "GEH-LOP",
 "ADDRESS1": "GEH LOP Street",
 "DEPARTMENT": "HR",
 "CONTACT_PERSON": "Adam",
 "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
 "FAX": "+91.ZZ.ZZ.ZZZ",
 "EMAIL": ""
}
]
}
</code>```

答:
You need to set dict1 to a new dict each time:</p>

```<code>import json
dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')
        else:
            dict2.update(dict1)
            dict1 = {}                             # set it to new dict
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")
</code>```

Body:
Hope you are doing fine,

I have a data file(containing 1000s of a structured pattern of data), like below

PARTNER="ABC"
  ADDRESS1="ABC Country INN"
  DEPARTMENT="ABC Department"
  CONTACT_PERSON="HR"
  TELEPHONE="+91.90.XX XX X XXX"
  FAX="+01.XX.XX XX XX XX"
  EMAIL=""

PARTNER="DEF"
  ADDRESS1="DEF Malaysia"
  DEPARTMENT=""
  CONTACT_PERSON=""
  TELEPHONE="(YYY)YYYYY"
  FAX="(001)YYYYYYYY"
  EMAIL=""

PARTNER="GEH-LOP"
  ADDRESS1="GEH LOP Street"
  DEPARTMENT="HR"
  CONTACT_PERSON="Adam"
  TELEPHONE="+91.ZZ.ZZ.ZZZZ"
  FAX="+91.ZZ.ZZ.ZZZ"
  EMAIL=""

I tried to convert the datafile(partner.txt) to JSON with below code:

Created empty dictionaries dict1 and dict2

Reading the data file line by line

used this if not line.isspace() to make sure the linefeed is read is written in dictionary dict1

When linebreak(empty line appears) appended the content of dict1 to dict2 using dict2.update(dict1)

import json

dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')

        else:
            dict2.update(dict1)
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")

But this code creates a json(test1.json) with only the single block of PARTNER

{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
}

Expected Output
I tried looking up a lot but couldn't find a way:-

{
"data":[
{
 "PARTNER": "ABC",
 "ADDRESS1": "ABC Country INN",
 "DEPARTMENT": "ABC Department",
 "CONTACT_PERSON": "HR",
 "TELEPHONE": "+91.90.XX XX X XXX",
 "FAX": "+01.XX.XX XX XX XX",
 "EMAIL": ""
},
{
 "PARTNER": "DEF",
 "ADDRESS1": "DEF Malaysia",
 "DEPARTMENT": "",
 "CONTACT_PERSON": "",
 "TELEPHONE": "(YYY)YYYYY",
 "FAX": "(001)YYYYYYYY",
 "EMAIL": ""
},
{
 "PARTNER": "GEH-LOP",
 "ADDRESS1": "GEH LOP Street",
 "DEPARTMENT": "HR",
 "CONTACT_PERSON": "Adam",
 "TELEPHONE": "+91.ZZ.ZZ.ZZZZ",
 "FAX": "+91.ZZ.ZZ.ZZZ",
 "EMAIL": ""
}
]
}

Body:
You need to set dict1 to a new dict each time:

import json
dict1 = {}
dict2 ={}

with open("partner.txt", "r") as fh:
    out_file = open("test1.json", "w")
    for line in fh:
        if not line.isspace():
            command, description = line.strip().split("=")
            dict1[command] = description.strip('"')
        else:
            dict2.update(dict1)
            dict1 = {}                             # set it to new dict
            print("space found")
    json.dump(dict2,out_file,indent=1)

out_file.close()

print("json file created")


问:
What is the right type definition to use for the onChange event for Grommet's RangeInput component?
I'm getting a typescript error for onChange of Grommet's RangeInput component.

```<code><RangeInput
 onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
  setAge(event.target.value)
 }
/>
</code>```

Error:

```<code>Type '(event: React.ChangeEvent<HTMLInputElement>) => void' is not assignable to type '((event: ChangeEvent<Element>) => void) & ((event: ChangeEvent<HTMLInputElement>) => void)'.
  Type '(event: React.ChangeEvent<HTMLInputElement>) => void' is not assignable to type '(event: ChangeEvent<Element>) => void'.
    Types of parameters 'event' and 'event' are incompatible.
      Type 'ChangeEvent<Element>' is not assignable to type 'ChangeEvent<HTMLInputElement>'.
        Type 'Element' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 159 more.ts(2322)
index.d.ts(8, 3): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & RangeInputProps & ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & { ...; }'
</code>```

What is the right type to use for the onChange? React.ChangeEvent?

答:
It's caused by the types of grommet, see https://github.com/grommet/grommet/blob/2a38c185e1/src/js/components/RangeInput/index.d.ts#L8.

The type of onChange omits generic param T, that means the typeof onChange is (event: React.ChangeEvent<Element>) => void.

A simple way to resolve this problem is use as in your project:

<RangeInput
 onChange={(event: React.ChangeEvent) =>
  setAge((event.target as HTMLInputElement).value)
 }
/>
```

A better way is create a pr for grommet to fix this problem, just need to remove the line of onChange declaration.

Body:
I'm getting a typescript error for onChange of Grommet's RangeInput component.

<RangeInput
 onChange={(event: React.ChangeEvent<HTMLInputElement>) =>
  setAge(event.target.value)
 }
/>

Error:

Type '(event: React.ChangeEvent<HTMLInputElement>) => void' is not assignable to type '((event: ChangeEvent<Element>) => void) & ((event: ChangeEvent<HTMLInputElement>) => void)'.
  Type '(event: React.ChangeEvent<HTMLInputElement>) => void' is not assignable to type '(event: ChangeEvent<Element>) => void'.
    Types of parameters 'event' and 'event' are incompatible.
      Type 'ChangeEvent<Element>' is not assignable to type 'ChangeEvent<HTMLInputElement>'.
        Type 'Element' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 159 more.ts(2322)
index.d.ts(8, 3): The expected type comes from property 'onChange' which is declared here on type 'IntrinsicAttributes & RangeInputProps & ClassAttributes<HTMLInputElement> & InputHTMLAttributes<HTMLInputElement> & { ...; }'

What is the right type to use for the onChange? React.ChangeEvent?

Body:
It's caused by the types of grommet, see https://github.com/grommet/grommet/blob/2a38c185e1/src/js/components/RangeInput/index.d.ts#L8.

The type of onChange omits generic param T, that means the typeof onChange is (event: React.ChangeEvent<Element>) => void.

A simple way to resolve this problem is use as in your project:

<RangeInput
 onChange={(event: React.ChangeEvent) =>
  setAge((event.target as HTMLInputElement).value)
 }
/>

A better way is create a pr for grommet to fix this problem, just need to remove the line of onChange declaration.


问:
Advance Custom Field to display specific content to logged in user
I am using Wordpress to show different clients information and I am new to ACF and I want to display contents as per a logged in customer. Different user have different data to be shown as a post. I have created fields to display for the user but I am not able to show the content as per a logged in user can any one help me?</p>

答:
In order to display for the user, you need to reference their username.

Use get_current_user_id() to capture the logged in user's ID and assign it as a variable:

```<code><?php $userid = get_current_user_id();?>
</code>```

Then you can pass the data just like any normal ACF field:

```<code><?php the_field('field_name', $userid);?>
</code>```

You can wrap both statements around a conditional if statement (such as is_user_logged_in()).

Body:
In order to display for the user, you need to reference their username.

Use get_current_user_id() to capture the logged in user's ID and assign it as a variable:

<?php $userid = get_current_user_id();?>

Then you can pass the data just like any normal ACF field:

<?php the_field('field_name', $userid);?>

You can wrap both statements around a conditional if statement (such as is_user_logged_in()).


问:
How to Generating Dynamic <meta> Tags on the Apache Server with react.js
I've created a react.js + router v4 project via facebookincubator/create-react-app, and I use Apache 2 without backend language to run my project.

I've read this official doc:

Generating Dynamic  Tags on the Server

Since Create React App doesn’t support server rendering, you might be wondering how to make  tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this:

```<code><!doctype html>
<html lang="en">
  <head>
    <meta property="og:title" content="__OG_TITLE__">
    <meta property="og:description" content="__OG_DESCRIPTION__">
</code>```

Then, on the server, regardless of the backend you use, you can read index.html into memory and replace OG_TITLE, OG_DESCRIPTION, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML!

If I use apache run my project without any backend language, is there have any way to Generating Dynamic  Tags?

Thanks.

答: With Apache serving up the React app you could solve this problem by jamming server side include statements into the index.html.</p>

Body:
I've created a react.js + router v4 project via facebookincubator/create-react-app, and I use Apache 2 without backend language to run my project.

I've read this official doc:

Generating Dynamic  Tags on the Server

Since Create React App doesn’t support server rendering, you might be wondering how to make  tags dynamic and reflect the current URL. To solve this, we recommend to add placeholders into the HTML, like this:

<!doctype html>

    <meta property="og:title" content="__OG_TITLE__">
    <meta property="og:description" content="__OG_DESCRIPTION__">

Then, on the server, regardless of the backend you use, you can read index.html into memory and replace OG_TITLE, OG_DESCRIPTION, and any other placeholders with values depending on the current URL. Just make sure to sanitize and escape the interpolated values so that they are safe to embed into HTML!

If I use apache run my project without any backend language, is there have any way to Generating Dynamic  Tags?

Thanks.


问:
Converting CIDR notation into IP range without other library
I want to find the IP range from CIDR.
For example, I input "192.168.1.1/24".
How do I calculate the IP range in Java?

I only can change the IP address and subnet mask to byte[].
But I don't know how to merge them.
This is my code.

```<code>String str = "192.168.1.1/24";
String[] cidr = str.split("/");
String[] buf = cidr[0].split(".");
byte[] ip = new byte[] {
                (byte)Integer.parseInt(buf[0]), (byte)Integer.parseInt(buf[1]),(byte)Integer.parseInt(buf[2]), (byte)Integer.parseInt(buf[3])
};

int mask = 0xffffffff << (32 - Integer.parseInt(cidr[1]));
        int value = mask;
        byte[] subnet = new byte[] {
                (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)
        };

</code>```

答:
First thing you need to do is fix the regex, because . has special meaning: cidr[0].split("\\.");

Then, to build the from and to addresses of the IP range, using bitwise AND, OR, and NOT:

byte[] from = new byte[4];
byte[] to = new byte[4];
for (int i = 0; i < to.length; i++) {
    from[i] = (byte) (ip[i] & subnet[i]);
    to[i] = (byte) (ip[i] | ~subnet[i]);
}
```

<p>Finally, print the result:</p>

<pre class="lang-java prettyprint-override"><code>System.out.printf("%d.%d.%d.%d - %d.%d.%d.%d%n",
        Byte.toUnsignedInt(from[0]), Byte.toUnsignedInt(from[1]),
        Byte.toUnsignedInt(from[2]), Byte.toUnsignedInt(from[3]),
        Byte.toUnsignedInt(to[0]), Byte.toUnsignedInt(to[1]),
        Byte.toUnsignedInt(to[2]), Byte.toUnsignedInt(to[3]));
</code>```

Output

192.168.1.0 - 192.168.1.255
```

FYI: The code fails for /0 because to mask value ends up wrong. I'll leave that as an exercise for you to fix that.

Body:
I want to find the IP range from CIDR.
For example, I input "192.168.1.1/24".
How do I calculate the IP range in Java?

I only can change the IP address and subnet mask to byte[].
But I don't know how to merge them.
This is my code.

String str = "192.168.1.1/24";
String[] cidr = str.split("/");
String[] buf = cidr[0].split(".");
byte[] ip = new byte[] {
                (byte)Integer.parseInt(buf[0]), (byte)Integer.parseInt(buf[1]),(byte)Integer.parseInt(buf[2]), (byte)Integer.parseInt(buf[3])
};

int mask = 0xffffffff << (32 - Integer.parseInt(cidr[1]));
        int value = mask;
        byte[] subnet = new byte[] {
                (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)
        };

Body:
First thing you need to do is fix the regex, because . has special meaning: cidr[0].split("\\.");

Then, to build the from and to addresses of the IP range, using bitwise AND, OR, and NOT:

byte[] from = new byte[4];
byte[] to = new byte[4];
for (int i = 0; i < to.length; i++) {
    from[i] = (byte) (ip[i] & subnet[i]);
    to[i] = (byte) (ip[i] | ~subnet[i]);
}

Finally, print the result:

System.out.printf("%d.%d.%d.%d - %d.%d.%d.%d%n",
        Byte.toUnsignedInt(from[0]), Byte.toUnsignedInt(from[1]),
        Byte.toUnsignedInt(from[2]), Byte.toUnsignedInt(from[3]),
        Byte.toUnsignedInt(to[0]), Byte.toUnsignedInt(to[1]),
        Byte.toUnsignedInt(to[2]), Byte.toUnsignedInt(to[3]));

Output

192.168.1.0 - 192.168.1.255

FYI: The code fails for /0 because to mask value ends up wrong. I'll leave that as an exercise for you to fix that.


问:
Why the need to redefine properties when implementing an interface in TypeScript?
I'm getting into classes and interfaces. And I got one thing about it that annoys me, this is the first time I work with these kind of things so bear with me here..

Let's say I got this interface:

```<code>// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}
</code>```

When I implement it in a class I do the following:

```<code>// FooModel.ts
import IFoo from './IFoo';

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}
</code>```

Why do I have to implement the same properties all over again?

This is basically the same as copy-paste but with a strict convention. Also, I have to type foo and bar a total of 6 times each to get it properly assigned with default optional values, based on an interface.

Is there a more efficient way to do this too?

Edit; I'm trying to achieve the following:

A class with the properties, from which the properties can be used for typescript's checking, like this:
interface

```<code>export default interface FooDTO {
  foo: string;
  bar: number;
}
</code>```

model

```<code>export interface IFoo {
  foo: string;
  bar: number;
}

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}
</code>```

controller

```<code>export default class FooController {
   public static async readAll(): Array<FooDTO> {
      // some model stuff which maps query to dto
      return Array<FooDTO>result;
   }
}
</code>```

答:
I think the canonical answer to "why do I have to implement the same properties all over again" is in the (increasingly outdated) TypeScript spec:

Note that because TypeScript has a structural type system, a class doesn't need to explicitly state that it implements an interface—it suffices for the class to simply contain the appropriate set of instance members. The implements clause of a class provides a mechanism to assert and validate that the class contains the appropriate sets of instance members, but otherwise it has no effect on the class type.

I added the emphasis above: the implements clause does not affect the class type at all; it doesn't add members to it or change the types of members.  All it does is tell the compiler to emit a warning if the class does not conform to the interface.

You may be interested in the GitHub issue microsoft/TypeScript#22815, which suggests that members of implemented interfaces should be copied down into the implementing classes.  (The title of the issue is about abstract classes, but the ensuing discussion is not limited to that.)  It looks like the sticking point is what to do about optional members (see this comment by the TS team lead).  The issue is an older one, but it's still open with a "needs proposal" tag, so if you care a lot about it you might want to go there, give it a , and maybe even give more details on what the behavior should be in edge cases so that it wouldn't be a breaking change.

Inside that issue is a suggested workaround using interface merging to tell the compiler that the class instance interface inherits properties:

```<code>interface FooModel extends IFoo { } // merge into FooModel
class FooModel {
    constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
        this.foo = foo;
        this.bar = bar;
    }
}
</code>```

This is less redundant but might be more confusing than just redeclaring the properties from the interface.

Anyway, hope that helps; good luck!

Playground link to code

Body:
I'm getting into classes and interfaces. And I got one thing about it that annoys me, this is the first time I work with these kind of things so bear with me here..

Let's say I got this interface:

// IFoo.d.ts
export default interface IFoo {
  foo: string;
  bar: number;
}

When I implement it in a class I do the following:

// FooModel.ts
import IFoo from './IFoo';

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}

Why do I have to implement the same properties all over again?

This is basically the same as copy-paste but with a strict convention. Also, I have to type foo and bar a total of 6 times each to get it properly assigned with default optional values, based on an interface.

Is there a more efficient way to do this too?

Edit; I'm trying to achieve the following:

A class with the properties, from which the properties can be used for typescript's checking, like this:
interface

export default interface FooDTO {
  foo: string;
  bar: number;
}

model

export interface IFoo {
  foo: string;
  bar: number;
}

export default class FooModel implements IFoo {
  foo: string;
  bar: number;

  constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
    this.foo = foo;
  }
}

controller

export default class FooController {
   public static async readAll(): Array<FooDTO> {
      // some model stuff which maps query to dto
      return Array<FooDTO>result;
   }
}

Body:
I think the canonical answer to "why do I have to implement the same properties all over again" is in the (increasingly outdated) TypeScript spec:

Note that because TypeScript has a structural type system, a class doesn't need to explicitly state that it implements an interface—it suffices for the class to simply contain the appropriate set of instance members. The implements clause of a class provides a mechanism to assert and validate that the class contains the appropriate sets of instance members, but otherwise it has no effect on the class type.

I added the emphasis above: the implements clause does not affect the class type at all; it doesn't add members to it or change the types of members.  All it does is tell the compiler to emit a warning if the class does not conform to the interface.

You may be interested in the GitHub issue microsoft/TypeScript#22815, which suggests that members of implemented interfaces should be copied down into the implementing classes.  (The title of the issue is about abstract classes, but the ensuing discussion is not limited to that.)  It looks like the sticking point is what to do about optional members (see this comment by the TS team lead).  The issue is an older one, but it's still open with a "needs proposal" tag, so if you care a lot about it you might want to go there, give it a , and maybe even give more details on what the behavior should be in edge cases so that it wouldn't be a breaking change.

Inside that issue is a suggested workaround using interface merging to tell the compiler that the class instance interface inherits properties:

interface FooModel extends IFoo { } // merge into FooModel
class FooModel {
    constructor({ foo, bar }: IFoo = { foo: 'hello', bar: 1 }) {
        this.foo = foo;
        this.bar = bar;
    }
}

This is less redundant but might be more confusing than just redeclaring the properties from the interface.

Anyway, hope that helps; good luck!

Playground link to code


问:
CS50 caesar part 1. What does return 1 do in the code below?
Why is the return 1 necessary in the code below? Is this to stop the loop from 'looping' after '1' cycle since it will go ON forever if the Boolean expression is false?

```<code>while (argc != 2 || isnumber(argv[1]) == false)
{
    printf("Usage: .caesar key\n");
    **return 1;**
}
</code>```

Can you explain this step by step?

答:
The statement should actually be if statement instead of while, as you execute the program once (with some input) and you cannot change it on-the-run.

return 1 (as well as EXIT_FAILURE macro) means that there was an error in the program, which in your case is bad number of arguments.

return 0 (and EXIT_SUCCESS macro) means that program finished without any errors.

Body:
Why is the return 1 necessary in the code below? Is this to stop the loop from 'looping' after '1' cycle since it will go ON forever if the Boolean expression is false?

while (argc != 2 || isnumber(argv[1]) == false)
{
    printf("Usage: .caesar key\n");
    **return 1;**
}

Can you explain this step by step?


问:
How can I set a global context in Next.js without getting a "Text content did not match" error?
I have a next.js App that needs to pull SESSION data in to a global context. Currently I have:

```<code>// _app.js

const App = ({ Component, pageProps }) => {

const start = typeof window !== 'undefined' ? window.sessionStorage.getItem('start') : 0;

  return (
    <ElapsedContext.Provider value={start}>
      <Component {...pageProps} />
    </ElapsedContext.Provider>
  )
};

export default App;
</code>```

and I'm consuming in my Component like so:

```<code>function MyComponent(props) {
  const start = useContext(ElapsedContext);
  return (
    // something using start;
  );
}
</code>```

However, when I consume that context in a component, the Component renders on the page as expected, but I get Warning: Text content did not match. Server: "0" Client: "5.883333333333345"

Which I think it because it initially passes the 0, then pulls the number from SESSION storage after the window loads.

How can I fix this warning?

Can I safely ignore this warning?

I've tried using useEffect in the _app.js file (which fires after window is loaded) but the initial state is then not available for my component to build what it needs built on initial render...

答:
Next.js renders pages either during build time or it server renders the page, which means window and therefore sessionStorage is not available as this runs in a Node.js environment.

If you ignore this warning, React will perform a re-render after the page loads. The great thing about server rendering React is that by the time the page loads React doesn't have to perform a re-render, so when this warning shows up you want to avoid it.

Although, because sessionStorage isn't available until the page is rendered in the browser, you'll have to wait to fill your Context until then.

Therefore, one way to avoid this error for your case would be to do something like:

// context.js
export const ElapsedContext = React.createContext(0);

export const ElapsedProvider = ({ children }) => {
  const [state, setState] = React.useState(0);

  React.useEffect(() => {
    // on client side mount, set starting value
    setState(window.sessionStorage.getItem('start'))
  }, [])

  return (
    <ElapsedContext.Provider
      value={state}
    >
      {children}
    </ElapsedContext.Provider>
  );
};

// pages/_app.js
export default function MyApp({ Component, pageProps }) {
  return <ElapsedProvider><Component {...pageProps} /></ElapsedProvider>
}

// pages/index.js
export default function MyPage() {
  const start = React.useContext(ElapsedContext);
  if (start === 0) {
    return <Loading />
  }

  return <MyComponentThatUsesElapsed />
}
```

Body:
I have a next.js App that needs to pull SESSION data in to a global context. Currently I have:

// _app.js

const App = ({ Component, pageProps }) => {

const start = typeof window !== 'undefined' ? window.sessionStorage.getItem('start') : 0;

  return (
    <ElapsedContext.Provider value={start}>
      <Component {...pageProps} />
    </ElapsedContext.Provider>
  )
};

export default App;

and I'm consuming in my Component like so:

function MyComponent(props) {
  const start = useContext(ElapsedContext);
  return (
    // something using start;
  );
}

However, when I consume that context in a component, the Component renders on the page as expected, but I get Warning: Text content did not match. Server: "0" Client: "5.883333333333345"

Which I think it because it initially passes the 0, then pulls the number from SESSION storage after the window loads.

How can I fix this warning?

Can I safely ignore this warning?

I've tried using useEffect in the _app.js file (which fires after window is loaded) but the initial state is then not available for my component to build what it needs built on initial render...


问:
A pattern that matches all except starting with a word
How can I set a regex pattern which matches all words but the strings which starts with

/word

/word/

/word/ following by anything else.

I think the pattern starts with  \A but I don'0t know how to tell that should not follow a word

Thanks

答:
You can use the regex:

```<code>^(?!\\/word).*$
</code>```

See it

Body:
You can use the regex:

^(?!\\/word).*$

See it


问:
How can I return jsx after a couple of seconds in a turnery operator?
Im using a turnery operator like this :

```<code>{
  typeof weather.data !== "undefined" ? (
    <React.Fragment>
      <div className="col-lg-6 col-md-6 col-sm-12 col-12 border">
        <Details
          temp={Math.round(weather.data.main.temp)}
          city={weather.data.name}
          country={weather.data.sys.country}
          date={dateBuilder}
          weather={weather.data.weather[0].main}
        />
      </div>
    </React.Fragment>
  ) : (
    setTimeout(() => {
      return (
        <div className="d-flex flex-column align-items-center w-100 font">
          <img style={{ width: "100px" }} src={require("./assets/wifi.png")} />
          <p className="mt-3">Please check your internet connection</p>
        </div>
      );
    }, 3000)
  );
}
</code>```

The problem is the If typeof weather.data is equal to undefined it doesn't return

Please check your connection

part after 3 seconds basically the setTimeout function doesn't work .

So how can I return value after a couple of seconds using setTimeout ?

答:
I would use a timeout to update a flag in state to show the JSX element</p>

```<code>const connFail = () => {
    setTimeout(() => {
        this.setState({ connFail: true });
    }, 3000);
};
</code>```

```<code>{
  typeof weather.data !== "undefined" && (
    <React.Fragment>
      <div className="col-lg-6 col-md-6 col-sm-12 col-12 border">
        <Details
          temp={Math.round(weather.data.main.temp)}
          city={weather.data.name}
          country={weather.data.sys.country}
          date={dateBuilder}
          weather={weather.data.weather[0].main}
        />
      </div>
    </React.Fragment>
  ) : connFail()
}
{
  this.state.connFail && (
    (
      <div className="d-flex flex-column align-items-center w-100 font">
        <img style={{ width: "100px" }} src={require("./assets/wifi.png")} />
        <p className="mt-3">Please check your internet connection</p>
      </div>
    );
  )
}
</code>```

Body:
Im using a turnery operator like this :

{
  typeof weather.data !== "undefined" ? (
    <React.Fragment>

    </React.Fragment>
  ) : (
    setTimeout(() => {
      return (

Please check your internet connection

      );
    }, 3000)
  );
}

The problem is the If typeof weather.data is equal to undefined it doesn't return

Please check your connection

part after 3 seconds basically the setTimeout function doesn't work .

So how can I return value after a couple of seconds using setTimeout ?

Body:
I would use a timeout to update a flag in state to show the JSX element

const connFail = () => {
    setTimeout(() => {
        this.setState({ connFail: true });
    }, 3000);
};

{
  typeof weather.data !== "undefined" && (
    <React.Fragment>
      <div className="col-lg-6 col-md-6 col-sm-12 col-12 border">
        <Details
          temp={Math.round(weather.data.main.temp)}
          city={weather.data.name}
          country={weather.data.sys.country}
          date={dateBuilder}
          weather={weather.data.weather[0].main}
        />
      </div>
    </React.Fragment>
  ) : connFail()
}
{
  this.state.connFail && (
    (
      <div className="d-flex flex-column align-items-center w-100 font">
        <img style={{ width: "100px" }} src={require("./assets/wifi.png")} />
        <p className="mt-3">Please check your internet connection</p>
      </div>
    );
  )
}


问:
Switching Pages with one pictureBox
I am trying to switch between 2 Pages with one pictureBox. I do not know how to do something like that.
I did try something like

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if(settings1.Visible)
            {
                isDisplayed = true;
                pictureBox2.Hide();
            }
            settings1.Show();
            settings1.BringToFront();
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            pictureBox1.Hide();
            pictureBox2.Show();
            pictureBox2.BringToFront();
            settings1.Hide();
        }
```

Maybe i am doing it completly wrong. Any Ideas?

答:
Here's one way that's in keeping with your original approach:

public partial class Form1 : Form
{
    PictureBox boxA, boxB;

    public Form1()
    {
        InitializeComponent();

        this.boxA = new System.Windows.Forms.PictureBox();
        this.boxA.BackColor = System.Drawing.Color.Red;
        this.boxA.Dock = System.Windows.Forms.DockStyle.Fill;
        this.boxA.Name = "boxA";
        this.boxA.Click += Box_Click;
        this.Controls.Add(this.boxA);

        this.boxB = new System.Windows.Forms.PictureBox();
        this.boxB.BackColor = System.Drawing.Color.Blue;
        this.boxB.Dock = System.Windows.Forms.DockStyle.Fill;
        this.boxB.Name = "boxB";
        this.boxB.Click += Box_Click;
        this.Controls.Add(this.boxB);

    }

    private void Box_Click(object sender, EventArgs e)
    {
        PictureBox box = sender as PictureBox;
        box.SendToBack();
    }
}

```

Title: Switching Pages with one pictureBox

Body:
I am trying to switch between 2 Pages with one pictureBox. I do not know how to do something like that.
I did try something like

        private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
        {
            if(settings1.Visible)
            {
                isDisplayed = true;
                pictureBox2.Hide();
            }
            settings1.Show();
            settings1.BringToFront();
        }

        private void pictureBox2_Click(object sender, EventArgs e)
        {
            pictureBox1.Hide();
            pictureBox2.Show();
            pictureBox2.BringToFront();
            settings1.Hide();
        }

Maybe i am doing it completly wrong. Any Ideas?


问:
InvalidServerSideConfigurationException when creating cache using XML
I'm new with terracotta. I want to create a clustered server cache but found some difficulties with configuration files.

Here is my tc-config-terracotta.xml file (with which I launch terracotta server)

```<code><?xml version="1.0" encoding="UTF-8"?>
<tc-config xmlns="http://www.terracotta.org/config"
    xmlns:ohr="http://www.terracotta.org/config/offheap-resource">

    <servers>
        <server host="localhost" name="clustered">
            <logs>/path/log/terracotta/server-logs</logs>
        </server>
    </servers>
    <plugins>
        <config>
            <ohr:offheap-resources>
                <ohr:resource name="primary-server-resource" unit="MB">128
                </ohr:resource>
                <ohr:resource name="secondary-server-resource" unit="MB">96
                </ohr:resource>
            </ohr:offheap-resources>
        </config>
    </plugins>
</tc-config>
</code>```

I used the ehcache-clustered-3.3.1-kit to launch the server.

```<code>$myPrompt/some/dir/with/ehcache/clustered/server/bin>./start-tc-server.sh -f /path/to/conf/tc-config-terracotta.xml
</code>```

No problem for the server to start

```<code>2017-06-01 11:29:14,052 INFO - New logging session started.
2017-06-01 11:29:14,066 INFO - Terracotta 5.2.2, as of 2017-03-29 at 15:26:20 PDT (Revision 397a456cfe4b8188dfe8b017a5c14346f79c2fcf from UNKNOWN)
2017-06-01 11:29:14,067 INFO - PID is 6114
2017-06-01 11:29:14,697 INFO - Successfully loaded base configuration from file at '/path/to/conf/tc-config-terracotta.xml'.
2017-06-01 11:29:14,757 INFO - Available Max Runtime Memory: 1822MB
2017-06-01 11:29:14,836 INFO - Log file: '/path/log/terracotta/server-logs/terracotta-server.log'.
2017-06-01 11:29:15,112 INFO - Becoming State[ ACTIVE-COORDINATOR ]
2017-06-01 11:29:15,129 INFO - Terracotta Server instance has started up as ACTIVE node on 0:0:0:0:0:0:0:0:9510 successfully, and is now ready for work.
</code>```

Here is the ehcache-terracotta.xml configuration file

```<code><ehcache:config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns:terracotta='http://www.ehcache.org/v3/clustered'
    xmlns:ehcache='http://www.ehcache.org/v3'
    xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.3.xsd
    http://www.ehcache.org/v3/clustered http://www.ehcache.org/schema/ehcache-clustered-ext-3.3.xsd">

    <ehcache:service>
        <terracotta:cluster>
            <terracotta:connection url="terracotta://localhost:9510/clustered" />
            <terracotta:server-side-config
                auto-create="true">
                <terracotta:default-resource from="primary-server-resource" />
            </terracotta:server-side-config>
        </terracotta:cluster>
    </ehcache:service>

    <ehcache:cache alias="myTest">
        <ehcache:key-type>java.lang.String</ehcache:key-type>
        <ehcache:value-type>java.lang.String</ehcache:value-type>
        <ehcache:resources>
            <terracotta:clustered-dedicated unit="MB">10
            </terracotta:clustered-dedicated>
        </ehcache:resources>
        <terracotta:clustered-store consistency="strong" />
    </ehcache:cache>
</ehcache:config>
</code>```

I have a class to test the conf:

```<code>import java.net.URL;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;

public class TestTerracottaCacheManager
{

   private static TestTerracottaCacheManager cacheManager = null;

   private CacheManager cm;

   private Cache<Object, Object> cache;

   private static final String DEFAULT_CACHE_NAME = "myTest";

   private String cacheName;

   public static TestTerracottaCacheManager getInstance()
   {
      if (cacheManager == null)
      {
         cacheManager = new TestTerracottaCacheManager();
      }
      return cacheManager;
   }

   private TestTerracottaCacheManager()
   {
      // 1. Create a cache manager
      final URL url =
         TestTerracottaCacheManager.class.getResource("/ehcache-terracotta.xml");
      System.out.println(url);
      Configuration xmlConfig = new XmlConfiguration(url);
      cm = CacheManagerBuilder.newCacheManager(xmlConfig);
      cm.init();
      intializeCache();
   }

   private void intializeCache()
   {
      // 2. Get a cache called "cache1", declared in ehcache.xml
      cache = cm.getCache(cacheName == null ? DEFAULT_CACHE_NAME : cacheName,
            Object.class, Object.class);
      if (cache == null)
      {
         throw new NullPointerException();
      }
   }

   public void put(Object key, Object value)
   {
      cache.put(key, value);
   }

   public Object get(String key)
   {
      // 5. Print out the element
      Object ele = cache.get(key);
      return ele;
   }

   public boolean isKeyInCache(Object key)
   {
      return cache.containsKey(key);
   }

   public void closeCache()
   {
      // 7. shut down the cache manager
      cm.close();
   }

   public static void main(String[] args)
   {
      TestTerracottaCacheManager testCache = TestTerracottaCacheManager.getInstance();
      testCache.put("titi", "1");
      System.out.println(testCache.get("titi"));
      testCache.closeCache();
   }

   public String getCacheName()
   {
      return cacheName;
   }

   public void setCacheName(String cacheName)
   {
      this.cacheName = cacheName;
   }
}
</code>```

I've got an exception. Here it's the stack trace:

```<code>14:18:38.978 [main] ERROR org.ehcache.core.EhcacheManager - Initialize failed.
Exception in thread "main" org.ehcache.StateTransitionException: Unable to validate cluster tier manager for id clustered
    at org.ehcache.core.StatusTransitioner$Transition.failed(StatusTransitioner.java:235)
    at org.ehcache.core.EhcacheManager.init(EhcacheManager.java:587)
    at fr.test.cache.TestTerracottaCacheManager.<init>(TestTerracottaCacheManager.java:41)
    at fr.test.cache.TestTerracottaCacheManager.getInstance(TestTerracottaCacheManager.java:28)
    at fr.test.cache.TestTerracottaCacheManager.main(TestTerracottaCacheManager.java:81)
Caused by: org.ehcache.clustered.client.internal.ClusterTierManagerValidationException: Unable to validate cluster tier manager for id clusteredENS
    at org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory.retrieve(ClusterTierManagerClientEntityFactory.java:196)
    at org.ehcache.clustered.client.internal.service.DefaultClusteringService.autoCreateEntity(DefaultClusteringService.java:215)
    at org.ehcache.clustered.client.internal.service.DefaultClusteringService.start(DefaultClusteringService.java:148)
    at org.ehcache.core.internal.service.ServiceLocator.startAllServices(ServiceLocator.java:118)
    at org.ehcache.core.EhcacheManager.init(EhcacheManager.java:559)
    ... 3 more
Caused by: org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException: Default resource not aligned. Client: primary-server-resource Server: null
    at org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException.withClientStackTrace(InvalidServerSideConfigurationException.java:43)
    at org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException.withClientStackTrace(InvalidServerSideConfigurationException.java:22)
    at org.ehcache.clustered.common.internal.messages.ResponseCodec.decode(ResponseCodec.java:197)
    at org.ehcache.clustered.common.internal.messages.EhcacheCodec.decodeResponse(EhcacheCodec.java:110)
    at org.ehcache.clustered.common.internal.messages.EhcacheCodec.decodeResponse(EhcacheCodec.java:37)
    at com.tc.object.EntityClientEndpointImpl$InvocationBuilderImpl$1.getWithTimeout(EntityClientEndpointImpl.java:193)
    at com.tc.object.EntityClientEndpointImpl$InvocationBuilderImpl$1.getWithTimeout(EntityClientEndpointImpl.java:175)
    at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.waitFor(SimpleClusterTierManagerClientEntity.java:184)
    at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.invokeInternal(SimpleClusterTierManagerClientEntity.java:148)
    at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.validate(SimpleClusterTierManagerClientEntity.java:120)
    at org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory.retrieve(ClusterTierManagerClientEntityFactory.java:190)
    ... 7 more
Caused by: org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException: Default resource not aligned. Client: primary-server-resource Server: null
    at org.ehcache.clustered.server.EhcacheStateServiceImpl.checkConfigurationCompatibility(EhcacheStateServiceImpl.java:207)
    at org.ehcache.clustered.server.EhcacheStateServiceImpl.validate(EhcacheStateServiceImpl.java:194)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.validate(ClusterTierManagerActiveEntity.java:253)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invokeLifeCycleOperation(ClusterTierManagerActiveEntity.java:203)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invoke(ClusterTierManagerActiveEntity.java:147)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invoke(ClusterTierManagerActiveEntity.java:57)
    at com.tc.objectserver.entity.ManagedEntityImpl.performAction(ManagedEntityImpl.java:741)
    at com.tc.objectserver.entity.ManagedEntityImpl.invoke(ManagedEntityImpl.java:488)
    at com.tc.objectserver.entity.ManagedEntityImpl.lambda$processInvokeRequest$2(ManagedEntityImpl.java:319)
    at com.tc.objectserver.entity.ManagedEntityImpl$SchedulingRunnable.run(ManagedEntityImpl.java:1048)
    at com.tc.objectserver.entity.RequestProcessor$EntityRequest.invoke(RequestProcessor.java:170)
    at com.tc.objectserver.entity.RequestProcessor$EntityRequest.run(RequestProcessor.java:161)
    at com.tc.objectserver.entity.RequestProcessorHandler.handleEvent(RequestProcessorHandler.java:27)
    at com.tc.objectserver.entity.RequestProcessorHandler.handleEvent(RequestProcessorHandler.java:23)
    at com.tc.async.impl.StageQueueImpl$HandledContext.runWithHandler(StageQueueImpl.java:502)
    at com.tc.async.impl.StageImpl$WorkerThread.run(StageImpl.java:192)
</code>```

I think it's a problem in the XML files, but I'm not sure. Someone can help please?

Thanks

答:
@AnthonyDahanne I am using ehcache-clustered-3.8.1-kit to launch the server. I have ehcache.xml my spring boot application is automatically picking my ehache.xml so I am not explicitly writing cacheManager.</p>

```<code><ehcache:config
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
  xmlns:terracotta='http://www.ehcache.org/v3/clustered'
  xmlns:ehcache='http://www.ehcache.org/v3'
  xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.8.xsd
    http://www.ehcache.org/v3/clustered http://www.ehcache.org/schema/ehcache-clustered-ext-3.8.xsd">

  <ehcache:service>
    <terracotta:cluster>
      <terracotta:connection url="terracotta://localhost:9410/clustered"/>
      <terracotta:server-side-config auto-create="true">
          <!--<terracotta:default-resource from="default-resource"/>-->
          <terracotta:shared-pool name="shared-pool-expense" unit="MB">100</terracotta:shared-pool>
      </terracotta:server-side-config>
    </terracotta:cluster>
 </ehcache:service>

  <ehcache:cache alias="areaOfCircleCache">
    <ehcache:key-type>java.lang.String</ehcache:key-type>
    <ehcache:value-type>com.db.entity.LogMessage</ehcache:value-type>
    <ehcache:resources>
      <!--      <ehcache:heap unit="entries">100</ehcache:heap>
       <ehcache:offheap unit="MB">10</ehcache:offheap>-->
      <terracotta:clustered-dedicated unit="MB">10</terracotta:clustered-dedicated>
    </ehcache:resources>
  </ehcache:cache>
</ehcache:config>
</code>```

Body:
I'm new with terracotta. I want to create a clustered server cache but found some difficulties with configuration files.

Here is my tc-config-terracotta.xml file (with which I launch terracotta server)

<?xml version="1.0" encoding="UTF-8"?>
<tc-config xmlns="http://www.terracotta.org/config"
    xmlns:ohr="http://www.terracotta.org/config/offheap-resource">

    <servers>
        <server host="localhost" name="clustered">
            <logs>/path/log/terracotta/server-logs</logs>
        </server>
    </servers>
    <plugins>
        <config>
            <ohr:offheap-resources>
                <ohr:resource name="primary-server-resource" unit="MB">128
                </ohr:resource>
                <ohr:resource name="secondary-server-resource" unit="MB">96
                </ohr:resource>
            </ohr:offheap-resources>
        </config>
    </plugins>
</tc-config>

I used the ehcache-clustered-3.3.1-kit to launch the server.

$myPrompt/some/dir/with/ehcache/clustered/server/bin>./start-tc-server.sh -f /path/to/conf/tc-config-terracotta.xml

No problem for the server to start

2017-06-01 11:29:14,052 INFO - New logging session started.
2017-06-01 11:29:14,066 INFO - Terracotta 5.2.2, as of 2017-03-29 at 15:26:20 PDT (Revision 397a456cfe4b8188dfe8b017a5c14346f79c2fcf from UNKNOWN)
2017-06-01 11:29:14,067 INFO - PID is 6114
2017-06-01 11:29:14,697 INFO - Successfully loaded base configuration from file at '/path/to/conf/tc-config-terracotta.xml'.
2017-06-01 11:29:14,757 INFO - Available Max Runtime Memory: 1822MB
2017-06-01 11:29:14,836 INFO - Log file: '/path/log/terracotta/server-logs/terracotta-server.log'.
2017-06-01 11:29:15,112 INFO - Becoming State[ ACTIVE-COORDINATOR ]
2017-06-01 11:29:15,129 INFO - Terracotta Server instance has started up as ACTIVE node on 0:0:0:0:0:0:0:0:9510 successfully, and is now ready for work.

Here is the ehcache-terracotta.xml configuration file

<ehcache:config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
    xmlns:terracotta='http://www.ehcache.org/v3/clustered'
    xmlns:ehcache='http://www.ehcache.org/v3'
    xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.3.xsd
    http://www.ehcache.org/v3/clustered http://www.ehcache.org/schema/ehcache-clustered-ext-3.3.xsd">

    <ehcache:service>
        <terracotta:cluster>
            <terracotta:connection url="terracotta://localhost:9510/clustered" />
            <terracotta:server-side-config
                auto-create="true">
                <terracotta:default-resource from="primary-server-resource" />
            </terracotta:server-side-config>
        </terracotta:cluster>
    </ehcache:service>

    <ehcache:cache alias="myTest">
        <ehcache:key-type>java.lang.String</ehcache:key-type>
        <ehcache:value-type>java.lang.String</ehcache:value-type>
        <ehcache:resources>
            <terracotta:clustered-dedicated unit="MB">10
            </terracotta:clustered-dedicated>
        </ehcache:resources>
        <terracotta:clustered-store consistency="strong" />
    </ehcache:cache>
</ehcache:config>

I have a class to test the conf:

import java.net.URL;

import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.Configuration;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.xml.XmlConfiguration;

public class TestTerracottaCacheManager
{

   private static TestTerracottaCacheManager cacheManager = null;

   private CacheManager cm;

   private Cache<Object, Object> cache;

   private static final String DEFAULT_CACHE_NAME = "myTest";

   private String cacheName;

   public static TestTerracottaCacheManager getInstance()
   {
      if (cacheManager == null)
      {
         cacheManager = new TestTerracottaCacheManager();
      }
      return cacheManager;
   }

   private TestTerracottaCacheManager()
   {
      // 1. Create a cache manager
      final URL url =
         TestTerracottaCacheManager.class.getResource("/ehcache-terracotta.xml");
      System.out.println(url);
      Configuration xmlConfig = new XmlConfiguration(url);
      cm = CacheManagerBuilder.newCacheManager(xmlConfig);
      cm.init();
      intializeCache();
   }

   private void intializeCache()
   {
      // 2. Get a cache called "cache1", declared in ehcache.xml
      cache = cm.getCache(cacheName == null ? DEFAULT_CACHE_NAME : cacheName,
            Object.class, Object.class);
      if (cache == null)
      {
         throw new NullPointerException();
      }
   }

   public void put(Object key, Object value)
   {
      cache.put(key, value);
   }

   public Object get(String key)
   {
      // 5. Print out the element
      Object ele = cache.get(key);
      return ele;
   }

   public boolean isKeyInCache(Object key)
   {
      return cache.containsKey(key);
   }

   public void closeCache()
   {
      // 7. shut down the cache manager
      cm.close();
   }

   public static void main(String[] args)
   {
      TestTerracottaCacheManager testCache = TestTerracottaCacheManager.getInstance();
      testCache.put("titi", "1");
      System.out.println(testCache.get("titi"));
      testCache.closeCache();
   }

   public String getCacheName()
   {
      return cacheName;
   }

   public void setCacheName(String cacheName)
   {
      this.cacheName = cacheName;
   }
}

I've got an exception. Here it's the stack trace:

14:18:38.978 [main] ERROR org.ehcache.core.EhcacheManager - Initialize failed.
Exception in thread "main" org.ehcache.StateTransitionException: Unable to validate cluster tier manager for id clustered
    at org.ehcache.core.StatusTransitioner$Transition.failed(StatusTransitioner.java:235)
    at org.ehcache.core.EhcacheManager.init(EhcacheManager.java:587)
    at fr.test.cache.TestTerracottaCacheManager.<init>(TestTerracottaCacheManager.java:41)
    at fr.test.cache.TestTerracottaCacheManager.getInstance(TestTerracottaCacheManager.java:28)
    at fr.test.cache.TestTerracottaCacheManager.main(TestTerracottaCacheManager.java:81)
Caused by: org.ehcache.clustered.client.internal.ClusterTierManagerValidationException: Unable to validate cluster tier manager for id clusteredENS
    at org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory.retrieve(ClusterTierManagerClientEntityFactory.java:196)
    at org.ehcache.clustered.client.internal.service.DefaultClusteringService.autoCreateEntity(DefaultClusteringService.java:215)
    at org.ehcache.clustered.client.internal.service.DefaultClusteringService.start(DefaultClusteringService.java:148)
    at org.ehcache.core.internal.service.ServiceLocator.startAllServices(ServiceLocator.java:118)
    at org.ehcache.core.EhcacheManager.init(EhcacheManager.java:559)
    ... 3 more
Caused by: org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException: Default resource not aligned. Client: primary-server-resource Server: null
    at org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException.withClientStackTrace(InvalidServerSideConfigurationException.java:43)
    at org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException.withClientStackTrace(InvalidServerSideConfigurationException.java:22)
    at org.ehcache.clustered.common.internal.messages.ResponseCodec.decode(ResponseCodec.java:197)
    at org.ehcache.clustered.common.internal.messages.EhcacheCodec.decodeResponse(EhcacheCodec.java:110)
    at org.ehcache.clustered.common.internal.messages.EhcacheCodec.decodeResponse(EhcacheCodec.java:37)
    at com.tc.object.EntityClientEndpointImpl$InvocationBuilderImpl$1.getWithTimeout(EntityClientEndpointImpl.java:193)
    at com.tc.object.EntityClientEndpointImpl$InvocationBuilderImpl$1.getWithTimeout(EntityClientEndpointImpl.java:175)
    at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.waitFor(SimpleClusterTierManagerClientEntity.java:184)
    at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.invokeInternal(SimpleClusterTierManagerClientEntity.java:148)
    at org.ehcache.clustered.client.internal.SimpleClusterTierManagerClientEntity.validate(SimpleClusterTierManagerClientEntity.java:120)
    at org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory.retrieve(ClusterTierManagerClientEntityFactory.java:190)
    ... 7 more
Caused by: org.ehcache.clustered.common.internal.exceptions.InvalidServerSideConfigurationException: Default resource not aligned. Client: primary-server-resource Server: null
    at org.ehcache.clustered.server.EhcacheStateServiceImpl.checkConfigurationCompatibility(EhcacheStateServiceImpl.java:207)
    at org.ehcache.clustered.server.EhcacheStateServiceImpl.validate(EhcacheStateServiceImpl.java:194)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.validate(ClusterTierManagerActiveEntity.java:253)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invokeLifeCycleOperation(ClusterTierManagerActiveEntity.java:203)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invoke(ClusterTierManagerActiveEntity.java:147)
    at org.ehcache.clustered.server.ClusterTierManagerActiveEntity.invoke(ClusterTierManagerActiveEntity.java:57)
    at com.tc.objectserver.entity.ManagedEntityImpl.performAction(ManagedEntityImpl.java:741)
    at com.tc.objectserver.entity.ManagedEntityImpl.invoke(ManagedEntityImpl.java:488)
    at com.tc.objectserver.entity.ManagedEntityImpl.lambda$processInvokeRequest$2(ManagedEntityImpl.java:319)
    at com.tc.objectserver.entity.ManagedEntityImpl$SchedulingRunnable.run(ManagedEntityImpl.java:1048)
    at com.tc.objectserver.entity.RequestProcessor$EntityRequest.invoke(RequestProcessor.java:170)
    at com.tc.objectserver.entity.RequestProcessor$EntityRequest.run(RequestProcessor.java:161)
    at com.tc.objectserver.entity.RequestProcessorHandler.handleEvent(RequestProcessorHandler.java:27)
    at com.tc.objectserver.entity.RequestProcessorHandler.handleEvent(RequestProcessorHandler.java:23)
    at com.tc.async.impl.StageQueueImpl$HandledContext.runWithHandler(StageQueueImpl.java:502)
    at com.tc.async.impl.StageImpl$WorkerThread.run(StageImpl.java:192)

I think it's a problem in the XML files, but I'm not sure. Someone can help please?

Thanks

Body:
@AnthonyDahanne I am using ehcache-clustered-3.8.1-kit to launch the server. I have ehcache.xml my spring boot application is automatically picking my ehache.xml so I am not explicitly writing cacheManager.

<ehcache:config
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
  xmlns:terracotta='http://www.ehcache.org/v3/clustered'
  xmlns:ehcache='http://www.ehcache.org/v3'
  xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.8.xsd
    http://www.ehcache.org/v3/clustered http://www.ehcache.org/schema/ehcache-clustered-ext-3.8.xsd">

  <ehcache:service>
    <terracotta:cluster>
      <terracotta:connection url="terracotta://localhost:9410/clustered"/>
      <terracotta:server-side-config auto-create="true">
          <!--<terracotta:default-resource from="default-resource"/>-->
          <terracotta:shared-pool name="shared-pool-expense" unit="MB">100</terracotta:shared-pool>
      </terracotta:server-side-config>
    </terracotta:cluster>
 </ehcache:service>

  <ehcache:cache alias="areaOfCircleCache">
    <ehcache:key-type>java.lang.String</ehcache:key-type>
    <ehcache:value-type>com.db.entity.LogMessage</ehcache:value-type>
    <ehcache:resources>
      <!--      <ehcache:heap unit="entries">100</ehcache:heap>
       <ehcache:offheap unit="MB">10</ehcache:offheap>-->
      <terracotta:clustered-dedicated unit="MB">10</terracotta:clustered-dedicated>
    </ehcache:resources>
  </ehcache:cache>
</ehcache:config>


问:
Using $in clause for insensitive search in mongo db driver c#
I am wondering how to use the case insensitive for $in expressions.

According to the official MongoDB manual you can do this:

```<code>{ name: { $in: [ /^acme/i, /^ack/ ] } }
</code>```

I tested out this on Compass and it's working fine, search is insensitive.

I need to this using the Mongo Driver in C#.

I am doing this:

```<code>  var array = new BsonArray(companyNames);

  var filter = new BsonDocument { { "Name", new BsonDocument { { "$in", new BsonArray(array) }} } };
  var result = _collection.Find(filter).ToList();
</code>```

companyNames is a string[]

However this retrieves me only exact matches. It's kind of obvious because I am not including the "regex" expression. But I don't know how I am able to include the regex in a string.

The workaround is to create an $or expresion with regex for every company name.

Does anyone knows how to do this?

Thanks

答:
My solution was an overloaded .In() as an extension method, taking an extra parameter for case-insensitivity:

```<code>public static class MongoExtensions
{
    public static FilterDefinition<TDocument> In<TDocument>(
        this FilterDefinitionBuilder<TDocument> builder,
        Expression<Func<TDocument, object>> expr,
        IEnumerable<string> values,
        bool ignoreCase)
    {
        if (!ignoreCase)
        {
            return builder.In(expr, values);
        }

        var filters = values
            .Select(v => builder.Regex(expr, new BsonRegularExpression($"^{Regex.Escape(v)}$", "i")));

        return builder.Or(filters);
    }
}
</code>```

Then you can simply:

```<code>var filter = Builders<Companies>.Filter.In(c => c.Name, companyNames, true);
var result = _collection.Find(filter).ToList();
</code>```

Body:
I am wondering how to use the case insensitive for $in expressions.

According to the official MongoDB manual you can do this:

{ name: { $in: [ /^acme/i, /^ack/ ] } }

I tested out this on Compass and it's working fine, search is insensitive.

I need to this using the Mongo Driver in C#.

I am doing this:

  var array = new BsonArray(companyNames);

  var filter = new BsonDocument { { "Name", new BsonDocument { { "$in", new BsonArray(array) }} } };
  var result = _collection.Find(filter).ToList();

companyNames is a string[]

However this retrieves me only exact matches. It's kind of obvious because I am not including the "regex" expression. But I don't know how I am able to include the regex in a string.

The workaround is to create an $or expresion with regex for every company name.

Does anyone knows how to do this?

Thanks

Body:
My solution was an overloaded .In() as an extension method, taking an extra parameter for case-insensitivity:

public static class MongoExtensions
{
    public static FilterDefinition<TDocument> In<TDocument>(
        this FilterDefinitionBuilder<TDocument> builder,
        Expression<Func<TDocument, object>> expr,
        IEnumerable<string> values,
        bool ignoreCase)
    {
        if (!ignoreCase)
        {
            return builder.In(expr, values);
        }

        var filters = values
            .Select(v => builder.Regex(expr, new BsonRegularExpression($"^{Regex.Escape(v)}$", "i")));

        return builder.Or(filters);
    }
}

Then you can simply:

var filter = Builders<Companies>.Filter.In(c => c.Name, companyNames, true);
var result = _collection.Find(filter).ToList();


问:
KeyError in multiIndex
Following code gives me keyerror, what's the right way to access multiindex dataframe, WITHOUT using functions like loc etc.?

```<code>arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
multi_idx=pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))
dfm=pd.DataFrame({"hello":[1,2,3,4]},index=multi_idx)
print(dfm[1]['red'])
</code>```

答:
Please Try

```<code> dfm.query('color == "red"')
</code>```

or slice rows.slice(None) selects all the contents of that level. It excempts the specifying of deeper levels. Slice(None) implies them.

```<code>dfm.loc[(slice(None),'red'),:]
</code>```

Title: KeyError in multiIndex

Body:
Following code gives me keyerror, what's the right way to access multiindex dataframe, WITHOUT using functions like loc etc.?

arrays = [[1, 1, 2, 2], ['red', 'blue', 'red', 'blue']]
multi_idx=pd.MultiIndex.from_arrays(arrays, names=('number', 'color'))
dfm=pd.DataFrame({"hello":[1,2,3,4]},index=multi_idx)
print(dfm[1]['red'])

Body:
Please Try

 dfm.query('color == "red"')

or slice rows.slice(None) selects all the contents of that level. It excempts the specifying of deeper levels. Slice(None) implies them.

dfm.loc[(slice(None),'red'),:]