问:
cURL error 60: SSL certificate problem: certificate has expired
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

```<code>cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)
</code>```

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1
</code>```

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

```<code>* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.
</code>```

My curl code -

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);
</code>```

答:
It seems like your truststore is not updated with the latest trusted root. Understanding that it happened to you beginning yesterday 30th May. I am assuming that you have Sectigo as your CA.

Update your trustore and you should be able to connect.

https://support.sectigo.com/articles/Knowledge/Sectigo-AddTrust-External-CA-Root-Expiring-May-30-2020

Body:
We running 2 application on amazon EC2 (backend.example.com & frontend.example.com). For that application, we used a paid SSL Certificate. That certificate expiration date at 2021 June. But today, we got an error -

cURL error 60: SSL certificate problem: certificate has expired (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

We check certificate expiration date, but there was no problem (2021 June). Then we follow this thread - curl: (60) SSL certificate problem: unable to get local issuer certificate (@Dahomz answer)

After that, when we curl example.com by - curl -v --url https://backend.example.com --cacert /etc/ssl/ssl.cert/cacert.pem, It working fine. Response like -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* found 139 certificates in /etc/ssl/ssl.cert/cacert.pem
* found 600 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ******_RSA_***_***_GCM_*****
*    server certificate verification OK
*    server certificate status verification SKIPPED
*    common name: *.example.com (matched)
*    server certificate expiration date OK
*    server certificate activation date OK
*    certificate public key: RSA
*    certificate version: #3
*    subject: OU=Domain Control Validated,OU=PositiveSSL Wildcard,CN=*.example.xyz
*    start date: Mon, 04 May 2019 00:00:00 GMT
*    expire date: Wed, 07 June 2021 23:59:59 GMT
*    issuer: C=GB,ST=Greater Manchester,L=Salford,O=Sectigo Limited,CN=Sectigo RSA Domain Validation Secure Server CA
*    compression: NULL
* ALPN, server accepted to use http/1.1

But when we hit from frontend.example.com to backend.example.com by curl, it throws this error -

* Rebuilt URL to: https://backend.example.com/
*   Trying 127.0.0.1...
* Connected to backend.example.com (127.0.0.1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/ssl.cert/cacert.pem
  CApath: /etc/ssl/certs
* SSL connection using TLSv1.2 / *****-RSA-*****-GCM-******
* ALPN, server accepted to use http/1.1
* Server certificate:
*    subject: OU=Domain Control Validated; OU=PositiveSSL Wildcard; CN=*.example.com
*    start date: Mar  4 00:00:00 2019 GMT
*    expire date: Apr  7 23:59:59 2021 GMT
*    issuer: C=GB; ST=Greater Manchester; L=Salford; O=Sectigo Limited; CN=Sectigo RSA Domain Validation Secure Server CA
*    SSL certificate verify result: certificate has expired (10), continuing anyway.

My curl code -

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://backend.example.com");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_STDERR, fopen(public_path("c.log"), 'w'));
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
$output = curl_exec($ch);
$error = curl_error($ch);
$info = curl_getinfo($ch);
curl_close($ch);


来源: stackexchange

问:
Shouldnt the x[1] just take the second array in the multidimensional array=
I have trouble understanding the lambda function, I always confuse myself because I overthink everything, here my problem:

```<code>nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []

for _ in range(n):
    arr.append(list(map(int, input().rstrip().split())))

k = int(input())

arr.sort(key=lambda x: x[1])
</code>```

What the Code does isn't important right now, but I receive following output if I print my array(for my example):

```<code>[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]
</code>```

As you can see it is a multidimensional array, now I want to sort it based on the second element of each list:

```<code>arr.sort(key=lambda x: x[1])
</code>```

So I have the list and I want to sort it with the key lambda and the variable x: x[1] shouldn't my variable x be the multidimensional array? Isnt it the same if I say x = arr,
how exactly does this function know i want to sort all the elements that are at position x[1] from each list, i would have thought using x[1] would only be the second array in the multidimensional array:

```<code>[[1, 2, 3], **[4, 2, 6]** ...
</code>```

Im a beginner so I would appreciate a beginner friendly response to my question,
cheers!

答:
Note that lambda x: x[1] is just convenient syntax for creating
function objects. So instead of

```<code>arr.sort(key=lambda x: x[1])
</code>```

you can write:

```<code>def key_fun(x):
    return x[1]
arr.sort(key=key_fun)
</code>```

I recommend doing it that way until you learn more about Python.

arr.sort with the key argument is also a type of convenient
syntax. Instead of arr.sort(key=key_fun) you can write:

```<code>arr2 = [(key_fun(x), x) for x in arr]
arr2.sort()
arr = [x for (key, x) in arr2]
</code>```

Under the hood, arr.sort(key=key_fun) does roughly the same job for
you.

ContentLicense: CC BY-SA 4.0

Body:
I have trouble understanding the lambda function, I always confuse myself because I overthink everything, here my problem:

nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []

for _ in range(n):
    arr.append(list(map(int, input().rstrip().split())))

k = int(input())

arr.sort(key=lambda x: x[1])

What the Code does isn't important right now, but I receive following output if I print my array(for my example):

[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]

As you can see it is a multidimensional array, now I want to sort it based on the second element of each list:

arr.sort(key=lambda x: x[1])

So I have the list and I want to sort it with the key lambda and the variable x: x[1] shouldn't my variable x be the multidimensional array? Isnt it the same if I say x = arr,
how exactly does this function know i want to sort all the elements that are at position x[1] from each list, i would have thought using x[1] would only be the second array in the multidimensional array:

[[1, 2, 3], **[4, 2, 6]** ...

Im a beginner so I would appreciate a beginner friendly response to my question,
cheers!

Body:
Note that lambda x: x[1] is just convenient syntax for creating
function objects. So instead of

arr.sort(key=lambda x: x[1])

you can write:

def key_fun(x):
    return x[1]
arr.sort(key=key_fun)

I recommend doing it that way until you learn more about Python.

arr.sort with the key argument is also a type of convenient
syntax. Instead of arr.sort(key=key_fun) you can write:

arr2 = [(key_fun(x), x) for x in arr]
arr2.sort()
arr = [x for (key, x) in arr2]

Under the hood, arr.sort(key=key_fun) does roughly the same job for
you.


问:
AWS S3 Glacier upload-archive taking a long time to finish execution - ways to check status or speed upload?
I am trying to upload some .tar.gz files to AWS S3 Glacier using the upload-archive command (docs).

I ran the upload-archive command over one day ago on a 29 GB .tar.gz file like so:

aws glacier upload-archive --vault-name my-vault --account-id - --archive-description "my description" --body my-file.tar.gz
```

<p>I checked today, and found it still has yet to finish execution.</p>

<hr>

<p>My question is two parts:</p>

<ul>
<li>Is there some way to see that the command is still running?

<ul>
<li>A progress bar would be awesome</li>
</ul></li>
<li>Are there any ways (or alternate methods) to speed up the <code>upload-archive</code>?</li>
</ul>

<p>FYI, I am using <code>aws-cli==2.0.17</code>.  Thank you in advance for any help!</p>

<hr>

<p><strong>**Edit**</strong></p>

<p>After running for two days, the <code>upload-archive</code> command errored out with the below message:</p>

```An error occurred (InvalidParameterValueException) when calling the UploadArchive operation: Invalid Content-Length: 30957118
```

Which lead to aws-cli #3413.  The posts there are in agreement with all the answers below.

答:
Take a look at multipart-upload to Glacier.

This example initiates a multipart upload to a vault named my-vault with a part size of 1 MiB:

```<code>aws glacier initiate-multipart-upload --account-id - --part-size 1048576 --vault-name my-vault
</code>```

As for checking if an existing upload is progressing, you can always look at the network activity on the uploading client and see if there is any bandwidth towards AWS IP addresses.

Docs

Body:
I am trying to upload some .tar.gz files to AWS S3 Glacier using the upload-archive command (docs).

I ran the upload-archive command over one day ago on a 29 GB .tar.gz file like so:

aws glacier upload-archive --vault-name my-vault --account-id - --archive-description "my description" --body my-file.tar.gz

I checked today, and found it still has yet to finish execution.

My question is two parts:

Is there some way to see that the command is still running?

A progress bar would be awesome

Are there any ways (or alternate methods) to speed up the upload-archive?

FYI, I am using aws-cli==2.0.17.  Thank you in advance for any help!

**Edit**

After running for two days, the upload-archive command errored out with the below message:

An error occurred (InvalidParameterValueException) when calling the UploadArchive operation: Invalid Content-Length: 30957118

Which lead to aws-cli #3413.  The posts there are in agreement with all the answers below.

Body:
Take a look at multipart-upload to Glacier.

This example initiates a multipart upload to a vault named my-vault with a part size of 1 MiB:

aws glacier initiate-multipart-upload --account-id - --part-size 1048576 --vault-name my-vault

As for checking if an existing upload is progressing, you can always look at the network activity on the uploading client and see if there is any bandwidth towards AWS IP addresses.

Docs


问:
Enabling recording devices programmatically
Enabling recording devices programmatically

I want to enable the disabled device in Sound - Recording devices list programmatically

I was able to get a list of disabled devices using Naudio

But there is no way to enable it using Naudio.

so I tried also using IMMDevice interface but I couldn't find out how to do this.

I tried also Registry Edit

```<code>//Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{87bd5990-b012-41f1-83f7-f267ed7780a7}
    RegistryKey root = Registry.LocalMachine.OpenSubKey("SOFTWARE", true).OpenSubKey("Microsoft", true).OpenSubKey("Windows", true).OpenSubKey("CurrentVersion", true).OpenSubKey("MMDevices", true).OpenSubKey("Audio", true).OpenSubKey("Render", true).OpenSubKey("{87bd5990-b012-41f1-83f7-f267ed7780a7}", true); //{87bd5990-b012-41f1-83f7-f267ed7780a7} any Playback Device ID
    MessageBox.Show($"Value Before {root.GetValue("DeviceState")}   { root.GetValueKind("DeviceState")}");
    root.SetValue("DeviceState", 0x10000001, RegistryValueKind.DWord);
    MessageBox.Show($"Value After {root.GetValue("DeviceState")}    { root.GetValueKind("DeviceState")}");
</code>```

or

```<code>Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{87bd5990-b012-41f1-83f7-f267ed7780a7}", "DeviceState", 0x10000001, RegistryValueKind.DWord);
</code>```

but this will need Administrator Rights and I want it to work for any user.

答:
Here you go, Console App code that enables any audio capture devices that are in a disabled state. you may compile to exe using VS or call with PowerShell using add-type </p>

```<code>using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1_Audio
{
    class Program
    {
        public enum HRESULT : uint
        {
            S_OK = 0,
            S_FALSE = 1,
            E_NOINTERFACE = 0x80004002,
            E_NOTIMPL = 0x80004001,
            E_FAIL = 0x80004005,
            E_UNEXPECTED = 0x8000FFFF
        }

        [ComImport]
        [Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IPropertyStore
        {
            HRESULT GetCount(out uint propertyCount);
            HRESULT GetAt([In] uint propertyIndex, [MarshalAs(UnmanagedType.Struct)] out PROPERTYKEY key);
            HRESULT GetValue([In][MarshalAs(UnmanagedType.Struct)] ref PROPERTYKEY key, [MarshalAs(UnmanagedType.Struct)] out PROPVARIANT pv);
            HRESULT SetValue([In][MarshalAs(UnmanagedType.Struct)] ref PROPERTYKEY key, [In][MarshalAs(UnmanagedType.Struct)] ref PROPVARIANT pv);
            HRESULT Commit();
        }

        public const int STGM_READ = 0x0;
        public const int STGM_WRITE = 0x1;
        public const int STGM_READWRITE = 0x2;

        public partial struct PROPERTYKEY
        {
            public PROPERTYKEY(Guid InputId, uint InputPid)
            {
                fmtid = InputId;
                pid = InputPid;
            }

            private Guid fmtid;
            private uint pid;
        }

        [StructLayout(LayoutKind.Sequential)]
        public partial struct PROPARRAY
        {
            public uint cElems;
            public IntPtr pElems;
        }

        [StructLayout(LayoutKind.Explicit, Pack = 1)]
        public partial struct PROPVARIANT
        {
            [FieldOffset(0)]
            public ushort varType;
            [FieldOffset(2)]
            public ushort wReserved1;
            [FieldOffset(4)]
            public ushort wReserved2;
            [FieldOffset(6)]
            public ushort wReserved3;
            [FieldOffset(8)]
            public byte bVal;
            [FieldOffset(8)]
            public sbyte cVal;
            [FieldOffset(8)]
            public ushort uiVal;
            [FieldOffset(8)]
            public short iVal;
            [FieldOffset(8)]
            public uint uintVal;
            [FieldOffset(8)]
            public int intVal;
            [FieldOffset(8)]
            public ulong ulVal;
            [FieldOffset(8)]
            public long lVal;
            [FieldOffset(8)]
            public float fltVal;
            [FieldOffset(8)]
            public double dblVal;
            [FieldOffset(8)]
            public short boolVal;
            [FieldOffset(8)]
            public IntPtr pclsidVal;
            [FieldOffset(8)]
            public IntPtr pszVal;
            [FieldOffset(8)]
            public IntPtr pwszVal;
            [FieldOffset(8)]
            public IntPtr punkVal;
            [FieldOffset(8)]
            public PROPARRAY ca;
            [FieldOffset(8)]
            public System.Runtime.InteropServices.ComTypes.FILETIME filetime;
        }

        public enum EDataFlow
        {
            eRender = 0,
            eCapture = eRender + 1,
            eAll = eCapture + 1,
            EDataFlow_enum_count = eAll + 1
        }

        public enum ERole
        {
            eConsole = 0,
            eMultimedia = eConsole + 1,
            eCommunications = eMultimedia + 1,
            ERole_enum_count = eCommunications + 1
        }

        [ComImport]
        [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMDeviceEnumerator
        {
            HRESULT EnumAudioEndpoints(EDataFlow dataFlow, int dwStateMask, out IMMDeviceCollection ppDevices);
            // for 0x80070490 : Element not found
            [PreserveSig]
            HRESULT GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppEndpoint);
            HRESULT GetDevice(string pwstrId, out IMMDevice ppDevice);
            HRESULT RegisterEndpointNotificationCallback(IMMNotificationClient pClient);
            HRESULT UnregisterEndpointNotificationCallback(IMMNotificationClient pClient);
        }

        public const int DEVICE_STATE_ACTIVE = 0x1;
        public const int DEVICE_STATE_DISABLED = 0x2;
        public const int DEVICE_STATE_NOTPRESENT = 0x4;
        public const int DEVICE_STATE_UNPLUGGED = 0x8;
        public const int DEVICE_STATEMASK_ALL = 0xF;

        [ComImport]
        [Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMDeviceCollection
        {
            HRESULT GetCount(out uint pcDevices);
            HRESULT Item(uint nDevice, out IMMDevice ppDevice);
        }

        [ComImport]
        [Guid("D666063F-1587-4E43-81F1-B948E807363F")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMDevice
        {
            HRESULT Activate(ref Guid iid, int dwClsCtx, ref PROPVARIANT pActivationParams, out IntPtr ppInterface);
            HRESULT OpenPropertyStore(int stgmAccess, out IPropertyStore ppProperties);
            HRESULT GetId(out IntPtr ppstrId);
            HRESULT GetState(out int pdwState);
        }

        [ComImport]
        [Guid("7991EEC9-7E89-4D85-8390-6C703CEC60C0")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMNotificationClient
        {
            HRESULT OnDeviceStateChanged(string pwstrDeviceId, int dwNewState);
            HRESULT OnDeviceAdded(string pwstrDeviceId);
            HRESULT OnDeviceRemoved(string pwstrDeviceId);
            HRESULT OnDefaultDeviceChanged(EDataFlow flow, ERole role, string pwstrDefaultDeviceId);
            HRESULT OnPropertyValueChanged(string pwstrDeviceId, ref PROPERTYKEY key);
        }

        [ComImport]
        [Guid("1BE09788-6894-4089-8586-9A2A6C265AC5")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMEndpoint
        {
            HRESULT GetDataFlow(out EDataFlow pDataFlow);
        }

        [ComImport]
        [Guid("f8679f50-850a-41cf-9c72-430f290290c8")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IPolicyConfig
        {
            HRESULT GetMixFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, out WAVEFORMATEXTENSIBLE ppFormat);
            HRESULT GetDeviceFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bDefault, out WAVEFORMATEXTENSIBLE ppFormat);
            HRESULT ResetDeviceFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName);
            HRESULT SetDeviceFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.LPStruct)] WAVEFORMATEXTENSIBLE pEndpointFormat, [In][MarshalAs(UnmanagedType.LPStruct)] WAVEFORMATEXTENSIBLE pMixFormat);
            HRESULT GetProcessingPeriod([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bDefault, out long pmftDefaultPeriod, out long pmftMinimumPeriod);
            HRESULT SetProcessingPeriod([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, long pmftPeriod);
            HRESULT GetShareMode([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, out DeviceShareMode pMode);
            HRESULT SetShareMode([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In] DeviceShareMode mode);
            HRESULT GetPropertyValue([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bFxStore, ref PROPERTYKEY pKey, out PROPVARIANT pv);
            HRESULT SetPropertyValue([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bFxStore, [In] ref PROPERTYKEY pKey, ref PROPVARIANT pv);
            HRESULT SetDefaultEndpoint([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.U4)] ERole role);
            HRESULT SetEndpointVisibility([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bVisible);
        }

        [StructLayout(LayoutKind.Explicit, Pack = 1)]
        public partial class WAVEFORMATEXTENSIBLE : WAVEFORMATEX
        {
            [FieldOffset(0)]
            public short wValidBitsPerSample;
            [FieldOffset(0)]
            public short wSamplesPerBlock;
            [FieldOffset(0)]
            public short wReserved;
            [FieldOffset(2)]
            public WaveMask dwChannelMask;
            [FieldOffset(6)]
            public Guid SubFormat;
        }

        [Flags]
        public enum WaveMask
        {
            None = 0x0,
            FrontLeft = 0x1,
            FrontRight = 0x2,
            FrontCenter = 0x4,
            LowFrequency = 0x8,
            BackLeft = 0x10,
            BackRight = 0x20,
            FrontLeftOfCenter = 0x40,
            FrontRightOfCenter = 0x80,
            BackCenter = 0x100,
            SideLeft = 0x200,
            SideRight = 0x400,
            TopCenter = 0x800,
            TopFrontLeft = 0x1000,
            TopFrontCenter = 0x2000,
            TopFrontRight = 0x4000,
            TopBackLeft = 0x8000,
            TopBackCenter = 0x10000,
            TopBackRight = 0x20000
        }

        [StructLayout(LayoutKind.Sequential, Pack = 2)]
        public partial class WAVEFORMATEX
        {
            public short wFormatTag;
            public short nChannels;
            public int nSamplesPerSec;
            public int nAvgBytesPerSec;
            public short nBlockAlign;
            public short wBitsPerSample;
            public short cbSize;
        }

        public enum DeviceShareMode
        {
            Shared,
            Exclusive
        }

        [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern int PathParseIconLocationW(string pszIconFile);

        public static PROPERTYKEY PKEY_Device_FriendlyName = new PROPERTYKEY(new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), 14);
        public static PROPERTYKEY PKEY_Device_DeviceDesc = new PROPERTYKEY(new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), 2);
        public static PROPERTYKEY PKEY_DeviceClass_IconPath = new PROPERTYKEY(new Guid("259abffc-50a7-47ce-af08-68c9a7d73366"), 12);
        static void Main(string[] args)
        {
            EnableMicsThatAreDisabled();
        }

        public static void EnableMicsThatAreDisabled()
        {
            var hr = HRESULT.E_FAIL;
            var CLSID_MMDeviceEnumerator = new Guid("{BCDE0395-E52F-467C-8E3D-C4579291692E}");
            var MMDeviceEnumeratorType = Type.GetTypeFromCLSID(CLSID_MMDeviceEnumerator, true);
            var MMDeviceEnumerator = Activator.CreateInstance(MMDeviceEnumeratorType);
            IMMDeviceEnumerator pMMDeviceEnumerator = (IMMDeviceEnumerator)MMDeviceEnumerator;
            if (pMMDeviceEnumerator is object)
            {
                string sIdDefaultRender = null;
                string sIdDefaultCapture = null;
                IMMDevice pDefaultDevice = null;
                hr = pMMDeviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, out pDefaultDevice);
                if (hr == HRESULT.S_OK)
                {
                    var hGlobal = Marshal.AllocHGlobal(260);
                    hr = pDefaultDevice.GetId(out hGlobal);
                    sIdDefaultRender = Marshal.PtrToStringUni(hGlobal);
                    Marshal.FreeHGlobal(hGlobal);
                    Marshal.ReleaseComObject(pDefaultDevice);
                }

                hr = pMMDeviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eConsole, out pDefaultDevice);
                if (hr == HRESULT.S_OK)
                {
                    var hGlobal = Marshal.AllocHGlobal(260);
                    hr = pDefaultDevice.GetId(out hGlobal);
                    sIdDefaultCapture = Marshal.PtrToStringUni(hGlobal);
                    Marshal.FreeHGlobal(hGlobal);
                    Marshal.ReleaseComObject(pDefaultDevice);
                }

                IMMDeviceCollection pDeviceCollection = null;
                //hr = pMMDeviceEnumerator.EnumAudioEndpoints(EDataFlow.eAll, DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED | DEVICE_STATE_DISABLED, out pDeviceCollection);
                hr = pMMDeviceEnumerator.EnumAudioEndpoints(EDataFlow.eAll, DEVICE_STATE_DISABLED, out pDeviceCollection);
                if (hr == HRESULT.S_OK)
                {
                    uint nDevices = 0;
                    hr = pDeviceCollection.GetCount(out nDevices);
                    if (nDevices == 0) //Return when no devices are enumerated.
                    {
                        return;
                    }
                    for (uint i = 0, loopTo = (uint)(nDevices - (long)1); i <= loopTo; i++)
                    {
                        IMMDevice pDevice = null;
                        hr = pDeviceCollection.Item(i, out pDevice);
                        if (hr == HRESULT.S_OK)
                        {
                            IPropertyStore pPropertyStore = null;
                            hr = pDevice.OpenPropertyStore(STGM_READ, out pPropertyStore);
                            if (hr == HRESULT.S_OK)
                            {
                                string sFriendlyName = null;
                                var pv = new PROPVARIANT();
                                hr = pPropertyStore.GetValue(ref PKEY_Device_FriendlyName, out pv);
                                if (hr == HRESULT.S_OK)
                                {
                                    sFriendlyName = Marshal.PtrToStringUni(pv.pwszVal);
                                }

                                string sIconPath = null;
                                int nIconId = 0;
                                var pvIconPath = new PROPVARIANT();
                                hr = pPropertyStore.GetValue(ref PKEY_DeviceClass_IconPath, out pvIconPath);
                                if (hr == HRESULT.S_OK)
                                {
                                    // %windir%\system32\mmres.dll,-3011
                                    sIconPath = Marshal.PtrToStringUni(pvIconPath.pwszVal);
                                    nIconId = PathParseIconLocationW(sIconPath);
                                }

                                var hGlobal = Marshal.AllocHGlobal(260);
                                hr = pDevice.GetId(out hGlobal);
                                string sId = Marshal.PtrToStringUni(hGlobal);
                                Marshal.FreeHGlobal(hGlobal);
                                IMMEndpoint pEndpoint = null;
                                pEndpoint = (IMMEndpoint)pDevice;
                                var eDirection = EDataFlow.eAll;
                                hr = pEndpoint.GetDataFlow(out eDirection);
                                int nState = 0;
                                string sState = "";
                                hr = pDevice.GetState(out nState);
                                if (nState == DEVICE_STATE_ACTIVE)
                                {
                                    sState = "Active";
                                }
                                else if (nState == DEVICE_STATE_DISABLED)
                                {
                                    sState = "Disabled";
                                }
                                else if (nState == DEVICE_STATE_NOTPRESENT)
                                {
                                    sState = "Not present";
                                }
                                else if (nState == DEVICE_STATE_UNPLUGGED)
                                {
                                    sState = "Unplugged";
                                }
                                if (eDirection == EDataFlow.eRender)
                                {

                                }
                                else if (eDirection == EDataFlow.eCapture)
                                {

                                    Console.WriteLine(sFriendlyName );
                                    EnableMic(sId, sState);
                                }

                                Marshal.ReleaseComObject(pPropertyStore);
                            }

                            Marshal.ReleaseComObject(pDevice);
                        }
                    }

                    Marshal.ReleaseComObject(pDeviceCollection);
                }

                Marshal.ReleaseComObject(pMMDeviceEnumerator);
            }
        }
        private static void EnableMic(string sCurrentId, string sState)
        {
            var hr = HRESULT.E_FAIL;
            var CLSID_PolicyConfig = new Guid("{870af99c-171d-4f9e-af0d-e63df40c2bc9}");
            var PolicyConfigType = Type.GetTypeFromCLSID(CLSID_PolicyConfig, true);
            var PolicyConfig = Activator.CreateInstance(PolicyConfigType);
            IPolicyConfig pPolicyConfig = (IPolicyConfig)PolicyConfig;
            bool bEnable = false;
            if (pPolicyConfig is object)
            {
                if (sState == "Disabled")
                {
                    bEnable = true;
                }
                else
                {
                    bEnable = false;
                }

                hr = pPolicyConfig.SetEndpointVisibility(sCurrentId, bEnable);
                Marshal.ReleaseComObject(PolicyConfig);
            }
        }
    }
 }
</code>```

Body:
Enabling recording devices programmatically

I want to enable the disabled device in Sound - Recording devices list programmatically

I was able to get a list of disabled devices using Naudio

But there is no way to enable it using Naudio.

so I tried also using IMMDevice interface but I couldn't find out how to do this.

I tried also Registry Edit

//Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{87bd5990-b012-41f1-83f7-f267ed7780a7}
    RegistryKey root = Registry.LocalMachine.OpenSubKey("SOFTWARE", true).OpenSubKey("Microsoft", true).OpenSubKey("Windows", true).OpenSubKey("CurrentVersion", true).OpenSubKey("MMDevices", true).OpenSubKey("Audio", true).OpenSubKey("Render", true).OpenSubKey("{87bd5990-b012-41f1-83f7-f267ed7780a7}", true); //{87bd5990-b012-41f1-83f7-f267ed7780a7} any Playback Device ID
    MessageBox.Show($"Value Before {root.GetValue("DeviceState")}   { root.GetValueKind("DeviceState")}");
    root.SetValue("DeviceState", 0x10000001, RegistryValueKind.DWord);
    MessageBox.Show($"Value After {root.GetValue("DeviceState")}    { root.GetValueKind("DeviceState")}");

or

Registry.SetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\MMDevices\Audio\Render\{87bd5990-b012-41f1-83f7-f267ed7780a7}", "DeviceState", 0x10000001, RegistryValueKind.DWord);

but this will need Administrator Rights and I want it to work for any user.

Body:
Here you go, Console App code that enables any audio capture devices that are in a disabled state. you may compile to exe using VS or call with PowerShell using add-type

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1_Audio
{
    class Program
    {
        public enum HRESULT : uint
        {
            S_OK = 0,
            S_FALSE = 1,
            E_NOINTERFACE = 0x80004002,
            E_NOTIMPL = 0x80004001,
            E_FAIL = 0x80004005,
            E_UNEXPECTED = 0x8000FFFF
        }

        [ComImport]
        [Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IPropertyStore
        {
            HRESULT GetCount(out uint propertyCount);
            HRESULT GetAt([In] uint propertyIndex, [MarshalAs(UnmanagedType.Struct)] out PROPERTYKEY key);
            HRESULT GetValue([In][MarshalAs(UnmanagedType.Struct)] ref PROPERTYKEY key, [MarshalAs(UnmanagedType.Struct)] out PROPVARIANT pv);
            HRESULT SetValue([In][MarshalAs(UnmanagedType.Struct)] ref PROPERTYKEY key, [In][MarshalAs(UnmanagedType.Struct)] ref PROPVARIANT pv);
            HRESULT Commit();
        }

        public const int STGM_READ = 0x0;
        public const int STGM_WRITE = 0x1;
        public const int STGM_READWRITE = 0x2;

        public partial struct PROPERTYKEY
        {
            public PROPERTYKEY(Guid InputId, uint InputPid)
            {
                fmtid = InputId;
                pid = InputPid;
            }

            private Guid fmtid;
            private uint pid;
        }

        [StructLayout(LayoutKind.Sequential)]
        public partial struct PROPARRAY
        {
            public uint cElems;
            public IntPtr pElems;
        }

        [StructLayout(LayoutKind.Explicit, Pack = 1)]
        public partial struct PROPVARIANT
        {
            [FieldOffset(0)]
            public ushort varType;
            [FieldOffset(2)]
            public ushort wReserved1;
            [FieldOffset(4)]
            public ushort wReserved2;
            [FieldOffset(6)]
            public ushort wReserved3;
            [FieldOffset(8)]
            public byte bVal;
            [FieldOffset(8)]
            public sbyte cVal;
            [FieldOffset(8)]
            public ushort uiVal;
            [FieldOffset(8)]
            public short iVal;
            [FieldOffset(8)]
            public uint uintVal;
            [FieldOffset(8)]
            public int intVal;
            [FieldOffset(8)]
            public ulong ulVal;
            [FieldOffset(8)]
            public long lVal;
            [FieldOffset(8)]
            public float fltVal;
            [FieldOffset(8)]
            public double dblVal;
            [FieldOffset(8)]
            public short boolVal;
            [FieldOffset(8)]
            public IntPtr pclsidVal;
            [FieldOffset(8)]
            public IntPtr pszVal;
            [FieldOffset(8)]
            public IntPtr pwszVal;
            [FieldOffset(8)]
            public IntPtr punkVal;
            [FieldOffset(8)]
            public PROPARRAY ca;
            [FieldOffset(8)]
            public System.Runtime.InteropServices.ComTypes.FILETIME filetime;
        }

        public enum EDataFlow
        {
            eRender = 0,
            eCapture = eRender + 1,
            eAll = eCapture + 1,
            EDataFlow_enum_count = eAll + 1
        }

        public enum ERole
        {
            eConsole = 0,
            eMultimedia = eConsole + 1,
            eCommunications = eMultimedia + 1,
            ERole_enum_count = eCommunications + 1
        }

        [ComImport]
        [Guid("A95664D2-9614-4F35-A746-DE8DB63617E6")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMDeviceEnumerator
        {
            HRESULT EnumAudioEndpoints(EDataFlow dataFlow, int dwStateMask, out IMMDeviceCollection ppDevices);
            // for 0x80070490 : Element not found
            [PreserveSig]
            HRESULT GetDefaultAudioEndpoint(EDataFlow dataFlow, ERole role, out IMMDevice ppEndpoint);
            HRESULT GetDevice(string pwstrId, out IMMDevice ppDevice);
            HRESULT RegisterEndpointNotificationCallback(IMMNotificationClient pClient);
            HRESULT UnregisterEndpointNotificationCallback(IMMNotificationClient pClient);
        }

        public const int DEVICE_STATE_ACTIVE = 0x1;
        public const int DEVICE_STATE_DISABLED = 0x2;
        public const int DEVICE_STATE_NOTPRESENT = 0x4;
        public const int DEVICE_STATE_UNPLUGGED = 0x8;
        public const int DEVICE_STATEMASK_ALL = 0xF;

        [ComImport]
        [Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMDeviceCollection
        {
            HRESULT GetCount(out uint pcDevices);
            HRESULT Item(uint nDevice, out IMMDevice ppDevice);
        }

        [ComImport]
        [Guid("D666063F-1587-4E43-81F1-B948E807363F")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMDevice
        {
            HRESULT Activate(ref Guid iid, int dwClsCtx, ref PROPVARIANT pActivationParams, out IntPtr ppInterface);
            HRESULT OpenPropertyStore(int stgmAccess, out IPropertyStore ppProperties);
            HRESULT GetId(out IntPtr ppstrId);
            HRESULT GetState(out int pdwState);
        }

        [ComImport]
        [Guid("7991EEC9-7E89-4D85-8390-6C703CEC60C0")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMNotificationClient
        {
            HRESULT OnDeviceStateChanged(string pwstrDeviceId, int dwNewState);
            HRESULT OnDeviceAdded(string pwstrDeviceId);
            HRESULT OnDeviceRemoved(string pwstrDeviceId);
            HRESULT OnDefaultDeviceChanged(EDataFlow flow, ERole role, string pwstrDefaultDeviceId);
            HRESULT OnPropertyValueChanged(string pwstrDeviceId, ref PROPERTYKEY key);
        }

        [ComImport]
        [Guid("1BE09788-6894-4089-8586-9A2A6C265AC5")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IMMEndpoint
        {
            HRESULT GetDataFlow(out EDataFlow pDataFlow);
        }

        [ComImport]
        [Guid("f8679f50-850a-41cf-9c72-430f290290c8")]
        [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
        public partial interface IPolicyConfig
        {
            HRESULT GetMixFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, out WAVEFORMATEXTENSIBLE ppFormat);
            HRESULT GetDeviceFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bDefault, out WAVEFORMATEXTENSIBLE ppFormat);
            HRESULT ResetDeviceFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName);
            HRESULT SetDeviceFormat([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.LPStruct)] WAVEFORMATEXTENSIBLE pEndpointFormat, [In][MarshalAs(UnmanagedType.LPStruct)] WAVEFORMATEXTENSIBLE pMixFormat);
            HRESULT GetProcessingPeriod([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bDefault, out long pmftDefaultPeriod, out long pmftMinimumPeriod);
            HRESULT SetProcessingPeriod([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, long pmftPeriod);
            HRESULT GetShareMode([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, out DeviceShareMode pMode);
            HRESULT SetShareMode([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In] DeviceShareMode mode);
            HRESULT GetPropertyValue([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bFxStore, ref PROPERTYKEY pKey, out PROPVARIANT pv);
            HRESULT SetPropertyValue([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bFxStore, [In] ref PROPERTYKEY pKey, ref PROPVARIANT pv);
            HRESULT SetDefaultEndpoint([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.U4)] ERole role);
            HRESULT SetEndpointVisibility([In][MarshalAs(UnmanagedType.LPWStr)] string pszDeviceName, [In][MarshalAs(UnmanagedType.Bool)] bool bVisible);
        }

        [StructLayout(LayoutKind.Explicit, Pack = 1)]
        public partial class WAVEFORMATEXTENSIBLE : WAVEFORMATEX
        {
            [FieldOffset(0)]
            public short wValidBitsPerSample;
            [FieldOffset(0)]
            public short wSamplesPerBlock;
            [FieldOffset(0)]
            public short wReserved;
            [FieldOffset(2)]
            public WaveMask dwChannelMask;
            [FieldOffset(6)]
            public Guid SubFormat;
        }

        [Flags]
        public enum WaveMask
        {
            None = 0x0,
            FrontLeft = 0x1,
            FrontRight = 0x2,
            FrontCenter = 0x4,
            LowFrequency = 0x8,
            BackLeft = 0x10,
            BackRight = 0x20,
            FrontLeftOfCenter = 0x40,
            FrontRightOfCenter = 0x80,
            BackCenter = 0x100,
            SideLeft = 0x200,
            SideRight = 0x400,
            TopCenter = 0x800,
            TopFrontLeft = 0x1000,
            TopFrontCenter = 0x2000,
            TopFrontRight = 0x4000,
            TopBackLeft = 0x8000,
            TopBackCenter = 0x10000,
            TopBackRight = 0x20000
        }

        [StructLayout(LayoutKind.Sequential, Pack = 2)]
        public partial class WAVEFORMATEX
        {
            public short wFormatTag;
            public short nChannels;
            public int nSamplesPerSec;
            public int nAvgBytesPerSec;
            public short nBlockAlign;
            public short wBitsPerSample;
            public short cbSize;
        }

        public enum DeviceShareMode
        {
            Shared,
            Exclusive
        }

        [DllImport("Shlwapi.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern int PathParseIconLocationW(string pszIconFile);

        public static PROPERTYKEY PKEY_Device_FriendlyName = new PROPERTYKEY(new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), 14);
        public static PROPERTYKEY PKEY_Device_DeviceDesc = new PROPERTYKEY(new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"), 2);
        public static PROPERTYKEY PKEY_DeviceClass_IconPath = new PROPERTYKEY(new Guid("259abffc-50a7-47ce-af08-68c9a7d73366"), 12);
        static void Main(string[] args)
        {
            EnableMicsThatAreDisabled();
        }

        public static void EnableMicsThatAreDisabled()
        {
            var hr = HRESULT.E_FAIL;
            var CLSID_MMDeviceEnumerator = new Guid("{BCDE0395-E52F-467C-8E3D-C4579291692E}");
            var MMDeviceEnumeratorType = Type.GetTypeFromCLSID(CLSID_MMDeviceEnumerator, true);
            var MMDeviceEnumerator = Activator.CreateInstance(MMDeviceEnumeratorType);
            IMMDeviceEnumerator pMMDeviceEnumerator = (IMMDeviceEnumerator)MMDeviceEnumerator;
            if (pMMDeviceEnumerator is object)
            {
                string sIdDefaultRender = null;
                string sIdDefaultCapture = null;
                IMMDevice pDefaultDevice = null;
                hr = pMMDeviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eConsole, out pDefaultDevice);
                if (hr == HRESULT.S_OK)
                {
                    var hGlobal = Marshal.AllocHGlobal(260);
                    hr = pDefaultDevice.GetId(out hGlobal);
                    sIdDefaultRender = Marshal.PtrToStringUni(hGlobal);
                    Marshal.FreeHGlobal(hGlobal);
                    Marshal.ReleaseComObject(pDefaultDevice);
                }

                hr = pMMDeviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eCapture, ERole.eConsole, out pDefaultDevice);
                if (hr == HRESULT.S_OK)
                {
                    var hGlobal = Marshal.AllocHGlobal(260);
                    hr = pDefaultDevice.GetId(out hGlobal);
                    sIdDefaultCapture = Marshal.PtrToStringUni(hGlobal);
                    Marshal.FreeHGlobal(hGlobal);
                    Marshal.ReleaseComObject(pDefaultDevice);
                }

                IMMDeviceCollection pDeviceCollection = null;
                //hr = pMMDeviceEnumerator.EnumAudioEndpoints(EDataFlow.eAll, DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED | DEVICE_STATE_DISABLED, out pDeviceCollection);
                hr = pMMDeviceEnumerator.EnumAudioEndpoints(EDataFlow.eAll, DEVICE_STATE_DISABLED, out pDeviceCollection);
                if (hr == HRESULT.S_OK)
                {
                    uint nDevices = 0;
                    hr = pDeviceCollection.GetCount(out nDevices);
                    if (nDevices == 0) //Return when no devices are enumerated.
                    {
                        return;
                    }
                    for (uint i = 0, loopTo = (uint)(nDevices - (long)1); i <= loopTo; i++)
                    {
                        IMMDevice pDevice = null;
                        hr = pDeviceCollection.Item(i, out pDevice);
                        if (hr == HRESULT.S_OK)
                        {
                            IPropertyStore pPropertyStore = null;
                            hr = pDevice.OpenPropertyStore(STGM_READ, out pPropertyStore);
                            if (hr == HRESULT.S_OK)
                            {
                                string sFriendlyName = null;
                                var pv = new PROPVARIANT();
                                hr = pPropertyStore.GetValue(ref PKEY_Device_FriendlyName, out pv);
                                if (hr == HRESULT.S_OK)
                                {
                                    sFriendlyName = Marshal.PtrToStringUni(pv.pwszVal);
                                }

                                string sIconPath = null;
                                int nIconId = 0;
                                var pvIconPath = new PROPVARIANT();
                                hr = pPropertyStore.GetValue(ref PKEY_DeviceClass_IconPath, out pvIconPath);
                                if (hr == HRESULT.S_OK)
                                {
                                    // %windir%\system32\mmres.dll,-3011
                                    sIconPath = Marshal.PtrToStringUni(pvIconPath.pwszVal);
                                    nIconId = PathParseIconLocationW(sIconPath);
                                }

                                var hGlobal = Marshal.AllocHGlobal(260);
                                hr = pDevice.GetId(out hGlobal);
                                string sId = Marshal.PtrToStringUni(hGlobal);
                                Marshal.FreeHGlobal(hGlobal);
                                IMMEndpoint pEndpoint = null;
                                pEndpoint = (IMMEndpoint)pDevice;
                                var eDirection = EDataFlow.eAll;
                                hr = pEndpoint.GetDataFlow(out eDirection);
                                int nState = 0;
                                string sState = "";
                                hr = pDevice.GetState(out nState);
                                if (nState == DEVICE_STATE_ACTIVE)
                                {
                                    sState = "Active";
                                }
                                else if (nState == DEVICE_STATE_DISABLED)
                                {
                                    sState = "Disabled";
                                }
                                else if (nState == DEVICE_STATE_NOTPRESENT)
                                {
                                    sState = "Not present";
                                }
                                else if (nState == DEVICE_STATE_UNPLUGGED)
                                {
                                    sState = "Unplugged";
                                }
                                if (eDirection == EDataFlow.eRender)
                                {

                                }
                                else if (eDirection == EDataFlow.eCapture)
                                {

                                    Console.WriteLine(sFriendlyName );
                                    EnableMic(sId, sState);
                                }

                                Marshal.ReleaseComObject(pPropertyStore);
                            }

                            Marshal.ReleaseComObject(pDevice);
                        }
                    }

                    Marshal.ReleaseComObject(pDeviceCollection);
                }

                Marshal.ReleaseComObject(pMMDeviceEnumerator);
            }
        }
        private static void EnableMic(string sCurrentId, string sState)
        {
            var hr = HRESULT.E_FAIL;
            var CLSID_PolicyConfig = new Guid("{870af99c-171d-4f9e-af0d-e63df40c2bc9}");
            var PolicyConfigType = Type.GetTypeFromCLSID(CLSID_PolicyConfig, true);
            var PolicyConfig = Activator.CreateInstance(PolicyConfigType);
            IPolicyConfig pPolicyConfig = (IPolicyConfig)PolicyConfig;
            bool bEnable = false;
            if (pPolicyConfig is object)
            {
                if (sState == "Disabled")
                {
                    bEnable = true;
                }
                else
                {
                    bEnable = false;
                }

                hr = pPolicyConfig.SetEndpointVisibility(sCurrentId, bEnable);
                Marshal.ReleaseComObject(PolicyConfig);
            }
        }
    }
 }


问:
Can't convert to Lower/uppercase a char* pointer using a loop in C without toupper
I am trying to make a function toLowerCase(char *string) but I am unable to make it work properly.

This is my code

```<code>void toLowerCase(char *string) {
    int i = 0;
    while (*(string+i) != '\0') {
        if (*(string+i) >= 'A' && *(string+i) <= 'Z') {
            *(string+i) = *(string+i) + 32;
        }
        i++;
    }
    printf("%s", string);
}
</code>```

I am trying to loop through the string that is a char * pointer by accessing each element using *(string + i) and using ASCII to convert to Lowercase.

I am new here, if this was answered before I am sorry, but I am asking because I couldn't find a specific solution to my problem. I've tried what's in this thread: Converting Char * to Uppercase in C
but it didn't work for me either.

EDIT: This is how I call my function

```<code>int main() {
    toLowerCase("HELLO WORLD");
    return 0;
}
</code>```

EDIT 2: So, I did this, as showed by PSkocik. And it worked, but I don't know why it works like this. Will the toLowerCase() function work with any char * pointer? even if I don't declare it as char array?

This also fixes the problem that Vlad from Moscow pointed out that I am using a string literal

```<code>#define T 100
int main() {
    char string[T] = "HELLO WORLD";
    toLowerCase(&string);
    return 0;
}
</code>```

EDIT 3: Thank you very much for your help! I wasn't expecting to get help so quickly! I didn't know what a string literal was!

Thank you very much for your time

答:
toLowerCase("HELLO WORLD"); => toLowerCase((char[]){"HELLO WORLD"});
 as changing the strings literal is an UB.

your function should return the string for easy use as parameter.

```<code>char *toLowerCase(char* string)
{
    int i=0;
    while (string[i])
    {
        if (string[i] >= 'A' && string[i] <= 'Z')
        {
            string[i] += 'a' - 'A';
        }
        i++;
    }
    return string;
}

int main()
{
    puts(toLowerCase((char[]){"HELLO WORLD"}));
    return 0;
}
</code>```

Body:
I am trying to make a function toLowerCase(char *string) but I am unable to make it work properly.

This is my code

void toLowerCase(char *string) {
    int i = 0;
    while (*(string+i) != '\0') {
        if (*(string+i) >= 'A' && *(string+i) <= 'Z') {
            *(string+i) = *(string+i) + 32;
        }
        i++;
    }
    printf("%s", string);
}

I am trying to loop through the string that is a char * pointer by accessing each element using *(string + i) and using ASCII to convert to Lowercase.

I am new here, if this was answered before I am sorry, but I am asking because I couldn't find a specific solution to my problem. I've tried what's in this thread: Converting Char * to Uppercase in C
but it didn't work for me either.

EDIT: This is how I call my function

int main() {
    toLowerCase("HELLO WORLD");
    return 0;
}

EDIT 2: So, I did this, as showed by PSkocik. And it worked, but I don't know why it works like this. Will the toLowerCase() function work with any char * pointer? even if I don't declare it as char array?

This also fixes the problem that Vlad from Moscow pointed out that I am using a string literal

#define T 100
int main() {
    char string[T] = "HELLO WORLD";
    toLowerCase(&string);
    return 0;
}

EDIT 3: Thank you very much for your help! I wasn't expecting to get help so quickly! I didn't know what a string literal was!

Thank you very much for your time

Body:
toLowerCase("HELLO WORLD"); => toLowerCase((char[]){"HELLO WORLD"});
 as changing the strings literal is an UB.

your function should return the string for easy use as parameter.

char *toLowerCase(char* string)
{
    int i=0;
    while (string[i])
    {
        if (string[i] >= 'A' && string[i] <= 'Z')
        {
            string[i] += 'a' - 'A';
        }
        i++;
    }
    return string;
}

int main()
{
    puts(toLowerCase((char[]){"HELLO WORLD"}));
    return 0;
}


问:
how can I use the event parameter when the code is written inline in the mxml tag in flex
What is the difference between :

giving a function reference in the result attribute of the HTTPService class like this :

```<code>protected function httpserviceCheckUpdate_resultHandler(event:ResultEvent):void
{
     var version:Number = event.result.text.version as Number;
     var xmldata:XML = XML(event.result);
     // and all the processing you want to do
}
<mx:HTTPService id="httpserviceCheckUpdate"
                    method="POST"
                    url="http://abc.com/actions.php"
                    resultFormat="text"
                    fault="httpservicexml_faultHandler(event)"
                    result="httpserviceCheckUpdate_resultHandler(event)">
        <mx:request xmlns="">
            <action>versionCheck</action>
        </mx:request>
    </mx:HTTPService>
</code>```

and

coding the complete function in the <mx:result></mx:result> of the same HTTPService class.

```<code><mx:HTTPService id="httpserviceCheckUpdate"
                method="POST"
                url="http://abc.com/actions.php"
                resultFormat="text"
                fault="httpservicexml_faultHandler(event)"
                result="httpserviceCheckUpdate_resultHandler(event)">
    <mx:request xmlns="">
        <action>versionCheck</action>
    </mx:request>
    <mx:result>
        <![CDATA[
        var version:Number = event.result.text.version as Number;
        var xmldata:XML = XML(event.result);
        // and all the processing you want to do
        ]]>
    </mx:result>
</mx:HTTPService>
</code>```

If both of them are same then how can I provide the event parameter using the second approach (as written in the result attribute of the httpservice class)?

Which one of them is the better way of doing things in FLEX

Thanks

答:
Well actually I mostly set events in the code, so not even like your first example but, say, in a complete event calling:

```<code>component.addEventListener(<event>, <handler>, <usecapture>, <priority>, <weakreference>)
</code>```

always using all 5 parameters. I do it in code since I tend to remove listener when they are not needed but then add them again when needed: this can only be done in code.

I use always all 5 parameters because it allows a fine control over the priorities (who gets the event first), second because of memory management: if I by any chance forget to remove a listener and the eventdispatcher is the only strong reference to the event handler the garbage collector will still be able to remove the object the handler belongs to. I think this alone is worth defining event handlers in code.

Back to you question: I have never found an example like yours second, what I found is something like this:

```<code><mx:HTTPService id="httpserviceCheckUpdate"
                method="POST"
                url="http://abc.com/actions.php"
                resultFormat="text"
                fault="httpservicexml_faultHandler(event)"
                result="httpserviceCheckUpdate_resultHandler(event)">
    <mx:request xmlns="">
        <action>versionCheck</action>
    </mx:request>
    <mx:result>
        <![CDATA[
        import ....ResultEvent;
        protected function httpserviceCheckUpdate_resultHandler(event:ResultEvent):void
        {
            var version:Number = event.result.text.version as Number;
            var xmldata:XML = XML(event.result);
            // and all the processing you want to do
        }
        ]]>
    </mx:result>
</mx:HTTPService>
</code>```

as you see you have a full function signature including Event here. The only difference is that handlers defined within a component will be called before those defined in the container, other than that I see them as equally good and both worse than setting handlers in code.

ContentLicense: CC BY-SA 3.0

Body:
What is the difference between :

giving a function reference in the result attribute of the HTTPService class like this :

protected function httpserviceCheckUpdate_resultHandler(event:ResultEvent):void
{
     var version:Number = event.result.text.version as Number;
     var xmldata:XML = XML(event.result);
     // and all the processing you want to do
}
<mx:HTTPService id="httpserviceCheckUpdate"
                    method="POST"
                    url="http://abc.com/actions.php"
                    resultFormat="text"
                    fault="httpservicexml_faultHandler(event)"
                    result="httpserviceCheckUpdate_resultHandler(event)">
        <mx:request xmlns="">
            <action>versionCheck</action>
        </mx:request>
    </mx:HTTPService>

and

coding the complete function in the <mx:result></mx:result> of the same HTTPService class.

<mx:HTTPService id="httpserviceCheckUpdate"
                method="POST"
                url="http://abc.com/actions.php"
                resultFormat="text"
                fault="httpservicexml_faultHandler(event)"
                result="httpserviceCheckUpdate_resultHandler(event)">
    <mx:request xmlns="">
        <action>versionCheck</action>
    </mx:request>
    <mx:result>
        <![CDATA[
        var version:Number = event.result.text.version as Number;
        var xmldata:XML = XML(event.result);
        // and all the processing you want to do
        ]]>
    </mx:result>
</mx:HTTPService>

If both of them are same then how can I provide the event parameter using the second approach (as written in the result attribute of the httpservice class)?

Which one of them is the better way of doing things in FLEX

Thanks

Body:
Well actually I mostly set events in the code, so not even like your first example but, say, in a complete event calling:

component.addEventListener(<event>, <handler>, <usecapture>, <priority>, <weakreference>)

always using all 5 parameters. I do it in code since I tend to remove listener when they are not needed but then add them again when needed: this can only be done in code.

I use always all 5 parameters because it allows a fine control over the priorities (who gets the event first), second because of memory management: if I by any chance forget to remove a listener and the eventdispatcher is the only strong reference to the event handler the garbage collector will still be able to remove the object the handler belongs to. I think this alone is worth defining event handlers in code.

Back to you question: I have never found an example like yours second, what I found is something like this:

<mx:HTTPService id="httpserviceCheckUpdate"
                method="POST"
                url="http://abc.com/actions.php"
                resultFormat="text"
                fault="httpservicexml_faultHandler(event)"
                result="httpserviceCheckUpdate_resultHandler(event)">
    <mx:request xmlns="">
        <action>versionCheck</action>
    </mx:request>
    <mx:result>
        <![CDATA[
        import ....ResultEvent;
        protected function httpserviceCheckUpdate_resultHandler(event:ResultEvent):void
        {
            var version:Number = event.result.text.version as Number;
            var xmldata:XML = XML(event.result);
            // and all the processing you want to do
        }
        ]]>
    </mx:result>
</mx:HTTPService>

as you see you have a full function signature including Event here. The only difference is that handlers defined within a component will be called before those defined in the container, other than that I see them as equally good and both worse than setting handlers in code.


问:
How to place a new file in a certian place on hard drive (python)
I am making a full python keylogger. It undergoes a simple processes. First store keystrokes inside a file on startup. Next, find the file and send the file across WiFi. Lastly, shutdown. For this to work I need to make a file for the keylogger to send the keystroke information to. I tried using:

```<code>open('myfile', 'w+')
</code>```

This will create my file but how do I place my file into a certain place?

Extra Information:

Python 3.7x

答:
I believe you're looking for a file path.  The open() function in Python takes a file path and the read/write mode.  In most programming languages and operating systems use dots and slashes to represent paths.  Currently your script opens a file called "myfile" in the directory (folder) that your script is executing in.  However, if you wanted to place that file one directory higher on the file tree, you could write the function as follows:

// Linux
open('../myfile', 'w+')
// Windows
open('..\myfile', 'w+')
```

Unfortunately, this method does require a knowledge of the system filetree.

Body:
I am making a full python keylogger. It undergoes a simple processes. First store keystrokes inside a file on startup. Next, find the file and send the file across WiFi. Lastly, shutdown. For this to work I need to make a file for the keylogger to send the keystroke information to. I tried using:

open('myfile', 'w+')

This will create my file but how do I place my file into a certain place?

Extra Information:

Python 3.7x

Body:
I believe you're looking for a file path.  The open() function in Python takes a file path and the read/write mode.  In most programming languages and operating systems use dots and slashes to represent paths.  Currently your script opens a file called "myfile" in the directory (folder) that your script is executing in.  However, if you wanted to place that file one directory higher on the file tree, you could write the function as follows:

// Linux
open('../myfile', 'w+')
// Windows
open('..\myfile', 'w+')

Unfortunately, this method does require a knowledge of the system filetree.


问:
List of card with ads on float right using flex or grid
I want to implement this html structure. I tried using flex but doesn't work as last ads column is not the same height and can take up to 2 - 4 rows. and i want to make it responsive too so on resize cards will go on next row if they did not find enough space.

```<code>.ads {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    grid-column: 6 / span 2;
    grid-row: 1 / span 3;
    margin: 0;
    float: none;
}
.container {
    display: grid;
    grid-gap: 22px;
    justify-content: space-between;
}
.card {
    margin:0;
}
</code>```

答:
Good news is - we can add ads in a parent container, which is 3 rows height. Here you go

.main-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr); /* determines 7 columns with same width */
  grid-auto-rows: minmax(100px, auto); /* determines the height of the row */
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.main-grid>div {
  background: #eee;
}

.main-grid>div.ads-grid {
  background: none;
  grid-area: 1 / 6 / 4 / 8; /* row-start / column-start / row-end / column end */
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(2, 1fr);
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.main-grid>div.ads-grid>div {
  background: #000;
}

/* example for screens less than 460 */
@media (max-width: 460px) {
  .main-grid {
    grid-template-columns: repeat(4, 1fr);
  }

  .main-grid>div.ads-grid {
    grid-area: 1 / 3 / 4 / 5;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="main-grid">
  <div class="ads-grid">
    <div></div>
    <div></div>
  </div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div></code>```

Don't forget to correct .main-grid {grid-template-columns: repeat(7, 1fr)} and .main-grid>div.ads-grid {grid-area: 1 / 6 / 4 / 8;} with @media width changing for small screens. More about grid-area here https://developer.mozilla.org/en-US/docs/Web/CSS/grid-area

And not a single flex was given that day.

Body:
I want to implement this html structure. I tried using flex but doesn't work as last ads column is not the same height and can take up to 2 - 4 rows. and i want to make it responsive too so on resize cards will go on next row if they did not find enough space.

.ads {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    grid-column: 6 / span 2;
    grid-row: 1 / span 3;
    margin: 0;
    float: none;
}
.container {
    display: grid;
    grid-gap: 22px;
    justify-content: space-between;
}
.card {
    margin:0;
}

Body:
Good news is - we can add ads in a parent container, which is 3 rows height. Here you go

.main-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr); /* determines 7 columns with same width */
  grid-auto-rows: minmax(100px, auto); /* determines the height of the row */
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.main-grid>div {
  background: #eee;
}

.main-grid>div.ads-grid {
  background: none;
  grid-area: 1 / 6 / 4 / 8; /* row-start / column-start / row-end / column end */
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: repeat(2, 1fr);
  grid-column-gap: 10px;
  grid-row-gap: 10px;
}

.main-grid>div.ads-grid>div {
  background: #000;
}

/* example for screens less than 460 */
@media (max-width: 460px) {
  .main-grid {
    grid-template-columns: repeat(4, 1fr);
  }

  .main-grid>div.ads-grid {
    grid-area: 1 / 3 / 4 / 5;
  }
}

<div class="main-grid">
  <div class="ads-grid">
    <div></div>
    <div></div>
  </div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Don't forget to correct .main-grid {grid-template-columns: repeat(7, 1fr)} and .main-grid>div.ads-grid {grid-area: 1 / 6 / 4 / 8;} with @media width changing for small screens. More about grid-area here https://developer.mozilla.org/en-US/docs/Web/CSS/grid-area

And not a single flex was given that day.


问:
Move footer above keyboard when it appear on mobile devices
I have found alot of artivles and posts here about how to hide footer when keyboard on mobile devices arise but not what I am trying to do which is opposite.

I want to move footer up above keyboard when keyboard is open.

HTML

```<code><div class="wrapper">
<input type="text">
<div class="footer">Here Footer</div>
</div>
</code>```

CSS

```<code> .wrapper {
    position:relative;
    }
    .footer {
      width: 100%;
      background-color: #4c66a4;
      color: #fff;
      position: absolute;
      left: 0px;
      bottom: 0px;
      text-align: center;
    }
</code>```

Any idea what am I doing wrong as it goes overflowed by keyboard all the time.

答: So it is not possible to stick div to the keyboard as keyboard on mobiles doesnt sit within viewport so. As i needed a numeric keyboard what I did is used jquery "KEY" functionality to make a keyboard based on divs.</p>

Body:
I have found alot of artivles and posts here about how to hide footer when keyboard on mobile devices arise but not what I am trying to do which is opposite.

I want to move footer up above keyboard when keyboard is open.

HTML

<input type="text">

Here Footer

CSS

 .wrapper {
    position:relative;
    }
    .footer {
      width: 100%;
      background-color: #4c66a4;
      color: #fff;
      position: absolute;
      left: 0px;
      bottom: 0px;
      text-align: center;
    }

Any idea what am I doing wrong as it goes overflowed by keyboard all the time.


问:
What's the difference between these two bindings?
Long ago, I looked at this MSDN walkthrough.  It implements a color editor, and the tooltip uses the color's name like "Red" or "Blue".

Today, I'm implementing a ListBox that is similar; it displays a box with the color and the name of the color next to it.  Except in my application, all of the color names display as the hex values like #FFFF0000 and #FF0000FF.  Why?

Here's the ColorsList class used in both projects:

```<code>public ColorsList()
{
    Type type = typeof(Colors);
    foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Static))
    {
        if (propertyInfo.PropertyType == typeof(Color))
        {
            Add((Color)propertyInfo.GetValue(null, null));
        }
    }
}
</code>```

This XAML snippet makes the tooltip use the color name in the MSDN project (you can see the rest of the code in the walkthrough):

```<code><ItemsControl.ItemTemplate>
    <DataTemplate>
        <Button Tag="{Binding}" Command="{x:Static PropertyEditing:PropertyValueEditorCommands.ShowInlineEditor}">
            <Button.Template>
                <ControlTemplate>
                    <Border Width="30" Height="30" BorderBrush="Black" BorderThickness="1" CornerRadius="5">
                        <Rectangle Width="22" Height="22" ToolTip="{Binding}">
                            <Rectangle.Fill>
                                <SolidColorBrush Color="{Binding}"/>
                            </Rectangle.Fill>
                        </Rectangle>
                    </Border>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </DataTemplate>
</ItemsControl.ItemTemplate>
</code>```

Here's my XAML that produces the hex codes:

```<code><ListBox x:Name="lstColors" Grid.Row="1" ItemsSource="{StaticResource colors}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Rectangle Stroke="Black"
                           StrokeThickness="3"
                           Width="24"
                           Height="24"
                           RadiusX="5"
                           RadiusY="5">
                    <Rectangle.Fill>
                        <SolidColorBrush Color="{Binding}" />
                    </Rectangle.Fill>
                </Rectangle>
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</code>```

It looks the same to me; what's the difference?

答:
Not exactly an answer to your question, more of an observation:

If you change ColorsList to inherit from ObservableCollection<string> instead of ObservableCollection<Color> and modify the following line:

```<code>Add((Color)propertyInfo.GetValue(null, null));
</code>```

to

```<code>Add(propertyInfo.Name);
</code>```

your code will work as you want it to work. Instead of converting Color to color name, this is going the other way around - using the built-in conversion from color name to Color.

As a side note, I tried the XAML code from the MSDN sample (only the part you're citing) but the tooltips display color codes and not color names.

OwnerDisplayName: OwenP

ContentLicense: CC BY-SA 2.5

Body:
Long ago, I looked at this MSDN walkthrough.  It implements a color editor, and the tooltip uses the color's name like "Red" or "Blue".

Today, I'm implementing a ListBox that is similar; it displays a box with the color and the name of the color next to it.  Except in my application, all of the color names display as the hex values like #FFFF0000 and #FF0000FF.  Why?

Here's the ColorsList class used in both projects:

public ColorsList()
{
    Type type = typeof(Colors);
    foreach (PropertyInfo propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Static))
    {
        if (propertyInfo.PropertyType == typeof(Color))
        {
            Add((Color)propertyInfo.GetValue(null, null));
        }
    }
}

This XAML snippet makes the tooltip use the color name in the MSDN project (you can see the rest of the code in the walkthrough):

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Button Tag="{Binding}" Command="{x:Static PropertyEditing:PropertyValueEditorCommands.ShowInlineEditor}">
            <Button.Template>
                <ControlTemplate>
                    <Border Width="30" Height="30" BorderBrush="Black" BorderThickness="1" CornerRadius="5">
                        <Rectangle Width="22" Height="22" ToolTip="{Binding}">
                            <Rectangle.Fill>
                                <SolidColorBrush Color="{Binding}"/>
                            </Rectangle.Fill>
                        </Rectangle>
                    </Border>
                </ControlTemplate>
            </Button.Template>
        </Button>
    </DataTemplate>
</ItemsControl.ItemTemplate>

Here's my XAML that produces the hex codes:

<ListBox x:Name="lstColors" Grid.Row="1" ItemsSource="{StaticResource colors}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Rectangle Stroke="Black"
                           StrokeThickness="3"
                           Width="24"
                           Height="24"
                           RadiusX="5"
                           RadiusY="5">
                    <Rectangle.Fill>
                        <SolidColorBrush Color="{Binding}" />
                    </Rectangle.Fill>
                </Rectangle>
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

It looks the same to me; what's the difference?

Body:
Not exactly an answer to your question, more of an observation:

If you change ColorsList to inherit from ObservableCollection<string> instead of ObservableCollection<Color> and modify the following line:

Add((Color)propertyInfo.GetValue(null, null));

to

Add(propertyInfo.Name);

your code will work as you want it to work. Instead of converting Color to color name, this is going the other way around - using the built-in conversion from color name to Color.

As a side note, I tried the XAML code from the MSDN sample (only the part you're citing) but the tooltips display color codes and not color names.


问:
Zend_Form not submitting
I built a custom Zend_Form "myForm" and I passed it to my view with:

```<code>$this->view->form=new myForm();
</code>```

Problem: form is not submitting (page doesn't reload/refresh).I thought something was wrong with the "form" tags,but I copyied the bottom code in another page (that is not a Zend environment) and is working.This is the source code:

```<code><form enctype="multipart/form-data" method="post" action="">

<input type="text" name="title" id="title" value="" class="">
<textarea name="text" id="text" class=""></textarea>
<input type="text" name="allegati" id="allegati" value="" class="">
<input type="hidden" name="MAX_FILE_SIZE" value="2097152" id="MAX_FILE_SIZE">
<input type="file" name="file" id="file" class="media[]"></span>

<input type="submit" name="submit" id="submit" value="submit" class="">
</form>
</code>```

SOLVED: As some of you guys suggested javascript is giving problems:
I had a js script overriding with:

```<code>$('form').submit();
</code>```

Thanks

Luca

答:
Form submitting issues are 99% related to javascript conflicts with the 'form' element or with a wrong defined 'form' tag.
Always check those above when encountering problems.

P.s. for the remaining 1% feel free to ask at Stack!

Best regards

Title: Zend_Form not submitting

Body:
I built a custom Zend_Form "myForm" and I passed it to my view with:

$this->view->form=new myForm();

Problem: form is not submitting (page doesn't reload/refresh).I thought something was wrong with the "form" tags,but I copyied the bottom code in another page (that is not a Zend environment) and is working.This is the source code:

<form enctype="multipart/form-data" method="post" action="">

<input type="text" name="title" id="title" value="" class="">
<textarea name="text" id="text" class=""></textarea>
<input type="text" name="allegati" id="allegati" value="" class="">
<input type="hidden" name="MAX_FILE_SIZE" value="2097152" id="MAX_FILE_SIZE">
<input type="file" name="file" id="file" class="media[]">

<input type="submit" name="submit" id="submit" value="submit" class="">
</form>

SOLVED: As some of you guys suggested javascript is giving problems:
I had a js script overriding with:

$('form').submit();

Thanks

Luca


问:
Discord.js - ReferenceError: member is not defined
I am having issues with this, i am trying to add a role called Simon Says Player, can anyone help??</p>

```<code>bot.on('message', message => {

    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
        case 'join':

            let person = message.guild.member

            if (!person) {
                return message.reply('Couldn`t find the user!');
            }

            let mainRole = (role => role.name === "Simon Says Player");

            member.addRole(mainRole.id);

            message.channel.send('Successfully Entered The Game!!')

            break;
    }
})
</code>```

答:
Try message.member.addRole(mainRole.id) instead of member.addRole(mainRole.id)

This should work in your example :

```<code>    switch (args[0]) {
        case 'join':

                let person = message.member

                if (!person) {
                    return message.reply('Couldn`t find the user!');
                }

                let mainRole = message.guild.roles.cache.find(role => role.name === "Simon Says Player");
                message.member.roles.add(mainRole);

                message.channel.send('Successfully Entered The Game!!')

            break;
    }
</code>```

Body:
I am having issues with this, i am trying to add a role called Simon Says Player, can anyone help??

bot.on('message', message => {

    let args = message.content.substring(PREFIX.length).split(" ");

    switch (args[0]) {
        case 'join':

            let person = message.guild.member

            if (!person) {
                return message.reply('Couldn`t find the user!');
            }

            let mainRole = (role => role.name === "Simon Says Player");

            member.addRole(mainRole.id);

            message.channel.send('Successfully Entered The Game!!')

            break;
    }
})

