问:
stm32 cdc+audio USB Composite Device
I am currently implementing the composite device of stm32 audio cdc, but the display of cdc in the windows device is normal, and the audio is an exclamation mark. May I ask where there may be problems?

I tried to adjust the interface of cdc and audio, but it will be successful. I want to know how to change it if the cdc is placed in front.

Below is my descriptor

```<code>__ALIGN_BEGIN static uint8_t USBD_AUDIO_CDC_CfgDesc[USB_AUDIO_CDC_CONFIG_DESC_SIZ] __ALIGN_END =
{
    0x09, /* bLength: Configuration Descriptor size */
    USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
    LOBYTE(USB_AUDIO_CDC_CONFIG_DESC_SIZ), /* wTotalLength: Bytes returned */
    HIBYTE(USB_AUDIO_CDC_CONFIG_DESC_SIZ),
    0x04,         /*bNumInterfaces: 4 interfaces (2 for AUDIO, 2 for CDC)*/
    0x01,         /*bConfigurationValue: Configuration value*/
    0x00,         /*iConfiguration: Index of string descriptor describing the configuration*/
    0x80,         /*bmAttributes: bus powered */
    0xFA,         /*MaxPower 100 mA: this current is used for detecting Vbus*/
    /*9*/
    /******** /IAD should be positioned just before the CDC interfaces ******
                IAD to associate the two CDC interfaces */

    0x08, /* bLength */
    0x0B, /* bDescriptorType */
    0x00, /* bFirstInterface */
    0x02, /* bInterfaceCount */
    0x02, /* bFunctionClass */
    0x02, /* bFunctionSubClass */
    0x01, /* bFunctionProtocol */
    0x02, /* iFunction (Index of string descriptor describing this function) */
    /*49(117)*/

    /************************  CDC interface ********************************/
    0x09,   /* bLength: Interface Descriptor size */
    USB_DESC_TYPE_INTERFACE,  /* bDescriptorType: Interface */
    /* Interface descriptor type */
    CDC_INTERFACE0,   /* bInterfaceNumber: Number of Interface */
    0x00,   /* bAlternateSetting: Alternate setting */
    0x01,   /* bNumEndpoints: One endpoints used */
    0x02,   /* bInterfaceClass: Communication Interface Class */
    0x02,   /* bInterfaceSubClass: Abstract Control Model */
    0x01,   /* bInterfaceProtocol: Common AT commands */
    0x00,   /* iInterface: */
    /*58 (126)*/

    /*Header Functional Descriptor*/
    0x05,   /* bLength: Endpoint Descriptor size */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x00,   /* bDescriptorSubtype: Header Func Desc */
    0x10,   /* bcdCDC: spec release number */
    0x01,
    /*63 (131)*/

    /*Call Management Functional Descriptor*/
    0x05,   /* bFunctionLength */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x01,   /* bDescriptorSubtype: Call Management Func Desc */
    0x00,   /* bmCapabilities: D0+D1 */
    0x01,   /* bDataInterface: 1 */
    /*68 (136)*/

    /*ACM Functional Descriptor*/
    0x04,   /* bFunctionLength */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x02,   /* bDescriptorSubtype: Abstract Control Management desc */
    0x02,   /* bmCapabilities */
    /*72 (140)*/

    /*Union Functional Descriptor*/
    0x05,   /* bFunctionLength */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x06,   /* bDescriptorSubtype: Union func desc */
    0x00,   /* bMasterInterface: Communication class interface */
    0x01,   /* bSlaveInterface0: Data Class Interface */
    /*77 (145)*/

    /*Endpoint 2 Descriptor*/
    0x07,                           /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_ENDPOINT,   /* bDescriptorType: Endpoint */
    CDC_CMD_EP,                     /* bEndpointAddress */
    0x03,                           /* bmAttributes: Interrupt */
    LOBYTE(CDC_CMD_PACKET_SIZE),     /* wMaxPacketSize: */
    HIBYTE(CDC_CMD_PACKET_SIZE),
    0x10,                           /* bInterval: */
    /*84 (152)*/

    /*---------------------------------------------------------------------------*/

    /*Data class interface descriptor*/
    0x09,   /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_INTERFACE,  /* bDescriptorType: */
    CDC_INTERFACE1,   /* bInterfaceNumber: Number of Interface */
    0x00,   /* bAlternateSetting: Alternate setting */
    0x02,   /* bNumEndpoints: Two endpoints used */
    0x0A,   /* bInterfaceClass: CDC */
    0x00,   /* bInterfaceSubClass: */
    0x00,   /* bInterfaceProtocol: */
    0x00,   /* iInterface: */
    /*93 (161)*/

    /*Endpoint OUT Descriptor*/
    0x07,   /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_ENDPOINT,      /* bDescriptorType: Endpoint */
    CDC_OUT_EP,                        /* bEndpointAddress */
    0x02,                              /* bmAttributes: Bulk */
    LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),  /* wMaxPacketSize: */
    HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
    0x00,                              /* bInterval: ignore for Bulk transfer */
    /*100 (168)*/

    /*Endpoint IN Descriptor*/
    0x07,   /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_ENDPOINT,      /* bDescriptorType: Endpoint */
    CDC_IN_EP,                         /* bEndpointAddress */
    0x02,                              /* bmAttributes: Bulk */
    LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),  /* wMaxPacketSize: */
    HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
    0x00,                               /* bInterval: ignore for Bulk transfer */
    /*107(175)*/
        /*** Interface Association Descriptor: Audio Function 1******/
    0x08, /* bLength */
    0x0B, /* bDescriptorType */
    0x02, /* bFirstInterface *///interafe 2 to 3
    0x02, /* bInterfaceCount */
    0x01, /* bFunctionClass */
    0x00, /* bFunctionSubClass */
    0x00, /* bFunctionProtocol */
    0x00, /* iFunction (Index of string descriptor describing this function) */
    /*8 (17)*/

    /* USB Speaker Standard interface descriptor */
    AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
    USB_DESC_TYPE_INTERFACE,              /* bDescriptorType */
    AUDIO_INTERFACE0,                     /* bInterfaceNumber */
    0x00,                                 /* bAlternateSetting */
    0x00,                                 /* bNumEndpoints */
    USB_DEVICE_CLASS_AUDIO,               /* bInterfaceClass */
    AUDIO_SUBCLASS_AUDIOCONTROL,          /* bInterfaceSubClass */
    AUDIO_PROTOCOL_UNDEFINED,             /* bInterfaceProtocol */
    0x00,                                 /* iInterface */
    /* 09 byte (26)*/

    /* USB Speaker Class-specific AC Interface Descriptor */
    AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_CONTROL_HEADER,                 /* bDescriptorSubtype */
    0x00,          /* 1.00 */             /* bcdADC */
    0x01,
    0x1E,                                 /* wTotalLength = 39 +1 channel -9*/
    0x00,
    0x01,                                 /* bInCollection */
    0x01,                                 /* baInterfaceNr */
    /* 09 byte (35)*/

    /* USB Speaker Input Terminal Descriptor */
    AUDIO_INPUT_TERMINAL_DESC_SIZE,       /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_CONTROL_INPUT_TERMINAL,         /* bDescriptorSubtype */
    0x01,                                 /* bTerminalID */
    0x01,                                 /* wTerminalType AUDIO_TERMINAL_USB_STREAMING   0x0101 */
    0x02,                                                               //0x01 -> 0x02
    0x00,                                 /* bAssocTerminal */
    0x02,                                 /* bNrChannels */ //0x01->0x02
    0x03,                                 /* wChannelConfig 0x0000  Mono */
    0x00,
    0x00,                                 /* iChannelNames */
    0x00,                                 /* iTerminal */
    /* 12 byte (47)*/

    /* USB Speaker Audio Feature Unit Descriptor */
    0x09,                                 /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_CONTROL_OUTPUT_TERMINAL,           /* bDescriptorSubtype */ //AUDIO_CONTROL_FEATURE_UNIT(0x06) -> AUDIO_CONTROL_OUTPUT_TERMINAL(0x03)
    AUDIO_OUT_STREAMING_CTRL,             /* bUnitID */
    0x01,                                 /* bSourceID */
    0x01,                                 /* bControlSize */
    0x00,  //AUDIO_CONTROL_MUTE,                   /* bmaControls(0) */
    0x01,  //0 ->1                                    /* bmaControls(1) */
    //0x01,
    0x00,                                 /* iTerminal */
    /* 09 +1 byte (57)*/

    /*USB Speaker Output Terminal Descriptor */
//  0x09,      /* bLength */
//  AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */ //AUDIO_INTERFACE_DESCRIPTOR_TYPE ->0x04
//  AUDIO_CONTROL_OUTPUT_TERMINAL,        /* bDescriptorSubtype */ //AUDIO_CONTROL_OUTPUT_TERMINAL -> 0x01
//  0x03,                                 /* bTerminalID */ //0x03->0x00
//  0x01,                                 /* wTerminalType  0x0301->0x0100*/ //0x01->0x00
//  0x03,                       //0x03 ->0x01
//  0x00,                                 /* bAssocTerminal */ //0x00->0x02
//  0x02,                                 /* bSourceID */ //0x02-> 0x00
//  0x00,                                 /* iTerminal */
    /* 09 byte (66)*/

    /* USB Speaker Standard AS Interface Descriptor - Audio Streaming Zero Bandwith */
  /* Interface 1, Alternate Setting 0                                             */
  AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
  USB_DESC_TYPE_INTERFACE,              /* bDescriptorType */
  AUDIO_INTERFACE1,                                 /* bInterfaceNumber */
  0x00,                                 /* bAlternateSetting *///0x00->0x01
  0x00,                                 /* bNumEndpoints *///0x00->0x01
  USB_DEVICE_CLASS_AUDIO,               /* bInterfaceClass */
  AUDIO_SUBCLASS_AUDIOSTREAMING,        /* bInterfaceSubClass */
  AUDIO_PROTOCOL_UNDEFINED,             /* bInterfaceProtocol */
  0x00,                                 /* iInterface */
  /* 09 byte*/

    /* USB Speaker Standard AS Interface Descriptor - Audio Streaming Operational */
    /* Interface 1, Alternate Setting 1                                           */
    AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
    USB_DESC_TYPE_INTERFACE,              /* bDescriptorType */
    AUDIO_INTERFACE1,                                 /* bInterfaceNumber */
    0x01,                                 /* bAlternateSetting */
    0x01,                                 /* bNumEndpoints */
    USB_DEVICE_CLASS_AUDIO,               /* bInterfaceClass */
    AUDIO_SUBCLASS_AUDIOSTREAMING,        /* bInterfaceSubClass */
    AUDIO_PROTOCOL_UNDEFINED,             /* bInterfaceProtocol */
    0x00,                                 /* iInterface */
    /* 09 byte (75)*/

    /* USB Speaker Audio Streaming Interface Descriptor */
    AUDIO_STREAMING_INTERFACE_DESC_SIZE,  /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_STREAMING_GENERAL,              /* bDescriptorSubtype */
    0x02,                                 /* bTerminalLink */  //0x01->0x02
    0x01,                                 /* bDelay */
    0x01,                                 /* wFormatTag AUDIO_FORMAT_PCM  0x0001 */
    0x00,
    /* 07 byte (82)*/

    /* USB Speaker Audio Type III Format Interface Descriptor */
    0x0B,                                 /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_STREAMING_FORMAT_TYPE,          /* bDescriptorSubtype */
    AUDIO_FORMAT_TYPE_I,                  /* bFormatType */
    0x01,                                 /* bNrChannels */ //0x02->0x01
    0x02,                                 /* bSubFrameSize :  2 Bytes per frame (16bits) */
    16,                                   /* bBitResolution (16-bits per sample) */
    0x01,                                 /* bSamFreqType only one frequency supported */
    AUDIO_SAMPLE_FREQ(USBD_AUDIO_FREQ),   /* Audio sampling frequency coded on 3 bytes */
    /* 11 byte (93)*/

    /* Endpoint 1 - Standard Descriptor */
    AUDIO_STANDARD_ENDPOINT_DESC_SIZE,    /* bLength */
    USB_DESC_TYPE_ENDPOINT,               /* bDescriptorType */
    AUDIO_IN_EP,                         /* bEndpointAddress 1 out endpoint */ //AUDIO_OUT_EP->0x81
    USBD_EP_TYPE_ISOC,                    /* bmAttributes */
    AUDIO_PACKET_SZE(USBD_AUDIO_FREQ),    /* wMaxPacketSize in Bytes (Freq(Samples)*2(Stereo)*2(HalfWord)) */
    AUDIO_FS_BINTERVAL,                   /* bInterval */
    0x00,                                 /* bRefresh */
    0x00,                                 /* bSynchAddress */
    /* 09 byte (102)*/

    /* Endpoint - Audio Streaming Descriptor*/
    AUDIO_STREAMING_ENDPOINT_DESC_SIZE,   /* bLength */
    AUDIO_ENDPOINT_DESCRIPTOR_TYPE,       /* bDescriptorType */
    AUDIO_ENDPOINT_GENERAL,               /* bDescriptor */
    0x80,                                 /* bmAttributes *///0x00->0x80
    0x00,                                 /* bLockDelayUnits */
    0x00,                                 /* wLockDelay */
    0x00,
    /* 07 byte (109)*/
} ;
</code>```

