text:
Q: pyusb no encuentra dispositivo Estoy tratando de dectar todos los usb conectados a mi pc utilizando pyusb, pero se me presentan los siguientes problemas:
1.- no encuentra todos los dispositivos(no aparece un hdd conectado en el momento de la ejecución)
2.- como puedo obtener el iInterface(para dectectar el nombre del dispositivo) intente:
for cfg in dev:
  print(cfg[0]['iInterface'])

aqui esta el codigo completo
import sys
import usb.core
import usb.util

dev = usb.core.find(find_all=True)

for cfg in dev:
  sys.stdout.write('hex VendedorID='+hex(cfg.idVendor)+'& ProductId'+hex(cfg.idProduct)+'\n')
  print(cfg)

Y esto es lo que devuelve:
hex VendedorID=0x413c& ProductId0x8187
    DEVICE ID 413c:8187 on Bus 000 Address 001 =================
     bLength                :   0x12 (18 bytes)
     bDescriptorType        :    0x1 Device
     bcdUSB                 :  0x200 USB 2.0
     bDeviceClass           :   0xe0 Wireless Controller
     bDeviceSubClass        :    0x1
     bDeviceProtocol        :    0x1
     bMaxPacketSize0        :   0x40 (64 bytes)
     idVendor               : 0x413c
     idProduct              : 0x8187
     bcdDevice              :  0x517 Device 5.17
     iManufacturer          :    0x1 Dell Computer Corp
     iProduct               :    0x2 DW375 Bluetooth Module
     iSerialNumber          :    0x3 E006E6DAC48E
     bNumConfigurations     :    0x1
      CONFIGURATION 1: 100 mA ==================================
       bLength              :    0x9 (9 bytes)
       bDescriptorType      :    0x2 Configuration
       wTotalLength         :   0xf4 (244 bytes)
       bNumInterfaces       :    0x4
       bConfigurationValue  :    0x1
       iConfiguration       :    0x0
       bmAttributes         :   0xe0 Self Powered, Remote Wakeup
       bMaxPower            :   0x32 (100 mA)
        INTERFACE 0: Wireless Controller =======================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x0
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x3
         bInterfaceClass    :   0xe0 Wireless Controller
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x1
         iInterface         :    0x0
          ENDPOINT 0x81: Interrupt IN ==========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x3 Interrupt
           wMaxPacketSize   :   0x10 (16 bytes)
           bInterval        :    0x1
          ENDPOINT 0x82: Bulk IN ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x82 IN
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x1
          ENDPOINT 0x2: Bulk OUT ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x2 OUT
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x1
        INTERFACE 1: Wireless Controller =======================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x2
         bInterfaceClass    :   0xe0 Wireless Controller
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x1
         iInterface         :    0x0
          ENDPOINT 0x83: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x83 IN
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :    0x0 (0 bytes)
           bInterval        :    0x1
          ENDPOINT 0x3: Isochronous OUT ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x3 OUT
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :    0x0 (0 bytes)
           bInterval        :    0x1
        INTERFACE 1, 1: Wireless Controller ====================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x1
         bNumEndpoints      :    0x2
         bInterfaceClass    :   0xe0 Wireless Controller
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x1
         iInterface         :    0x0
          ENDPOINT 0x83: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x83 IN
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :    0x9 (9 bytes)
           bInterval        :    0x1
          ENDPOINT 0x3: Isochronous OUT ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x3 OUT
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :    0x9 (9 bytes)
           bInterval        :    0x1
        INTERFACE 1, 2: Wireless Controller ====================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x2
         bNumEndpoints      :    0x2
         bInterfaceClass    :   0xe0 Wireless Controller
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x1
         iInterface         :    0x0
          ENDPOINT 0x83: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x83 IN
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x11 (17 bytes)
           bInterval        :    0x1
          ENDPOINT 0x3: Isochronous OUT ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x3 OUT
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x11 (17 bytes)
           bInterval        :    0x1
        INTERFACE 1, 3: Wireless Controller ====================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x3
         bNumEndpoints      :    0x2
         bInterfaceClass    :   0xe0 Wireless Controller
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x1
         iInterface         :    0x0
          ENDPOINT 0x83: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x83 IN
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x20 (32 bytes)
           bInterval        :    0x1
          ENDPOINT 0x3: Isochronous OUT ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x3 OUT
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x20 (32 bytes)
           bInterval        :    0x1
        INTERFACE 1, 4: Wireless Controller ====================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x4
         bNumEndpoints      :    0x2
         bInterfaceClass    :   0xe0 Wireless Controller
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x1
         iInterface         :    0x0
          ENDPOINT 0x83: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x83 IN
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x1
          ENDPOINT 0x3: Isochronous OUT ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x3 OUT
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x1
        INTERFACE 1, 5: Wireless Controller ====================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x5
         bNumEndpoints      :    0x2
         bInterfaceClass    :   0xe0 Wireless Controller
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x1
         iInterface         :    0x0
          ENDPOINT 0x83: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x83 IN
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x1
          ENDPOINT 0x3: Isochronous OUT ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x3 OUT
           bmAttributes     :    0x1 Isochronous
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x1
        INTERFACE 2: Vendor Specific ===========================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x2
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x2
         bInterfaceClass    :   0xff Vendor Specific
         bInterfaceSubClass :   0xff
         bInterfaceProtocol :   0xff
         iInterface         :    0x0
          ENDPOINT 0x84: Bulk IN ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x84 IN
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x20 (32 bytes)
           bInterval        :    0x1
          ENDPOINT 0x4: Bulk OUT ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x4 OUT
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x20 (32 bytes)
           bInterval        :    0x1
        INTERFACE 3: Application Specific ======================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x3
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x0
         bInterfaceClass    :   0xfe Application Specific
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x0
         iInterface         :    0x0
    hex VendedorID=0xc45& ProductId0x6433
    DEVICE ID 0c45:6433 on Bus 000 Address 002 =================
     bLength                :   0x12 (18 bytes)
     bDescriptorType        :    0x1 Device
     bcdUSB                 :  0x200 USB 2.0
     bDeviceClass           :   0xef Miscellaneous
     bDeviceSubClass        :    0x2
     bDeviceProtocol        :    0x1
     bMaxPacketSize0        :   0x40 (64 bytes)
     idVendor               : 0x0c45
     idProduct              : 0x6433
     bcdDevice              : 0x1315 Device 19.15
     iManufacturer          :    0x2 CN018T967248725GB6YMA01
     iProduct               :    0x1 Laptop_Integrated_Webcam_HD
     iSerialNumber          :    0x0
     bNumConfigurations     :    0x1
      CONFIGURATION 1: 500 mA ==================================
       bLength              :    0x9 (9 bytes)
       bDescriptorType      :    0x2 Configuration
       wTotalLength         :  0x37b (891 bytes)
       bNumInterfaces       :    0x2
       bConfigurationValue  :    0x1
       iConfiguration       :    0x0
       bmAttributes         :   0x80 Bus Powered
       bMaxPower            :   0xfa (500 mA)
        INTERFACE 0: Video =====================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x0
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x1
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x1
         bInterfaceProtocol :    0x0
         iInterface         :    0x5 Integrated Webcam
          ENDPOINT 0x83: Interrupt IN ==========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x83 IN
           bmAttributes     :    0x3 Interrupt
           wMaxPacketSize   :   0x10 (16 bytes)
           bInterval        :    0x6
        INTERFACE 1: Video =====================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x0
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x2
         bInterfaceProtocol :    0x0
         iInterface         :    0x5 Integrated Webcam
        INTERFACE 1, 1: Video ==================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x1
         bNumEndpoints      :    0x1
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x2
         bInterfaceProtocol :    0x0
         iInterface         :    0x0
          ENDPOINT 0x81: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x5 Isochronous
           wMaxPacketSize   :   0x80 (128 bytes)
           bInterval        :    0x1
        INTERFACE 1, 2: Video ==================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x2
         bNumEndpoints      :    0x1
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x2
         bInterfaceProtocol :    0x0
         iInterface         :    0x0
          ENDPOINT 0x81: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x5 Isochronous
           wMaxPacketSize   :  0x100 (256 bytes)
           bInterval        :    0x1
        INTERFACE 1, 3: Video ==================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x3
         bNumEndpoints      :    0x1
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x2
         bInterfaceProtocol :    0x0
         iInterface         :    0x0
          ENDPOINT 0x81: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x5 Isochronous
           wMaxPacketSize   :  0x320 (800 bytes)
           bInterval        :    0x1
        INTERFACE 1, 4: Video ==================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x4
         bNumEndpoints      :    0x1
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x2
         bInterfaceProtocol :    0x0
         iInterface         :    0x0
          ENDPOINT 0x81: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x5 Isochronous
           wMaxPacketSize   :  0xb20 (2848 bytes)
           bInterval        :    0x1
        INTERFACE 1, 5: Video ==================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x5
         bNumEndpoints      :    0x1
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x2
         bInterfaceProtocol :    0x0
         iInterface         :    0x0
          ENDPOINT 0x81: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x5 Isochronous
           wMaxPacketSize   : 0x1320 (4896 bytes)
           bInterval        :    0x1
        INTERFACE 1, 6: Video ==================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x6
         bNumEndpoints      :    0x1
         bInterfaceClass    :    0xe Video
         bInterfaceSubClass :    0x2
         bInterfaceProtocol :    0x0
         iInterface         :    0x0
          ENDPOINT 0x81: Isochronous IN ========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x5 Isochronous
           wMaxPacketSize   : 0x1400 (5120 bytes)
           bInterval        :    0x1
    hex VendedorID=0xa5c& ProductId0x5801
    DEVICE ID 0a5c:5801 on Bus 000 Address 003 =================
     bLength                :   0x12 (18 bytes)
     bDescriptorType        :    0x1 Device
     bcdUSB                 :  0x110 USB 1.1
     bDeviceClass           :    0x0 Specified at interface
     bDeviceSubClass        :    0x0
     bDeviceProtocol        :    0x0
     bMaxPacketSize0        :   0x40 (64 bytes)
     idVendor               : 0x0a5c
     idProduct              : 0x5801
     bcdDevice              :  0x101 Device 1.01
     iManufacturer          :    0x1 Broadcom Corp
     iProduct               :    0x2 5880
     iSerialNumber          :    0x3 0123456789ABCD
     bNumConfigurations     :    0x1
      CONFIGURATION 0: 100 mA ==================================
       bLength              :    0x9 (9 bytes)
       bDescriptorType      :    0x2 Configuration
       wTotalLength         :   0xab (171 bytes)
       bNumInterfaces       :    0x3
       bConfigurationValue  :    0x0
       iConfiguration       :    0x0
       bmAttributes         :   0xc0 Self Powered
       bMaxPower            :   0x32 (100 mA)
        INTERFACE 0: Application Specific ======================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x0
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x3
         bInterfaceClass    :   0xfe Application Specific
         bInterfaceSubClass :    0x0
         bInterfaceProtocol :    0x0
         iInterface         :    0x4 Broadcom USH w/swipe sensor
          ENDPOINT 0x81: Bulk IN ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x81 IN
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x0
          ENDPOINT 0x1: Bulk OUT ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x1 OUT
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x0
          ENDPOINT 0x85: Interrupt IN ==========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x85 IN
           bmAttributes     :    0x3 Interrupt
           wMaxPacketSize   :   0x10 (16 bytes)
           bInterval        :   0x20
        INTERFACE 1: Smart Card ================================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x1
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x3
         bInterfaceClass    :    0xb Smart Card
         bInterfaceSubClass :    0x0
         bInterfaceProtocol :    0x0
         iInterface         :    0x5 Contacted SmartCard
          ENDPOINT 0x82: Bulk IN ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x82 IN
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x0
          ENDPOINT 0x2: Bulk OUT ===============================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :    0x2 OUT
           bmAttributes     :    0x2 Bulk
           wMaxPacketSize   :   0x40 (64 bytes)
           bInterval        :    0x0
          ENDPOINT 0x86: Interrupt IN ==========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x86 IN
           bmAttributes     :    0x3 Interrupt
           wMaxPacketSize   :   0x10 (16 bytes)
           bInterval        :   0x20
        INTERFACE 3: Application Specific ======================
         bLength            :    0x9 (9 bytes)
         bDescriptorType    :    0x4 Interface
         bInterfaceNumber   :    0x3
         bAlternateSetting  :    0x0
         bNumEndpoints      :    0x1
         bInterfaceClass    :   0xfe Application Specific
         bInterfaceSubClass :    0x0
         bInterfaceProtocol :    0x0
         iInterface         :    0x7 Broadcom USH
          ENDPOINT 0x87: Interrupt IN ==========================
           bLength          :    0x7 (7 bytes)
           bDescriptorType  :    0x5 Endpoint
           bEndpointAddress :   0x87 IN
           bmAttributes     :    0x3 Interrupt
           wMaxPacketSize   :   0x10 (16 bytes)
           bInterval        :   0x20
    [Finished in 0.5s]