Body:
Try message.member.addRole(mainRole.id) instead of member.addRole(mainRole.id)

This should work in your example :

    switch (args[0]) {
        case 'join':

                let person = message.member

                if (!person) {
                    return message.reply('Couldn`t find the user!');
                }

                let mainRole = message.guild.roles.cache.find(role => role.name === "Simon Says Player");
                message.member.roles.add(mainRole);

                message.channel.send('Successfully Entered The Game!!')

            break;
    }


问:
How to remove this white HTML space below footer?
I've created a responsive webpage and everything is working fine. I mean the layout for mobile like smartphones and tablets is ok. If I switch to desktop it looks good too except for the footer and that's because there is an empty white space at the end of the webpage if I click on inspect the browser focus the HTML tag.

One thing you have to notice is that the height of this empty space depends on the width of the viewport. Also I'm using sass. I can't share all the code here because it's divided across too many files. If you want to see all the code go here: https://github.com/justanindieguy/podcast-landing-page

And also you can see the webpage in this github personal page: https://justanindieguy.github.io/podcast-landing-page/

Thanks a lot for all your answers. This is driving me nuts, I can't find the solution.

答:
I tried the given solutions from others to make sure none already did the trick on your page, but no success.

I then found the reason you're getting the issue. It's related to the :before of the news section, it's overflowing from the element.