Title: stm32 cdc+audio USB Composite Device

Body:
I am currently implementing the composite device of stm32 audio cdc, but the display of cdc in the windows device is normal, and the audio is an exclamation mark. May I ask where there may be problems?

I tried to adjust the interface of cdc and audio, but it will be successful. I want to know how to change it if the cdc is placed in front.

Below is my descriptor

__ALIGN_BEGIN static uint8_t USBD_AUDIO_CDC_CfgDesc[USB_AUDIO_CDC_CONFIG_DESC_SIZ] __ALIGN_END =
{
    0x09, /* bLength: Configuration Descriptor size */
    USB_DESC_TYPE_CONFIGURATION, /* bDescriptorType: Configuration */
    LOBYTE(USB_AUDIO_CDC_CONFIG_DESC_SIZ), /* wTotalLength: Bytes returned */
    HIBYTE(USB_AUDIO_CDC_CONFIG_DESC_SIZ),
    0x04,         /*bNumInterfaces: 4 interfaces (2 for AUDIO, 2 for CDC)*/
    0x01,         /*bConfigurationValue: Configuration value*/
    0x00,         /*iConfiguration: Index of string descriptor describing the configuration*/
    0x80,         /*bmAttributes: bus powered */
    0xFA,         /*MaxPower 100 mA: this current is used for detecting Vbus*/
    /*9*/
    /******** /IAD should be positioned just before the CDC interfaces ******
                IAD to associate the two CDC interfaces */

    0x08, /* bLength */
    0x0B, /* bDescriptorType */
    0x00, /* bFirstInterface */
    0x02, /* bInterfaceCount */
    0x02, /* bFunctionClass */
    0x02, /* bFunctionSubClass */
    0x01, /* bFunctionProtocol */
    0x02, /* iFunction (Index of string descriptor describing this function) */
    /*49(117)*/

    /************************  CDC interface ********************************/
    0x09,   /* bLength: Interface Descriptor size */
    USB_DESC_TYPE_INTERFACE,  /* bDescriptorType: Interface */
    /* Interface descriptor type */
    CDC_INTERFACE0,   /* bInterfaceNumber: Number of Interface */
    0x00,   /* bAlternateSetting: Alternate setting */
    0x01,   /* bNumEndpoints: One endpoints used */
    0x02,   /* bInterfaceClass: Communication Interface Class */
    0x02,   /* bInterfaceSubClass: Abstract Control Model */
    0x01,   /* bInterfaceProtocol: Common AT commands */
    0x00,   /* iInterface: */
    /*58 (126)*/

    /*Header Functional Descriptor*/
    0x05,   /* bLength: Endpoint Descriptor size */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x00,   /* bDescriptorSubtype: Header Func Desc */
    0x10,   /* bcdCDC: spec release number */
    0x01,
    /*63 (131)*/

    /*Call Management Functional Descriptor*/
    0x05,   /* bFunctionLength */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x01,   /* bDescriptorSubtype: Call Management Func Desc */
    0x00,   /* bmCapabilities: D0+D1 */
    0x01,   /* bDataInterface: 1 */
    /*68 (136)*/

    /*ACM Functional Descriptor*/
    0x04,   /* bFunctionLength */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x02,   /* bDescriptorSubtype: Abstract Control Management desc */
    0x02,   /* bmCapabilities */
    /*72 (140)*/

    /*Union Functional Descriptor*/
    0x05,   /* bFunctionLength */
    0x24,   /* bDescriptorType: CS_INTERFACE */
    0x06,   /* bDescriptorSubtype: Union func desc */
    0x00,   /* bMasterInterface: Communication class interface */
    0x01,   /* bSlaveInterface0: Data Class Interface */
    /*77 (145)*/

    /*Endpoint 2 Descriptor*/
    0x07,                           /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_ENDPOINT,   /* bDescriptorType: Endpoint */
    CDC_CMD_EP,                     /* bEndpointAddress */
    0x03,                           /* bmAttributes: Interrupt */
    LOBYTE(CDC_CMD_PACKET_SIZE),     /* wMaxPacketSize: */
    HIBYTE(CDC_CMD_PACKET_SIZE),
    0x10,                           /* bInterval: */
    /*84 (152)*/

    /*---------------------------------------------------------------------------*/

    /*Data class interface descriptor*/
    0x09,   /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_INTERFACE,  /* bDescriptorType: */
    CDC_INTERFACE1,   /* bInterfaceNumber: Number of Interface */
    0x00,   /* bAlternateSetting: Alternate setting */
    0x02,   /* bNumEndpoints: Two endpoints used */
    0x0A,   /* bInterfaceClass: CDC */
    0x00,   /* bInterfaceSubClass: */
    0x00,   /* bInterfaceProtocol: */
    0x00,   /* iInterface: */
    /*93 (161)*/

    /*Endpoint OUT Descriptor*/
    0x07,   /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_ENDPOINT,      /* bDescriptorType: Endpoint */
    CDC_OUT_EP,                        /* bEndpointAddress */
    0x02,                              /* bmAttributes: Bulk */
    LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),  /* wMaxPacketSize: */
    HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
    0x00,                              /* bInterval: ignore for Bulk transfer */
    /*100 (168)*/

    /*Endpoint IN Descriptor*/
    0x07,   /* bLength: Endpoint Descriptor size */
    USB_DESC_TYPE_ENDPOINT,      /* bDescriptorType: Endpoint */
    CDC_IN_EP,                         /* bEndpointAddress */
    0x02,                              /* bmAttributes: Bulk */
    LOBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),  /* wMaxPacketSize: */
    HIBYTE(CDC_DATA_FS_MAX_PACKET_SIZE),
    0x00,                               /* bInterval: ignore for Bulk transfer */
    /*107(175)*/
        /*** Interface Association Descriptor: Audio Function 1******/
    0x08, /* bLength */
    0x0B, /* bDescriptorType */
    0x02, /* bFirstInterface *///interafe 2 to 3
    0x02, /* bInterfaceCount */
    0x01, /* bFunctionClass */
    0x00, /* bFunctionSubClass */
    0x00, /* bFunctionProtocol */
    0x00, /* iFunction (Index of string descriptor describing this function) */
    /*8 (17)*/

    /* USB Speaker Standard interface descriptor */
    AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
    USB_DESC_TYPE_INTERFACE,              /* bDescriptorType */
    AUDIO_INTERFACE0,                     /* bInterfaceNumber */
    0x00,                                 /* bAlternateSetting */
    0x00,                                 /* bNumEndpoints */
    USB_DEVICE_CLASS_AUDIO,               /* bInterfaceClass */
    AUDIO_SUBCLASS_AUDIOCONTROL,          /* bInterfaceSubClass */
    AUDIO_PROTOCOL_UNDEFINED,             /* bInterfaceProtocol */
    0x00,                                 /* iInterface */
    /* 09 byte (26)*/

    /* USB Speaker Class-specific AC Interface Descriptor */
    AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_CONTROL_HEADER,                 /* bDescriptorSubtype */
    0x00,          /* 1.00 */             /* bcdADC */
    0x01,
    0x1E,                                 /* wTotalLength = 39 +1 channel -9*/
    0x00,
    0x01,                                 /* bInCollection */
    0x01,                                 /* baInterfaceNr */
    /* 09 byte (35)*/

    /* USB Speaker Input Terminal Descriptor */
    AUDIO_INPUT_TERMINAL_DESC_SIZE,       /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_CONTROL_INPUT_TERMINAL,         /* bDescriptorSubtype */
    0x01,                                 /* bTerminalID */
    0x01,                                 /* wTerminalType AUDIO_TERMINAL_USB_STREAMING   0x0101 */
    0x02,                                                               //0x01 -> 0x02
    0x00,                                 /* bAssocTerminal */
    0x02,                                 /* bNrChannels */ //0x01->0x02
    0x03,                                 /* wChannelConfig 0x0000  Mono */
    0x00,
    0x00,                                 /* iChannelNames */
    0x00,                                 /* iTerminal */
    /* 12 byte (47)*/

    /* USB Speaker Audio Feature Unit Descriptor */
    0x09,                                 /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_CONTROL_OUTPUT_TERMINAL,           /* bDescriptorSubtype */ //AUDIO_CONTROL_FEATURE_UNIT(0x06) -> AUDIO_CONTROL_OUTPUT_TERMINAL(0x03)
    AUDIO_OUT_STREAMING_CTRL,             /* bUnitID */
    0x01,                                 /* bSourceID */
    0x01,                                 /* bControlSize */
    0x00,  //AUDIO_CONTROL_MUTE,                   /* bmaControls(0) */
    0x01,  //0 ->1                                    /* bmaControls(1) */
    //0x01,
    0x00,                                 /* iTerminal */
    /* 09 +1 byte (57)*/

    /*USB Speaker Output Terminal Descriptor */