este es el dispositivo que no detecta:

A: Para que pyusb detecte a los dipsositivos externos al pc es necesario.
descargar la herramienta libusb-win32-bin-1.2.6.0 para poder instalar el archivo .info correspondiente a cada dispositivo.


text:
Q: iOS Core Audio What is the difference between AUAudioUnit and AVAudioUnit? Both the AUAudioUnit and AVAudioUnit APIs look really similar,
what's the difference? When to use which one?

A: An AVAudioUnit is connected as a node in an AVAudioEngine. An AUAudioUnit is typically connected in an AUGraph. The functionalities should be similar, as both are audio units, but using an AVAudioEngine is the modern way of audio control in iOS and therefore AVAudioUnits have a more modernized API behind them.
I'm sure there are use cases where one can be preferred over the other, but I'd say use AVAudioUnits unless there's something specific you need that they don't provide. The customizability of AUAudioUnits and their processing graph is great, but in my experience comes with a steep learning curve and a lot more code. Many sleepless nights I've spent inspecting my AUGraphs, but AVAudioEngine has been very kind to me.
Also, AVAudioNodes, and therefore AVAudioUnits, are not functional until attached to a AVAudioEngine, however you can set up AUAudioUnits without an AUGraph using render callbacks.

A: Note that AUAudioUnit represents a V3 audio unit, even though it starts with 'AU'. It is available in iOS 9. Older APIs also start with 'AU' (such as AUSampler) but they are V2.
In general in your app you should use AVAudioUnit. Note that it is available only in iOS 8+. As tnev mentioned above, you can use the AVAudioNode classes to easily set up AVAudioEngine. You cannot do this with AUAudioUnit.
If you are writing your own audio unit you should use AUAudioUnit by subclassing it.
EDIT: Also use AUAudioUnit if you intend to display the viewController of V3 audio units.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Permission denied on getimagesize In my functions.php I got:
$size = getimagesize($avatarpath . "/" . $file);

$avatarpath is $avatarpath = dirname(__FILE__)."/img/avatars";
My structure:
functions.php (in the same directory as img folder).
img/avatars
Chmods of functions.php , img, avatars has been set to 777.
And I still receive the following message:
Warning: getimagesize(/home/godaddy/private_html/img/avatars/avatar_1.png): failed to open stream: Permission denied in /home/godaddy/private_html/img/avatars/functions.php on line 1337

A: Check the user that php runs under.  If you're with godaddy, they use virtual servers so your php user may not actually have access even if you've chmod'd it.  Find out the user, then chown it to that user and see if it helps.


text:
Q: Should using SMO classification in WEKA take so long with large dataset? I have a dataset of 205 features and 238000 samples. It is a combined dataset of several subjects' data that I want to use for between-subject classification.
I am using WEKA 3.8 with a 64-bit JVM and have chosen the SMO classifier with the default configuration (uses the PolyKernel kernel).
I am running on a Windows 7 64-bit PC with 8GB RAM and have already increased the memory settings for Java and WEKA to 6133MB, by following the information from here:
http://www.heritagehealthprize.com/c/hhp/forums/t/646/using-weka-on-large-data-sets
However, so far when I start my classification test, it has been running for over 90 minutes with no sign of getting anywhere.
Can anyone advise me on how long a test like this should take, given my settings, please?
Or is there a way I can speed up the process?
I have already subsampled the data in MATLAB and was hoping to not have to reduce the number of samples any further. Or will this be inevitable?

A: Training time complexity of non-linear SVMs is between O(n2) and O(n3)
Weka SMO seems to be closer to the latter.
For instance, the execution time in ms for a random set with 205 features with Weka SMO looks like this:

It's hard to predict, but it could take anywhere from 1 day (n2) and 124 days (n3)
Depending on your use-case, you could use a linear kernel implementation, like LIBLINEAR.

A: Consider using Vowpal Wabbit for large datasets. It can consume very large datasets even on a laptop in no time. And it also supports kernels.
Vowpal Wabbit performs learning in online fashion - data points are streamed in one-by-one. You may want to shuffle your dataset before feeding it in.


text:
Q: How to fetch unchecked checkbox value into a cursor in Oracle Apex Here is my PL/SQL code to fetch checked checkbox value in a button's dynamic action.
DECLARE
IHC_ID_Y VARCHAR2(9);
IHC_ID_N VARCHAR2(9);
CURSOR Y IS
    SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level)
    FROM DUAL
    CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NOT NULL;
CURSOR N IS
    SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level)
    FROM DUAL
    CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NULL;
BEGIN
    OPEN Y;
    OPEN N;
    LOOP
        FETCH Y INTO IHC_ID_Y;
        EXIT WHEN Y%NOTFOUND;
        INSERT INTO INFANT_RESPONSE (INF_ID, IHC_ID, IR_DESCRIPTION) VALUES (:INF_ID, IHC_ID_Y, 'Y');
    END LOOP;
    CLOSE Y;
        LOOP
        FETCH N INTO IHC_ID_N;
        EXIT WHEN N%NOTFOUND;
        INSERT INTO INFANT_RESPONSE (INF_ID, IHC_ID, IR_DESCRIPTION) VALUES (:INF_ID, IHC_ID_N, 'N');
    END LOOP;
    CLOSE N;
END;

However, I met a problem in this part,
CURSOR N IS
    SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level)
    FROM DUAL
    CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NULL;

 LOOP
        FETCH N INTO IHC_ID_N;
        EXIT WHEN N%NOTFOUND;
        INSERT INTO INFANT_RESPONSE (INF_ID, IHC_ID, IR_DESCRIPTION) VALUES (:INF_ID, IHC_ID_N, 'N')

As you can see, when I change the condition from IS NOT NULL to IS NULL, the values being fetched will all be nulls and hence cannot be inserted into the table rows. Is there any way to fetch the unchecked checkbox values?

A: I'd suggest a different approach:

*

*insert checked health conditions (as you know how to identify them; it is your cursor Y); I used it as well, but within the cursor FOR loop as it is way simpler to use - you don't have to explicitly open it, pay attention about exiting the loop nor when to close the cursor - Oracle does that for you.

*in order to insert unchecked health conditions, do that for all conditions that exist in a table you use to create those checkboxes that aren't inserted as "checked" in the first step

Something like this:
begin
  -- Checked conditions (using your cursor, but as a cursor FOR loop)
  for cur_y in
    (SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) ihc_id_y
     FROM DUAL
     CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NOT NULL
    )
  loop
    insert into infant_response (inf_id, ihc_id, ir_description)
    values (:inf_id, cur_y.ihc_id_y, 'Y');
  end loop;

  -- To insert unchecked conditions, insert values that exist in the table
  -- that contains ALL health conditions (let's call it LIST_OF_HEALTH_CONDITIONS)
  -- that aren't inserted as "checked" in the above cursor FOR loop
  insert into infant_response (inf_id, ihc_id, ir_description)
  select :inf_id,
         h.ihc_id,
         'N'
  from list_of_health_conditions h
  where h.ihc_id not in (select r.ihc_id
                         from infant_response r
                         where r.inf_id = :inf_id
                           and r.ir_description = 'Y'
                        );
end;

Can't test it as I don't have your tables nor data, but - unless I made a typo, that should be OK.

A: This is how I use MINUS set operator to achieve the result I want.
CURSOR N IS
    SELECT IHC_ID FROM INFANT_HEALTH_CONDITIONS
    MINUS
    SELECT regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level)
    FROM DUAL
    CONNECT BY regexp_substr(:INFANT_HEALTH_CONDITIONS, '[^:]+', 1, level) IS NOT NULL;