Try adding this CSS :

```<code>#news {
    overflow: hidden;
}
</code>```

Now the news section crops the :before element relative to its own dimensions.
I noticed you achieved the layout with skew, but I recommend you to look into clip path generators and create this shape that way.

Body:
I tried the given solutions from others to make sure none already did the trick on your page, but no success.

I then found the reason you're getting the issue. It's related to the :before of the news section, it's overflowing from the element.

Try adding this CSS :

#news {
    overflow: hidden;
}

Now the news section crops the :before element relative to its own dimensions.
I noticed you achieved the layout with skew, but I recommend you to look into clip path generators and create this shape that way.


问:
Send java UUID list with post request vie postman
Anybody Please help me in sending java UUID list via postman.
I tryed this way

```<code> @PostMapping(path = "/alerts/sent/recipientstatistics")
    public List<SentAlertRecipientStatistics> getRecipientStatisticsForSentAlerts(@RequestBody List<StatisticsRequest> uuids) {}
</code>```

and this way of sending via postman

```<code>    [{"notifHisUUID":"0000000a-0019-3000-806c-bea5b65658cf"}]
</code>```

and getting error.

```<code>Caused by: java.lang.NoSuchMethodException: java.util.List.<init>()
</code>```

My request class is

```<code>public class StatisticsRequest {

private List<UUID> notifHisUUID;

public List<UUID> getNotifHisUUID() {
    return notifHisUUID;
}

public void setNotifHisUUID(List<UUID> notifHisUUID) {
    this.notifHisUUID = notifHisUUID;
}
</code>```

}