//  0x09,      /* bLength */
//  AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */ //AUDIO_INTERFACE_DESCRIPTOR_TYPE ->0x04
//  AUDIO_CONTROL_OUTPUT_TERMINAL,        /* bDescriptorSubtype */ //AUDIO_CONTROL_OUTPUT_TERMINAL -> 0x01
//  0x03,                                 /* bTerminalID */ //0x03->0x00
//  0x01,                                 /* wTerminalType  0x0301->0x0100*/ //0x01->0x00
//  0x03,                       //0x03 ->0x01
//  0x00,                                 /* bAssocTerminal */ //0x00->0x02
//  0x02,                                 /* bSourceID */ //0x02-> 0x00
//  0x00,                                 /* iTerminal */
    /* 09 byte (66)*/

    /* USB Speaker Standard AS Interface Descriptor - Audio Streaming Zero Bandwith */
  /* Interface 1, Alternate Setting 0                                             */
  AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
  USB_DESC_TYPE_INTERFACE,              /* bDescriptorType */
  AUDIO_INTERFACE1,                                 /* bInterfaceNumber */
  0x00,                                 /* bAlternateSetting *///0x00->0x01
  0x00,                                 /* bNumEndpoints *///0x00->0x01
  USB_DEVICE_CLASS_AUDIO,               /* bInterfaceClass */
  AUDIO_SUBCLASS_AUDIOSTREAMING,        /* bInterfaceSubClass */
  AUDIO_PROTOCOL_UNDEFINED,             /* bInterfaceProtocol */
  0x00,                                 /* iInterface */
  /* 09 byte*/

    /* USB Speaker Standard AS Interface Descriptor - Audio Streaming Operational */
    /* Interface 1, Alternate Setting 1                                           */
    AUDIO_INTERFACE_DESC_SIZE,            /* bLength */
    USB_DESC_TYPE_INTERFACE,              /* bDescriptorType */
    AUDIO_INTERFACE1,                                 /* bInterfaceNumber */
    0x01,                                 /* bAlternateSetting */
    0x01,                                 /* bNumEndpoints */
    USB_DEVICE_CLASS_AUDIO,               /* bInterfaceClass */
    AUDIO_SUBCLASS_AUDIOSTREAMING,        /* bInterfaceSubClass */
    AUDIO_PROTOCOL_UNDEFINED,             /* bInterfaceProtocol */
    0x00,                                 /* iInterface */
    /* 09 byte (75)*/

    /* USB Speaker Audio Streaming Interface Descriptor */
    AUDIO_STREAMING_INTERFACE_DESC_SIZE,  /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_STREAMING_GENERAL,              /* bDescriptorSubtype */
    0x02,                                 /* bTerminalLink */  //0x01->0x02
    0x01,                                 /* bDelay */
    0x01,                                 /* wFormatTag AUDIO_FORMAT_PCM  0x0001 */
    0x00,
    /* 07 byte (82)*/

    /* USB Speaker Audio Type III Format Interface Descriptor */
    0x0B,                                 /* bLength */
    AUDIO_INTERFACE_DESCRIPTOR_TYPE,      /* bDescriptorType */
    AUDIO_STREAMING_FORMAT_TYPE,          /* bDescriptorSubtype */
    AUDIO_FORMAT_TYPE_I,                  /* bFormatType */
    0x01,                                 /* bNrChannels */ //0x02->0x01
    0x02,                                 /* bSubFrameSize :  2 Bytes per frame (16bits) */
    16,                                   /* bBitResolution (16-bits per sample) */
    0x01,                                 /* bSamFreqType only one frequency supported */
    AUDIO_SAMPLE_FREQ(USBD_AUDIO_FREQ),   /* Audio sampling frequency coded on 3 bytes */
    /* 11 byte (93)*/

    /* Endpoint 1 - Standard Descriptor */
    AUDIO_STANDARD_ENDPOINT_DESC_SIZE,    /* bLength */
    USB_DESC_TYPE_ENDPOINT,               /* bDescriptorType */
    AUDIO_IN_EP,                         /* bEndpointAddress 1 out endpoint */ //AUDIO_OUT_EP->0x81
    USBD_EP_TYPE_ISOC,                    /* bmAttributes */
    AUDIO_PACKET_SZE(USBD_AUDIO_FREQ),    /* wMaxPacketSize in Bytes (Freq(Samples)*2(Stereo)*2(HalfWord)) */
    AUDIO_FS_BINTERVAL,                   /* bInterval */
    0x00,                                 /* bRefresh */
    0x00,                                 /* bSynchAddress */
    /* 09 byte (102)*/

    /* Endpoint - Audio Streaming Descriptor*/
    AUDIO_STREAMING_ENDPOINT_DESC_SIZE,   /* bLength */
    AUDIO_ENDPOINT_DESCRIPTOR_TYPE,       /* bDescriptorType */
    AUDIO_ENDPOINT_GENERAL,               /* bDescriptor */
    0x80,                                 /* bmAttributes *///0x00->0x80
    0x00,                                 /* bLockDelayUnits */
    0x00,                                 /* wLockDelay */
    0x00,
    /* 07 byte (109)*/
} ;


来源: stackexchange

问:
How can I host a dynamic flask app that acts as a listener for a twilio phone number?
I made a simple flask app that acts as a listener connected to twilio via a webhook. The logic within the app generates a response and returns the response. I'm stuck trying to deploy and host this app. Anyone have experience with this and suggestions?

Below is similar my python file some things are changed such has account info. This is all I have at the moment:

```<code># IMPORTS =============================================================
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse

# FIELD VARIBALES ===========================================================

account_sid = 'ACCOUNT_SID'
auth_token = 'AUTH_TOKEN'
twilio_number = 'TWILIO_NUMBER'

# FUNCTIONS =======================================================

# Functions to be used in generating response. These are left out for this thread.

# APP =================================================================
app = Flask(__name__)

@app.route("https://mywebhook.com/sms", methods=['GET', 'POST'])
def sms():
    """Send a dynamic reply to an incoming text message"""
    # Get the message the user sent our Twilio number
    body = request.values.get('Body', None)

    # Start our TwiML response
    resp = MessagingResponse()

    # Determine the right reply for this message
    if body == 'hello':
        resp.message("Hi!")
    elif body == 'bye':
        resp.message("Goodbye")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)
</code>```

I've tried using Netlify and expected a response when texting my twilio number. However there is no response.

ContentLicense: CC BY-SA 4.0

Body:
I made a simple flask app that acts as a listener connected to twilio via a webhook. The logic within the app generates a response and returns the response. I'm stuck trying to deploy and host this app. Anyone have experience with this and suggestions?

Below is similar my python file some things are changed such has account info. This is all I have at the moment:

# IMPORTS =============================================================
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse

# FIELD VARIBALES ===========================================================

account_sid = 'ACCOUNT_SID'
auth_token = 'AUTH_TOKEN'
twilio_number = 'TWILIO_NUMBER'

# FUNCTIONS =======================================================

# Functions to be used in generating response. These are left out for this thread.

# APP =================================================================
app = Flask(__name__)

@app.route("https://mywebhook.com/sms", methods=['GET', 'POST'])
def sms():
    """Send a dynamic reply to an incoming text message"""
    # Get the message the user sent our Twilio number
    body = request.values.get('Body', None)

    # Start our TwiML response
    resp = MessagingResponse()

    # Determine the right reply for this message
    if body == 'hello':
        resp.message("Hi!")
    elif body == 'bye':
        resp.message("Goodbye")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)

I've tried using Netlify and expected a response when texting my twilio number. However there is no response.


