答:
The problem was with how the server was using bouncy castle in adding the X509v3 Subject Key Identifier to the certificate's X509v3 extensions.

Instead of doing:

x509v3CertificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, pk10Holder.getSubjectPublicKeyInfo());
```

<p>Which produces garbage:</p>

<pre class="lang-sh prettyprint-override"><code>        X509v3 extensions:
            X509v3 Subject Key Identifier:
..........0..   0.."0
@%,.....&Nv.
..r.s..I......)K..Y.<..:...I ...B...U.\.....*j8c...`W..X.....MXCI.Ic.O...........[.E.[L.:jK&%.8N...A1R.dv{.j........>X.E..n...H:..wcN#........Aq..v..q...h......g.L....".6_TM
</code>```

Do:

x509v3CertificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(inputCSR.getPublicKey()));

```

<p>Which produces a proper hash of the certificate:</p>

<pre class="lang-sh prettyprint-override"><code>X509v3 extensions:
        X509v3 Subject Key Identifier:
                10:47:60:D7:98:D5:3C:D6:AC:66:FC:17:B4:F5:44:15:7B:AF:0B:D1
</code>```

Title: Can't parse certificate after upgrading openssl on the client side

Body:
We've upgraded openssl on the client side from OpenSSL 1.0.1e-fips to OpenSSL 1.1.1b. The server side is running Bouncy Castle 1.46.

With OpenSSL 1.0.1e-fips on the client side, the server sends a certificate that looks like this:

PEM
---
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1553073698333 (0x1699a67f61d)
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=US, CN=10.12.204.189
        Validity
            Not Before: May 21 05:38:35 2019 GMT
            Not After : May 20 21:00:00 2049 GMT
        Subject:
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:b7:7f:20:0c:21:a2:7a:79:4f:12:8b:cd:db:92:
                    b6:76:79:34:34:bc:6a:c0:c9:87:ab:1b:df:e9:a1:
                    ff:f0:de:6f:15:bd:5e:cb:f3:bf:fb:fd:06:9d:8b:
                    f1:62:28:48:e0:e1:bd:79:48:f8:53:a0:15:93:65:
                    c2:b6:b5:88:93:63:a7:47:44:7c:96:84:48:1d:ed:
                    49:09:0e:10:57:31:60:bb:7a:3b:8b:61:bd:47:3c:
                    8a:e6:0a:c1:86:f1:75:84:62:5a:05:6a:43:25:7d:
                    0b:40:33:68:ce:f8:07:71:52:8e:3d:d1:df:57:ee:
                    23:86:51:7f:d9:3e:0a:f8:19:b8:49:a5:2e:77:8a:
                    5c:8d:26:f9:3a:94:e0:dc:62:81:47:1b:e5:e4:da:
                    45:a4:2a:70:ed:61:50:68:b5:0f:b7:5f:d4:cd:36:
                    3f:85:6f:c8:cb:1b:7b:a0:ec:f1:3c:5e:d4:e0:08:
                    65:aa:4a:7e:88:05:cc:ac:45:4e:09:f2:36:d9:a9:
                    96:9f:05:9d:95:e6:37:f8:f7:3c:62:cb:0d:4a:1c:
                    4e:be:7e:15:d2:50:69:eb:65:16:11:f2:58:03:52:
                    6f:71:64:26:08:de:50:cc:52:c3:8a:b6:9a:9f:98:
                    56:6b:0d:85:4a:09:e2:e5:72:3b:cc:77:49:9c:90:
                    b5:f9
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
..........0..   0.."0
....... .!.zyO......vy44.j...........o..^.........b(H...yH.S...e.....c.GD|..H..I...W1`.z;.a.G<..
...u.bZ.jC%}.@3h...qR.=..W.#.Q..>
.J...r;.wI.........d&..P.R......Vk_..6?.o...{...<^...e.J~....EN..6........7..<b.
    Signature Algorithm: sha1WithRSAEncryption
         ab:b6:5d:1a:cb:9d:4c:44:6c:50:a5:fd:dc:b7:88:a3:37:51:
         d1:aa:7b:a5:75:7b:8f:14:1e:fd:c1:72:c9:9c:a3:51:38:92:
         6b:03:68:4d:52:41:df:21:b7:3f:b7:47:5b:36:df:19:5d:6f:
         92:e0:b8:2b:8c:de:0c:b0:f1:7d:a5:cf:11:28:a0:a3:84:5f:
         1c:e9:01:1b:c8:e6:be:06:81:22:85:c5:cf:de:e1:97:2f:ae:
         92:ff:41:69:07:cc:fb:39:c9:5a:47:aa:32:01:8f:9f:9e:c3:
         eb:c4:83:97:b1:a9:04:78:d1:a3:57:74:a9:63:96:07:b2:81:
         ec:ec:8f:be:32:30:20:af:2d:45:3e:44:48:3c:ab:77:47:18:
         0d:a8:0e:ca:60:cf:12:93:82:ea:13:20:82:25:aa:89:3e:15:
         83:38:8e:84:47:e0:de:be:87:e3:bf:f2:b1:1c:06:75:9e:3e:
         6d:eb:6e:6d:2c:36:76:fe:1a:05:84:8e:ce:1b:36:8b:02:41:
         21:22:6e:80:a1:a1:60:d4:93:63:d3:cd:d1:f5:26:16:83:ed:
         7b:3c:74:f1:54:2b:64:3f:ae:ee:8f:60:30:e0:1b:0b:38:27:
         7a:b0:f8:d0:c2:08:f6:55:7e:a6:97:ee:4f:b6:b9:ca:f6:eb:
         60:bc:64:4d

ANS.1
-----
    0:d=0  hl=4 l= 990 cons: SEQUENCE
    4:d=1  hl=4 l= 710 cons: SEQUENCE
    8:d=2  hl=2 l=   3 cons: cont [ 0 ]
   10:d=3  hl=2 l=   1 prim: INTEGER           :02
   13:d=2  hl=2 l=   6 prim: INTEGER           :01699A67F61D
   21:d=2  hl=2 l=  13 cons: SEQUENCE
   23:d=3  hl=2 l=   9 prim: OBJECT            :sha1WithRSAEncryption
   34:d=3  hl=2 l=   0 prim: NULL
   36:d=2  hl=2 l=  37 cons: SEQUENCE
   38:d=3  hl=2 l=  11 cons: SET
   40:d=4  hl=2 l=   9 cons: SEQUENCE
   42:d=5  hl=2 l=   3 prim: OBJECT            :countryName
   47:d=5  hl=2 l=   2 prim: PRINTABLESTRING   :US
   51:d=3  hl=2 l=  22 cons: SET
   53:d=4  hl=2 l=  20 cons: SEQUENCE
   55:d=5  hl=2 l=   3 prim: OBJECT            :commonName
   60:d=5  hl=2 l=  13 prim: UTF8STRING        :10.12.204.189
   75:d=2  hl=2 l=  30 cons: SEQUENCE
   77:d=3  hl=2 l=  13 prim: UTCTIME           :190521053835Z
   92:d=3  hl=2 l=  13 prim: UTCTIME           :490520210000Z
  107:d=2  hl=2 l=   0 cons: SEQUENCE
  109:d=2  hl=4 l= 290 cons: SEQUENCE
  113:d=3  hl=2 l=  13 cons: SEQUENCE
  115:d=4  hl=2 l=   9 prim: OBJECT            :rsaEncryption
  126:d=4  hl=2 l=   0 prim: NULL
  128:d=3  hl=4 l= 271 prim: BIT STRING
  403:d=2  hl=4 l= 311 cons: cont [ 3 ]
  407:d=3  hl=4 l= 307 cons: SEQUENCE
  411:d=4  hl=4 l= 303 cons: SEQUENCE
  415:d=5  hl=2 l=   3 prim: OBJECT            :X509v3 Subject Key Identifier
  420:d=5  hl=4 l= 294 prim: OCTET STRING      [HEX DUMP]:30820122300D06092A864886F70D01010105000382010F003082010A0282010100B77F200C21A27A794F128BCDDB92B676793434BC6AC0C987AB1BDFE9A1FFF0DE6F15BD5ECBF3BFFBFD069D8BF1622848E0E1BD7948F853A0159365C2B6B5889363A747447C9684481DED49090E10573160BB7A3B8B61BD473C8AE60AC186F17584625A056A43257D0B403368CEF80771528E3DD1DF57EE2386517FD93E0AF819B849A52E778A5C8D26F93A94E0DC6281471BE5E4DA45A42A70ED615068B50FB75FD4CD363F856FC8CB1B7BA0ECF13C5ED4E00865AA4A7E8805CCAC454E09F236D9A9969F059D95E637F8F73C62CB0D4A1C4EBE7E15D25069EB651611F25803526F71642608DE50CC52C38AB69A9F98566B0D854A09E2E5723BCC77499C90B5F90203010001
  718:d=1  hl=2 l=  13 cons: SEQUENCE
  720:d=2  hl=2 l=   9 prim: OBJECT            :sha1WithRSAEncryption
  731:d=2  hl=2 l=   0 prim: NULL
  733:d=1  hl=4 l= 257 prim: BIT STRING

With OpenSSL 1.1.1b on the client side, the server sends a certificate that looks like this:

PEM
---
Certificate:
    Data:
        Version: 3 (0x2)
        Serial Number: 1553073698340 (0x1699a67f624)
    Signature Algorithm: sha1WithRSAEncryption
        Issuer: C=US, CN=10.12.204.189
        Validity
            Not Before: May 21 07:05:20 2019 GMT
            Not After : May 20 21:00:00 2049 GMT
        Subject:
        Subject Public Key Info:
            Public Key Algorithm: rsaEncryption
                Public-Key: (2048 bit)
                Modulus:
                    00:a6:bc:b2:26:4e:76:9f:0d:40:25:2c:0a:aa:6a:
                    67:ba:31:fc:09:8b:7d:d1:de:13:73:11:8a:d6:9d:
                    68:55:b2:74:66:09:9c:b3:db:a0:ab:46:42:5d:ba:
                    6b:d6:97:3c:fd:88:cf:de:55:8d:bd:74:1c:6e:19:
                    13:fb:93:86:11:54:55:b6:f5:8d:2f:62:5e:2b:07:
                    b4:ac:d3:bb:30:51:17:61:56:35:19:5a:cc:f0:f3:
                    e7:1a:13:f2:5b:f8:45:c5:5b:4c:a9:3a:6a:4b:26:
                    25:fc:38:4e:be:b2:ac:41:31:52:ee:64:76:7b:fd:
                    6a:81:87:08:1c:8c:c8:f4:17:3e:58:08:45:90:db:
                    6e:11:05:8e:48:3a:8d:82:77:63:4e:23:a4:a4:d6:
                    94:a5:89:1a:91:41:71:c9:e3:76:b8:c3:71:b0:e7:
                    94:68:04:ee:1f:c9:e6:b1:67:d7:4c:b3:ee:b4:11:
                    22:f4:36:5f:54:4d:0d:d1:cf:72:d7:73:ed:80:49:
                    09:ff:a4:e9:93:f6:29:4b:96:b1:59:d2:3c:fe:04:
                    3a:16:dd:17:49:20:b9:dc:80:42:a4:b6:14:55:1e:
                    5c:bd:90:bb:fe:14:2a:6a:38:63:f3:09:b1:60:57:
                    85:f0:58:fe:b6:dd:da:17:4d:58:43:49:ee:49:63:
                    00:4f
                Exponent: 65537 (0x10001)
        X509v3 extensions:
            X509v3 Subject Key Identifier:
..........0..   0.."0
@%,.....&Nv.
..r.s..I......)K..Y.<..:...I ...B...U.\.....*j8c...`W..X.....MXCI.Ic.O...........[.E.[L.:jK&%.8N...A1R.dv{.j........>X.E..n...H:..wcN#........Aq..v..q...h......g.L....".6_TM
    Signature Algorithm: sha1WithRSAEncryption
         6d:7a:aa:de:d5:cf:74:6d:3e:b4:04:5f:27:0d:17:cf:2e:eb:
         43:f6:a2:5e:9f:c8:f5:2d:10:ec:4b:c2:04:6f:47:f7:3c:30:
         3f:46:89:3d:91:a9:fe:60:f5:a6:b7:40:31:59:ec:f1:f8:e1:
         ab:36:7b:ce:10:6e:cb:94:05:d6:c9:c2:27:9c:3f:d6:d7:49:
         48:4e:83:d1:fc:06:4d:9d:19:11:2a:f9:7c:8b:0f:7e:da:21:
         91:de:93:95:16:e0:96:a2:e3:a5:27:bf:dd:ae:ec:1a:25:e2:
         59:2c:4f:2c:b6:91:34:4e:46:6b:bc:75:c7:39:58:f4:b4:1a:
         c7:d2:cc:ae:59:2c:fd:6f:d7:30:98:ba:f5:8f:eb:f8:dc:62:
         f0:48:35:d3:0b:da:ee:b9:6e:20:b8:87:a9:ed:a7:db:38:eb:
         86:ed:1d:8d:00:fd:25:7f:fd:37:c7:4a:f3:46:95:94:1c:6f:
         46:8e:46:3e:5c:97:1f:11:d3:7e:d4:70:2c:92:e6:4e:6a:40:
         d0:bf:0d:48:19:c8:f7:ba:35:b1:62:d4:58:17:fa:7d:e5:12:
         af:fe:eb:ac:e6:f4:5e:91:9d:58:c9:1f:1c:a2:32:ff:06:a1:
         82:bf:3b:39:e9:27:a7:bc:2b:7c:ab:4d:b2:5c:82:77:2c:c7:
         d8:76:10:a4

ASN.1
-----
    0:d=0  hl=4 l= 990 cons: SEQUENCE
    4:d=1  hl=4 l= 710 cons: SEQUENCE
    8:d=2  hl=2 l=   3 cons: cont [ 0 ]
   10:d=3  hl=2 l=   1 prim: INTEGER           :02
   13:d=2  hl=2 l=   6 prim: INTEGER           :01699A67F624
   21:d=2  hl=2 l=  13 cons: SEQUENCE
   23:d=3  hl=2 l=   9 prim: OBJECT            :sha1WithRSAEncryption
   34:d=3  hl=2 l=   0 prim: NULL
   36:d=2  hl=2 l=  37 cons: SEQUENCE
   38:d=3  hl=2 l=  11 cons: SET
   40:d=4  hl=2 l=   9 cons: SEQUENCE
   42:d=5  hl=2 l=   3 prim: OBJECT            :countryName
   47:d=5  hl=2 l=   2 prim: PRINTABLESTRING   :US
   51:d=3  hl=2 l=  22 cons: SET
   53:d=4  hl=2 l=  20 cons: SEQUENCE
   55:d=5  hl=2 l=   3 prim: OBJECT            :commonName
   60:d=5  hl=2 l=  13 prim: UTF8STRING        :10.12.204.189
   75:d=2  hl=2 l=  30 cons: SEQUENCE
   77:d=3  hl=2 l=  13 prim: UTCTIME           :190521070520Z
   92:d=3  hl=2 l=  13 prim: UTCTIME           :490520210000Z
  107:d=2  hl=2 l=   0 cons: SEQUENCE
  109:d=2  hl=4 l= 290 cons: SEQUENCE
  113:d=3  hl=2 l=  13 cons: SEQUENCE
  115:d=4  hl=2 l=   9 prim: OBJECT            :rsaEncryption
  126:d=4  hl=2 l=   0 prim: NULL
  128:d=3  hl=4 l= 271 prim: BIT STRING
  403:d=2  hl=4 l= 311 cons: cont [ 3 ]
  407:d=3  hl=4 l= 307 cons: SEQUENCE
  411:d=4  hl=4 l= 303 cons: SEQUENCE
  415:d=5  hl=2 l=   3 prim: OBJECT            :X509v3 Subject Key Identifier
  420:d=5  hl=4 l= 294 prim: OCTET STRING      [HEX DUMP]:30820122300D06092A864886F70D01010105000382010F003082010A0282010100A6BCB2264E769F0D40252C0AAA6A67BA31FC098B7DD1DE1373118AD69D6855B27466099CB3DBA0AB46425DBA6BD6973CFD88CFDE558DBD741C6E1913FB9386115455B6F58D2F625E2B07B4ACD3BB305117615635195ACCF0F3E71A13F25BF845C55B4CA93A6A4B2625FC384EBEB2AC413152EE64767BFD6A8187081C8CC8F4173E58084590DB6E11058E483A8D8277634E23A4A4D694A5891A914171C9E376B8C371B0E7946804EE1FC9E6B167D74CB3EEB41122F4365F544D0DD1CF72D773ED804909FFA4E993F6294B96B159D23CFE043A16DD174920B9DC8042A4B614551E5CBD90BBFE142A6A3863F309B1605785F058FEB6DDDA174D584349EE4963004F0203010001
  718:d=1  hl=2 l=  13 cons: SEQUENCE
  720:d=2  hl=2 l=   9 prim: OBJECT            :sha1WithRSAEncryption
  731:d=2  hl=2 l=   0 prim: NULL
  733:d=1  hl=4 l= 257 prim: BIT STRING

They are very similar if you ask me, and yet our existing unchanged flow fails when it calls:

SSL_CTX_use_certificate_chain_file(ssl_ctx, "certificate.crt");

The error message from openssl is:

error:0D0680A8:asn1 encoding routines:asn1_check_tlen:wrong tag

Should we sign the certificate differently somehow? Or change some other field?

Which tag went wrong?

EDIT Added PEM formats of the certificates. The server doesn't use openssl at all, it uses Bouncy Castle 1.46 in java

Many thanks!

Body:
The problem was with how the server was using bouncy castle in adding the X509v3 Subject Key Identifier to the certificate's X509v3 extensions.

Instead of doing:

x509v3CertificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, pk10Holder.getSubjectPublicKeyInfo());

Which produces garbage:

        X509v3 extensions:
            X509v3 Subject Key Identifier:
..........0..   0.."0
@%,.....&Nv.
..r.s..I......)K..Y.<..:...I ...B...U.\.....*j8c...`W..X.....MXCI.Ic.O...........[.E.[L.:jK&%.8N...A1R.dv{.j........>X.E..n...H:..wcN#........Aq..v..q...h......g.L....".6_TM

Do:

x509v3CertificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(inputCSR.getPublicKey()));

Which produces a proper hash of the certificate:

X509v3 extensions:
        X509v3 Subject Key Identifier:
                10:47:60:D7:98:D5:3C:D6:AC:66:FC:17:B4:F5:44:15:7B:AF:0B:D1


来源: stackexchange

问:
Windows 10 toast notification icon referencing
I decided to throw away the "old school" windows baloon notifications and use the new
windows 10 native toast notifications.

Right now, I'm struggling with referencing an icon for the toast notification. According to the Microsocft documentation (here and here), I should be able to add a notification icon like this:

```<code>// Get a toast XML template
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);

// Create image element
var image = toastXml.CreateElement("image");
image.SetAttribute("src", "https://picsum.photos/48?image=883");
image.SetAttribute("placement", "appLogoOverride");
toastXml.DocumentElement.AppendChild(image);
</code>```

Instead, a default application icon appears:

The only way that is actually working is to use an absolute path to the image:

```<code>"file:///" + Path.GetFullPath("../../Assets/myicon.png");
</code>```

That however, doesn't satisfy my needs because I either need to reference a resource icon or an icon from the web.

Hence my questions:

How can I properly reference a web image (https://picsum.photos/48?image=883) in my toast notification?

How can I properly reference a resource icon?

What image types are allowed in the toast notifications icons? Am I able to reference, for example the .svg image?

答:
How can I properly reference a web image (https://picsum.photos/48?image=883) in my toast notification?

We could realize toast notification via UWP Community Toolkit Notifications nuget package easily. if you want to reference a web image  for  AppLogoOverride, please create AppLogoOverride instance and set Source property like the following.

For example:

```<code>var toastContent = new ToastContent()
{
    Visual = new ToastVisual()
    {
        BindingGeneric = new ToastBindingGeneric()
        {
            Children =
            {
                new AdaptiveText()
                {
                    Text = "Matt sent you a friend request"
                },
                new AdaptiveText()
                {
                    Text = "Hey, wanna dress up as wizards and ride around on our hoverboards together?"
                }
            },
            AppLogoOverride = new ToastGenericAppLogo()
            {
                Source = "https://unsplash.it/64?image=1005",
                HintCrop = ToastGenericAppLogoCrop.Circle
            }
        }
    },
    Actions = new ToastActionsCustom()
    {
        Buttons =
        {
            new ToastButton("Accept", "action=acceptFriendRequest&userId=49183")
            {
                ActivationType = ToastActivationType.Background
            },
            new ToastButton("Decline", "action=declineFriendRequest&userId=49183")
            {
                ActivationType = ToastActivationType.Background
            }
        }
    },
    Launch = "action=viewFriendRequest&userId=49183"
};

// Create the toast notification
var toastNotif = new ToastNotification(toastContent.GetXml());

// And send the notification
ToastNotificationManager.CreateToastNotifier().Show(toastNotif);
</code>```

How can I properly reference a resource icon?

If you want to reference a resource icon and the icon resource in the Assets folder, you could refer the following code.

```<code>new AdaptiveImage()
{
   Source = "Assets/Apps/Food/RestaurantMap.jpg"
}
</code>```

What image types are allowed in the toast notifications icons? Am I able to reference, for example the .svg image?

For my testing png, jpg and svg image available for toast notifications.

ContentLicense: CC BY-SA 4.0

Body:
I decided to throw away the "old school" windows baloon notifications and use the new
windows 10 native toast notifications.

Right now, I'm struggling with referencing an icon for the toast notification. According to the Microsocft documentation (here and here), I should be able to add a notification icon like this:

// Get a toast XML template
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);

// Create image element
var image = toastXml.CreateElement("image");
image.SetAttribute("src", "https://picsum.photos/48?image=883");
image.SetAttribute("placement", "appLogoOverride");
toastXml.DocumentElement.AppendChild(image);

Instead, a default application icon appears:

The only way that is actually working is to use an absolute path to the image:

"file:///" + Path.GetFullPath("../../Assets/myicon.png");

That however, doesn't satisfy my needs because I either need to reference a resource icon or an icon from the web.

Hence my questions:

How can I properly reference a web image (https://picsum.photos/48?image=883) in my toast notification?

How can I properly reference a resource icon?

What image types are allowed in the toast notifications icons? Am I able to reference, for example the .svg image?

Body:
How can I properly reference a web image (https://picsum.photos/48?image=883) in my toast notification?

We could realize toast notification via UWP Community Toolkit Notifications nuget package easily. if you want to reference a web image  for  AppLogoOverride, please create AppLogoOverride instance and set Source property like the following.

For example:

var toastContent = new ToastContent()
{
    Visual = new ToastVisual()
    {
        BindingGeneric = new ToastBindingGeneric()
        {
            Children =
            {
                new AdaptiveText()
                {
                    Text = "Matt sent you a friend request"
                },
                new AdaptiveText()
                {
                    Text = "Hey, wanna dress up as wizards and ride around on our hoverboards together?"
                }
            },
            AppLogoOverride = new ToastGenericAppLogo()
            {
                Source = "https://unsplash.it/64?image=1005",
                HintCrop = ToastGenericAppLogoCrop.Circle
            }
        }
    },
    Actions = new ToastActionsCustom()
    {
        Buttons =
        {
            new ToastButton("Accept", "action=acceptFriendRequest&userId=49183")
            {
                ActivationType = ToastActivationType.Background
            },
            new ToastButton("Decline", "action=declineFriendRequest&userId=49183")
            {
                ActivationType = ToastActivationType.Background
            }
        }
    },
    Launch = "action=viewFriendRequest&userId=49183"
};

// Create the toast notification
var toastNotif = new ToastNotification(toastContent.GetXml());

// And send the notification
ToastNotificationManager.CreateToastNotifier().Show(toastNotif);

How can I properly reference a resource icon?

If you want to reference a resource icon and the icon resource in the Assets folder, you could refer the following code.

new AdaptiveImage()
{
   Source = "Assets/Apps/Food/RestaurantMap.jpg"
}

What image types are allowed in the toast notifications icons? Am I able to reference, for example the .svg image?

For my testing png, jpg and svg image available for toast notifications.


问:
Implementing partial recursive function in C#
I am having trouble with somwhow implementing a partial recursive function (at least in my mind though).

for any given p and arbitrary maxsteps = 100, calculate L:

答:
I appreciate you want a recursive function, but I figured I'd provide a non-recursive alternative in case it turns out to be preferred:

```<code>private static double CalculateL(double p, int maxsteps)
{
    double val = 1 / (p + 1);
    for (int i = 1; i <= maxsteps; ++i)
    {
        val = 1 / (p + val);
    }
    return val;
}
</code>```

I'm not 100% sure about maxsteps, based on the other answers. If the answer isn't right, then you probably want < maxsteps where I've got <= maxsteps.

Also, please read Is floating point math broken? if you're expecting very precise results.

Body:
I appreciate you want a recursive function, but I figured I'd provide a non-recursive alternative in case it turns out to be preferred:

private static double CalculateL(double p, int maxsteps)
{
    double val = 1 / (p + 1);
    for (int i = 1; i <= maxsteps; ++i)
    {
        val = 1 / (p + val);
    }
    return val;
}

I'm not 100% sure about maxsteps, based on the other answers. If the answer isn't right, then you probably want < maxsteps where I've got <= maxsteps.

Also, please read Is floating point math broken? if you're expecting very precise results.


问:
Sonata Admin - convert seconds to milliseconds
I am generating my view with fields to display in sonata admin panel. I have a float field in my db that is representing seconds that needs to be converted in milliseconds (multiplied by 1000 and rounded to 0 decimals) for display.

Can anybody help out.

Code:

```<code>  protected function configureShowFields(ShowMapper $showMapper)
{

    $ms = $getMs->getResponseTime(); --- this works
    $milliseconds = round($ms / 1000, 2);

    $showMapper
        ->tab('Info')
        ->add('id')
        ->add('fieldOne')
        ->add('fildTwo')
        ->add('seconds', 'decimal', array(
            'pattern' => $milliseconds
        ))
        ->end()
        ->end()
}
</code>```

答:
To round a number UP to the nearest integer, look at the ceil function.
To round a number DOWN to the nearest integer, look at the floor function.</p>

```<code>/* Seconds */
$s = $getMs->getResponseTime();

/* Milliseconds */
$ms = $s*1000;

/* Rounded milliseconds */
$milliseconds = floor($ms);
</code>```

Body:
I am generating my view with fields to display in sonata admin panel. I have a float field in my db that is representing seconds that needs to be converted in milliseconds (multiplied by 1000 and rounded to 0 decimals) for display.

Can anybody help out.

Code:

  protected function configureShowFields(ShowMapper $showMapper)
{

    $ms = $getMs->getResponseTime(); --- this works
    $milliseconds = round($ms / 1000, 2);

    $showMapper
        ->tab('Info')
        ->add('id')
        ->add('fieldOne')
        ->add('fildTwo')
        ->add('seconds', 'decimal', array(
            'pattern' => $milliseconds
        ))
        ->end()
        ->end()
}

Body:
To round a number UP to the nearest integer, look at the ceil function.
To round a number DOWN to the nearest integer, look at the floor function.

/* Seconds */
$s = $getMs->getResponseTime();

/* Milliseconds */
$ms = $s*1000;

/* Rounded milliseconds */
$milliseconds = floor($ms);


问:
Check which of an array value is also an object property
I have a object 'ecom' which will have a property that is one of ['detail','add','remove','checkout','purchase']

I want to know which of the 5 potential properties the object has.

What is the shortest, cleanest way to get that?

答:
You can use filter() and hasOwnProperty()

let arr = ['detail','add','remove','checkout','purchase'];
let obj = {detail:'val',add:0,purchase:33}

let res = arr.filter(x => obj.hasOwnProperty(x));
console.log(res)```
</div>
</div>
</p>
<h3>Without arrow function</h3>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = ['detail','add','remove','checkout','purchase'];
let obj = {detail:'val',add:0,purchase:33}

let res = arr.filter(function(x){
    return obj.hasOwnProperty(x)
})
console.log(res)</code>```

Body:
You can use filter() and hasOwnProperty()

let arr = ['detail','add','remove','checkout','purchase'];
let obj = {detail:'val',add:0,purchase:33}

let res = arr.filter(x => obj.hasOwnProperty(x));
console.log(res)

Without arrow function

let arr = ['detail','add','remove','checkout','purchase'];
let obj = {detail:'val',add:0,purchase:33}

let res = arr.filter(function(x){
    return obj.hasOwnProperty(x)
})
console.log(res)


问:
Conventional prefix for "public" as the underscore is for "private"?
First of all I'm aware what the _ is actually used for, it's just an easier way to frame the question :).

Just a curiosity if there ever was such a thing, and if so, what was it.

答:
The programming language Go, for instance, uses initial upper case for exported declarations and initial lower case for non-exported declarations.

Example:

```<code>func Product(x int, y int) int { //exported function
    return x * y
}

func sum(x int, y int) int { //non-exported function
    return x + y
}
</code>```

Body:
The programming language Go, for instance, uses initial upper case for exported declarations and initial lower case for non-exported declarations.

Example:

func Product(x int, y int) int { //exported function
    return x * y
}

func sum(x int, y int) int { //non-exported function
    return x + y
}


问:
Why does std::set.insert() return a non-const iterator, and yet I cannot modify it?
Consider this code example:

```<code>#include <set>
#include <string>

using namespace std;

set<string> string_set;

void foo(const string& a)
{
    pair<set<string>::iterator, bool> insert_result = string_set.insert(a);

    string& val = *(insert_result.first);
    val += " - inserted";
}
</code>```

So, correctness aside, such as not checking for successful insertion and so on, this code looks like it should allow me to amend the string after insertion, but the compiler (VS2010) forbids dereferencing the iterator to a non-const string (we're migrating from VS2005 which waved this through without a warning).

Now, I know this should be forbidden since it may make the string non-unique, and I'm kind of glad it works this way, but in the real world case it's not quite so clear cut as that, as I want to amend a non-mutable data member that doesn't participate in equivalence testing or ordering.

What I want to know is, how does the compiler KNOW I'm not allowed to do this, and how do I know without reference to the documentation (which doesn't mention this anyway)?

Cheers,
Guy

答:
Because according to the standard, modifications through
a set<>::iterator are not allowed.  The standard specifically
allows set<>::iterator and set<>::const_iterator to be the
same type.  And although it doesn't require them to be the same
type, it does require the value_type of set<>::iterator to
be const.

The reason for this, of course, is that any modifications to the
value could invalidate the invariants of std::set<>.

ContentLicense: CC BY-SA 3.0

Body:
Consider this code example:

#include <set>
#include <string>

using namespace std;

set<string> string_set;

void foo(const string& a)
{
    pair<set<string>::iterator, bool> insert_result = string_set.insert(a);

    string& val = *(insert_result.first);
    val += " - inserted";
}

So, correctness aside, such as not checking for successful insertion and so on, this code looks like it should allow me to amend the string after insertion, but the compiler (VS2010) forbids dereferencing the iterator to a non-const string (we're migrating from VS2005 which waved this through without a warning).

Now, I know this should be forbidden since it may make the string non-unique, and I'm kind of glad it works this way, but in the real world case it's not quite so clear cut as that, as I want to amend a non-mutable data member that doesn't participate in equivalence testing or ordering.

What I want to know is, how does the compiler KNOW I'm not allowed to do this, and how do I know without reference to the documentation (which doesn't mention this anyway)?

Cheers,
Guy


问:
MPD mountpoint not showing up on icecast
I am trying to setup MPD to work with Icecast to setup an internet radio streaming service.
MPD and Icecast do seem to work fine. However i donot see anything listed under Mountpoints on the dashboard on icecast. What needs to be done to enable the same

Here are my config files. Could you please help me on what i might be missing?

MPD Conf :

```<code>music_directory "/home/username/Downloads/Music"
playlist_directory "/home/username/.mpd/playlists"
db_file "/home/username/.mpd/mpd.db"
log_file "/home/username/.mpd/mpd.log"
pid_file "/home/username/.mpd/mpd.pid"
state_file "/home/username/.mpd/mpdstate"
audio_output {
    type        "shout"
    encoding    "ogg"
    name        "my cool stream"
    host        "127.0.0.1"
    port        "8000"
    mount       "/stream.ogg"
    bind_to_address "127.0.0.1"

# This is the source password in icecast.xml
    password    "username123"

# Set either quality or bit rate
   quality     "5.0"
#    bitrate     "64"

    format      "44100:16:1"

# Optional Parameters
    user        "source"
#   description "here is my long description"
#   genre       "jazz"
} # end of audio_output

audio_output {
    type "alsa"
    name "username"
    driver "null"
}
</code>```

Icecast config

```<code><icecast>
    <!-- location and admin are two arbitrary strings that are e.g. visible
         on the server info page of the icecast web interface
         (server_version.xsl). -->
    <location>Earth</location>
    <admin>support@mydomain.com</admin>

    <!-- IMPORTANT!
         Especially for inexperienced users:
         Start out by ONLY changing all passwords and restarting Icecast.
         For detailed setup instructions please refer to the documentation.
         It's also available here: http://icecast.org/docs/
    -->

    <limits>
        <clients>100</clients>
        <sources>2</sources>
        <queue-size>524288</queue-size>
        <client-timeout>30</client-timeout>
        <header-timeout>15</header-timeout>
        <source-timeout>10</source-timeout>
        <!-- If enabled, this will provide a burst of data when a client
             first connects, thereby significantly reducing the startup
             time for listeners that do substantial buffering. However,
             it also significantly increases latency between the source
             client and listening client.  For low-latency setups, you
             might want to disable this. -->
        <burst-on-connect>1</burst-on-connect>
        <!-- same as burst-on-connect, but this allows for being more
             specific on how much to burst. Most people won't need to
             change from the default 64k. Applies to all mountpoints  -->
        <burst-size>65535</burst-size>
    </limits>

    <authentication>
        <!-- Sources log in with username 'source' -->
        <source-password>username123</source-password>
        <!-- Relays log in with username 'relay' -->
        <relay-password>username123</relay-password>

        <!-- Admin logs in with the username given below -->
        <admin-user>admin</admin-user>
        <admin-password>username123</admin-password>
    </authentication>

    <!-- set the mountpoint for a shoutcast source to use, the default if not
         specified is /stream but you can change it here if an alternative is
         wanted or an extension is required
    <shoutcast-mount>/live.nsv</shoutcast-mount>
    -->

    <!-- Uncomment this if you want directory listings -->
    <!--
    <directory>
        <yp-url-timeout>15</yp-url-timeout>
        <yp-url>http://dir.xiph.org/cgi-bin/yp-cgi</yp-url>
    </directory>
    -->

    <!-- This is the hostname other people will use to connect to your server.
         It affects mainly the urls generated by Icecast for playlists and yp
         listings. You MUST configure it properly for YP listings to work!
    -->
    <hostname>127.0.0.1</hostname>

    <!-- You may have multiple <listener> elements -->
    <listen-socket>
        <port>8000</port>
        <!-- <bind-address>127.0.0.1</bind-address> -->
        <!-- <shoutcast-mount>/stream</shoutcast-mount> -->
    </listen-socket>
    <!--
    <listen-socket>
        <port>8080</port>
    </listen-socket>
    -->
    <!--
    <listen-socket>
        <port>8443</port>
        <ssl>1</ssl>
    </listen-socket>
    -->

    <!-- Global header settings
         Headers defined here will be returned for every HTTP request to Icecast.

         The ACAO header makes Icecast public content/API by default
         This will make streams easier embeddable (some HTML5 functionality needs it).
         Also it allows direct access to e.g. /status-json.xsl from other sites.
         If you don't want this, comment out the following line or read up on CORS.
    -->
    <http-headers>
        <header name="Access-Control-Allow-Origin" value="*" />
    </http-headers>

    <!-- Relaying
         You don't need this if you only have one server.
         Please refer to the config for a detailed explanation.
    -->
    <!--<master-server>127.0.0.1</master-server>-->
    <!--<master-server-port>8001</master-server-port>-->
    <!--<master-update-interval>120</master-update-interval>-->
    <!--<master-password>hackme</master-password>-->

    <!-- setting this makes all relays on-demand unless overridden, this is
         useful for master relays which do not have <relay> definitions here.
         The default is 0 -->
    <!--<relays-on-demand>1</relays-on-demand>-->

    <!--
    <relay>
        <server>127.0.0.1</server>
        <port>8080</port>
        <mount>/example.ogg</mount>
        <local-mount>/different.ogg</local-mount>
        <on-demand>0</on-demand>

        <relay-shoutcast-metadata>0</relay-shoutcast-metadata>
    </relay>
    -->

    <!-- Mountpoints
         Only define <mount> sections if you want to use advanced options,
         like alternative usernames or passwords
    -->

    <!-- Default settings for all mounts that don't have a specific <mount type="normal">.
    -->
    <!--
    <mount type="default">
        <public>0</public>
        <intro>/server-wide-intro.ogg</intro>
        <max-listener-duration>3600</max-listener-duration>
        <authentication type="url">
                <option name="mount_add" value="http://auth.example.org/stream_start.php"/>
        </authentication>
        <http-headers>
                <header name="foo" value="bar" />
        </http-headers>
    </mount>
    -->

    <!-- Normal mounts -->
    <!--
    <mount type="normal">
        <mount-name>/example-complex.ogg</mount-name>

        <username>othersource</username>
        <password>hackmemore</password>

        <max-listeners>1</max-listeners>
        <dump-file>/tmp/dump-example1.ogg</dump-file>
        <burst-size>65536</burst-size>
        <fallback-mount>/example2.ogg</fallback-mount>
        <fallback-override>1</fallback-override>
        <fallback-when-full>1</fallback-when-full>
        <intro>/example_intro.ogg</intro>
        <hidden>1</hidden>
        <public>1</public>
        <authentication type="htpasswd">
                <option name="filename" value="myauth"/>
                <option name="allow_duplicate_users" value="0"/>
        </authentication>
        <http-headers>
                <header name="Access-Control-Allow-Origin" value="http://webplayer.example.org" />
                <header name="baz" value="quux" />
        </http-headers>
        <on-connect>/home/icecast/bin/stream-start</on-connect>
        <on-disconnect>/home/icecast/bin/stream-stop</on-disconnect>
    </mount>
    -->

    <!--
    <mount type="normal">
        <mount-name>/auth_example.ogg</mount-name>
        <authentication type="url">
            <option name="mount_add"       value="http://myauthserver.net/notify_mount.php"/>
            <option name="mount_remove"    value="http://myauthserver.net/notify_mount.php"/>
            <option name="listener_add"    value="http://myauthserver.net/notify_listener.php"/>
            <option name="listener_remove" value="http://myauthserver.net/notify_listener.php"/>
            <option name="headers"         value="x-pragma,x-token"/>
            <option name="header_prefix"   value="ClientHeader."/>
        </authentication>
    </mount>
    -->

    <fileserve>1</fileserve>

    <paths>
        <!-- basedir is only used if chroot is enabled -->
        <basedir>/usr/share/icecast</basedir>

        <!-- Note that if <chroot> is turned on below, these paths must both
             be relative to the new root, not the original root -->
        <logdir>/var/log/icecast</logdir>
        <webroot>/usr/share/icecast/web</webroot>
        <adminroot>/usr/share/icecast/admin</adminroot>
        <!-- <pidfile>/usr/share/icecast/icecast.pid</pidfile> -->

        <!-- Aliases: treat requests for 'source' path as being for 'dest' path
             May be made specific to a port or bound address using the "port"
             and "bind-address" attributes.
          -->
        <!--
        <alias source="/foo" destination="/bar"/>
        -->
        <!-- Aliases: can also be used for simple redirections as well,
             this example will redirect all requests for http://server:port/ to
             the status page
        -->
        <alias source="/" destination="/status.xsl"/>
        <!-- The certificate file needs to contain both public and private part.
             Both should be PEM encoded.
        <ssl-certificate>/usr/share/icecast/icecast.pem</ssl-certificate>
        -->
    </paths>

    <logging>
        <accesslog>access.log</accesslog>
        <errorlog>error.log</errorlog>
        <!-- <playlistlog>playlist.log</playlistlog> -->
        <loglevel>3</loglevel> <!-- 4 Debug, 3 Info, 2 Warn, 1 Error -->
        <logsize>10000</logsize> <!-- Max size of a logfile -->
        <!-- If logarchive is enabled (1), then when logsize is reached
             the logfile will be moved to [error|access|playlist].log.DATESTAMP,
             otherwise it will be moved to [error|access|playlist].log.old.
             Default is non-archive mode (i.e. overwrite)
        -->
        <!-- <logarchive>1</logarchive> -->
    </logging>

    <security>
        <chroot>0</chroot>
        <changeowner>
            <user>nobody</user>
            <group>nobody</group>
        </changeowner>
    </security>
</icecast>
</code>```

MPD : Music Player Daemon 0.19.12

Error log:

```<code>Jan 05 15:10 : update: added /3185.mp3
Jan 05 15:10 : client: [5] closed
Jan 05 15:12 : client: [6] opened from [::1]:46344
Jan 05 15:13 : client: [6] closed
Jan 05 15:17 : pulse_output: Failed to enable "username" [pulse]: pa_context_connect() has failed: Connection refused
Jan 05 15:17 : client: [0] opened from [::1]:47352
Jan 05 15:17 : client: [1] opened from [::1]:47354
Jan 05 15:17 : client: [1] closed
</code>```

答:
Within your MPD.Conf file there are TWO audio_output{} sections.
And the second one could overwrite the frist one.
So delete/disable the part at the end of your config</p>

```<code>> #audio_output {
> #    type "alsa"
> #    name "username"
> #    driver "null" }
</code>```

Body:
I am trying to setup MPD to work with Icecast to setup an internet radio streaming service.
MPD and Icecast do seem to work fine. However i donot see anything listed under Mountpoints on the dashboard on icecast. What needs to be done to enable the same

Here are my config files. Could you please help me on what i might be missing?

MPD Conf :

music_directory "/home/username/Downloads/Music"
playlist_directory "/home/username/.mpd/playlists"
db_file "/home/username/.mpd/mpd.db"
log_file "/home/username/.mpd/mpd.log"
pid_file "/home/username/.mpd/mpd.pid"
state_file "/home/username/.mpd/mpdstate"
audio_output {
    type        "shout"
    encoding    "ogg"
    name        "my cool stream"
    host        "127.0.0.1"
    port        "8000"
    mount       "/stream.ogg"
    bind_to_address "127.0.0.1"

# This is the source password in icecast.xml
    password    "username123"

# Set either quality or bit rate
   quality     "5.0"
#    bitrate     "64"

    format      "44100:16:1"

# Optional Parameters
    user        "source"
#   description "here is my long description"
#   genre       "jazz"
} # end of audio_output

audio_output {
    type "alsa"
    name "username"
    driver "null"
}

Icecast config

<icecast>

    <location>Earth</location>
    <admin>support@mydomain.com</admin>

    <limits>
        <clients>100</clients>
        <sources>2</sources>
        <queue-size>524288</queue-size>
        <client-timeout>30</client-timeout>
        15
        <source-timeout>10</source-timeout>

        <burst-on-connect>1</burst-on-connect>

        <burst-size>65535</burst-size>
    </limits>

    <authentication>

        <source-password>username123</source-password>

        <relay-password>username123</relay-password>

        <admin-user>admin</admin-user>
        <admin-password>username123</admin-password>
    </authentication>

    <hostname>127.0.0.1</hostname>

    <listen-socket>
        <port>8000</port>

    </listen-socket>

    <http-headers>

    </http-headers>

    <fileserve>1</fileserve>

    <paths>

        <basedir>/usr/share/icecast</basedir>

        <logdir>/var/log/icecast</logdir>
        <webroot>/usr/share/icecast/web</webroot>
        <adminroot>/usr/share/icecast/admin</adminroot>

        <alias source="/" destination="/status.xsl"/>

    </paths>

    <logging>
        <accesslog>access.log</accesslog>
        <errorlog>error.log</errorlog>

        <loglevel>3</loglevel>
        <logsize>10000</logsize>

    </logging>

    <security>
        <chroot>0</chroot>
        <changeowner>
            <user>nobody</user>
            <group>nobody</group>
        </changeowner>
    </security>
</icecast>

MPD : Music Player Daemon 0.19.12

Error log:

Jan 05 15:10 : update: added /3185.mp3
Jan 05 15:10 : client: [5] closed
Jan 05 15:12 : client: [6] opened from [::1]:46344
Jan 05 15:13 : client: [6] closed
Jan 05 15:17 : pulse_output: Failed to enable "username" [pulse]: pa_context_connect() has failed: Connection refused
Jan 05 15:17 : client: [0] opened from [::1]:47352
Jan 05 15:17 : client: [1] opened from [::1]:47354
Jan 05 15:17 : client: [1] closed

Body:
Within your MPD.Conf file there are TWO audio_output{} sections.
And the second one could overwrite the frist one.
So delete/disable the part at the end of your config

> #audio_output {
> #    type "alsa"
> #    name "username"
> #    driver "null" }


问:
JsTree: Show more options
Is there any way to have a show more option/link in jsTree?
I want to show only part of the children and have a link to expand to show all elements.
I tried a few google searches but could not find a solution. Any help/hint would be useful.

Let's say parent-1 has 10 child nodes and the Main Root has 5 parent nodes.

```<code>Main Parent
    - Parent - 1
        - child-1
        - child-2
        - child-3
        show 7 more parent-1 elements //LINK
    - Parent - 2
        - child-1
        - child-2
    - Parent - 3
        - child-1
        - child-2
    show 2 more Main Parent elements //LINK
</code>```

I'm trying to achieve the following result

Is this possible? Are there any available plugins for this? Are there any alternatives for jsTree that support this?

答:
did you try to use "before_open.jstree" event to show the tree the way you need?
see the example (I use part of the demo page from the jstree site):

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>jstree basic demos</title>

 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />

Interaction and events demo

 <button id="evts_button">select node with id 1</button> either click the button or a node in the tree

```

I hope this helped.

Title: JsTree: Show more options

Body:
Is there any way to have a show more option/link in jsTree?
I want to show only part of the children and have a link to expand to show all elements.
I tried a few google searches but could not find a solution. Any help/hint would be useful.

Let's say parent-1 has 10 child nodes and the Main Root has 5 parent nodes.

Main Parent
    - Parent - 1
        - child-1
        - child-2
        - child-3
        show 7 more parent-1 elements //LINK
    - Parent - 2
        - child-1
        - child-2
    - Parent - 3
        - child-1
        - child-2
    show 2 more Main Parent elements //LINK

I'm trying to achieve the following result

Is this possible? Are there any available plugins for this? Are there any alternatives for jsTree that support this?

Body:
did you try to use "before_open.jstree" event to show the tree the way you need?
see the example (I use part of the demo page from the jstree site):

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>jstree basic demos</title>
 <style>
 html { margin:0; padding:0; font-size:62.5%; }
 body { max-width:800px; min-width:300px; margin:0 auto; padding:20px 10px; font-size:14px; font-size:1.4em; }
 h1 { font-size:1.8em; }
 .demo { overflow:auto; border:1px solid silver; min-height:100px; }
 </style>
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
</head>
<body>
 <h1>Interaction and events demo</h1>
 <button id="evts_button">select node with id 1</button> <em>either click the button or a node in the tree</em>
 <div id="evts" class="demo"></div>

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>

 <script>

 // interaction and events
 $('#evts_button').on("click", function () {
  var instance = $('#evts').jstree(true);
  instance.deselect_all();
  instance.select_node('1');
 });
 $('#evts')
  .on("changed.jstree", function (e, data) {
   if(data.selected.length) {
    alert('The selected node is: ' + data.instance.get_node(data.selected[0]).text);
   }
  })
  .on("before_open.jstree", function (e, data,a,b,c,d) {
   $('#' + data.node.id + ' ul li:nth-child(n + 2)').hide();
   var str = '<li class="jstree-node  jstree-leaf jstree-last" role="treeitem">press to show ' + $('#' + data.node.id + ' ul li:nth-child(n + 2)').length + ' more items</li>';
   var li = $(str).on('click', function(a,b,c,d) {$(a.target).parent().find('li').show(); $(a.target).hide()});
   $('#' + data.node.id + ' ul').append(li);
  })
  .jstree({
   'core' : {
    'multiple' : false,
    'data' : [
     { "text" : "Root node", "children" : [
       { "text" : "Child node 1", "id" : 1 },
       { "text" : "Child node 2" }
     ]}
    ]
   }
  });
 </script>
</body>
</html>

I hope this helped.


问:
How to add AM/PM to Bootstrap Material DatePicker
I am trying to add AM/PM to bootstrapMaterialDatePicker, I set twelvehour: true but nothing seemed to work. How do i add AM/PM because on my device, those aren't options and it instead uses a 24 hour clock?

```<code>$('.timer').bootstrapMaterialDatePicker
            ({
                date: false,
                shortTime: false,
                format: 'HH:mm',
                twelvehour: true
            });
</code>```

答:
You can add a to your format HH:mm a and set the value shortTime: true
to show the AM/PM in your GUI to allow the user to select it

```<code>  // Bootstrap timepicker
  $('.timer').bootstrapMaterialDatePicker({
     date: false,
     shortTime: true,
     twelvehour: false,
     format: 'HH:mm a'
  });
</code>```

Body:
I am trying to add AM/PM to bootstrapMaterialDatePicker, I set twelvehour: true but nothing seemed to work. How do i add AM/PM because on my device, those aren't options and it instead uses a 24 hour clock?

$('.timer').bootstrapMaterialDatePicker
            ({
                date: false,
                shortTime: false,
                format: 'HH:mm',
                twelvehour: true
            });

Body:
You can add a to your format HH:mm a and set the value shortTime: true
to show the AM/PM in your GUI to allow the user to select it

  // Bootstrap timepicker
  $('.timer').bootstrapMaterialDatePicker({
     date: false,
     shortTime: true,
     twelvehour: false,
     format: 'HH:mm a'
  });


问:
in ASP.NET MVC3 how can I see the request?
I'm using a simple route as

```<code>routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);
</code>```

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

```<code>//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}
</code>```

The thing is that, when I insert this in the browser:

```<code>http://localhost:14951/client_name/hashed_id
</code>```

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.

答: If you have breakpoint inside controller you can use watch where you can simply create new watch. Type in Request and search it...

Body:
I'm using a simple route as

routes.MapRoute(
    "Default2", // Route name
    "{cliurl}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

routes.MapRoute(
    "Default", // Route name
    "{cliurl}/{controller}/{action}/{id}", // URL with parameters
    new { cliurl = "none", controller = "ABook", action = "Index", id = "none" } // Parameter defaults
);

and when I debug the website (VS2010 SP1), I have a breakpoint in my ABook Controller, inside the Index action method witch contains only:

//
// GET: /ABook/
public ActionResult Index()
{
    if (currentClient == null)
        return RedirectToAction("Empty");

    return View();
}

//
// GET: /Empty/
public ActionResult Empty()
{
    return View();
}

The thing is that, when I insert this in the browser:

http://localhost:14951/client_name/hashed_id

I get 3 breaks in that breakpoint.

How can I see what in the world is going on? why 3 times when I just requested 1, what is exactly the browser requesting?

I can only get the Route Parameters and I do get the first correct, but 2nd and 3rd are using the default values, and I tried to navigate through the RequestContext and I can't see anything useful :(

Just want to know if there is a way to really see what's been requested.


问:
Slicer to slice particular columns only in PowerBI
I'm trying to create some dynamic charts in power BI.

My data looks like this:

```<code>year    Product  exp    claim_type  clCost     clCount
2010    A    0.21               0             0
2010    A    0.85               0             0
2010    A    0.15   BI          5000          1
2010    B    1.00   BI          1000          1
2010    B    0.33               0             0
2011    B    0.96               0             0
2011    B    0.16   BI          200           1
2011    B    1.00   MD          2500          1
2011    A    1.00               0             0
2011    A    0.91   MD          6000          1
</code>```

End goal is have a chart with the x axis being "Year", and Y axis being the sum(clCount)/sum(exp) and two lines for product A,B.
But in powerBI I want to be able to filter by claim type. So I want to only select certain rows for clCount to sum up, but sum up all the rows for exp. (Per group)

So for example, with a slicer, someone can click "BI", and the resulting value for the 2010 year andproduct A would be sum(clCount) = 1 and sum(exp) = .21+.85+.15

And for product B, similarly for the 2010 year sum(clCount) = 1 and sum(exp) = 1+.33

And ofcourse the same for the 2011 year...

Now the issue is, if I put a Slicer for the variable claim_type, and choose BI, it sums up the clCount per year correctly, but the exp, it only sums it up for the rows that contain "BI" (ie for 2010 and product the exp will only be .15 instead of .21+.85+.15. I need the sum(exp) to be of the year and product as the denominator.

Any ideas on how this can be done?

答:
Found the solution: you can fix the calculation of exp to be independent of your slicer selection of claim type using this:</p>

```<code>CALCULATE(sum('Data'[exp]),all('Data'[claim_type]))
</code>```

Body:
I'm trying to create some dynamic charts in power BI.

My data looks like this:

year    Product  exp    claim_type  clCost     clCount
2010    A    0.21               0             0
2010    A    0.85               0             0
2010    A    0.15   BI          5000          1
2010    B    1.00   BI          1000          1
2010    B    0.33               0             0
2011    B    0.96               0             0
2011    B    0.16   BI          200           1
2011    B    1.00   MD          2500          1
2011    A    1.00               0             0
2011    A    0.91   MD          6000          1

End goal is have a chart with the x axis being "Year", and Y axis being the sum(clCount)/sum(exp) and two lines for product A,B.
But in powerBI I want to be able to filter by claim type. So I want to only select certain rows for clCount to sum up, but sum up all the rows for exp. (Per group)

So for example, with a slicer, someone can click "BI", and the resulting value for the 2010 year andproduct A would be sum(clCount) = 1 and sum(exp) = .21+.85+.15

And for product B, similarly for the 2010 year sum(clCount) = 1 and sum(exp) = 1+.33

And ofcourse the same for the 2011 year...

Now the issue is, if I put a Slicer for the variable claim_type, and choose BI, it sums up the clCount per year correctly, but the exp, it only sums it up for the rows that contain "BI" (ie for 2010 and product the exp will only be .15 instead of .21+.85+.15. I need the sum(exp) to be of the year and product as the denominator.

Any ideas on how this can be done?

Body:
Found the solution: you can fix the calculation of exp to be independent of your slicer selection of claim type using this:

CALCULATE(sum('Data'[exp]),all('Data'[claim_type]))


问:
How to access existing user email in devise in ruby on rails
I am using ruby on rails with Devise gem to authenticate user. Every time a new user signs with his/her email address, I can see devise is allocating new user ID to that user and registering there email address. Now I want to display a welcome message for all the first time user ( I do not want this message to appear when they login for 2nd or 3rd time).
To display the message I want to check current_user.email against all the registered email in the user table (logic here is: if the user already exists in the user table then I can safely assume that the user has already visited the website so I prevent the welcome being displayed). I am not sure how to access all the email id's in the table?? also where to do this check. I want this welcome message to be the first thing user sees as soon as there sign in is successful. Can anyone help please.

I tried to use "resource" resource_name" within sessions controller but nothing works. Not sure weather those are even remotely relevant.

```<code>    # POST /resource/sign_in
    def create
      self.resource = warden.authenticate!(auth_options)
      $sign = sign_in_count
      set_flash_message!(:notice, :signed_in)
      sign_in(resource_name, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    end
</code>```

I am trying to assign sign_in_count for logged in user to a global variable called $sign so that I can use it's value to check if user has signed in for first time or not.

答:
To display a message the first time user logs in your app why not use the sign_in_count ?

This avoids you to get all email addresses in your db to check if it exist already

Body:
I am using ruby on rails with Devise gem to authenticate user. Every time a new user signs with his/her email address, I can see devise is allocating new user ID to that user and registering there email address. Now I want to display a welcome message for all the first time user ( I do not want this message to appear when they login for 2nd or 3rd time).
To display the message I want to check current_user.email against all the registered email in the user table (logic here is: if the user already exists in the user table then I can safely assume that the user has already visited the website so I prevent the welcome being displayed). I am not sure how to access all the email id's in the table?? also where to do this check. I want this welcome message to be the first thing user sees as soon as there sign in is successful. Can anyone help please.

I tried to use "resource" resource_name" within sessions controller but nothing works. Not sure weather those are even remotely relevant.

    # POST /resource/sign_in
    def create
      self.resource = warden.authenticate!(auth_options)
      $sign = sign_in_count
      set_flash_message!(:notice, :signed_in)
      sign_in(resource_name, resource)
      yield resource if block_given?
      respond_with resource, location: after_sign_in_path_for(resource)
    end

I am trying to assign sign_in_count for logged in user to a global variable called $sign so that I can use it's value to check if user has signed in for first time or not.


问:
docker-compose start/up without running command
Is there any way to make docker-compose start a service without running the declared command?

Not sure if any such option exists, nothing obvious in the flags for docker-compose up. It would be useful for debugging as presently I have to comment out the command in order to enter a container that otherwise exits on startup.

In this case, there's no command in the Dockerfile, but there's a command in docker-compose.yml.

答:
Based on jonrsharpe's comment, the answer is to use run instead as it will start the container.

docker-compose run service bash

This makes it possible to enter the container and debug the problem so the real command can run.


问:
LINQ side effects
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

```<code>List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);
</code>```

To:

```<code>List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);
</code>```

答:
You can use the List<T>.ForEach method.

```<code>l.ForEach(i => Console.WriteLine(i));
</code>```

Title: LINQ side effects

Body:
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);

To:

List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);

Body:
You can use the List<T>.ForEach method.

l.ForEach(i => Console.WriteLine(i));


问:
How do I Track Work item history using Power BI?
I am trying to track work progress of Azure Devops using POWER BI. How can I get a work item history data for all work item from Azure Devops? I want to know when it started, When a particular work item in which stage and when its done?</p>

答:
You could track work item history using Power BI by the following steps.

From the web portal for Azure devops:

1.Install the Analytic extension in your org

2.Open Analytics view in Overview

3.Select Work Items-All history by month this default ananlytics view

4.Edit the Fields of this default analytics view ,add the fields you need like created date ,closed date,state and so on

5.Choose the Verification tab and then the Verify view button to verify the default Analytics view for your data

From the Power BI Desktop:

1.Choose Get Data -> Online Services -> Azure DevOps (Beta) -> choose Connect.

2.Enter your organization name and project name for the data you want to report on

3.Expand the Shared Views folder ->choose the analytics view ->choose Load

4.Select the data button on the left side of the page -> all work item history listed

For details you can refer to this document.


问:
Prevent XML empty tag parsing to zero
I have an XML parameter with empty tag like this.

```<code><dietTypes><dietType><dietaryID></dietaryID></dietType></dietTypes>
</code>```

I am trying to parse it to an integer like this in a stored procedure,

```<code>DECLARE @MemDietTypes TABLE(DietaryID INT);
INSERT INTO @MemDietTypes
SELECT  DietTypes.Col.value('dietaryID[1]', 'INT')
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);
</code>```

The above is parsed as zero, which is problematic for me. How can I prevent this happening? Thanks

答:
you can use text() function:

```<code>declare @data xml = '
    <dietTypes><dietType><dietaryID></dietaryID></dietType><dietType><dietaryID>2</dietaryID></dietType></dietTypes>';

select
    t.c.value('(dietaryID/text())[1]', 'int')
from @data.nodes('//dietType') as t(c);
</code>```

returns:

```<code>dietaryID
-----------
NULL
2
</code>```

Title: Prevent XML empty tag parsing to zero

Body:
I have an XML parameter with empty tag like this.

<dietTypes><dietType><dietaryID></dietaryID></dietType></dietTypes>

I am trying to parse it to an integer like this in a stored procedure,

DECLARE @MemDietTypes TABLE(DietaryID INT);
INSERT INTO @MemDietTypes
SELECT  DietTypes.Col.value('dietaryID[1]', 'INT')
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);

The above is parsed as zero, which is problematic for me. How can I prevent this happening? Thanks

Body:
you can use text() function:

declare @data xml = '
    <dietTypes><dietType><dietaryID></dietaryID></dietType><dietType><dietaryID>2</dietaryID></dietType></dietTypes>';

select
    t.c.value('(dietaryID/text())[1]', 'int')
from @data.nodes('//dietType') as t(c);

returns:

dietaryID
-----------
NULL
2


问:
WPF Binding ViewModel
So I am currently trying to learn WPF with MVVM and I was following some tutorials online. Now that I have a simple Project, I tried to do it on my own but somehow the ListBox stays empty. It doesn't get bound to the ViewModel, I think. What am I missing here?

ViewModel:

```<code>public class PersonViewModel
{
    ObservableCollection<Person> Personen { get; set; } = new ObservableCollection<Person>();

    public PersonViewModel()
    {
        Personen.Add(new Person { Vorname = "My", Nachname = "Name", Email = "my@name.com" });
        Personen.Add(new Person { Vorname = "Max", Nachname = "Mustermann", Email = "max@mustermann.de" });
        Personen.Add(new Person { Vorname = "John", Nachname = "Doe", Email = "john@doe.com" });
        Personen.Add(new Person { Vorname = "Jane", Nachname = "Doe", Email = "jane@doe.com" });
    }
}
</code>```

}

Also, I'm setting my DataContext like this:

```<code>public PersonenView()
{
    InitializeComponent();
    this.DataContext = new ViewModel.PersonViewModel();
}
</code>```

答:
You just need to give a public accessor to ObservableCollection Personen in your ViewModel.

You should also make the property readonly (or fire a property change notification from its setter):

```<code>public ObservableCollection<Person> Personen { get; }
    = new ObservableCollection<Person>();
</code>```

Title: WPF Binding ViewModel

Body:
So I am currently trying to learn WPF with MVVM and I was following some tutorials online. Now that I have a simple Project, I tried to do it on my own but somehow the ListBox stays empty. It doesn't get bound to the ViewModel, I think. What am I missing here?

ViewModel:

public class PersonViewModel
{
    ObservableCollection<Person> Personen { get; set; } = new ObservableCollection<Person>();

    public PersonViewModel()
    {
        Personen.Add(new Person { Vorname = "My", Nachname = "Name", Email = "my@name.com" });
        Personen.Add(new Person { Vorname = "Max", Nachname = "Mustermann", Email = "max@mustermann.de" });
        Personen.Add(new Person { Vorname = "John", Nachname = "Doe", Email = "john@doe.com" });
        Personen.Add(new Person { Vorname = "Jane", Nachname = "Doe", Email = "jane@doe.com" });
    }
}

}

Also, I'm setting my DataContext like this:

public PersonenView()
{
    InitializeComponent();
    this.DataContext = new ViewModel.PersonViewModel();
}

Body:
You just need to give a public accessor to ObservableCollection Personen in your ViewModel.

You should also make the property readonly (or fire a property change notification from its setter):

public ObservableCollection<Person> Personen { get; }
    = new ObservableCollection<Person>();


问:
What is this error?: unbound method requires a vtkRenderingCorePython.vtkAbstractMapper as the first argument
I am using VTK in Python now. And This is the first time I have been programming with Python.
After outputting the 3D object, we want to output the cross section of the object using the AddClippingPlane function.
However, the following error will be displayed and it will not be executed:

TypeError: unbound method requires a
  vtkRenderingCorePython.vtkAbstractMapper as the first argument.

When you see the attached code, can you tell me what's wrong? I would appreciate a lot your help.

```<code>import vtk
import sys
from PyQt5 import QtCore,QtWidgets
from PyQt5.QtGui import  *
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from PyQt5.QtWidgets import QMainWindow, QApplication
from foo import Ui_MainWindow
from PyQt5 import Qt

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setMouseTracking(True)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.OpenVTK)
        self.pushButton2.clicked.connect(
            QtCore.QCoreApplication.instance().quit)

    def OpenVTK(self):
        self.setMouseTracking(True)

        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl = Qt.QVBoxLayout()
        self.vl.addWidget(self.vtkWidget)
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        reader = vtk.vtkDICOMImageReader()
        reader.SetDirectoryName(FilePath)

        reader.Update()
        colors = vtk.vtkNamedColors()
        colors.SetColor("BkgColor", [51, 77, 102, 255])
        boneExtractor = vtk.vtkMarchingCubes()
        boneExtractor.SetInputConnection(reader.GetOutputPort())
        boneExtractor.SetValue(0, 1000)
        boneStripper = vtk.vtkStripper()
        boneStripper.SetInputConnection(boneExtractor.GetOutputPort())
        boneMapper = vtk.vtkPolyDataMapper()
        boneMapper.SetInputConnection(boneStripper.GetOutputPort())
        boneMapper.ScalarVisibilityOff()
        plane1 = vtk.vtkPlane()
        plane1.SetOrigin(0.05, 0.0, 0.0)  # [*1]
        plane1.SetNormal(-1.0, 0.0, 0.0)

        bone = vtk.vtkActor()
        bone.SetMapper(boneMapper)
        bone.GetProperty().SetDiffuseColor(colors.GetColor3d("Ivory"))
        bone = vtk.vtkAbstractMapper.AddClippingPlane(plane1)

        bwLut = vtk.vtkLookupTable()
        bwLut.SetTableRange(0, 2000)
        bwLut.SetSaturationRange(0, 1)
        bwLut.SetHueRange(0, 0)
        bwLut.SetValueRange(0, 1)
        bwLut.Build()

        sagittalColors = vtk.vtkImageMapToColors()
        sagittalColors.SetInputConnection(reader.GetOutputPort())
        sagittalColors.SetLookupTable(bwLut)
        sagittalColors.Update()

        sagittal = vtk.vtkImageActor()
        sagittal.GetMapper().SetInputConnection(sagittalColors.GetOutputPort())
        sagittal.SetDisplayExtent(250, 250, 0, 501, 0, 500)

        aCamera = vtk.vtkCamera()
        aCamera.SetViewUp(0, 0, -1)
        aCamera.SetPosition(0, -1, 0)
        aCamera.SetFocalPoint(0, 0, 0)
        aCamera.ComputeViewPlaneNormal()
        aCamera.Azimuth(0.0)
        aCamera.Elevation(0.0)

        self.ren.AddActor(sagittal)
        self.ren.AddActor(bone)
        self.ren.SetActiveCamera(aCamera)
        self.show()
        self.ren.ResetCamera()
        self.frame.setLayout(self.vl)
        aCamera.Dolly(1.0)

        self.ren.ResetCameraClippingRange()
        self.show()
        self.iren.Initialize()
        self.iren.Start()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
</code>```

答:
Your error comes from the line bone = vtk.vtkAbstractMapper.AddClippingPlane(plane1).

AddClippingPlane()is an instance method and has to be applied on a object.

It should be something like boneMapper.AddClippingPlane(plane1)

Body:
I am using VTK in Python now. And This is the first time I have been programming with Python.
After outputting the 3D object, we want to output the cross section of the object using the AddClippingPlane function.
However, the following error will be displayed and it will not be executed:

TypeError: unbound method requires a
  vtkRenderingCorePython.vtkAbstractMapper as the first argument.

When you see the attached code, can you tell me what's wrong? I would appreciate a lot your help.

import vtk
import sys
from PyQt5 import QtCore,QtWidgets
from PyQt5.QtGui import  *
from vtk.qt.QVTKRenderWindowInteractor import QVTKRenderWindowInteractor
from PyQt5.QtWidgets import QMainWindow, QApplication
from foo import Ui_MainWindow
from PyQt5 import Qt

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setMouseTracking(True)
        self.setupUi(self)
        self.pushButton.clicked.connect(self.OpenVTK)
        self.pushButton2.clicked.connect(
            QtCore.QCoreApplication.instance().quit)

    def OpenVTK(self):
        self.setMouseTracking(True)

        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl = Qt.QVBoxLayout()
        self.vl.addWidget(self.vtkWidget)
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        reader = vtk.vtkDICOMImageReader()
        reader.SetDirectoryName(FilePath)

        reader.Update()
        colors = vtk.vtkNamedColors()
        colors.SetColor("BkgColor", [51, 77, 102, 255])
        boneExtractor = vtk.vtkMarchingCubes()
        boneExtractor.SetInputConnection(reader.GetOutputPort())
        boneExtractor.SetValue(0, 1000)
        boneStripper = vtk.vtkStripper()
        boneStripper.SetInputConnection(boneExtractor.GetOutputPort())
        boneMapper = vtk.vtkPolyDataMapper()
        boneMapper.SetInputConnection(boneStripper.GetOutputPort())
        boneMapper.ScalarVisibilityOff()
        plane1 = vtk.vtkPlane()
        plane1.SetOrigin(0.05, 0.0, 0.0)  # [*1]
        plane1.SetNormal(-1.0, 0.0, 0.0)

        bone = vtk.vtkActor()
        bone.SetMapper(boneMapper)
        bone.GetProperty().SetDiffuseColor(colors.GetColor3d("Ivory"))
        bone = vtk.vtkAbstractMapper.AddClippingPlane(plane1)

        bwLut = vtk.vtkLookupTable()
        bwLut.SetTableRange(0, 2000)
        bwLut.SetSaturationRange(0, 1)
        bwLut.SetHueRange(0, 0)
        bwLut.SetValueRange(0, 1)
        bwLut.Build()

        sagittalColors = vtk.vtkImageMapToColors()
        sagittalColors.SetInputConnection(reader.GetOutputPort())
        sagittalColors.SetLookupTable(bwLut)
        sagittalColors.Update()

        sagittal = vtk.vtkImageActor()
        sagittal.GetMapper().SetInputConnection(sagittalColors.GetOutputPort())
        sagittal.SetDisplayExtent(250, 250, 0, 501, 0, 500)

        aCamera = vtk.vtkCamera()
        aCamera.SetViewUp(0, 0, -1)
        aCamera.SetPosition(0, -1, 0)
        aCamera.SetFocalPoint(0, 0, 0)
        aCamera.ComputeViewPlaneNormal()
        aCamera.Azimuth(0.0)
        aCamera.Elevation(0.0)

        self.ren.AddActor(sagittal)
        self.ren.AddActor(bone)
        self.ren.SetActiveCamera(aCamera)
        self.show()
        self.ren.ResetCamera()
        self.frame.setLayout(self.vl)
        aCamera.Dolly(1.0)

        self.ren.ResetCameraClippingRange()
        self.show()
        self.iren.Initialize()
        self.iren.Start()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


答:
Try this to understand the implicit defaults:

```<code>SELECT CAST(NULL AS INT)
      ,CAST('' AS INT)
      ,CAST('      ' AS INT);
</code>```

A NULL remains unchanged, but empty is defaulted to a zero. That is the designed behaviour.

Now back to your issue:

```<code>DECLARE @DietaryTypeXML XML='<dietTypes>
                               <dietType>
                                 <dietaryID></dietaryID> <!-- This is empty -->
                               </dietType>
                             </dietTypes>';
</code>```

--The engine gets an empty value and defaults it to a zero.

--If you use varchar instead, you get a blank, but you'll have to deal with string-typed numbers.

```<code>SELECT  DietTypes.Col.value('dietaryID[1]', 'INT') AS Empty_in_INT_is_implicitly_taken_as_zero
       ,DietTypes.Col.value('dietaryID[1]', 'VARCHAR(100)') AS Empty_in_VARCHAR_is_implicitly_taken_as_empty_string
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);
</code>```

--The solution I suggest:

```<code>SELECT  DietTypes.Col.value('dietaryID[1] cast as xs:int?', 'INT')
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);
</code>```

Using the XQuery cast as xs:int? tells the engine, that the given value is a nullable int. Now the value returned is no more empty but NULL.

Title: Prevent XML empty tag parsing to zero

Body:
Try this to understand the implicit defaults:

SELECT CAST(NULL AS INT)
      ,CAST('' AS INT)
      ,CAST('      ' AS INT);

A NULL remains unchanged, but empty is defaulted to a zero. That is the designed behaviour.

Now back to your issue:

DECLARE @DietaryTypeXML XML='<dietTypes>
                               <dietType>
                                 <dietaryID></dietaryID> <!-- This is empty -->
                               </dietType>
                             </dietTypes>';

--The engine gets an empty value and defaults it to a zero.

--If you use varchar instead, you get a blank, but you'll have to deal with string-typed numbers.

SELECT  DietTypes.Col.value('dietaryID[1]', 'INT') AS Empty_in_INT_is_implicitly_taken_as_zero
       ,DietTypes.Col.value('dietaryID[1]', 'VARCHAR(100)') AS Empty_in_VARCHAR_is_implicitly_taken_as_empty_string
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);

--The solution I suggest:

SELECT  DietTypes.Col.value('dietaryID[1] cast as xs:int?', 'INT')
FROM   @DietaryTypeXML.nodes('//dietType') DietTypes(Col);

Using the XQuery cast as xs:int? tells the engine, that the given value is a nullable int. Now the value returned is no more empty but NULL.


问:
How to change the item inside the menu from span to custom div?
I want to replace the span in the context menu to a custom div:
This is the code used:

```<code>$.contextMenu({
            selector: '.context-menu-row',
            items: {
                copy: {
                    name: function(){
                        return "Layout"
                        },
                    callback: function(key, opt){
                        alert("Clicked on " + key);
                    }
                    }
                }
            });