text:
Q: Can I store firebase data & run the application functions in offline mode in React-native? I found some tutorials about offline mode firebase for React-native but still I don't know how can I enable this thing in my application.
So, how can I store all recieved data and run the functions in offline mode?

A: you can search on persistence in the firebase component you use and set it to true
an popular one is react-native-firebase
and you can set this in it's configuration-options


text:
Q: How to make an address Default from multiple addresses in PHP A user can multiple addresses. Then he as the option to make an address Default. Currently i am totally confused either to do in 1 table or second table. Here what i did so far and DB pic is alose attached.
<?php
if (isset($_POST['make_default'])) {
$is_default     = $_POST['is_default'];
$UpdateDaddress  = mysqli_query($con, "UPDATE buyer_address SET

is_default      = '$is_default'

WHERE user_id='$userId'");
if ($UpdateDaddress) {
$_SESSION['success'] = "
Your address is updated successfully!
";
echo '';
} else {
$tempalert = "Query Error 404";
include('libraries/alertmodalyet.php');
         }
}
?>
<form method="post">

<?php
$ShowAdresses = mysqli_query($con, "SELECT * FROM buyer_address WHERE user_id='$userId'");
while($ADrow=mysqli_fetch_assoc($ShowAdresses)){
?>

<input type="radio" name="is_default" value="<?php echo $ADrow['id'];?>"> <?php echo $ADrow['address'];?>, <?php echo $ADrow['city'];?>,
<?php echo $ADrow['suburb'];?>, <?php echo $ADrow['post_code'];?>

<?php } ?>

<input type="submit" name="make_default" class="savebtn" vlaue="Update">

</form>

A: $is_default     = $_POST['is_default'];
$UpdateDaddress = mysqli_query($con, "UPDATE buyer_address SET

is_default      = '$is_default'

WHERE user_id='$userId'");

So you have an attempt at doing this at the top of your code...
Basically, what you need to do is set all addresses for the user to "false" (or in your case it looks like '') and then update the newly appointed default as "default".
Note: we'll use 0 and 1 as true/false
$user_id = $_SESSION["user_id"]; // Or wherever you get it from!

$default_address_id = $_POST["is__default"];

// With mysqli and `IF` logic
$sql = "
    UPDATE buyer_address SET is_default = IF(id = ?, 1, 0) WHERE user_id = ?;
";
$query = $con->prepare($sql);
$query->bind_param("ii", $default_address_id, $user_id);
$query->execute();

// With mysqli and `CASE` logic
$sql = "
    UPDATE buyer_address SET is_default = CASE
        WHEN
            id = ?
        THEN
            1
        ELSE
            0
    WHERE user_id = ?;
";

$query = $con->prepare($sql);
$query->bind_param("ii", $default_address_id, $user_id);
$query->execute();

// With PDO and emulate prepares
$sql = "
    UPDATE buyer_address SET is_default = 0 WHERE user_id = ?;
    UPDATE buyer_address SET is_default = 1 WHERE user_id = ? AND id = ?;
";
$query = $pdo->prepare($sql);
$query->execute([$user_id, $user_id, $default_address_id]);

You may want to add in additional checks to see if the form was submitted etc.


text:
Q: PHP cookies setting I hate to say it but I have been working on what should have been a 30 minute assignment for a good 6 hours now with little to no progress. I am attempting to capture a name and email in a form, and set them to cookies that will last 10 minutes. While the cookies are active, the page should skip the form and just display the input. I have tried this with both cookies and sessions and cannot get it to work.
At this point I have written and deleted at least a hundred lines of code and just can't really see what the problem is. This is my first time working with PHP. Any help would be appreciated.
Currently this code creates the form, takes the info and posts it to the page correctly. When I go back to the page, it shows the form again. I assume this means the cookie isn't setting / sticking.
<?php
 if (!empty($_POST)) {
  setcookie('Cname',$_POST['name'], time()+600);
  setcookie('Cemail', $_POST['email'], time()+600);
//  header("Location:HW2.php");
 }

?>

<title> Assignment 2 Alcausin </title>

<?php

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

$visibleForm = True;
if(isset($_COOKIE['name'])){
    $visibleForm = False;
}
if(isset($_POST['submit'])){
    $visibleForm = False;
    echo "Your Name: ";
    echo $_COOKIE['Cname'];
    echo "
";
    echo "Your Email: ";
    echo $_COOKIE['Cemail'];
}
if($visibleForm){ // close php if form is displayed
    ?>
<form action ="HW2.php" method="post">
    Name:* <input type="text" name="name">

    E-mail:* <input type="text" name="email">

    <input type="submit" name="submit" value="Submit">
</form>
<?php   // back to php
}
?>

A: I rewrote your script using sessions, so that your data is actually stored on the server and the client only has a session cookie which is a reference to the server-side data, so the client has no way of tampering with that data.
While this may not be important for your homework, this is definitely important when you deal with user accounts and privileges (imagine an "admin" cookie that tells if the user is admin or not - anyone can manually set that cookie and that's it, he's an admin on your website).
This wasn't tested and may not work at all - feel free to downvote my answer if that's the case.
<?php

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
ini_set("session.cookie_lifetime","600"); // sets the session cookie's lifetime to 10 minutes / 600 seconds

session_start(); // starts the session, this will create a new session cookie on the client if there's not one already

if (isset($_POST["name"]) && isset($_POST["email"])) { // if there's POST data
    $_SESSION["name"] = $_POST["name"]; // this saves your values to the session so you can retrieve them later
    $_SESSION["email"] = $_POST["email"]; // same here
};

?>

<title> Assignment 2 Alcausin </title>

<?php

$visibleForm = !isset($_SESSION["name"]); // visibleForm will be the opposite of isset, so if there's a "name" in the session then the form will be invisible

if ($visibleForm) { // if there's no session data, we display the form
    echo '<form action ="HW2.php" method="post">Name:* <input type="text" name="name">
E-mail:* <input type="text" name="email">
<input type="submit" name="submit" value="Submit"></form>';
} else { // this means there is some data in the session and we display that instead of the form
    echo "Your Name: ";
    echo $_SESSION["name"];
    echo "
";
    echo "Your Email: ";
    echo $_SESSION["email"];
};
?>

A: First of all, you must add the session_start() at the highest level of your code as it is essential for any of this to work. session_start() actually generates the PHPSESSID cookie and is also the session identifier; you won't need to set anything to the PHPSESSID cookie using setcookie() if you use session_start().
For a basic way to do what you're trying to achieve, I'd try to set sessions whenever the page loads and if there is a current session, then it will skip the form like you said.
$_SESSION['SESSID'] = $someVar;
$_SESSION['SESSNAME'] = "someOtherVar";

Then right before your form, check if any of those are set by using
if(isset($someVar) && isset($someOtherVar))

You know the deal.
Then create a button that does a session_destroy() so that it ends the current session.


text:
Q: Using CSS Peek in React is there a way of using CSS Peek in *.js files, specifically in React components.

If not, is there any extension that allows me to see inline CSS styling for selected className?

A: This seems like an old issue - CSS Peek doesn't provide built-in support for jumping to css from jsx code. However, I have also not found any extension in the marketplace for this.

A: Initial support is shiping in version 2.2.0
(More information)


text:
Q: wkhtmltopdf dynamic margins Is it possible, using wkhtmltopdf, to define dynamic margins ?
I'm generating a pdf for an invoice, on the first page I have the BVR in the footer so the user can cut it out and pay with it. On pages besides the first one, I have no footer.
The problem is that, when having enough content to fill the second page fully, the page breaks occurs at the given footer margin, leaving me with a page empty for 1/3.
Is it possible to define (javascript or other ways) a dynamic margin size for the first page, and then remove the bottom margin for any other ?

A: Nope. You can create a feature request at https://github.com/wkhtmltopdf/wkhtmltopdf/issues, but I don't think this is coming any time soon because the underlying technology (webkit) has stabilised (doesn't change often) and doesn't really need this feature.
How about for a workaround you examine the content and if it's the specific length you split the HTML to two files and convert them individually. Then you can join them with pdftk for example.


text:
Q: Kafka 8.2.2 Dynamic Topic drops first event EDIT : I am seeing the same exact behavior with the Kafka 9 Consumer API also.
I have a simple Kafaka 8.2.2 Producer with the enable topic creation property set to true.  It will create a new topic when an event with a non-existent topic is created, but the event that creates that topic does not end up in Kafka and the RecordMetadata returned has no errors.
    public void receiveEvent(@RequestBody EventWrapper events) throws InterruptedException, ExecutionException, TimeoutException {
    log.info("Sending " + events.getEvents().size() + " Events ");
    for (Event event : events.getEvents()) {
        log.info("Sending Event - " + event);
        ProducerRecord<String, String> record = new ProducerRecord<>(event.getTopic(), event.getData());

        Future<RecordMetadata> ack = eventProducer.send(record);
        log.info("ACK - " + ack.get());
    }

    log.info("SENT!");
}

I have a program that polls for new topics (I wasn't happy with the dynamic/regex topic code in Kafka 8) and it finds the new queue and subscribes, and it does see subsequent events, but never that first event.
I also tried the kafka-console-consumer script and it sees that exact same.  First event never seen, then after that events start flowing.
Ideas?

A: Turns out there is a property you can set props.put("auto.offset.reset","earliest");
And after setting this, the Consumer does receive the first event put on the topic.


text:
Q: Toolbar doesn't show the overflow icon I'm using the new Toolbar instead of the ActionBar.
On Android 5.0 everything is just fine:

On 4.4 it doesn't show the Overflow icon (though the function is there):

This is the toolbar.xml I'm using:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/HeaderBar"
    app:theme="@style/ActionBarThemeOverlay"
    app:popupTheme="@style/ActionBarPopupThemeOverlay"
    android:id="@+id/toolbar_actionbar"
    app:titleTextAppearance="@style/ActionBar.TitleText"
    app:contentInsetStart="?actionBarInsetStart"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize" />

A: you should probably use ActionBarAcitivity  if you don't already,
and then set
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"

or inherit from another theme from AppCompat
also in your onCreate you should set the tool bar as your actionbar:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

        Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
        setSupportActionBar(toolbar);
    }

source: chris bane's blog

A: In the styles.xml it is needed to add the color for pre 5.0 versions:
<style name="Theme.APP.Base" parent="Theme">
    <item name="actionBarIconColor">#fff</item>
    ...
</style>


text:
Q: Paste a content with HTML tags to Contenteditable DIV I'll try to explain my problem)
I have a DIV element with content like:

Some text

Some text

Some text

Some text

And I want to paste some outside html content in the middle of this - for example - after id=111 parag.
This outside html content looks like:

Some text

Some text

Some text

But this outside html content should be formatted automatically. Why?
Because I should change img src "OUTERSERVER/path" to "myserver/path" for pasted content only.
Im really tired with this problem. Can you help me please?)
I use javascript only.

A: If you want to do it with pure javascript. then it should be look like
function insertAfter(refer, external) {
   refer.parentNode.insertBefore(external, refer.nextSibling);
}
var external = document.getElementById('external');
var refer = document.getElementById('111');
insertAfter(refer, external);

please go through the link for more details of the html
working demo


text:
Q: How to open links in default browser using Electron i'm using a simple browserWindow like so:
let win = new BrowserWindow({
  width: 500,
  height: 613,
  title: 'My App',
  autoHideMenuBar:true,
  icon: path.join(__dirname, 'logo.ico'),
  resizable:false,
  backgroundColor:"#2c2f33",
  webPreferences: {
    session : session,
    webSecurity: false,
  }
})
win.on('closed', () => {
  win = null
})

// Load a remote URL
win.loadURL('http://192.168.40.189:1337')
session.fromPartition('persist:name');
session.defaultSession.cookies.get({}, (error, cookies) => {
  console.log(error, cookies)
})

Whenever i click a link within the browserwindow, a new instance of an electron-browserwindow is created. Is is possible to open links with the default system-browser? (chrome/firefox/vivaldi/etc)
I've read these resources amongst others. But none has yielded any success:
Electron Browser-Window Doc
How do I open a url from  on default OS browser?
EDIT:
I've tried this, and it seems like it would be the most likely to work of all the solutions i've found, but it gives me: webContents.on is not a function.
const {webContents} = require('electron')
var handleRedirect = (e, url) => {
  if(url != webContents.getURL()) {
    e.preventDefault()
    require('electron').shell.openExternal(url)
  }
}

webContents.on('will-navigate', handleRedirect)
webContents.on('new-window', handleRedirect)

HTML:
<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
            <link rel="stylesheet" href="/css/normalize.css">
            <link rel="stylesheet" href="/css/main.css">

            <input type="text" id="input" class=" message-to-send" tabindex="1" disabled="disabled" placeholder="Enter name" />

Connecting...

JS-frontend:
// "use strict";

// for better performance - to avoid searching in DOM
const inputElement = document.getElementById('input');
const contentElement = document.getElementById('content');
const statusElement = document.getElementById('status');
var userName = document.getElementById('status');

// my color
var myColor = false;
// my name
var myName = false;

// if mozilla, use built in.
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
  contentElement.innerHTML = "
Sorry, your browser doesn't support websocket.
";
  inputElement.style = "display: none";
  statusElement.style = "display: none";
}
// open connection
const connection = new WebSocket('ws://192.168.40.189:1337');