答:
I think that the problem lies in JSON that you are sending. You declare "notifHisUUID" like it was a string field, but it should be an array instead.

```<code>[
  {
    "notifHisUUID": [ "0000000a-0019-3000-806c-bea5b65658cf" ]
  }
]
</code>```

Body:
Anybody Please help me in sending java UUID list via postman.
I tryed this way

 @PostMapping(path = "/alerts/sent/recipientstatistics")
    public List<SentAlertRecipientStatistics> getRecipientStatisticsForSentAlerts(@RequestBody List<StatisticsRequest> uuids) {}

and this way of sending via postman

    [{"notifHisUUID":"0000000a-0019-3000-806c-bea5b65658cf"}]

and getting error.

Caused by: java.lang.NoSuchMethodException: java.util.List.<init>()

My request class is

public class StatisticsRequest {

private List<UUID> notifHisUUID;

public List<UUID> getNotifHisUUID() {
    return notifHisUUID;
}

public void setNotifHisUUID(List<UUID> notifHisUUID) {
    this.notifHisUUID = notifHisUUID;
}

}

Body:
I think that the problem lies in JSON that you are sending. You declare "notifHisUUID" like it was a string field, but it should be an array instead.

[
  {
    "notifHisUUID": [ "0000000a-0019-3000-806c-bea5b65658cf" ]
  }
]