</code>```

So instead of "Layout" I need to put a div divided into 3 divs.

答:
Instead of replacing an element, you can have both in the document and change their display property, hiding or displaying the element as you like. To hide an object, just disable the display property as follows:

```<code>display: none;
</code>```

To display it again, change the display property to whatever you need to.

More information:

https://developer.mozilla.org/es/docs/Web/CSS/display

Body:
I want to replace the span in the context menu to a custom div:
This is the code used:

$.contextMenu({
            selector: '.context-menu-row',
            items: {
                copy: {
                    name: function(){
                        return "Layout"
                        },
                    callback: function(key, opt){
                        alert("Clicked on " + key);
                    }
                    }
                }
            });

So instead of "Layout" I need to put a div divided into 3 divs.

Body:
Instead of replacing an element, you can have both in the document and change their display property, hiding or displaying the element as you like. To hide an object, just disable the display property as follows:

display: none;

To display it again, change the display property to whatever you need to.

More information:

https://developer.mozilla.org/es/docs/Web/CSS/display


问:
Sending an array of integers with MPI_Send, a subtle confusion
I am new to MPI. Apologies if it is a stupid question. I wonder whether the parameter count in MPI_Send() means that it will send an array (size count) of the given datatype in one go or that it will spits the given datatype one at a time and do so count times.

答:
Logically, one message is sent by a call to MPI_Send().

How this maps to the actual network or local communication is up to the implementation. You may safely assume that it is efficient, but it should not matter to your application how many streams, packets, fragments, flits or whatever are involved in transferring the message.


问:
Can HTML checkboxes be set to readonly?
I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything.

I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.

答:
Belated answer, but most answers seem to over complicate it.

As I understand it, the OP was basically wanting:

Readonly checkbox to show status.

Value returned with form.

It should be noted that:

The OP preferred not to use the disabled attribute, because they 'want the checked check boxes to be submitted with the rest of the form'.

Unchecked checkboxes are not submitted with the form, as the quote from the OP in 1. above indicates they knew already. Basically, the value of the checkbox only exists if it is checked.

A disabled checkbox clearly indicates that it cannot be changed, by design, so a user is unlikely to attempt to change it.

The value of a checkbox is not limited to indicating its status, such as yes or false, but can be any text.

Therefore, since the readonly attribute does not work, the best solution, requiring no javascript, is:

A disabled checkbox, with no name or value.

If the checkbox is to be displayed as checked, a hidden field with the name and value as stored on the server.

So for a checked checkbox:

<input type="checkbox" checked="checked" disabled="disabled" />
<input type="hidden" name="fieldname" value="fieldvalue" />```
</div>
</div>
</p>