connection.addEventListener('open', function(e) {
  inputElement.removeAttribute('disabled');
  statusElement.innerHTML = ' ';
});

connection.addEventListener('error', function (error) {
  contentElement.innerHTML = '
Sorry, but there\'s some problem with your connection, or the server is down.
';
});
connection.addEventListener('message', function (message) {
  var json;
  try {
    json = JSON.parse(message.data);
  } catch (e) {
    console.log('Invalid JSON: ', message.data);
    return;
  }
  if (json.type === 'color') {
    myColor = json.data;
    statusElement.innerHTML = myName + '';
    statusElement.style.color = myColor;
    inputElement.removeAttribute('disabled');
    userName = userName;
  } else if (json.type === 'history') {
    for (var i=0; i < json.data.length; i++) {
      var str = json.data[i].text;
      var strChanged  = str.replace(/https?:\/\/[^ ]+/g, '➜[Link]'); // match any word until space
      addMessage(json.data[i].author, strChanged, json.data[i].color, new Date(json.data[i].time));
    }
  } else if(json.type === 'message' && (json.data.author != userName)){
    // console.log("author: "+ json.data.author + userName.value);
      var str = json.data.text;
      var strChanged  = str.replace(/https?:\/\/[^ ]+/g, '➜[Link]'); // match any word until space
      addMessage(json.data.author,strChanged,json.data.color, new Date(json.data.time));
    }
  else if (json.type === 'message' && json.data.text.length > 60) { //spam protection....
    inputElement.value = "Denna checken gjordes speciellt för Christian...";
  }
   else if (json.type === 'message') {
    // standard message.
    inputElement.removeAttribute('disabled');
    // convert urls to links.
    var str = json.data.text;
    var strChanged  = str.replace(/https?:\/\/[^ ]+/g, '➜[Link]'); // match any word until space
    addMessageRight(json.data.author, strChanged, json.data.color, new Date(json.data.time));
  }
   else {
    console.log('Hmm..., I\'ve never seen JSON like this:', json);
  }
});

//username cookie
 function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) != 0) return nameEQ.match("([^=]*)")[i];
    console.log(nameEQ.match("([^=]*)")[i]);
    }
    return nameEQ.match("([^=]*)");
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
/**
 * Send message when user presses Enter key
 */

//Cookie Check
 if(readCookie(document.cookie) != ""){
  var listener = function(){
    var myName = ' ';
    myName = readCookie(document.cookie);
    connection.send(myName);
    console.log("HE222EEJ: ")
    inputElement.setAttribute('placeholder','Send Message...');
    document.removeEventListener('click',listener,true);
  };
  document.addEventListener('click',listener,true);

  // connection.send(msg);
}
if(getCookie(document.cookie) == null){
  console.log("HEE333EJ: ")
input.addEventListener('keydown', function(e) {
  if (e.keyCode === 13) {
    const msg = inputElement.value;
    if (!msg) {
      return;
    }
      connection.send(msg);
      inputElement.value = '';
      inputElement.setAttribute('placeholder','Send Message...');

    if(!myName && msg.length > 20){inputElement.value="Sluta nu Christian...";}
      if(myName === false){
        myName = msg;
        userName = myName;
        createCookie(userName,userName,7);
      }
    }
    else{
      return;
    }
});
}
/* om det är connection-problem */
setInterval(function() {
  if (connection.readyState !== 1) {
    statusElement.innerHTML = 'ERROR';
    inputElement.setAttribute('disabled', 'disabled');
    inputElement.value = 'Unable to communicate with the WebSocket server.';
  }
}, 3000);

/**
 * Add message to the chat window
 */
function addMessage(author, message, color, dt) {
  contentElement.innerHTML += `

                                    `
                                    +author+
                                  `
                                  `
                                    + (dt.getHours() < 10 ? '0'
                                    + dt.getHours() : dt.getHours()) + ':'
                                    + (dt.getMinutes() < 10
                                    ? '0' + dt.getMinutes() : dt.getMinutes())+
                                  `

`
                                +`<div class="message my-message" style="background:`+color+`;--my-color-var:`+color+`;">`+message+`

`;
        contentElement.scrollIntoView({block: "end"}); //gjord speciellt för christian.
}

function addMessageRight(author, message, color, dt) {
  contentElement.innerHTML += `

                                  ` + (dt.getHours() < 10 ? '0'+ dt.getHours() : dt.getHours()) + ':'+ (dt.getMinutes() < 10? '0' + dt.getMinutes() : dt.getMinutes())+`
                                  ` +author+`

`
                                +`<div class="message other-message float-right" style="background:`+color+`;--my-other-color-var:`+color+`;">`+message+`

`;
        contentElement.scrollIntoView({block: "end"});
        var audio = new Audio('notification.mp3');
        audio.play();
}

Thanks

A: This worked for me
mainWindow.webContents.on('new-window', function(e, url) {
  e.preventDefault();
  require('electron').shell.openExternal(url);
});

Ref: Reference Here

A: You can do this the way you tried using webContents's class instance methods instead of static functions
const { app, BrowserWindow, shell } = require('electron')

app.once('ready', () => {
  const handleRedirect = (e, url) => {
    if (url !== e.sender.getURL()) {
      e.preventDefault()
      shell.openExternal(url)
    }
  }
  const win = new BrowserWindow()
  // Instead bare webContents:
  win.webContents.on('will-navigate', handleRedirect)
  win.loadURL('http://google.com')
})

A: Are these links  tags?
If so, this worked for me:
const shell = require('electron').shell

const links = document.querySelectorAll('a[href]')

Array.prototype.forEach.call(links, function (link) {
   const url = link.getAttribute('href')
   if (url.indexOf('http') === 0) {
      link.addEventListener('click', function (e) {
          e.preventDefault()
          shell.openExternal(url)
      })
   }
})