问:
Linking certain C++ libraries only when necessary
I integrated Tesseract into our own C++ library, whereas it was mentioned that Tesseract may take too much time and spaces and Tesseract ISN'T ALWAYS NEEDED when our library is being used as we also have our own deep learning models for the purpose of text recognition, so I wonder if it's possible to link certain libraries on demand, both on Windows and Linux.


问:
Spring webflux: code breaking the reactive chain, which causes it not to be executed
I am currently experimenting with reactive programming and Spring Webflux. I am facing a situation where part of my code is not being executed. After doing some research I understood that when such situation arises it might mean that my code is breaking the "reactive chain".

Here is the code causing me headaches:

```<code>return getPlayerOrdersForAuction(order.getPlayerAddress(), order.getAuctionID())
        .map(el -> el.getWeight())
        .reduce((long) 0,(a,b) -> a+b)
        .doOnNext(sum -> validateOrder(order,sum)) // side effect
        .flatMap(el -> {
           return orderRepository.save(order);
        });
</code>```

Everything gets executed besides the save() operation in the flatMap(). In this case how am I breaking the reactive chain? What concept am I misunderstanding/missing? Since save() returns a Mono shouldn't it be captured in the main reactive flow by flatMap() and thus preserve the chain?

NB: please don't mind the horrible code structure, this is just experimentation.

Body:
I am currently experimenting with reactive programming and Spring Webflux. I am facing a situation where part of my code is not being executed. After doing some research I understood that when such situation arises it might mean that my code is breaking the "reactive chain".

Here is the code causing me headaches:

return getPlayerOrdersForAuction(order.getPlayerAddress(), order.getAuctionID())
        .map(el -> el.getWeight())
        .reduce((long) 0,(a,b) -> a+b)
        .doOnNext(sum -> validateOrder(order,sum)) // side effect
        .flatMap(el -> {
           return orderRepository.save(order);
        });

Everything gets executed besides the save() operation in the flatMap(). In this case how am I breaking the reactive chain? What concept am I misunderstanding/missing? Since save() returns a Mono shouldn't it be captured in the main reactive flow by flatMap() and thus preserve the chain?

NB: please don't mind the horrible code structure, this is just experimentation.


问:
Get an error when set up the name of `environment` with UTF-8 content

GitLab version: GitLab Community Edition 14.10.5

I have found that the old CI configuration has broken after upgrading GitLab, and it throws the error This job could not be executed because it would create an environment with an invalid parameter. How do I fix it? when the CI_COMMIT_REF_NAME has UTF-8 content like Chinese.

environment: review/$CI_COMMIT_REF_NAME
```

I tried CI_COMMIT_REF_SLUG, but it still did not work.

Body:
GitLab version: GitLab Community Edition 14.10.5

I have found that the old CI configuration has broken after upgrading GitLab, and it throws the error This job could not be executed because it would create an environment with an invalid parameter. How do I fix it? when the CI_COMMIT_REF_NAME has UTF-8 content like Chinese.

environment: review/$CI_COMMIT_REF_NAME

I tried CI_COMMIT_REF_SLUG, but it still did not work.


问:
I cannot get event with ProcessingTimeWindows
I am trying to write a demo code with Flink Data stream. I create source with fromElement. I process data with *ProcessingTimeWindows. But I cannot get any event in the window.

```<code>public class OrderSummaryJob {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<OrderItem> orderItemDataStream = env.fromElements(
                "B001 Jack 1671537515000 3",
                "B002 Jack 1671537515000 2",
                "B001 Tom 1671537518000 1",
                "B003 Jason 1671537519000 5",
                "B002 Jason 1671537519000 7",
                "B005 Jason 1671537519000 -1",
                "B001 Green 1671537539000 4"
        ).flatMap(new OrderItemFlatMapFunction())
                .filter(new OrderItemFilterFunction());

        orderItemDataStream.print();

        /*
             The following code seemed cannot be run with  *ProcessingTimeWindows
        */

        DataStream<OrderSkuQty> orderSkuQtyDataStream = orderItemDataStream
                .keyBy(OrderItem::getSkuNo)
                //.window(TumblingProcessingTimeWindows.of(Time.seconds(30)))
                .window(SlidingProcessingTimeWindows.of(Time.seconds(60),Time.seconds(60)))
                .process(new OrderSkuQtyProcessWindowFunction());

        orderSkuQtyDataStream.print();

        env.execute("Order Item");
    }

}

</code>```

The output show that the process functions are never called.

I try to use EventTimeWindows then I can have the window work, but when I use *ProcessingTimeWindows, it cannot work.

Body:
I am trying to write a demo code with Flink Data stream. I create source with fromElement. I process data with *ProcessingTimeWindows. But I cannot get any event in the window.

public class OrderSummaryJob {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<OrderItem> orderItemDataStream = env.fromElements(
                "B001 Jack 1671537515000 3",
                "B002 Jack 1671537515000 2",
                "B001 Tom 1671537518000 1",
                "B003 Jason 1671537519000 5",
                "B002 Jason 1671537519000 7",
                "B005 Jason 1671537519000 -1",
                "B001 Green 1671537539000 4"
        ).flatMap(new OrderItemFlatMapFunction())
                .filter(new OrderItemFilterFunction());

        orderItemDataStream.print();

        /*
             The following code seemed cannot be run with  *ProcessingTimeWindows
        */

        DataStream<OrderSkuQty> orderSkuQtyDataStream = orderItemDataStream
                .keyBy(OrderItem::getSkuNo)
                //.window(TumblingProcessingTimeWindows.of(Time.seconds(30)))
                .window(SlidingProcessingTimeWindows.of(Time.seconds(60),Time.seconds(60)))
                .process(new OrderSkuQtyProcessWindowFunction());

        orderSkuQtyDataStream.print();

        env.execute("Order Item");
    }

}

The output show that the process functions are never called.

I try to use EventTimeWindows then I can have the window work, but when I use *ProcessingTimeWindows, it cannot work.


问:
Reddit Redgifs downloading
I completed a part of a python script for downloading all images from a reddit users posts and also go thru redgifs and download the videos from there.

But I can't get the redgifs part to work, I Tried all kinds of libraries to get it, but wasn't able to. It basically asks for the username, then a directory where to save it and launches from there.

```<code>import os
import re
import requests
from redgifdl import download
from tkinter import filedialog
from tkinter import Tk
from tqdm import tqdm

def download_image(url, save_dir):
    response = requests.get(url, stream=True)
    file_size = int(response.headers.get("Content-Length", 0))
    filename = os.path.join(save_dir, url.split("/")[-1])
    progress = tqdm(response.iter_content(1024), f"Downloading {filename}", total=file_size, unit="B", unit_scale=True, unit_divisor=1024)
    with open(filename, "wb") as f:
        for data in progress:
            f.write(data)
            progress.update(len(data))

def download_video(url, save_dir):
    try:
        # download the video using the redgifdl library
        download.url_file(url, save_dir)
    except Exception as e:
        # print the error message
        print(f"Error downloading video: {e}")

def download_images_for_user(user, save_dir):
    after = None
    count = 0

    while True:
        # get the current batch of posts from the user
        params = {"limit": 100}
        if after:
            params["after"] = after
        url = f"https://www.reddit.com/user/{user}/submitted.json"
        headers = {"User-Agent": "MyBot/0.0.1"}
        response = requests.get(url, params=params, headers=headers)

        # exit the loop if there are no more posts to download
        if not response.json()["data"]["children"]:
            break

        # download the images and videos from the current batch of posts
        for child in response.json()["data"]["children"]:
            # check if the post is an image
            if child["data"]["url"].endswith((".jpg", ".png", ".gif")):
                # download the image
                download_image(child["data"]["url"], save_dir)
                count += 1
            # check if the post is a video from redgifs.com
            elif "redgifs.com" in child["data"]["url"]:
                # download the video
                download_video(child["data"]["url"], save_dir)
                count += 1

        after = response.json()["data"]["after"]

    print(f"Finished downloading {count} images and videos for user {user}")

def main():
    user = input("Enter the Reddit user name: ")

    root = Tk()
    root.withdraw()
    save_dir = filedialog.askdirectory(initialdir=os.getcwd(), title="Select save directory")

    download_images_for_user(user, save_dir)

if __name__ == "__main__":
    main()
</code>```

Title: Reddit Redgifs downloading

Body:
I completed a part of a python script for downloading all images from a reddit users posts and also go thru redgifs and download the videos from there.

But I can't get the redgifs part to work, I Tried all kinds of libraries to get it, but wasn't able to. It basically asks for the username, then a directory where to save it and launches from there.

import os
import re
import requests
from redgifdl import download
from tkinter import filedialog
from tkinter import Tk
from tqdm import tqdm

def download_image(url, save_dir):
    response = requests.get(url, stream=True)
    file_size = int(response.headers.get("Content-Length", 0))
    filename = os.path.join(save_dir, url.split("/")[-1])
    progress = tqdm(response.iter_content(1024), f"Downloading {filename}", total=file_size, unit="B", unit_scale=True, unit_divisor=1024)
    with open(filename, "wb") as f:
        for data in progress:
            f.write(data)
            progress.update(len(data))

def download_video(url, save_dir):
    try:
        # download the video using the redgifdl library
        download.url_file(url, save_dir)
    except Exception as e:
        # print the error message
        print(f"Error downloading video: {e}")

def download_images_for_user(user, save_dir):
    after = None
    count = 0

    while True:
        # get the current batch of posts from the user
        params = {"limit": 100}
        if after:
            params["after"] = after
        url = f"https://www.reddit.com/user/{user}/submitted.json"
        headers = {"User-Agent": "MyBot/0.0.1"}
        response = requests.get(url, params=params, headers=headers)

        # exit the loop if there are no more posts to download
        if not response.json()["data"]["children"]:
            break

        # download the images and videos from the current batch of posts
        for child in response.json()["data"]["children"]:
            # check if the post is an image
            if child["data"]["url"].endswith((".jpg", ".png", ".gif")):
                # download the image
                download_image(child["data"]["url"], save_dir)
                count += 1
            # check if the post is a video from redgifs.com
            elif "redgifs.com" in child["data"]["url"]:
                # download the video
                download_video(child["data"]["url"], save_dir)
                count += 1

        after = response.json()["data"]["after"]

    print(f"Finished downloading {count} images and videos for user {user}")

def main():
    user = input("Enter the Reddit user name: ")

    root = Tk()
    root.withdraw()
    save_dir = filedialog.askdirectory(initialdir=os.getcwd(), title="Select save directory")

    download_images_for_user(user, save_dir)

if __name__ == "__main__":
    main()


问:
Loop-Generated Tkinter buttons all generate the value when passed through a function
The following code is my first attempt at a Tkinter program- please go easy. Upon running the code it is meant to be like a Reminders app. I'm having trouble with it however, upon running the program a windows is generated with the option to load from the accompanying TXT file (I've used them before).

After clicking on the button, more buttons are meant to be loaded. These buttons do load but they instead each contain the same value (despite the item loop assigning them each different values)- and they pass this value to the described function. They are meant to have their own value, corresponding to the amount of 'tasks' or rather spaces in the 'cache' that exist eg; each task has it's own unique value.

Button command is surrounded by asterix.

`