<p>For an unchecked checkbox:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" disabled="disabled" /></code>```

The main problem with disabled inputs, especially checkboxes, is their poor contrast which may be a problem for some with certain visual disabilities. It may be better to indicate a value by plain words, such as Status: none or Status: implemented, but including the hidden input above when the latter is used, such as:

Status: Implemented<input type="hidden" name="status" value="implemented" />
```

ContentLicense: CC BY-SA 2.5

Title: Can HTML checkboxes be set to readonly?

Body:
Belated answer, but most answers seem to over complicate it.

As I understand it, the OP was basically wanting:

Readonly checkbox to show status.

Value returned with form.

It should be noted that:

The OP preferred not to use the disabled attribute, because they 'want the checked check boxes to be submitted with the rest of the form'.

Unchecked checkboxes are not submitted with the form, as the quote from the OP in 1. above indicates they knew already. Basically, the value of the checkbox only exists if it is checked.

A disabled checkbox clearly indicates that it cannot be changed, by design, so a user is unlikely to attempt to change it.

The value of a checkbox is not limited to indicating its status, such as yes or false, but can be any text.

Therefore, since the readonly attribute does not work, the best solution, requiring no javascript, is:

A disabled checkbox, with no name or value.

If the checkbox is to be displayed as checked, a hidden field with the name and value as stored on the server.

So for a checked checkbox:

<input type="checkbox" checked="checked" disabled="disabled" />
<input type="hidden" name="fieldname" value="fieldvalue" />

For an unchecked checkbox:

<input type="checkbox" disabled="disabled" />

The main problem with disabled inputs, especially checkboxes, is their poor contrast which may be a problem for some with certain visual disabilities. It may be better to indicate a value by plain words, such as Status: none or Status: implemented, but including the hidden input above when the latter is used, such as:

<p>Status: Implemented<input type="hidden" name="status" value="implemented" /></p>


问:
How to set a Master Workbooks Object?
I was thinking if its possible to set a Master Workbook in Excel VBA and access it on all procedures and functions?

Since I am pretty new to VBA I don't understand the syntax VBA is using..

```<code>Dim MasterWB as Workbook
Set MasterWB = Workbooks.Open("Path to my Workbook")
</code>```

But if I want to access it in an another Procedure or Function I'll get a Object Definition Error.

I don't want to declare the Object in every Sub or Function.
Thanks a lot!

答:
There are two ways of doing this:

The good practice:

```<code>Option Explicit
Sub Test()

    Dim MasterWB As Workbook
    Set MasterWB = Workbooks.Open("Path")
    UseWb MasterWB