It's from the Electron API Demos.
EDIT:
For the new links, try something like this (I haven't tested it):
function addMessage(author, message, color, dt) {
  contentElement.innerHTML += `

                                    `
                                    +author+
                                  `
                                  `
                                    + (dt.getHours() < 10 ? '0'
                                    + dt.getHours() : dt.getHours()) + ':'
                                    + (dt.getMinutes() < 10
                                    ? '0' + dt.getMinutes() : dt.getMinutes())+
                                  `

`
                                +`<div class="message my-message" style="background:`+color+`;--my-color-var:`+color+`;">`+message+`

`;
        changeLinkBehaviour();
        contentElement.scrollIntoView({block: "end"}); //gjord speciellt för christian.
}

function changeLinkBehaviour(){
 var link = contentElement.findElementsByClassName("message my-message")[0].querySelectorAll('a[href]')[0];
  //repetition of code I pasted eariler:
 const url = link.getAttribute('href')
   if (url.indexOf('http') === 0) {
      link.addEventListener('click', function (e) {
          e.preventDefault()
          shell.openExternal(url)
      })
   }
}

A: I took a different approach after trying several of the above suggestions which led to my answer, so thank you all. My project is a little different: I'm using Vue and Vuetify, as well as Pug for easier templating.
First the template (just the top to illustrate link)
<template lang="pug">
    div(style="height:220px;")
        v-card(height="220").ma-2
            v-layout(row wrap)
                v-flex(xs4)
                    div.mt-2.ml-2
                        a(@click="openExternalLink(twitterLink)")
                            v-avatar(size="80px" slot="activator")
                                v-img(src="https://abs.twimg.com/sticky/default_profile_images/default_profile.png" height="80px" contain alt="member.fullName")

Added a click listener to link
script tag:

I hope this helps others.


text:
Q: How do you generate a CSR in Java without signing it by the requester? Basically, I need to isolate the data of the constructed CSR (Certificate Signing Request) prior to it being first signed by the entity making the request, preferably in Java. Many thanks in advance!
It would also be useful to note how to subsequently append the signature to the CSR as the CSR data will be initially signed by an HSM.

A: I hope this helps:
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;

import javax.security.auth.x500.X500Principal;

import sun.security.pkcs10.*;
import sun.security.x509.*;

public class GenerateCSR {
    private static PublicKey publicKey = null;
    private static PrivateKey privateKey = null;
    private static KeyPairGenerator keyGen = null;
    private static GenerateCSR gcsr = null;

    private GenerateCSR() {
        try {
            keyGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyGen.initialize(2048, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        publicKey = keypair.getPublic();
        privateKey = keypair.getPrivate();
    }

    public static GenerateCSR getInstance() {
        if (gcsr == null)
            gcsr = new GenerateCSR();
        return gcsr;
    }

    public String getCSR(String cn) throws Exception {
        byte[] csr = generatePKCS10(cn, "Java", "JournalDev", "Cupertino",
                "California", "USA");
        return new String(csr);
    }

    /**
     *
     * @param CN
     *            Common Name, is X.509 speak for the name that distinguishes
     *            the Certificate best, and ties it to your Organization
     * @param OU
     *            Organizational unit
     * @param O
     *            Organization NAME
     * @param L
     *            Location
     * @param S
     *            State
     * @param C
     *            Country
     * @return
     * @throws Exception
     */
    private static byte[] generatePKCS10(String CN, String OU, String O,
            String L, String S, String C) throws Exception {
        // generate PKCS10 certificate request
        String sigAlg = "MD5WithRSA";
        PKCS10 pkcs10 = new PKCS10(publicKey);
        Signature signature = Signature.getInstance(sigAlg);
        signature.initSign(privateKey);
        // common, orgUnit, org, locality, state, country
        X500Principal principal = new X500Principal( "CN=Ole Nordmann, OU=ACME, O=Sales, C=NO");

   //     pkcs10CertificationRequest kpGen = new PKCS10CertificationRequest(sigAlg, principal, publicKey, null, privateKey);
     //   byte[] c = kpGen.getEncoded();
        X500Name x500name=null;
        x500name= new X500Name(principal.getEncoded());
      pkcs10.encodeAndSign(x500name, signature);
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(bs);
        pkcs10.print(ps);
        byte[] c = bs.toByteArray();
        try {
            if (ps != null)
                ps.close();
            if (bs != null)
                bs.close();
        } catch (Throwable th) {
        }
        return c;
    }

    public PublicKey getPublicKey() {
        return publicKey;
    }

    public PrivateKey getPrivateKey() {
        return privateKey;
    }

    public static void main(String[] args) throws Exception {
        GenerateCSR gcsr = GenerateCSR.getInstance();

        System.out.println("Public Key:\n"+gcsr.getPublicKey().toString());

        System.out.println("Private Key:\n"+gcsr.getPrivateKey().toString());
        String csr = gcsr.getCSR("journaldev.com <http://www.journaldev.com>");
        System.out.println("CSR Request Generated!!");
        System.out.println(csr);
    }

}

A: I used the Bouncy Castle libraries to produce a certificate request without signing it. The problem I was facing was that a lot of applications available to generate a CSR took care of both generating it AND signing it. I only wanted to produce an unsigned CSR. Unfortunately, I cannot divulge the code used to produce the unsigned CSR due to company policy but I have listed many hints below that should help others. Here are some steps that might aid someone else trying to do the same thing:

*

*Look at example CSR data generated with openssl or some other tool using the following website.
http://lapo.it/asn1js/
This site even includes an example certificate object to see it in action.

*Become familiar with ASN1 encoding. This is how certificate data is encoded and you will need to encode the CSR similarly using Bouncy Castle.

*Use Bouncy Castle to produce the CSR data. Here is a code snippet on initializing some of the fields typically found in CSR data.
// Create Organization Name<br/>
DERObjectIdentifier oidOrgName     = new DERObjectIdentifier("2.5.4.10");
DERPrintableString  prntstrOrgName = new DERPrintableString("Test Organization");
DERSet              setOrgName     = new DERSet(new DERSequence(new ASN1Encodable[] {oidOrgName, prntstrOrgName}));

// Create org unit name
DERObjectIdentifier oidOrgUnitName     = new DERObjectIdentifier(2.5.4.11);
DERPrintableString  prntstrOrgUnitName = new DERPrintableString("Org Unit Name");
DERSet              setOrgUnitName     = new DERSet(new DERSequence(new ASN1Encodable[] {oidOrgUnitName, prntstrOrgUnitName}));


text:
Q: Actions must be plain objects. Redux not working I am trying to add redux-thunk middleware to put register and login functionality in my app. But the code doesnt seem to work for register. It is giving the following error -
Actions must be plain objects. Use custom middleware for async actions.
The code is as follows
Index.js - Importing thunk and using it
 import {createStore, applyMiddleware} from 'redux';
 import thunk from 'redux-thunk';
 const store = createStore(authReducer,applyMiddleware(
                            thunk,
                            loggerMiddleware
                            ),window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root'));

actions/authActions.js -Creating register function to dispatch action
export function register(){
    return (dispatch)=>{

        dispatch({type:'auth_user'})

    }
}

components/Register.js - Component which is using the above register function using redux
import  * as actions  from '../actions/authActions';

class RegisterForm extends React.Component{

handleRegister = (e)=>{
    e.preventDefault();
    console.log("inside handle register");
    console.log(this.props);
    this.props.register();
 }
}
var Register = connect(mapStateToProps,actions)(RegisterForm);

authReducer.js
import {AUTH_ERROR,UNAUTH_USER,FETCH_MESSAGE, AUTH_USER} from '../actions/types';

const initialState = {
    loggedIn:false,
    errorMessage:''
}

const   authReducer = (state=initialState,action)=>{
    console.log("action is")
    console.log(action);
    switch(action.type){
        case AUTH_USER:
            {
                console.log("Reached in reducer");
                return {...state,loggedIn:true}}

        case UNAUTH_USER:
            return {...state, loggedIn:false}
        default:
            return state;
    }

}

export default authReducer;

/action/types.js
export const AUTH_USER = 'auth_user'
export const UNAUTH_USER = 'unauth_user'
export const AUTH_ERROR = 'auth_error'
export const FETCH_MESSAGE = 'fetch_message'

A: Your store setup seems incorrect. Write your store as:
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  authReducer,
  {},
  composeEnhancers(
    applyMiddleware(
      thunk,
      loggerMiddleware
    )
  )
);

A: Can you try the following snippet in the actions.
export function register=()=>{
    return {
        type:'auth_user'
    }
}


text:
Q: Spring boot expiredURL not working I have "Vaadin 10 with Spring Boot" application. I want to allow user to access application from one place at a time. So I used maximumSessions(1). Example, from Chrome browser I have logged in with user "XYZ". Now with the same user (i.e. "XYZ") I tried to login to Opera browser. So as per configuration shown below, it will expire session of Chrome browser but it is not redirecting to "/login". It shows message "Invalid JSON response from Server". Below is the Spring security configuration:
@Override
protected void configure(HttpSecurity http) throws Exception {
    // Not using Spring CSRF here to be able to use plain HTML for the login page
    http.csrf().disable()

            // Register our CustomRequestCache, that saves unauthorized access attempts, so
            // the user is redirected after login.
            .requestCache().requestCache(new CustomRequestCache())

            // Restrict access to our application.
            .and().authorizeRequests()
            .antMatchers("/ForgetPassword","/ChangePassword","/login").permitAll()
            // Allow all flow internal requests.
            .requestMatchers(SecurityUtils::isFrameworkInternalRequest).permitAll()

            // Allow all requests by logged in users.
            .anyRequest().authenticated()
            // Configure the login page.
            .and().formLogin().loginPage("/login").permitAll().loginProcessingUrl("/login")
            .failureUrl("/login?error")

            // Register the success handler that redirects users to the page they last tried
            // to access
            .successHandler(new SavedRequestAwareAuthenticationSuccessHandler())

            // Configure logout
            .and().logout().logoutSuccessUrl(LOGOUT_SUCCESS_URL)
            .deleteCookies("JSESSIONID")
            //.invalidateHttpSession(true)
            .and()
            .sessionManagement()
            //.invalidSessionUrl("/login")
            .maximumSessions(1)
            //.maxSessionsPreventsLogin(false)
            .sessionRegistry(sessionRegistry())
            .expiredUrl("/login");

A: The problem is that, by redirecting the request, Vaadin receives the login page as a response to a internal request.
This seems to work:
        .expiredSessionStrategy(e -> {
            final String redirectUrl = e.getRequest().getContextPath() + "/login";
            if(SecurityUtils.isFrameworkInternalRequest(e.getRequest())) {
                e.getResponse().setHeader("Content-Type", "text/plain");
                e.getResponse().getWriter().write("Vaadin-Refresh: " + redirectUrl);
            } else {
                e.getResponse().sendRedirect(redirectUrl);
            }
        });

It is documented in the
ConnectionStateHandler
public interface ConnectionStateHandler {

/**
 * A string that, if found in a non-JSON response to a UIDL request, will
 * cause the browser to refresh the page. If followed by a colon, optional
 * whitespace, and a URI, causes the browser to synchronously load the URI.
 *
 *

 * This allows, for instance, a servlet filter to redirect the application
 * to a custom login page when the session expires. For example:
 *

 *
 *

 * if (sessionExpired) {
 *     response.setHeader("Content-Type", "text/html");
 *     response.getWriter().write(myLoginPageHtml + "<!-- Vaadin-Refresh: "
 *             + request.getContextPath() + " -->");
 * }
 *

 */
String UIDL_REFRESH_TOKEN = "Vaadin-Refresh";


text:
Q: Excel Conditional Formatting to recognise specific case sensitive text I have this issue with Highlighting of Cells in the Ms Excel worksheet. The range of cells required is, lets say A1 to D10. Cells in this range will be highlighted Red only if it is entered with a lower case text x. If any other text (even a capital X) is entered, that particular cell must be Red. So each cells in that range can remain normal when BLANK and also when entered with lower case x. But if any input is entered other than the lower case x, that cells must turn Red. Can anyone please suggest way out with the Conditional Formatting for this issue.
Tried EXACT(x,A1:D10), with and without quotations and all varuous combinations of FIND, MATCH, SEARCH, etc, but no success.

A: The conditional format will change the cell reference automatically. You are not required to include the whole range in the formula. That only creates a formula error.
Simply EXACT("x",A1) should be fine for string - x.


text:
Q: Ways to log exact wifi connection establishment issues I have recently started working with a museum (UK) who's 1-year-old Cisco wifi setup has been experiencing connectivity issues from day 1.
Essentially a significant proportion of devices (both in-house and personal) are unable to connect to wifi - user selects an SSID, enters correct password, authenticates and instantly the connection is dropped.
This effects some laptops, phones and tablets, but oddly some others connect and stay connected perfectly well - both "remembered" and new connections, doesn't seem device age or brand related. Interestingly apple iThings seem to suffer less issues.
The APs are Cisco Aironet 2802i, there are 14 throughout the building, connected to a council-owned controller (To which I don't have admin access, but the admin can't find any config issues)
So I need to do some client-side investigation, and want to capture exactly what happens during the connection/authentication and subsequent drop process.
What is a good way to do this on both windows and android ?


text:
Q: Value in Column I am developing a small hobby application. Though I've worked with MySQL and PostgreSQL before, I'm more of a n00b here and would appreciate any help.
I have a table in my MySQL database called "TECH". This table has two columns: "ID" (primary key) and "name" (name of the tech - not a key of any sort). Here are a couple of example rows:
+----+--------+
| ID |  name  |
+----+--------+
| 1  |  Python|
| 2  |  ASP   |
| 3  |  java  |
+----+--------+

Here is the code that creates TECH:
CREATE TABLE TECH (
        id      INT(5) ,
        name    VARCHAR(20),
        PRIMARY KEY (id)
);

I have developed an html form for the user to input a new technology into TECH. However, I would like to ensure that duplicate entries do not exist in TECH. For example, the user should not be allowed to enter "Python" to be assigned ID 4. Further, the user should also not be allowed to enter "pYthon" (or any variant of capitalization) at another ID.
Currently, I have the following code that does this (on the PHP side, not the MySQL side):
// I discovered that MySQL is not case sensitive with TECH.name
$rows = 0;
$result = $mysql_query("SELECT * FROM tech AS T WHERE T.name='python'");
while ($row = mysql_fetch_array($result)) {
    $rows += 1;
}

if ($rows != 0) {
    echo "'python' cannot be inserted as it already exists";
} else {
    // insertion code
}

Now, I know that the correct way to do this would be to constrain TECH.name to be UNIQUE by doing UNIQUE (name) and catching an "insert error" on the PHP side.
However, I have the following two questions regarding this process:

*

*Does defining the UNIQUE constraint maintain the apparent case-insensitivity addressed above?

*How do I go about catching exactly such an insert error on the PHP side?

I'd appreciate any help with this or any better ideas that anyone has.

A: When you manipulate mysql form php (i.e. by doing an INSERT or UPDATE), you can call mysql_get_rows_affected which will return the rows affected. If the query has failed due to the UNIQUE constraint then the affected rows will be 0
http://php.net/manual/en/function.mysql-affected-rows.php
I usually check the number of rows returned from that function, The same check can be applyed if you take the INSERT OR IGNORE approach

A: TRY
INSERT IGNORE INTO mytable
    (primaryKey, field1, field2)
VALUES
    ('abc', 1, 2),
    ('def', 3, 4),
    ('ghi', 5, 6);

duplicated rows would be ignored

A: Changing the collation of the field to _ci or _cs would determine whether a unique key was caseinsensitive or casesensitive.
As for catching the error, you should try using mysqli or PDO to run db queries: http://www.php.net/manual/en/pdo.exec.php
You can catch a duplicate error entry with PDO like so:
try
{
    $dbh->exec($mySqlQuery);
    // insert was successful...
} catch (PDOException $e) {
    if ($e->errorInfo[1]==1062) {
        // a 'duplicate' error occurred...
    } else {
        // a non 'duplicate error' occurred...
    }
}

Edit:
If you're not using PDO, this should work after your mysql_query:
if (mysql_errno() == 1062)
{
   // you have a duplicate error...
}


text:
Q: JApplet in Jar file can only be run from html contained in Jar file I have a JApplet that is based off an application. I need it to read in a text based file containing all of it's data. So I stuck it in the Jar file and everything became happy in AppletViewer.
Unfortunately not everything is happy in browser land.
When I try to run the applet in a browser from a html page which is not in the jar, then I get the good old: java.security.AccessControlException: access denied (java.io.FilePermission
(it then lists the location of the jar on my filesystem and the !resource address)
But if I open the jar file up in a zip extractor/viewer like winzip and open the page that launches the applet (that I put inside the jar) it works fine. As expected, it can only access resources that have the same host, which seems in this case to come right down to the jar file itself.
SO my question is WTF? Can I open the html file inside the jar file from a browser... even inside an iframe or anything would be ok, as long as it doesn't further mess up the permissions.
Or can I call the applet from a html page outside the jar? I'm not using JNLP right now, cos I wanted to cobble together a prototype applet ASAP.
<applet code = 'CatalogApplet'
archive = 'ContactCatalog.jar',
width = 1000,
height = 800 />

Is the entirity of the HTML call to the applet.
I'm not going to sign it, because it really shouldn't need signed. I am just wanting to call back to jar.

A: The file should be accessed via URL, not by FileInputStream. Use this to get the URL:
URL urlToText = this.getClass().getResource("path/to/the.html");

That will work in a sand-boxed applet.

A: the clean way is :
package your ".class" files in a jar . have an html file outside the jar that references your jar inside applet tag. if your applet requires access to user filesystem then the right way to go is to sign your applet jar. see http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed.html


text:
Q: Excess pressure in drops While calculating the excess pressure in a bubble or a drop, we consider one half of the bubble or a drop and equate the surface tension times the circumference of the half of the drop or bubble to excess pressure times area.
$$\tau \cdot c = P_{excess} \cdot A$$
Doesn't surface tension pull any point on the drop or bubble with equal force in all directions? Why should there be an excess pressure?

A: If you do a force balance on a small element of surface on a balloon or drop (say, "window shaped"), there is curvature of the surface, and the surface tension forces acting at the edge of the element (or the elastic forces in the case of the balloon) have a net resultant in the radial direction.  This is why the pressure inside is higher than the pressure outside.  When you did your analysis, you just neglected the curvature effect.

A: It seems to me that you call "excess pressure" what I call "capillary pressure". Take a look at this figure from a wiki of a course at Harvard. The surface tension doesn't pull any point on the drop or bubble with equal force in all direction. Instead, it pulls the point in a direction that is tangential to the surface.


text:
Q: Как запустить файл .py в обход командной строки? Решил сделать себе что-то "Мудрый совет на каждый день", только про иероглифы.
Описание программы:
Суть программы простая: есть скачанная таблица с сайта с полным списком кандзи (японские иероглифы(неважно)) в таком формате:
русский перевод, сам иероглиф, звучание 1, звучание 2, ключ иероглифа, номер ключа
и таким образом 2045 строчек.
Я открываю файл 'ier.txt' питоном, читаю его питоном, записываю все строки этого файла как элементы list[]
f=open(r'ier.txt',encoding='utf-8',errors='ignore')
textr=f.readlines()
for i in textr:
    i =i.strip("\n")
    i =i.replace("\t", " ")

Как видите, убираю пробелы и переносы.
Беру рандомное число, потому что мне нужно, чтобы каждый раз какая-нибудь случайная строка открывалась.
Дальше задаю новый list[] путем запихивания в него строки из выдачи от textr.
rdd=random.randint(1,2044)
strr=textr[rdd]
stg=strr.split( )

Разделяю его пробелами и таким образом получаю что каждое слово это элемент.
arlen=len(stg)
n=1
self = Tk()
self.geometry('200x250')
self.number_y = 5
self.number = 0
Label(self, text=stg[0].format(self.number),font=("Arial", 20)).place(x=0, y=self.number_y)
for i in range(arlen):
    self.number_y += 35
    self.number += 1
    Label(self, text=stg[n].format(self.number),font=("Arial", 20)).place(x=0, y=self.number_y)
    n+=1
self.mainloop()

Тут я создал форму и сделал цикл, который добавляет новый лейбл в форму в зависимости от количества элементов в list stg, потому что количество элементов там нефиксированное.
В чем проблема?
Проблема в том, что, если я открываю весь мой код в Python 3.7.3 IDLE, там жму кнопку Run(F5), программа запускается и работает красиво, от души. Но моя задача засунуть это дело в автозагрузку. И вот, нехитрыми манипуляциями я засунул ярлык от этой программы в автозагрузку, перезагружаю компьютер и... ничего не работает. Я решил сделать по-другому. Сделал ту же программу, только чтобы она запускалась через консоль. Дважды кликаю мышкой по файлу 'программа.py' - запустилось, нарисовалось.
 Уродливо правда, но работает. Дважды кликаю мышкой по файлу с программой, описанной выше - ничего. Хотя в IDLE все запускалось нормально.
 Я решил открыть cmd и в командной строке одновременно стартануть питон и файл с программой .py. Командная строка мне ответила:
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

Попытка поиска решения в интернете результата не принесла.
Я пытался настроить программу Python 3.7.3 IDLE и по совместительству Python 3.7.3 Shell как основные для открытия всех файлов типа .py, но при таком раскладе файл сразу открывается для ... редактирования, а не для запуска.

A: Решение нашлось в банальном:
У меня было установлено две разных версии Python на компьютере, и они вместе не стыковались, вызывая такую дурацкую ошибку. Я снес обе версии и все что связано с Питоном и установил заново Python 3.8. После этого мне выдало ошибку, что n out of range, легко поправил ее, и все заработало


text:
Q: What is causing my error? I am trying to create a player class and store a players name as a variable another noob here, so I hope someone with a bit of sense can help me! As my question states, I am simply trying to create a player class (it is for an RPG game). However, I have tried multiple ways of doing this, with the code shown being the latest, however I keep coming across different errors. I am using Microsoft visual c++ 2010 express and the error that I am currently facing is:

1>player.obj : error LNK2001: unresolved external symbol "private:
  static class std::basic_string,class std::allocator >
  Player::m_playerName"
  (?m_playerName@Player@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A)

I hope this is enough detail! The rest of the code/files I have created are as follows:
game.cpp
#include <iostream>
#include "player.h"

using namespace std;

int main()
{

    Player main;

   main.setStats();
   main.showStats();

    int stopper;
   cin >> stopper;

    return 0;

}

player.h
#include <string>

class Player
    {
    public:

        Player();
        void showStats();
        void setStats();

    private:

         int m_playerLVL;
         static std::string m_playerName;
    };

player.cpp
#include "player.h"
#include <iostream>
#include <string>

using namespace std;

Player::Player()
{
    cout << "Please enter your name: ";
    string playerName;
    getline (cin, playerName);
    m_playerName = playerName;
}

    void Player::showStats()
    {
        cout << "Hello, i am " << m_playerName << "and i am lvl " << m_playerLVL;
    }

    void Player::setStats()
    {
        m_playerLVL = 1;
    }

A: You are declaring the name of the player to be static:
static std::string m_playerName; // DON'T MAKE IT STATIC!

That's semantically incorrect, and removing static happens to solve your problem. Each instance of Player should associate a different value to m_playerName (because each player has their own name). Declaring a data member static makes it global for the whole Player class (i.e. it is not given a per-instance value, but one global value which is the same for all Player objects). That doesn't sound like something you would want.

Now if for any reason you really meant to declare this as a static data member, then you should provide a definition for it at the global namespace scope:
std::string Player::m_playerName;

The linker is complaining about the lack of such a definition.


text:
Q: Fail to connect to database after change IP I know this probably be one of the popular questions but my situation seems to a bit different. I used to connect my android device to mysql using IP 192.168.1.x, everything worked fine. But when I connect to other network with IP 192.168.0.x, the connection fails, I din change anything on my code and the WampServer is online too. How could this happens?

04-22 16:45:46.150 6533-6578/? W/System.err: java.net.SocketTimeoutException: failed to connect to /192.168.0.5 (port 80) after 15000ms

A: In your Android code you should update your Current IP Address instead of old IP Address


text:
Q: Remove duplications from Mongodb collection on multiple key I have a mongodb collection.
I want to remove duplicate docs if two key fields are duplicated.
db.getCollection("collection").aggregate([
{
    // only match documents that have this field
    // you can omit this stage if you don't have missing fieldX
    $match: {"user_id": {$nin:[null]}}
},
{
    $group: { "_id": "$user_id", "doc" : {"$first": "$$ROOT"}}
},
{
    $replaceRoot: { "newRoot": "$doc"}
},
{$out: "collection2"}
],
{allowDiskUse:true}
)

The query above works for one key field.
from this solution
for 2 fields, how can I edit it?
Sample collection;
   repo_id    user_id
0  667006     1060
1  667006     1060 #duplicated ! repo_id and user_id
2  667006     2467194
3  667006     21979

Desired output;
   repo_id    user_id
0  667006     1060
1  667006     2467194
2  667006     21979

A: All you need to change is $group stage, now group on unique pairs of repo_id & user_id.
Try to replace group stage with below :
{
   $group: { _id: {repo_id: '$repo_id',user_id: "$user_id"} , doc: { $first: "$$ROOT" } }
}

Test : mongoplayground


text:
Q: Sort a calculated column SSAS Tabular Model I am looking for a way to sort a calculated column in my SSAS Tabular Model. I tried using the property Sort by column but apparently it is not working. Is it in general possible to do this?
In my case specific use case, I made a parent-child hierarchy where I want to sort on another column. Despite trying a lot of possibilities, it doesn't work. But neither does sorting a calculated column.
Note: Working with tabular compatibility 1400 (SQL2017).

A: Sort by column does work. The column to be sorted and the "Sort by column" must match values one for one, i.e. both columns need to be at the same level of granularity. In general, this is done on dimension tables, not fact tables.
The classic example for this feature is for sorting month labels. To change the sorting of MonthName from April, August, December... to January, February, March..., you need to sort MonthName by MonthNumber. Select the column to be sorted and set the Sort by column to a numeric column in the same table with the correct sort order. You would do this in the Date dimension, not in the Fact table with all the data.
Here's before and after pictures to prove it works:


text:
Q: Why the size of a class is getting increased by 1 if I inherit more than 2 classes in C++ In the following code snippet, If I inherit the first 2 classes the size of derived class is 1, from omwards if inherit more number of classes to derived the size of derived class is getting incresed by those many number of classes. Why?
// Remove the comment one by one at derived class (//Base1, //Base2//, Base3//, Base5, //Base6) and check.

struct Base {
    Base(){}
};
struct Base1 {
    Base1(){}
};
struct Base2 {
    Base2(){}
};
struct Base3 {
    Base3(){}
};
struct Base5 {
    Base5(){}
};
struct Base6 {
    Base6(){}
};
struct Derived : Base, Base1, Base2//, Base3//, Base5, //Base6
{
public:
    Derived(){}
};

int main() {
    Derived der;
    cout << "Sizeof der: " << sizeof(der) << endl;
}

A: It means your compiler's empty base optimization is not as extensive as on other compilers.
Output of your program with all six Bases uncommented (and with the necessary include and the "void main" error fixed)

gcc 4.6.2: Sizeof der: 1
clang 3.0: Sizeof der: 1
intel 11.1 Sizeof der: 1
Sun C++ 5.8: Sizeof der: 1
Visual Studio 2010 SP1 (release build): Sizeof der: 5

A: Every time you extend a class it becomes a part of the final object and therefore increases its size by the size of the base class object. As already mentioned there may be some compiler optimizations going on that cause the observed effect.


text:
Q: Translate StructureMap component registration to Autofac version I'm new to Autofac and have the following StructureMap component registrations that I would like to translate, but am concerned that my implementation may not be done the recommended way. Autofac puts great emphasis on the fact that you should not be resolving outside of a lifetime scope (i.e. container.Resolve), but of course, container.BeginLifetimeScope() isn't available until the ContainerBuilder is built.
 For<ISessionSource>().Singleton().Use<NHibernateSessionSource>();

 For<ISession>().Use(ctx => {
    var unitOfWork = (INHibernateUnitOfWork)ctx.GetInstance<IUnitOfWork>();
    return unitOfWork.Session;
 });

 For<IUnitOfWork>().HybridHttpOrThreadLocalScoped().Use<NHibernateUnitOfWork>();

Autofac:
 builder.RegisterType<NHibernateSessionSource>().As<ISessionSource>().SingleInstance();

 // Is the following recommended? Define that whenever request an `ISession` it should return the `Session` property of the concrete implementation of `INHibernateUnitOfWork`:
 builder.Register(ctx =>
 {
     var unitOfWork = (INHibernateUnitOfWork)ctx.Resolve<IUnitOfWork>();
     return unitOfWork.Session;
 }).As<ISession>().InstancePerRequest();

 builder.RegisterType<NHibernateUnitOfWork>().As<IUnitOfWork>().InstancePerRequest();

A: Here's what we got out from the comments.
The OP was worried that ctx in the lambda represented the root container, and as a result thought that these registrations didn't stick to best practices since Autofac - like any other IoC container - advises against resolving services from the root container.
It turns out that, in fact, ctx represents the current resolution context at the time of the lambda execution.
The use of InstancePerRequest in the registrations points towards the fact ctx will, in this case, be the HTTP request lifetime scope context.
All in all, the current Autofac registrations look good and similar to the StructureMap ones.


text:
Q: Doubt on the notation of quotient sets and quotient vector spaces In pure set theory level, to construct the quotient set we need:
$1)$ A set $X$
$2)$ A equivalence relation $\thicksim$
$3)$ With $2)$ and $3)$, we can form the pair $(X, \thicksim)$.
$4)$ With $(X, \thicksim)$, we can form a patition on the set $X$ and then stablish the equivalence classes on $X$.
$5)$ Finally, the set of all equivalence classes is the desired quotient set $Y := X/\thicksim$ (*).
Now, in linear algebra level, we denote the quotient vector space as:
$$\mathcal{Y} = \mathcal{X}/\mathcal{Z}$$
When I compare the notations $X/\thicksim$ and $\mathcal{X}/\mathcal{Z}$, I feel a bit confuse. So my question is: why in linear algebra we do not denote the quotient vector space simply as $\mathcal{Y} = \mathcal{X}/\thicksim$? In other words, since $\mathcal{Z} \subset \mathcal{X}$, is the $\thicksim
\hspace{0.5mm}\subset X$ (the symbol $\thicksim$ denotes a subset)?