问:
Do I need to place the manifest.json file at the root of my webserver?
I read that on some sources and don't see any mention of that point on other, like MDN.

I would like to have it in /assets/manifest.json. Even if that would work, I would still wonder if it is "working by design" or just "tolerated".

答:
You can have it anywhere you like and link to it like so:

...
<link rel="manifest" href="/assets/manifest.json" />
...
```

As long as you modify the src of the assets in manifest.json this should be fine.

Body:
You can have it anywhere you like and link to it like so:

...<head>
<link rel="manifest" href="/assets/manifest.json" />
...</head>

As long as you modify the src of the assets in manifest.json this should be fine.


问:
Remove consecutive duplicates from a list using yield generator?
i'm trying to compress a list using generator:

examples

```<code>[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]
</code>```

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

```<code>test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]

ans = compress(test)
for x in ans:
    print(ans)
</code>```

but i keep getting

generator object compress at 0x00000254D383C820.
why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

答:
Heh, I recognize this question from somewhere. ;)

I went about it a different way than you but I figured you might find it useful to peep at:

```<code>def compress(i:list):
    return[i[x]for x in range(len(i))if x==0 or i[x-1]!=i[x]]
</code>```

The other answers fit the specifics of your question better, I just happened to recognize the setup and figured I'd dig up and offer the solution I gave to this very same problem.  Cheers!

Body:
i'm trying to compress a list using generator:

examples

[1, 1, 1, 1, 2, 2, 2, 1, 1, 1] == [1, 2, 1]

[5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0])) == [5, 4, 5, 6, 5, 7, 8, 0]

I tried to use a generator that checks if the 1st and 2nd element are equal then check 2nd and 3rd and so on until it is no longer equal "when it reaches 4" and then yield "5" then it would repeat the process starting with "4"

code

test = [5, 5, 5, 4, 5, 6, 6, 5, 5, 7, 8, 0, 0] # sample list
from typing import Iterable
def compress(items: list) -> Iterable:

    x = 0
    while items[x] == items[x + 1]:
        x += 1
    yield items[x]

ans = compress(test)
for x in ans:
    print(ans)

but i keep getting

generator object compress at 0x00000254D383C820.
why won't it loop?

if i try and use next() it only goes up to 5 and wont check the other numbers.

any assistance is greatly appreciated.

Body:
Heh, I recognize this question from somewhere. ;)

I went about it a different way than you but I figured you might find it useful to peep at:

def compress(i:list):
    return[i[x]for x in range(len(i))if x==0 or i[x-1]!=i[x]]

The other answers fit the specifics of your question better, I just happened to recognize the setup and figured I'd dig up and offer the solution I gave to this very same problem.  Cheers!


问:
Discord bot is not joining voice channel
```<code>import discord
from discord.ext.commands import Bot
from discord.ext import commands,tasks
from discord.utils import get
from discord import Game