End Sub
Sub UseWb(wb As Workbook)

    wb.Close

End Sub
</code>```

The you shouldn't use practice:

```<code>Option Explicit
Public MasterWB As Workbook
Sub Test()

    Set MasterWB = Workbooks.Open("Path")
    UseWb MasterWB

End Sub
Sub UseWb()

    wb.Close

End Sub
</code>```

The first one allows you to pass the Workbook Variable as parameter to other functions in this case you can't use ByVal but other variables like Integeror Long can be used as ByVal instead of (per default) ByRef.

ByVal means you are only passing the value of that variable, so you won't modify it on the function.

ByRef means you pass the reference, so the other function can modify that original variable.

The second way only allows you to use the variable as a reference so there might be changes on it without noticing.

Hope this clears out a bit your question.

Title: How to set a Master Workbooks Object?

Body:
I was thinking if its possible to set a Master Workbook in Excel VBA and access it on all procedures and functions?

Since I am pretty new to VBA I don't understand the syntax VBA is using..

Dim MasterWB as Workbook
Set MasterWB = Workbooks.Open("Path to my Workbook")

But if I want to access it in an another Procedure or Function I'll get a Object Definition Error.

I don't want to declare the Object in every Sub or Function.
Thanks a lot!

Body:
There are two ways of doing this:

The good practice:

Option Explicit
Sub Test()

    Dim MasterWB As Workbook
    Set MasterWB = Workbooks.Open("Path")
    UseWb MasterWB

End Sub
Sub UseWb(wb As Workbook)

    wb.Close

End Sub

The you shouldn't use practice:

Option Explicit
Public MasterWB As Workbook
Sub Test()

    Set MasterWB = Workbooks.Open("Path")
    UseWb MasterWB

End Sub
Sub UseWb()

    wb.Close

End Sub

The first one allows you to pass the Workbook Variable as parameter to other functions in this case you can't use ByVal but other variables like Integeror Long can be used as ByVal instead of (per default) ByRef.

ByVal means you are only passing the value of that variable, so you won't modify it on the function.

ByRef means you pass the reference, so the other function can modify that original variable.

The second way only allows you to use the variable as a reference so there might be changes on it without noticing.

Hope this clears out a bit your question.


问:
How can I see which CPU core a thread is running in?
In Linux, supposing a thread's pid is [pid], from the directory /proc/[pid] we can get many useful information. For example, these proc files, /proc/[pid]/status,/proc/[pid]/stat and /proc/[pid]/schedstat are all useful. But how can I get the CPU core number that a thread is running in? If a thread is in sleep state, how can I know which core it will run after it is scheduled again?

BTW, is there a way to dump the process(thread) list of running and sleeping tasks for each CPU core?

Body:
To see the threads of a process :

ps -T -p PID

To see the thread run info

ps -mo pid,tid,%cpu,psr -p PID

Example :

/tmp # ps -T -p 3725
  PID  SPID TTY          TIME CMD
 3725  3725 ?        00:00:00 Apps
 3725  3732 ?        00:00:10 t9xz1d920
 3725  3738 ?        00:00:00 XTimer
 3725  3739 ?        00:00:05 Japps
 3725  4017 ?        00:00:00 QTask
 3725  4024 ?        00:00:00 Kapps
 3725  4025 ?        00:00:17 PTimer
 3725  4026 ?        00:01:17 PTask
 3725  4027 ?        00:00:00 RTask
 3725  4028 ?        00:00:00 Recv
 3725  4029 ?        00:00:00 QTimer
 3725  4033 ?        00:00:01 STask
 3725  4034 ?        00:00:02 XTask
 3725  4035 ?        00:00:01 QTimer
 3725  4036 ?        00:00:00 RTimer
 3725  4145 ?        00:00:00 t9xz1d920
 3725  4147 ?        00:00:02 t9xz1d920
 3725  4148 ?        00:00:00 t9xz1d920
 3725  4149 ?        00:00:00 t9xz1d920
 3725  4150 ?        00:00:00 t9xz1d920
 3725  4865 ?        00:00:02 STimer

/tmp #
/tmp #
/tmp # ps -mo pid,tid,%cpu,psr -p 3725
  PID   TID %CPU PSR
 3725     -  1.1   -
    -  3725  0.0   2
    -  3732  0.1   0
    -  3738  0.0   0
    -  3739  0.0   0
    -  4017  0.0   6
    -  4024  0.0   3
    -  4025  0.1   0
    -  4026  0.7   0
    -  4027  0.0   3
    -  4028  0.0   7
    -  4029  0.0   0
    -  4033  0.0   4
    -  4034  0.0   1
    -  4035  0.0   0
    -  4036  0.0   2
    -  4145  0.0   2
    -  4147  0.0   0
    -  4148  0.0   5
    -  4149  0.0   2
    -  4150  0.0   7
    -  4865  0.0   0
/tmp #


问:
IPA file is not created in Xamarin.IOS
I have problem creating the IPA file for Xamarin.IOS project.
In properties of the project i've selected the certificate and the provision and also selected the "create IPA file".
The build finishing succesfully but no IPA file there.
The project is on Release mode.
Any ideas?

I also tried to make archive from the Mac but i am getting errors "file not found" because the icons folder have extention of .app and its not recognised by Mac

答:
In the following link of Microsoft docs, it shows you the steps you need to take for creating an IPA.

In the Solution Explorer, right-click the Xamarin.iOS project name and select Properties to open them for editing:

Select iOS IPA Options and select Ad-Hoc from the Configuration dropdown list:

If you are including an option iTunesMetadata.plist file, click the ... button, select it from the list and click the Open button:

You can optionally specify a Package Name for the IPA, if not specified it will have the same name as the Xamarin.iOS project.

Save your changes to the Project Properties.

Select Ad Hoc from the Build Configuration dropdown if it is available. Otherwise select Release:

Build the project to create the IPA package.

The IPA will be build in the Bin > iOS Device > Ad Hoc (or Release) folder:

Title: IPA file is not created in Xamarin.IOS


问:
How to write very small text in HTML
I would like to have a font smaller than an Arial 9px text.

I've tried to find other font name but I did not succeed to get a very small text. Is there a way to achieve this easily using css ?

EDIT :
I can't go under 9px using Arial
I have tried font-size, small, transform, scale, other fonts... everything as I am an experienced web developper.

答:
You can try it

div p {
  font-family: 'Arial';
  -webkit-text-size-adjust: none;
  font-size: 5px
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>lorem</p>
</div></code>```