```<code>import tkinter
from tkinter import *
from tkinter import ttk

exit_command = False
version = 0.1
taskstats = []
lineread = 'a'
line = []
cache = []
buttonlist = []
taskpadtop = 50
windowwidth = 200
windowheight = 400
window3 = 10
window4 = 10
counter_ID = 0
save_loaded = False

#
# def add_at_end():
#     with open('tasker.txt', 'w') as file:
#         file.write('TEST')
#         file.close()

def tick_task(number):
    button_name = buttonlist[number]
    button_name.configure(text='clicked')

def load_file():
    global counter_ID
    if len(cache) == 0:
        with open('tasker.txt', 'r') as file:
            save_loaded = True
            alllines = file.readlines()
            for item in alllines:
                evtit, evdisc, evstat = item.split()
                finalline = [evtit, evdisc, evstat]
                cache.append(finalline)

            file.close()

    else:

        print('Error, already loaded savedata')
        save_loaded = False

    if save_loaded:
        # Each 'item' will contain a task, of course.

        for item in range(0, len(cache)):
            counter_ID = counter_ID + 1
            # So yes, stick a label for each one!
            txt = Label(text=cache[item][0])
            # Place that label in X=0, and then space them by 100 pixels
            txt.place(x=0, y=(item * 50) + taskpadtop)
**
confirm = Button(window, text='Task {} Complete'.format(item + 1), padx=30, command=lambda: tick_task(item))****
            confirm.grid(column=3)
            buttonlist.append(confirm)
            print(buttonlist)
            # tickvalue=IntVar()
            # cache[2].append(tickvalue)
            # taskstatus = Checkbutton(window, name=str(item),variable=tickvalue)
            # print(tickvalue)
            # # command = lambda: task_change(counter_ID)
            # taskstatus.place(x=30, y=(item * 50) + taskpadtop)

window = Tk()
# window.grid()
# window.columnconfigure(3)

btn = Radiobutton(window, text="Load from internal TXT!", fg='blue', command=load_file)
btn.grid(column=0)
btn.place(x=0, y=0)

window.title('Tasker {}'.format(version))
window.geometry("{}x{}+{}+{}".format(windowwidth, windowheight, window3, window4))

window.mainloop()

</code>```

`

I was expecting that the buttons would each individually pass their own unique value (numeric from 0 upwards) to the function in tkinters command argument.

I have looked at tutorials, using tkinters own button naming scheme and appending to a list etc. None have worked...

Body:
The following code is my first attempt at a Tkinter program- please go easy. Upon running the code it is meant to be like a Reminders app. I'm having trouble with it however, upon running the program a windows is generated with the option to load from the accompanying TXT file (I've used them before).

After clicking on the button, more buttons are meant to be loaded. These buttons do load but they instead each contain the same value (despite the item loop assigning them each different values)- and they pass this value to the described function. They are meant to have their own value, corresponding to the amount of 'tasks' or rather spaces in the 'cache' that exist eg; each task has it's own unique value.

Button command is surrounded by asterix.

`

import tkinter
from tkinter import *
from tkinter import ttk

exit_command = False
version = 0.1
taskstats = []
lineread = 'a'
line = []
cache = []
buttonlist = []
taskpadtop = 50
windowwidth = 200
windowheight = 400
window3 = 10
window4 = 10
counter_ID = 0
save_loaded = False

#
# def add_at_end():
#     with open('tasker.txt', 'w') as file:
#         file.write('TEST')
#         file.close()

def tick_task(number):
    button_name = buttonlist[number]
    button_name.configure(text='clicked')

def load_file():
    global counter_ID
    if len(cache) == 0:
        with open('tasker.txt', 'r') as file:
            save_loaded = True
            alllines = file.readlines()
            for item in alllines:
                evtit, evdisc, evstat = item.split()
                finalline = [evtit, evdisc, evstat]
                cache.append(finalline)

            file.close()

    else:

        print('Error, already loaded savedata')
        save_loaded = False

    if save_loaded:
        # Each 'item' will contain a task, of course.

        for item in range(0, len(cache)):
            counter_ID = counter_ID + 1
            # So yes, stick a label for each one!
            txt = Label(text=cache[item][0])
            # Place that label in X=0, and then space them by 100 pixels
            txt.place(x=0, y=(item * 50) + taskpadtop)
**
confirm = Button(window, text='Task {} Complete'.format(item + 1), padx=30, command=lambda: tick_task(item))****
            confirm.grid(column=3)
            buttonlist.append(confirm)
            print(buttonlist)
            # tickvalue=IntVar()
            # cache[2].append(tickvalue)
            # taskstatus = Checkbutton(window, name=str(item),variable=tickvalue)
            # print(tickvalue)
            # # command = lambda: task_change(counter_ID)
            # taskstatus.place(x=30, y=(item * 50) + taskpadtop)

window = Tk()
# window.grid()
# window.columnconfigure(3)

btn = Radiobutton(window, text="Load from internal TXT!", fg='blue', command=load_file)
btn.grid(column=0)
btn.place(x=0, y=0)

window.title('Tasker {}'.format(version))
window.geometry("{}x{}+{}+{}".format(windowwidth, windowheight, window3, window4))

window.mainloop()

`

I was expecting that the buttons would each individually pass their own unique value (numeric from 0 upwards) to the function in tkinters command argument.

I have looked at tutorials, using tkinters own button naming scheme and appending to a list etc. None have worked...


问:
ESP32: Attaching an interrupt directly to system time
Currently I'm setting a separate hardware timer to the system time periodically to trigger timed interrupts. It's working fine but for elegance sake, but I wondered if it was possible to attach an interrupt directly to the system time

The events are pretty fast: one every 260 microseconds

ESP32 has a few clocks used for system time. The default full power clock is an 80 MHz called APB_CLK. But even the slow RTC clock has 6.6667 μs resolution. (Documentation here: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html)

I have a GPS module that I use to update the system time periodically using adjtime(3). The advantage of that being that it gradually adjusts the system time monotonically. Also system time calls are thread safe

I'm using the Arduino IDE, so my knowledge of accessing registers and interrupts directly is poor. Here's a semi boiled down version of what I'm doing. Bit banging a synchronized digital signal. Rotating in 160 bit pages that are prepped from the other core. It's not all of my code, so something not important might be missing:

```<code>#define CPU_SPEED 40

hw_timer_t* timer = NULL;

PageData pages[2];
PageData* timerCurrentPage = &pages[0];
PageData* loopCurrentPage = &pages[1];

TaskHandle_t prepTaskHandle;

volatile int bitCount = 0;

void IRAM_ATTR onTimer() {
    int level = timerCurrentPage->data[bitCount];
    dac_output_voltage(DAC_CHANNEL_1, level?high:low);
    bitCount++;

    if(bitCount<160) {
        timerAlarmWrite(timer, (timerCurrentPage->startTick+timerCurrentPage->ticksPerPage*bitCount), false);
    } else {
        if(timerCurrentPage == &pages[0]) timerCurrentPage = &pages[1];
        else timerCurrentPage = &pages[0];

        bitCount = 0;

        timerAlarmWrite(timer, (timerCurrentPage->startTick), false);
        vTaskResume(prepTaskHandle);
    }
}

uint64_t nowTick() {
    timeval timeStruct;
    gettimeofday(&timeStruct, NULL);
    uint64_t result = (uint64_t)timeStruct.tv_sec*1000000UL + (uint64_t)timeStruct.tv_usec;
    return result;
}

void gpsUpdate(uint64_t micros) {
    int64_t now = nowTick();
    int64_t offset = micros - now;

    timeval adjustStruct = {0,offset};
    adjtime(&adjustStruct,NULL);
}

void setup() {
    setCpuFrequencyMhz(CPU_SPEED);
    timer = timerBegin(0, CPU_SPEED, true);

    timerWrite(timer, nowTick());

    timerAttachInterrupt(timer, &onTimer, true);

    setPage(&pages[0]);

    xTaskCreatePinnedToCore(
             prepLoop,  /* Task function. */
             "Prep Task",    /* name of task. */
             10000,      /* Stack size of task */
             NULL,       /* parameter of the task */
             1,          /* priority of the task */
             &prepTaskHandle,     /* Task handle to keep track of created task */
             1);         /* pin task to core 0 */

    timerAlarmWrite(timer, (timerCurrentPage->startTick), false);
}