(*) I interpret the quotient set as: given the set $X$, its elements are all there "interacting" together. With a equivalence relation on $X$ we can divide, factor or quotient the elements of $X$ into classes (we "separate the grains"), then form a whole new set $Y$"

A: We use $Y=X/Z$ as the notation for the quotient space because the equivalence relation $\sim$, or strictly speaking $\sim_{X,Z}$, is completely known once you know the subspace $Z$. The definition of the relation is: for every $v,w\in X$, we say $v\sim w$ if and only if $v-w\in Z$. Then, you can easily verify that $\sim$ so defined is an equivalence relation on $X$, depending on $Z$.
So, the notation $X/Z$ quickly conveys what is meant. Contrast with $Y=X/\sim$. How would I know which relation $\sim$ refers to (without further elaboration)? Math is about communicating ideas. Now, you may want to use notation like $Y/\sim_{X,Z}$ to denote the quotient set by the above defined equivalence relation. This is fine if you're first learning the subject. For example, some teachers when introducing linear algebra write $0_V,0_W$ or $+_V,+_W$ to denote the zeros/addition operation on different vector spaces $V,W$ so as to distinguish the difference between them, but after a few lectures, they'll drop this extra notation and leave it up to the student to decipher the (almost always obvious) meaning from context. It's the same with quotient vector spaces: given a vector space $X$ and a subspace $Z\subset X$, the set $X/Z$ denotes the quotient set for the above relation, and you know that as long as you're working with vector spaces, the defining property of the equivalence relation is never messed around with. Hence, it quickly gets the meaning across without excessive notation. Also, the operations on $X/Z$ are the 'obvious ones' (well they're obvious once you work them out in detail atleast once).

An obligatory remark: in different contexts, we use the same notation to denote different things. For example, if you start with a topological space $X$, and a subset $A\subset X$, then the notation $X/A$ means something completely different. There are no vector spaces around, so it's obviously not the above meaning. What is meant is we let $\sim_A$ denote the equivalence relation generated by $a_1\sim_A a_2$, for $a_1,a_2\in A$ (or more explicitly, the intersection of all equivalence relations on $X$ containing $\{(a_1,a_2)\in X\times X\,:\, a_1,a_2\in A\}$); then $X/A:= X/\sim_A$. This equivalence relation has the following equivalence classes: for any point $x\in X\setminus A$, $[x]=\{x\}$ is a singleton, whereas for any $a\in A$, $[a]=A$. So, this 'collapses $A$ to a point'.
Now, one can consider the following situation: $X$ is a topological vector space (e.g $\Bbb{R}^n$) and $Z\subset X$ a vector subspace. Then, the symbol $X/Z$ has two potential meanings, the first as a quotient of vector spaces, the second as a quotient of topological spaces collapsing the subset to a single point. The intended meaning should always be decided based on context. Context is always important.


text:
Q: Two users in ActiveDirectory with same name I am creating application that will add new users to AD through LDAP.
I can generate users, but my problem is when I have two users with same givenname and sn, because I construct name and cn from (givenname [space] sn), and from there I also construct DN (distinguished name). The problem is with same cn and path both users have same DN
I can not put users in different OU's, they have to have same path.
What is the best way to handle this automaticly? Just add a number to cn? Add another attribute to cn?

A: Adding a number is a common approach. The approach I prefer however is to set the CN to something guaranteed to be unique, e.g. employee ID or username.


text:
Q: How do you add a page to a WinUI 3 project created with template studio? I know this is a simple question but I just can't figure out how to add a new page after creating a WinUI 3 with template studio (and I don't want to make another project just to add another page). I can see that template studio auto creates a navigation helper which navigates to the pages but when i use the helpers it just throws an exception. (ShellPage.xaml)
<Page
    x:Class="WinUI_App.Views.ShellPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:helpers="using:WinUI_App.Helpers"
    xmlns:behaviors="using:WinUI_App.Behaviors"
    xmlns:i="using:Microsoft.Xaml.Interactivity"
    Loaded="OnLoaded"
    Style="{StaticResource PageStyle}">

    <NavigationView
        x:Name="navigationView"
        IsBackButtonVisible="Visible"
        IsBackEnabled="{x:Bind ViewModel.IsBackEnabled, Mode=OneWay}"
        SelectedItem="{x:Bind ViewModel.Selected, Mode=OneWay}"
        IsSettingsVisible="True"
        ExpandedModeThresholdWidth="1280"
        Header="{x:Bind ((ContentControl)ViewModel.Selected).Content, Mode=OneWay}"
        Background="{ThemeResource SystemControlBackgroundAltHighBrush}">
        <NavigationView.MenuItems>
            <!--
            TODO: Change the symbols for each item as appropriate for your app
            More on Segoe UI Symbol icons: https://learn.microsoft.com/windows/uwp/style/segoe-ui-symbol-font
            Or to use an IconElement instead of a Symbol see https://github.com/microsoft/TemplateStudio/blob/main/docs/UWP/projectTypes/navigationpane.md
            Edit String/en-US/Resources.resw: Add a menu item title for each page
            -->

            <NavigationViewItem x:Uid="Shell_Main" Icon="ThreeBars" helpers:NavigationHelper.NavigateTo="WinUI_App.ViewModels.MainViewModel" />
            <NavigationViewItem x:Uid="Shell_ListDetails" Icon="list" helpers:NavigationHelper.NavigateTo="WinUI_App.ViewModels.ListDetailsViewModel" />
        </NavigationView.MenuItems>
        <NavigationView.HeaderTemplate>
            <DataTemplate>
                <Grid>
                    <TextBlock
                        Text="{Binding}"
                        Style="{ThemeResource TitleTextBlockStyle}"
                        Margin="{StaticResource SmallLeftRightMargin}" />
                </Grid>
            </DataTemplate>
        </NavigationView.HeaderTemplate>
        <i:Interaction.Behaviors>
            <behaviors:NavigationViewHeaderBehavior
                DefaultHeader="{x:Bind ((ContentControl)ViewModel.Selected).Content, Mode=OneWay}">
                <behaviors:NavigationViewHeaderBehavior.DefaultHeaderTemplate>
                    <DataTemplate>
                        <Grid>
                            <TextBlock
                                Text="{Binding}"
                                Style="{ThemeResource TitleTextBlockStyle}"
                                Margin="{StaticResource SmallLeftRightMargin}" />
                        </Grid>
                    </DataTemplate>
                </behaviors:NavigationViewHeaderBehavior.DefaultHeaderTemplate>
            </behaviors:NavigationViewHeaderBehavior>
        </i:Interaction.Behaviors>
        <Grid>
            <Frame x:Name="shellFrame" />
        </Grid>
        <NavigationView.FooterMenuItems>
            <NavigationViewItem Content="Account" Tag="SamplePage4" Icon="Contact"/>
        </NavigationView.FooterMenuItems>
    </NavigationView>