client = Bot(command_prefix = BOT_PREFIX)

@client.command()
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()
    await ctx.send('Joined {}'.format(channel))
</code>```

I just wanted to make a simple method that allows my discord bot to join a channel. I have looked at multiple threads and some of them are outdated because they were before discord.py migrated to v1.0. I have used type() and dir() to check what type the channel is and also see what methods it has. I compared it to the API from discord.py and a problem I found was that the dir() made a field called connect but the API shows that the channel object has a method called connect(). I am stuck at the moment trying to figure out how to make the discord bot join as it seems the connect() method does not allow me to connect as it does not allow me to continue with the method after I try using that connect() method. All help is appreciated! :)

答:
Remove the message from channel = ctx.message.author.voice.channel.
Test this :)

```<code>channel = ctx.author.voice.channel
voice = await channel.connect()
await ctx.send('Joined {}'.format(channel))
</code>```

Body:
import discord
from discord.ext.commands import Bot
from discord.ext import commands,tasks
from discord.utils import get
from discord import Game

client = Bot(command_prefix = BOT_PREFIX)

@client.command()
async def join(ctx):
    channel = ctx.message.author.voice.channel
    voice = await channel.connect()
    await ctx.send('Joined {}'.format(channel))

I just wanted to make a simple method that allows my discord bot to join a channel. I have looked at multiple threads and some of them are outdated because they were before discord.py migrated to v1.0. I have used type() and dir() to check what type the channel is and also see what methods it has. I compared it to the API from discord.py and a problem I found was that the dir() made a field called connect but the API shows that the channel object has a method called connect(). I am stuck at the moment trying to figure out how to make the discord bot join as it seems the connect() method does not allow me to connect as it does not allow me to continue with the method after I try using that connect() method. All help is appreciated! :)

Body:
Remove the message from channel = ctx.message.author.voice.channel.
Test this :)

channel = ctx.author.voice.channel
voice = await channel.connect()
await ctx.send('Joined {}'.format(channel))


问:
Should I be saving my data in a .csv file?
I am writing a small .py file that contains some classes to be imported later repetitively into other work. The mentioned .py file uses some small database (in order of KB) in the form of tables. Do you think it is better to store this data in the same .py file or is it better to keep it in a separate .csv file? What are the differences in terms of performance and convenience for later use? A point that I might have to mention is that this data is numerical and is not prone to any possible change in the future.
Single items are to be accessed from this data at a time.

答:
If readability of the python class is not a concern (although it's best practice to keep code as readable as possible), the big question here will be 'how much' data are we talking about? If you have gigabytes of data then you don't want to have this all sitting in memory at the same time (i.e. what would happen if you just kept it as a constant in a .py file). Instead, for such large data, you want to read it from disk (maybe as a csv) as and when you need it.

Of course storing it in disk has a performance hit because reading from disk is slower than reading from memory. Whether or not the performance hit is okay for your application is up to you to decide.

A good in-between to ensure readability and good performance might be (assuming you have enough memory) to store the data in a csv, read it all at once on start up and keep it in memory for repeated calls.


问:
SQL combine two rows with common batch number into one line
I have an Oracle SQL (select *) query that spools batch transactional information, the result of which outputs the main sender and receivers to different lines for the same transaction like below:

```<code>BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME RECEIVER_ACCT_NO    RECEIVER NAME
12345678    15-May-20   103.55  400001000        ENDCORP         (null)
12345678    15-May-20   34.55   400001000        (null)          78909909         JOHN SMITH
12345678    15-May-20   44.00   400001000        (null)          78853229         HENRY FAGIL
12345678    15-May-20   4.00    400001000        (null)          76849852        BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        (null)          72555099          FELIX MAGS
12222222    16-May-20   1902.00 400000105       ZENDCORP          (null)
12222222    17-May-20   1899.00 400000105        (null)          90333300          KEN GOTL
12222222    18-May-20   3.00    400000105        (null)          90127765         JONES MAST
</code>```

In this case, ENDCORP and ZENDCORP sent out batch payments of a total of 103.55 and 1902.00 to 4 and 2 clients respectively.

However, I would prefer my results to be in the form below:

```<code>BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME    RECEIVER_ACCT_NO        RECEIVER NAME
12345678    15-May-20   34.55   400001000        ENDCORP        78909909                JOHN SMITH
12345678    15-May-20   44.00   400001000        ENDCORP        78853229                HENRY FAGIL
12345678    15-May-20   4.00    400001000        ENDCORP        76849852                BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        ENDCORP        72555099                 FELIX MAGS
12222222    17-May-20  1899.00  400000105       ZENDCORP        90333300                  KEN GOTL
12222222    18-May-20   3.00    400000105       ZENDCORP        90127765                 JONES MAST
</code>```

I would appreciate guidance on how to formulate my query for this result

答:
I think you can use window functions to impute the name and then filter:</p>

```<code>select . . .   -- columns you want
from (select t.*,
             max(sender_name) over (partition by batch_no) as imputed_sender_name
      from t
     ) t