//On Core 1
void prepLoop() {
    while(1) {
        vTaskSuspend(NULL); //prepTaskHandle

        timerWrite(timer, nowTick());

        if(loopCurrentPage == &pages[0]) loopCurrentPage = &pages[1];
        else loopCurrentPage = &pages[0];

        setPage(loopCurrentPage);
    }
}
</code>```

Body:
Currently I'm setting a separate hardware timer to the system time periodically to trigger timed interrupts. It's working fine but for elegance sake, but I wondered if it was possible to attach an interrupt directly to the system time

The events are pretty fast: one every 260 microseconds

ESP32 has a few clocks used for system time. The default full power clock is an 80 MHz called APB_CLK. But even the slow RTC clock has 6.6667 μs resolution. (Documentation here: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/system_time.html)

I have a GPS module that I use to update the system time periodically using adjtime(3). The advantage of that being that it gradually adjusts the system time monotonically. Also system time calls are thread safe

I'm using the Arduino IDE, so my knowledge of accessing registers and interrupts directly is poor. Here's a semi boiled down version of what I'm doing. Bit banging a synchronized digital signal. Rotating in 160 bit pages that are prepped from the other core. It's not all of my code, so something not important might be missing:

#define CPU_SPEED 40

hw_timer_t* timer = NULL;

PageData pages[2];
PageData* timerCurrentPage = &pages[0];
PageData* loopCurrentPage = &pages[1];

TaskHandle_t prepTaskHandle;

volatile int bitCount = 0;

void IRAM_ATTR onTimer() {
    int level = timerCurrentPage->data[bitCount];
    dac_output_voltage(DAC_CHANNEL_1, level?high:low);
    bitCount++;

    if(bitCount<160) {
        timerAlarmWrite(timer, (timerCurrentPage->startTick+timerCurrentPage->ticksPerPage*bitCount), false);
    } else {
        if(timerCurrentPage == &pages[0]) timerCurrentPage = &pages[1];
        else timerCurrentPage = &pages[0];

        bitCount = 0;

        timerAlarmWrite(timer, (timerCurrentPage->startTick), false);
        vTaskResume(prepTaskHandle);
    }
}

uint64_t nowTick() {
    timeval timeStruct;
    gettimeofday(&timeStruct, NULL);
    uint64_t result = (uint64_t)timeStruct.tv_sec*1000000UL + (uint64_t)timeStruct.tv_usec;
    return result;
}

void gpsUpdate(uint64_t micros) {
    int64_t now = nowTick();
    int64_t offset = micros - now;

    timeval adjustStruct = {0,offset};
    adjtime(&adjustStruct,NULL);
}

void setup() {
    setCpuFrequencyMhz(CPU_SPEED);
    timer = timerBegin(0, CPU_SPEED, true);

    timerWrite(timer, nowTick());

    timerAttachInterrupt(timer, &onTimer, true);

    setPage(&pages[0]);

    xTaskCreatePinnedToCore(
             prepLoop,  /* Task function. */
             "Prep Task",    /* name of task. */
             10000,      /* Stack size of task */
             NULL,       /* parameter of the task */
             1,          /* priority of the task */
             &prepTaskHandle,     /* Task handle to keep track of created task */
             1);         /* pin task to core 0 */

    timerAlarmWrite(timer, (timerCurrentPage->startTick), false);
}

//On Core 1
void prepLoop() {
    while(1) {
        vTaskSuspend(NULL); //prepTaskHandle

        timerWrite(timer, nowTick());

        if(loopCurrentPage == &pages[0]) loopCurrentPage = &pages[1];
        else loopCurrentPage = &pages[0];

        setPage(loopCurrentPage);
    }
}


问:
How to set up a cron job for cypress test with page objects
I want to set up a cron job for a cypress test that contains page objects. However, it's giving me an error. When I set up the job for a file with no page objects (spec.js) it works.

This is the code, see that the test file has multiple page objects as enclosed in rectangle no 2:

This is the error I got:

I believe this means that the page objects are not being read however it works when I run it in cypress.


问:
AWS VM-Import of hardened Image
We successfully converted the VMDK file to AWS AMI image and ran in AWS EC2 service.

VMDK file is a hardened image, only a few pre-defined credentials (username & password) were allowed to log in.

Wondering, how AWS Image Import Service could push the SSH-KEY (Public key) to newly created EC2 instance, which AWS have no clue on Username and password. And No AWS-related agents/services like AWS SDK or System Managers are in the VM.

OS is RHEL 7

Summarising the question as,
On EC2 instance creation, On KEY_PAIR attachment for SSH login, how does this public key file get pushed to that VM?

Title: AWS VM-Import of hardened Image


问:
why the function method inside of the object doesnt work?
so im doing a object exercise about 2 guys and i have to calculte their BMI.
my code is like this:

```<code>  const mark = {
  firstName: "Mark",
  lastName: "Miller",
  Mass: "78 kg",
  Height: "1.69 m",

  calcBMI: function () {
    return (
      this.Mass / this.Height ** 2 - this.Mass / (this.Height * this.Height)
    );
  },
};

const john = {
  firstName: "John",
  lastName: "Smith",
  Mass: "92 kg",
  Height: "1.95 m",

  calcBMI: function () {
    return (
      this.Mass / this.Height ** 2 - this.Mass / (this.Height * this.Height)
    );
  },
};

if (john.calcBMI > mark.calcBMI) {
  console.log(
    `${john.firstName} has a BMI of ${john.calcBMI} which is higher than ${
      mark.firstName
    } who has a BMI of ${mark.calcBMI()}`
  );
} else {
  console.log(
    `${mark.firstName} has a BMI of ${mark.calcBMI} which is higher than ${
      john.firstName
    } who has a BMI of ${john.calcBMI()}`
  );
}
</code>```

the problem is the "this"?
im having a problem with calcBMI function which its not doing the calculations of BMI

Body:
so im doing a object exercise about 2 guys and i have to calculte their BMI.
my code is like this:

  const mark = {
  firstName: "Mark",
  lastName: "Miller",
  Mass: "78 kg",
  Height: "1.69 m",

  calcBMI: function () {
    return (
      this.Mass / this.Height ** 2 - this.Mass / (this.Height * this.Height)
    );
  },
};

const john = {
  firstName: "John",
  lastName: "Smith",
  Mass: "92 kg",
  Height: "1.95 m",

  calcBMI: function () {
    return (
      this.Mass / this.Height ** 2 - this.Mass / (this.Height * this.Height)
    );
  },
};

if (john.calcBMI > mark.calcBMI) {
  console.log(
    `${john.firstName} has a BMI of ${john.calcBMI} which is higher than ${
      mark.firstName
    } who has a BMI of ${mark.calcBMI()}`
  );
} else {
  console.log(
    `${mark.firstName} has a BMI of ${mark.calcBMI} which is higher than ${
      john.firstName
    } who has a BMI of ${john.calcBMI()}`
  );
}

the problem is the "this"?
im having a problem with calcBMI function which its not doing the calculations of BMI


问:
API Automation - signer information does not match signer information of other classes in the same package
enter image description hereWhile executing the POST API endpoint am getting "java.lang.SecurityException": class "org.hamcrest.Matchers"'s signer information does not match signer information of other classes in the same package.

Anyone solution for this issue

enter image description here


问:
Reducing time querying Scalikejdbc
I own an amount about 80 000 rows on 3 tables of database, every time I execute my code, it can take 4-5 minutes to display the result. Do you know if it's possible to reduce this time by adding whatever ?

```<code>  def findAirportAndRunwayByCountry(code: String)(implicit session : DBSession = AutoSession) : List[(Airports,Runway)] =    {
    val (c, a, r) = (Country.syntax("c"), Airports.syntax("a"), Runway.syntax("r"))
    withSQL { select.from(Airports as a).innerJoin(Runway as r).on(r.ID, a.ID).innerJoin(Country as c).on(c.Code, a.Country).where.eq(c.Code, code).or.like(c.Name, code + "%") }.map(rs => (Airports(rs),Runway(rs))).list.apply()
  }
</code>```

This is the code taking the time described (~4-5 mins)

Title: Reducing time querying Scalikejdbc

Body:
I own an amount about 80 000 rows on 3 tables of database, every time I execute my code, it can take 4-5 minutes to display the result. Do you know if it's possible to reduce this time by adding whatever ?

  def findAirportAndRunwayByCountry(code: String)(implicit session : DBSession = AutoSession) : List[(Airports,Runway)] =    {
    val (c, a, r) = (Country.syntax("c"), Airports.syntax("a"), Runway.syntax("r"))
    withSQL { select.from(Airports as a).innerJoin(Runway as r).on(r.ID, a.ID).innerJoin(Country as c).on(c.Code, a.Country).where.eq(c.Code, code).or.like(c.Name, code + "%") }.map(rs => (Airports(rs),Runway(rs))).list.apply()
  }

This is the code taking the time described (~4-5 mins)


问:
ViteJS Minify InnerHTML
I'm currently running Native Javascript for my application w/o any frameworks. And upon running npm run build
It minified everything except for all of my html code which contains lot of whitespace.
Is there a way to minified it w/o any whitespaces?

Here's the configuration I have in my vite.config.js

```<code>

export default defineConfig({
    build: {
        manifest: true,
        rollupOptions: {
            input: [
                //css/js files
            ],
        },
        target: 'esnext',
    },
    base: '/dist/', //base public path for build
    resolve: {
        alias: {
            '@modules': path.resolve(__dirname, 'assets/revamp/js/modules')
        }
    }
});
</code>```

Title: ViteJS Minify InnerHTML

Body:
I'm currently running Native Javascript for my application w/o any frameworks. And upon running npm run build
It minified everything except for all of my html code which contains lot of whitespace.
Is there a way to minified it w/o any whitespaces?

Here's the configuration I have in my vite.config.js

export default defineConfig({
    build: {
        manifest: true,
        rollupOptions: {
            input: [
                //css/js files
            ],
        },
        target: 'esnext',
    },
    base: '/dist/', //base public path for build
    resolve: {
        alias: {
            '@modules': path.resolve(__dirname, 'assets/revamp/js/modules')
        }
    }
});


问:
How to make a collection for users bookmarks in Supabase?
I previously made a blog using Firebase where users could log in and bookmark posts. Now I'm transitioning to Supabase and I'd like to know how I can make a collection for users bookmarks. In Firebase I used to create a collection for every user bookmarks like this:

Root Collection (users) > Documents (user_uid) > Collection (bookmarks) > Documents (post_id)

How can I do this in Supabase postgresql?


问:
Spreadsheet formula to rank and assign values based on certain conditions
I have 2 tables. Table 1 is the given data. It contains a maximum of 8 possible combinations of the following items (A,B,C,D,E,AB,BC,CD,DE,ABC,BCD,CDE,null). Table 2 contains the resulting values which can either be 1 or 0. See screenshot for details.

Condition:
In filling the values in Table 2, priority is given to A, then B, then C, then D, and lastly to E. For example, if the column data contain A,AB,CDE then the value of 1 will be assigned to A, B and C only. D and E will be 0. If the column data contain C,C,CDE then the value of 1 will be assigned to C and D only and A, B, and E will be 0.

I tried using conditional statements such as IFS, COUNTIF, and * wildcard but it doesn't seem to capture all possible scenarios. Is this possible using a spreadsheet formula? Thank you in advance.


问:
Issue in Checkbox
Hai I have a code below

```<code><div class="col-md-3">
 <div class="form-group">
 <label class="control-label">Status <span class="text-danger">*</span></label>