Title: How to write very small text in HTML

Body:
You can try it

div p {
  font-family: 'Arial';
  -webkit-text-size-adjust: none;
  font-size: 5px
}

<div>
  <p>lorem</p>
</div>


问:
Azure REST API get resource parentResourcePath parameter
Context

I am willing to get a resource details with the Azure REST API. And more particularly, I want to get the IAM associated with a resource.

Problem

So, I searched in the doc reference and found that endpoint: https://learn.microsoft.com/en-us/rest/api/resources/resources/get which provides an identity response attribute that meets my needs.

However, I can't find any information about the required path parameter parentResourcePath. What does that parameter mean and how can I get its value for a specific resource ?

Also, when I tried going through the resources group path, I can get a path to the resource details but without the parentResourcePath parameter, and the response doesn't include the identity attribute.

Finally, am I going the right way (using GET resource API) ? And if so, where can I find that parentResourcePath value ?

答:
Well I made it throught the Role assignment list for scope endpoint, giving the subscription/resourcegroup/resource in the scope. And the output contains a principalId attribute that seems to point to a user or group or service principal.

Ref: https://learn.microsoft.com/en-us/rest/api/authorization/roleassignments/listforscope


问:
Python script to retrieve remote OS information without using nmap
I am trying to write a python script that can retrieve remote OS information (username, OS name, version, etc), like Nmap. Is it possible to do so without using Nmap ?</p>