</Page>

Can anyone help me please I can share more code if needed.

A: Let's say that you want to add a "TestPage":

*

*Add a new page named TestPage.xaml in the Views folder

*Create a TestViewModel.cs a TestViewModel class in the ViewModels folder and implement it. (Use other pages as a reference for how to implement it.)

*Register TestViewModel class as a service in App.xaml.cs

*Register TestViewModel and TestPage in PageService.cs

*Add a NavigationViewItem for TestPage in ShellPage.xaml

*Add a string resource in Resources.resw for Shell_TestPage.Content

A: To add more pages to your project using Template Studio you could try this:

*

*Right-click the project in Solution Explorer

*Select Add

*Select New Item (Template Studio)

*Select New Page...

*Choose the page type, then click next etc..


text:
Q: How can I change element attribute with $("this").change? Edit: Thank you all for your suggestions. I've made suggested changes on my question. I edited the code, no syntax errors anymore, I get no errors from browser anymore.
This is the problem I'm dealing with now: I get the alert message "null" in each perform.
I've been trying to change the value of an element with a checkbox, make the value "1" or "0" for a number of reasons.
 To check if I was successful, I placed an alert() inside the code to get the changed attribute. Whether I check or uncheck the checkbox, I only get "undefined" message. I think I'm messing up with synchronization but I don't know how.