<div class="can-toggle">
@Html.CheckBoxFor(m=>m.IsActive)
<label for="IsActive">
<div class="can-toggle__switch" data-checked="InActive" data-unchecked="Active"></div>
 </label>
</div>
</div>
</div>
</code>```

i will send "IsActive" always true from controller so label will be active
but when i toggle label still "IsActive" will be true

Title: Issue in Checkbox

Body:
Hai I have a code below

 Status *

@Html.CheckBoxFor(m=>m.IsActive)

i will send "IsActive" always true from controller so label will be active
but when i toggle label still "IsActive" will be true


问:
How can I create with openssl, a certified to enable Tls 1.2 for SQL Server 2019?
I am working how to enable tls 1.2 for sql server 2019. I want create csr following the Microsoft Documentation. I need CSR to send to my CA:

The certificate must be meant for server authentication. This requires the Enhanced Key Usage property of the certificate to
specify Server Authentication (1.3.6.1.5.5.7.3.1).

The certificate must be created using the KeySpec option of AT_KEYEXCHANGE. This requires a legacy certificate. Usually, the
certificate's key usage property (KEY_USAGE) will also include key
encipherment (CERT_KEY_ENCIPHERMENT_KEY_USAGE) and a digital
signature (CERT_DIGITAL_SIGNATURE_KEY_USAGE).

The Subject property of the certificate must indicate that the common name (CN) is the same as the host name or fully qualified
domain name (FQDN) of the server computer. When using the host name,
the DNS suffix must be specified in the certificate. If SQL Server
is running on a failover cluster, the common name must match the
host name or FQDN of the virtual server, and the certificates must
be provisioned on all nodes in the failover cluster. For example, if
you have a two-node cluster, with nodes named test1..com and test2..com, and you have a virtual
server named virtsql, you need to install a certificate for
virtsql..com on both nodes. For more information on
SQL clusters, see Before Installing Failover Clustering.

The Subject Alternate Name should include all the names your clients may use to connect to a SQL Server instance.

Info Ref
Microsoft requirements for Certified

I tried with the next.cnf configuriation

FQDN=subdominio.dominio.com.mx

[ new_oids ]

tsa_policy = 2.5.29.37

[ req ] default_bits = 2048 default_keyfile = llave.key
distinguished_name = req_distinguished_name attributes =
req_attributes default_days = 1095 x509_extensions= v3_ca

[ req_distinguished_name ]  countryName = MX stateOrProvidenceName =
CDMX localityName = CDMX organizationName = Empresa SA de CV
organizationalUnitName = dirTic commonName= server emailAddress=
correoFalso@dominio.com.mx

[ v3_req ]

certificate= request basicConstrains = CA:FALSE keyUsage=
digitalSignature, KeyEncipherment extendedKeyUsage= serverAuth

[ v3_ca ]

using the next command

```<code>req -new -config myserver_auth.cnf -keyout myserver.key -out myserver.csr
</code>```

but dont work, my .cnf is badly done

How i must crete  .cnf File or the correct command syntax for create the certification?

Body:
I am working how to enable tls 1.2 for sql server 2019. I want create csr following the Microsoft Documentation. I need CSR to send to my CA:

The certificate must be meant for server authentication. This requires the Enhanced Key Usage property of the certificate to
specify Server Authentication (1.3.6.1.5.5.7.3.1).

The certificate must be created using the KeySpec option of AT_KEYEXCHANGE. This requires a legacy certificate. Usually, the
certificate's key usage property (KEY_USAGE) will also include key
encipherment (CERT_KEY_ENCIPHERMENT_KEY_USAGE) and a digital
signature (CERT_DIGITAL_SIGNATURE_KEY_USAGE).

The Subject property of the certificate must indicate that the common name (CN) is the same as the host name or fully qualified
domain name (FQDN) of the server computer. When using the host name,
the DNS suffix must be specified in the certificate. If SQL Server
is running on a failover cluster, the common name must match the
host name or FQDN of the virtual server, and the certificates must
be provisioned on all nodes in the failover cluster. For example, if
you have a two-node cluster, with nodes named test1..com and test2..com, and you have a virtual
server named virtsql, you need to install a certificate for
virtsql..com on both nodes. For more information on
SQL clusters, see Before Installing Failover Clustering.

The Subject Alternate Name should include all the names your clients may use to connect to a SQL Server instance.

Info Ref
Microsoft requirements for Certified

I tried with the next.cnf configuriation

FQDN=subdominio.dominio.com.mx

[ new_oids ]

tsa_policy = 2.5.29.37

[ req ] default_bits = 2048 default_keyfile = llave.key
distinguished_name = req_distinguished_name attributes =
req_attributes default_days = 1095 x509_extensions= v3_ca

[ req_distinguished_name ]  countryName = MX stateOrProvidenceName =
CDMX localityName = CDMX organizationName = Empresa SA de CV
organizationalUnitName = dirTic commonName= server emailAddress=
correoFalso@dominio.com.mx

[ v3_req ]

certificate= request basicConstrains = CA:FALSE keyUsage=
digitalSignature, KeyEncipherment extendedKeyUsage= serverAuth

[ v3_ca ]

using the next command

req -new -config myserver_auth.cnf -keyout myserver.key -out myserver.csr

but dont work, my .cnf is badly done

How i must crete  .cnf File or the correct command syntax for create the certification?


问:
Why is this function causing a compiler error on trading view?
I'm not a huge fan of being told answers but can anyone please help me deduce what the problem here is? This is a function in a trading view library script and it results in an error at compile time due to the return statement. The compiler gives the error: '_counter' is not a valid type keyword in variable declaration. As much as I appreciate it, if someone answers this, please tell me how you came to your conclusion
`

```<code>// @function Counts how many candles are below the MA
// @param int _lookback The lookback period to look back over
// @param float _ma The moving average to check
// @returns The bar count of how many recent bars are below the MA
export barsBelowMA(int _lookback, float _ma) =>
    _counter = 0
    for i = 1 to _lookback by 1
        if close[i] < _ma
            _counter := _counter + 1
    _counter // Return number of recent bars below MA - Problem returning this value
</code>```

`

As far as I can tell the syntax is correct, and the logic makes sense. No matter what I do, returning the "_counter" variable always results in a compiler error.

Body:
I'm not a huge fan of being told answers but can anyone please help me deduce what the problem here is? This is a function in a trading view library script and it results in an error at compile time due to the return statement. The compiler gives the error: '_counter' is not a valid type keyword in variable declaration. As much as I appreciate it, if someone answers this, please tell me how you came to your conclusion
`

// @function Counts how many candles are below the MA
// @param int _lookback The lookback period to look back over
// @param float _ma The moving average to check
// @returns The bar count of how many recent bars are below the MA
export barsBelowMA(int _lookback, float _ma) =>
    _counter = 0
    for i = 1 to _lookback by 1
        if close[i] < _ma
            _counter := _counter + 1
    _counter // Return number of recent bars below MA - Problem returning this value

`

As far as I can tell the syntax is correct, and the logic makes sense. No matter what I do, returning the "_counter" variable always results in a compiler error.


问:
Why range based for loop doesn't work with iterator, which points to container?
I have this code and it doesn't compile. It has an error:

cannot assign to variable 'value' with const-qualified type 'const int &'

value = 5;

```<code>#include <vector>
#include <set>