答: Of course it is possible but consider this, nmap guess OS type and version by checking remote system response and compare it with its signature database and it is not accurate.</p>


问:
Login failed when trying to perform git push to Azure Devops
I am on a Windows 10 machine, and this morning my git credentials were working as expected, and I was busy pushing and pulling code to our Azure Devops project.
Now I cannot, from this specific VM anyways. When I do git pull I get the standard MS authentication prompt, and I can see my MS account (which is connected to windows via our federated AD)

I click on my account, and the prompt goes away, and I get an error in my prompt:

Logon failed, use ctrl+c to cancel basic credential prompt.
Password for 'https://myOrg@dev.azure.com':

If I enter my AD password (or anything else) I get a authentication failed message. I also tried to re-enter my credentials by selecting "Use another account" in the MS sign in window, and I get the same results.

I have seen issues that were solved by removing the cached credentials from the Credential Manager. So I go Control Panel -> Credential Manager and remove all of the credentials that are stored and try the git operation again.

I get the same MS login window, and oddly enough my account is still there, and Connected to windows (and fails the same way when I click on it)

So then I removed my accounts that were associated via Settings -> Accounts -> Access work or school. I could see my MS account there, so that looked promising, but same behaviour.
I tried to update git (it is v2.21.0.windows.1)
I also installed microsoft's git credential manager as per some answers that I found on SO and microsoft's forums.
Still getting the same error.