$(document).ready(function() {

$("#checkTabsence").change(function(){
    if($(this).is(':checked'))
    {
        var tutorPresence = document.getElementById("tutorCheckEl");
            tutorPresence.setAttribute = ("href", "1");
        var alertme = tutorPresence.getAttribute("href");
        alert(alertme)
    }
    else
    {
        var tutorPresence = document.getElementById("tutorCheckEl");
            tutorPresence.setAttribute = ("href", "0");
        var alertme = tutorPresence.getAttribute("href");
        alert(alertme)
    }

});
  });

<input type="checkbox" id="checkTabsence">

A: You've got a few problems:

*

*You're trying to call .attr() on a plain DOM element but .attr() is a jQuery function. Either call setAttribute() on the DOM element, or use jQuery instead of getElementById.

*You're forgetting the jQuery ID selectors need to be prefixed with a #. Change $("tutorCheckEl") to $("#tutorCheckEl").

*If you are going to use .attr() in jQuery, the syntax to set an attribute is tutorPresence.attr("value", "1")

*If you are going to use setAttribute(), the syntax to set an attribute is tutorPresence.setAttribute("value", "1")

A: The problem is that $("tutorCheckEl") matches against a <tutorCheckEl> which I doubt you have on the page.
Did you perhaps mean to use $("#tutorCheckEl"), which would match  (or indeed any element with id="tutorCheckEl") ?
Also, an anchor tag () has no value attribute.  value is for input-type elements.