where RECEIVER_ACCT_NO is not null;
</code>```

Body:
I have an Oracle SQL (select *) query that spools batch transactional information, the result of which outputs the main sender and receivers to different lines for the same transaction like below:

BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME RECEIVER_ACCT_NO    RECEIVER NAME
12345678    15-May-20   103.55  400001000        ENDCORP         (null)
12345678    15-May-20   34.55   400001000        (null)          78909909         JOHN SMITH
12345678    15-May-20   44.00   400001000        (null)          78853229         HENRY FAGIL
12345678    15-May-20   4.00    400001000        (null)          76849852        BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        (null)          72555099          FELIX MAGS
12222222    16-May-20   1902.00 400000105       ZENDCORP          (null)
12222222    17-May-20   1899.00 400000105        (null)          90333300          KEN GOTL
12222222    18-May-20   3.00    400000105        (null)          90127765         JONES MAST

In this case, ENDCORP and ZENDCORP sent out batch payments of a total of 103.55 and 1902.00 to 4 and 2 clients respectively.

However, I would prefer my results to be in the form below:

BATCH_NO    DATE      AMOUNT    SENDER_ACCT_NO  SENDER NAME    RECEIVER_ACCT_NO        RECEIVER NAME
12345678    15-May-20   34.55   400001000        ENDCORP        78909909                JOHN SMITH
12345678    15-May-20   44.00   400001000        ENDCORP        78853229                HENRY FAGIL
12345678    15-May-20   4.00    400001000        ENDCORP        76849852                BENJAMIN HOOK
12345678    15-May-20   21.00   400001000        ENDCORP        72555099                 FELIX MAGS
12222222    17-May-20  1899.00  400000105       ZENDCORP        90333300                  KEN GOTL
12222222    18-May-20   3.00    400000105       ZENDCORP        90127765                 JONES MAST

I would appreciate guidance on how to formulate my query for this result

Body:
I think you can use window functions to impute the name and then filter:

select . . .   -- columns you want
from (select t.*,
             max(sender_name) over (partition by batch_no) as imputed_sender_name
      from t
     ) t
where RECEIVER_ACCT_NO is not null;