I rebooted and removed all the credentials/accounts again, then tried from Visual Studio instead of calling git from the command line.

Same error!

My next steps are to rebuild my Windows profile which I am hoping will reset all this stuff. I am able to access the site from another VM, so it seems to be some sort of git configuration/cached credentials on this machine.

Any assistance/ideas are appreciated.

答:
Try disconnecting from the team server.

Then try redoing your commit from the Team Explorer window, reconnecting if required.


问:
How to use Array.protoype.map() on array of objects to filter out some specific keys based on it's values?
I have the following array of objects, in which some specific keys have a value which is either a string or an array. I want to get the keys with string values as it is and remove "NA" from keys with array values.

I am trying to achieve the same by doing .map method on the array, check the type of the value of each key in the data object, if an array then use .filter to remove the "NA" values.

```<code>var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];
dataArr.map(dataObj => {
    for (let key in dataObj) {
        if (key !== 'a')
            dataObj[key] = dataObj[key].filter(val => { if(val != "NA") return val})
    }
    return dataObj;
});
</code>```

The above block of code works as expected but I want a better and future-proof solution. Moreover, this looks bad too.

答:
Use for...of on the object's entries. For each entry check if it's an array. If it's an array filter, and then assign to the new object. If not, assign without filtering. This will not mutate the original array.