int main() {
    std::vector<std::set<int>> data;
    for (auto it = data.begin(); it != data.end(); ++it) {
        auto& inner = *it;
        for (auto& value: inner) {
            value = 5;
        }
    }
    return 0;
}
</code>```

I thought inner is std::set<int>& and value would be int& in this case. Could someone explain this case?

Body:
I have this code and it doesn't compile. It has an error:

cannot assign to variable 'value' with const-qualified type 'const int &'

value = 5;

#include <vector>
#include <set>

int main() {
    std::vector<std::set<int>> data;
    for (auto it = data.begin(); it != data.end(); ++it) {
        auto& inner = *it;
        for (auto& value: inner) {
            value = 5;
        }
    }
    return 0;
}

I thought inner is std::set<int>& and value would be int& in this case. Could someone explain this case?


问:
OIDC and OAUTH2 access tokens with additional info
Here is what I have :

ASP.NET Framework 4.8 server side web app which authenticates users with Azure AD via OIDC.

Native Android app which also authenticates the users with Azure AD via OIDC.

ASP.NET Framework 4.8 Web API which exposes API's for use by the Android app (the Web API is only used by the mobile app)

The web app authenticates with OIDC and when valid, adds additional claims to the auth ticket for the session (obtained from the database for the user).
So the additional claims are available to all pages in the web app.

Now, the mobile app also authenticates the users with OIDC and all API requests will receive the associated access token.
This works great, but like the web app, I need to get additional claims from the database for the user.

I am trying to find a way to avoid doing the database calls on each API request.
Ideally, the claims I need would be retrieved once from the database and then stored in the access token at login and then would be available in each API request.
But not sure if this is possible since the access token is obtained from the mobile app.

Any suggestions on how to handle this kind of situation? Currently on each API request, when the access token is validated I get the additional info from the database and store the info as claims in the ticket but obvously, this is not persistent and will happen on each API request.


问:
Facebook Pages Access Token (multiple) to a single Webhook
I am trying to add about 10 different Pages Access Tokens as ".env" in order to send the "verify token" to a single webhook, because all pages will use the same Facebook App.

I am using a Heroku "Node.JS" app and my goal is replicating the same I managed to deploy for a single page, with a single Page Acees Token, recalled from an .env file.

Is there any module to do that?

Any guidance will be super appreciated.

Thanks in Advance guys!

When I do it using Page Access Token recalling one .env, I do it like this:

```<code>const MY_VERIFY_TOKEN = process.env.MY_VERIFY_TOKEN;
</code>```

Then I recall it like this:

```<code>let getWebHook = (req, res) => {
// Your verify token. Should be a random string.
let VERIFY_TOKEN = MY_VERIFY_TOKEN;
</code>```

Body:
I am trying to add about 10 different Pages Access Tokens as ".env" in order to send the "verify token" to a single webhook, because all pages will use the same Facebook App.

I am using a Heroku "Node.JS" app and my goal is replicating the same I managed to deploy for a single page, with a single Page Acees Token, recalled from an .env file.

Is there any module to do that?

Any guidance will be super appreciated.

Thanks in Advance guys!

When I do it using Page Access Token recalling one .env, I do it like this:

const MY_VERIFY_TOKEN = process.env.MY_VERIFY_TOKEN;

Then I recall it like this:

let getWebHook = (req, res) => {
// Your verify token. Should be a random string.
let VERIFY_TOKEN = MY_VERIFY_TOKEN;


问:
Python Find Duplicates - Keep First - BUT reference first in duplicates. - Categorization
This would be an "enhanced" version of the duplicated function.

I want to do the duplicated function, but then reference the "keep" (duplicate = False) record in the duplicates.

This is what I use currently:

 final_data_merge['duplicate'] = final_data_merge.duplicated(subset=['web-main','title'], keep='first').astype(int).astype(str)

I merge this into the dataset as an column called "isduplicate" that acts like a yes/no flag. I need the duplicated records (duplicated = True) to reference the "keep" record as it will have the result of the full processing and results.

For example:
(Using web-main and title)

```<code>.....web-main.....title.........stuff

1... Dog Food.....Purina.......40 Calories

2... Cat Food.....Friskies.....80 Calories

3... Dog Food.....GravyTrain...120 Calories

4... Dog Food.....Purina.......40 Calories ##<-Duplicate Record
</code>```

~

~

Output

```<code>.....web-main.....title.........stuff..........IsDuplicate..........Reference

1... Dog Food.....Purina.......40 Calories.....False................nan

2... Cat Food.....Friskies.....80 Calories.....False................nan

3... Dog Food.....GravyTrain...120 Calories.....False................nan

4... Dog Food.....Purina.......40 Calories.....True................1       ###<- Duplicate Record
</code>```

For reference, I'm doing categorization. As a result, original data is important, but if it's a duplicate, then redundant processing is unnecessary.

This is integral as my dataset updates daily and has many duplicates. After setting the duplicate flag, the system continues in the processing. For example, detecting duplicates would be step 2 of 30....

At the moment, I have 150 days worth of information with 600K records, but only 250K "unique" records. Each day 10-20K new records are added.

If I delete the duplicates I can only do analysis on the entirety, but if I keep the duplicates I can do analysis on the daily level by referencing the "keep" record.

I'm trying to keep this simple without having to flag the duplicates and then do heavy processing to reloop through the entire dataset to find the "keep" key (if possible).

Also:
I use a column called "uniquekey" to assign a uniqueID to each record. I can use either the index value or this uniquekey.

Body:
This would be an "enhanced" version of the duplicated function.

I want to do the duplicated function, but then reference the "keep" (duplicate = False) record in the duplicates.

This is what I use currently:

 final_data_merge['duplicate'] = final_data_merge.duplicated(subset=['web-main','title'], keep='first').astype(int).astype(str)

I merge this into the dataset as an column called "isduplicate" that acts like a yes/no flag. I need the duplicated records (duplicated = True) to reference the "keep" record as it will have the result of the full processing and results.

For example:
(Using web-main and title)

.....web-main.....title.........stuff

1... Dog Food.....Purina.......40 Calories

2... Cat Food.....Friskies.....80 Calories

3... Dog Food.....GravyTrain...120 Calories

4... Dog Food.....Purina.......40 Calories ##<-Duplicate Record

~

~

Output

.....web-main.....title.........stuff..........IsDuplicate..........Reference

1... Dog Food.....Purina.......40 Calories.....False................nan

2... Cat Food.....Friskies.....80 Calories.....False................nan

3... Dog Food.....GravyTrain...120 Calories.....False................nan

4... Dog Food.....Purina.......40 Calories.....True................1       ###<- Duplicate Record

For reference, I'm doing categorization. As a result, original data is important, but if it's a duplicate, then redundant processing is unnecessary.

This is integral as my dataset updates daily and has many duplicates. After setting the duplicate flag, the system continues in the processing. For example, detecting duplicates would be step 2 of 30....

At the moment, I have 150 days worth of information with 600K records, but only 250K "unique" records. Each day 10-20K new records are added.

If I delete the duplicates I can only do analysis on the entirety, but if I keep the duplicates I can do analysis on the daily level by referencing the "keep" record.

I'm trying to keep this simple without having to flag the duplicates and then do heavy processing to reloop through the entire dataset to find the "keep" key (if possible).

Also:
I use a column called "uniquekey" to assign a uniqueID to each record. I can use either the index value or this uniquekey.


问:
Mybatis insert function can not return model id
I used Mybatis. I have Class Form (id, name). I want to insert a new record in the database and get it's Id.

my code is

```<code>Form form = new Form();
form.setName("insertid");
formMapper.insert(form);
Long id = form.getId();
System.out.println("----" + id);
</code>```

but form.getId() is null.
how to fix it? Thanks.

I have inquired a lot of information, but no one else was in the same situation

Body:
I used Mybatis. I have Class Form (id, name). I want to insert a new record in the database and get it's Id.

my code is

Form form = new Form();
form.setName("insertid");
formMapper.insert(form);
Long id = form.getId();
System.out.println("----" + id);

but form.getId() is null.
how to fix it? Thanks.

I have inquired a lot of information, but no one else was in the same situation


问:
Changing/Resize image size from stream only for read or view in picturebox in vb.net
I want to change the size of the image or Resize image from stream only for read in each picturebox to small or not display the original size of the image and then when I double click the image appears with the original size. I'm using "FocusedRowChanged" in DevExpress.XtraGrid because the image data there are thousands hence it makes it a bit slow when moving from row to row gridview.
Is there a best solution or recommendation?

Thanks

```<code>        If Not String.IsNullOrWhiteSpace(filePath1) Then
            PictureEdit1.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath1)), True, False)
            If Not String.IsNullOrWhiteSpace(filePath2) Then
                PictureEdit2.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath2)), True, False)
                If Not String.IsNullOrWhiteSpace(filePath3) Then
                    PictureEdit3.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath3)), True, False)
                    If Not String.IsNullOrWhiteSpace(filePath4) Then
                        PictureEdit4.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath4)), True, False)
                        If Not String.IsNullOrWhiteSpace(filePath5) Then
                            PictureEdit5.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath5)), True, False)
                            If Not String.IsNullOrWhiteSpace(filePath6) Then
                                PictureEdit6.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath6)), True, False)
                            End If
                        End If
                    End If
                End If
            End If
        End If
    Private Sub PictureEditAll_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureEdit1.DoubleClick, PictureEdit2.DoubleClick, PictureEdit3.DoubleClick, PictureEdit4.DoubleClick, PictureEdit5.DoubleClick, PictureEdit6.DoubleClick
        Dim picEdit As PictureEdit = DirectCast(sender, PictureEdit)
        Dim f2 As New Preview(picEdit.Image)
        f2.Show(Me)
    End Sub
</code>```

Body:
I want to change the size of the image or Resize image from stream only for read in each picturebox to small or not display the original size of the image and then when I double click the image appears with the original size. I'm using "FocusedRowChanged" in DevExpress.XtraGrid because the image data there are thousands hence it makes it a bit slow when moving from row to row gridview.
Is there a best solution or recommendation?

Thanks

        If Not String.IsNullOrWhiteSpace(filePath1) Then
            PictureEdit1.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath1)), True, False)
            If Not String.IsNullOrWhiteSpace(filePath2) Then
                PictureEdit2.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath2)), True, False)
                If Not String.IsNullOrWhiteSpace(filePath3) Then
                    PictureEdit3.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath3)), True, False)
                    If Not String.IsNullOrWhiteSpace(filePath4) Then
                        PictureEdit4.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath4)), True, False)
                        If Not String.IsNullOrWhiteSpace(filePath5) Then
                            PictureEdit5.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath5)), True, False)
                            If Not String.IsNullOrWhiteSpace(filePath6) Then
                                PictureEdit6.Image = Image.FromStream(New MemoryStream(File.ReadAllBytes(filePath6)), True, False)
                            End If
                        End If
                    End If
                End If
            End If
        End If
    Private Sub PictureEditAll_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureEdit1.DoubleClick, PictureEdit2.DoubleClick, PictureEdit3.DoubleClick, PictureEdit4.DoubleClick, PictureEdit5.DoubleClick, PictureEdit6.DoubleClick
        Dim picEdit As PictureEdit = DirectCast(sender, PictureEdit)
        Dim f2 As New Preview(picEdit.Image)
        f2.Show(Me)
    End Sub


问:
What is the difference between Press() and PressButton()
In Acumatica frame work there are two methods to make a press.

Can somebody explain what are differences between these two?