const dataArr = [{"a":"foo","b":[1,2,"NA","NA",3],"c":["NA",6]},{"a":"bar","b":["NA","NA","NA"],"c":[]}]

const result = dataArr.map(dataObj => {
  const filterObject = {};

  for (const [key, val] of Object.entries(dataObj)) {
    filterObject[key] = Array.isArray(val) ?
      dataObj[key].filter(val => val != 'NA')
      :
      val;
  }

  return filterObject;
});

console.log(result);```

Body:
I have the following array of objects, in which some specific keys have a value which is either a string or an array. I want to get the keys with string values as it is and remove "NA" from keys with array values.

I am trying to achieve the same by doing .map method on the array, check the type of the value of each key in the data object, if an array then use .filter to remove the "NA" values.

var dataArr = [
    {
     a: 'foo',
     b: [1, 2, "NA", "NA", 3],
     c: ["NA", 6]
    },
    {
     a: 'bar',
     b: ["NA", "NA", "NA"],
     c: []
    }
];
dataArr.map(dataObj => {
    for (let key in dataObj) {
        if (key !== 'a')
            dataObj[key] = dataObj[key].filter(val => { if(val != "NA") return val})
    }
    return dataObj;
});

The above block of code works as expected but I want a better and future-proof solution. Moreover, this looks bad too.


问:
Can you kill a smart contract in Hyperledger Fabric
Can you delete hyperledger fabric smart contract like the kill function in ethereum?</p>

答:
To kill a chaincode(Smart contract) you need to follow following steps:

Kill chaincode containers belonging to respective chaincode version, which you want to kill. You may kill containers using following command:-

docker rm -f [Chaincode docker container's ids separated by space]

Delete chaincode images, using following command:-

docker rmi [Chaincode images ids]

Delete the chaincode from the file system of each peer under /var/hyperledger/production/chaincodes

Right now this is the procedure to uninstall a chaincode, in future there will be stop and start command to stop and resume a smart contract respectively. You may checkout the same in official documentation:-

Hyperledger fabric chaincode lifecycle


问:
Set options for single instance of an Angular Toastr?
I am using Angular JS 1.4.1 and Angular Toastr 1.7.0.

Most of the toastrs in my app are the default top right, and work fine.

However, I want to call ONE with the positionClass: 'toast-top-full-width' and I can't get it to work.  It still opens at the defaults set it my app config.

```<code>   $scope.tabLeave = function () {
    toastr.warning('Warning', 'You have unsaved data.', {
      closeButton: true,
      positionClass: 'toast-top-full-width'
    });
  };
</code>```

What am missing here?

答:
```<code>this.toastr.info('No credit remaining', '', { disableTimeOut: true, closeButton: true });
</code>```

Body:
I am using Angular JS 1.4.1 and Angular Toastr 1.7.0.

Most of the toastrs in my app are the default top right, and work fine.

However, I want to call ONE with the positionClass: 'toast-top-full-width' and I can't get it to work.  It still opens at the defaults set it my app config.

   $scope.tabLeave = function () {
    toastr.warning('Warning', 'You have unsaved data.', {
      closeButton: true,
      positionClass: 'toast-top-full-width'
    });
  };

What am missing here?


问:
What are the often misunderstood concepts in C++?
What are the often misunderstood concepts in c++?</p>

答:
Arrays are not pointers

They are different. So &array is not a pointer to a pointer, but a pointer to an array. This is the most misunderstood concept in both C and C++ in my opinion. You gotta have a visit to all those SO answers that tell to pass 2-d arrays as type** !

OwnerDisplayName: rajKumar

LastEditorDisplayName: starblue

OwnerDisplayName: litb

LastEditorDisplayName: litb