Q: Why do I have to insert USB storage twice to mount it? Often, I insert my USB storage into my computer and it will not mount. I can see the USB drive recognised in KDE's panel, but it will not be mounted. I can click on the "mount" button in the panel, but nothing happens. If I remove the device and reconnect, always mounts the second time.
I looked through sudo journalctl for the relevant log lines, and there were two differences. Firstly, the failed mounting had the additional lines:
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver usb-storage
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver uas

Secondly (perhaps unimportant), the failed mounting did mtp-probe before the kernel detected the USB mass storage device; this order was inverted when it worked.
The full log is reproduced below. This represents a failed connection, a disconnection, and a working connection. How can I make my USB device be mounted on the first connection?
I am using Arch Linux, but I also experienced this (I think) when I was using Kubuntu.
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 7 using ehci-pci
Mar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: checking bus 4, device 7: "/sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2"
Mar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: bus: 4, device: 7 was not an MTP device
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detected
Mar 04 14:35:34 sparhawk-XPS-17 kernel: scsi host6: usb-storage 4-1.2:1.0
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver usb-storage
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver uas
Mar 04 14:35:35 sparhawk-XPS-17 kernel: scsi 6:0:0:0: Direct-Access              USB Flash Memory PMAP PQ: 0 ANSI: 4
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Write Protect is off
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Mode Sense: 23 00 00 00
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] No Caching mode page found
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Assuming drive cache: write through
Mar 04 14:35:36 sparhawk-XPS-17 kernel:  sdc: sdc1
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Attached SCSI removable disk
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8" has new interfaces: ("org.freedesktop.UDisks2.Drive")
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8"
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.PartitionTable")
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc"
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.Filesystem", "org.freedesktop.UDisks2.Part
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:39 sparhawk-XPS-17 kernel: usb 4-1.2: USB disconnect, device number 7
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1" lost interfaces: ("org.freedesktop.UDisks2.Partition", "org.freedesktop.UDisks2.Filesystem", "org.freedesktop.UDisks2.Blo
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc" lost interfaces: ("org.freedesktop.UDisks2.PartitionTable", "org.freedesktop.UDisks2.Block")
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: "/org/freedesktop/UDisks2/block_devices/sdc"
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8" lost interfaces: ("org.freedesktop.UDisks2.Drive")
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8"
Mar 04 14:35:39 sparhawk-XPS-17 systemd-udevd[212]: error opening USB device 'descriptors' file
Mar 04 14:35:43 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 8 using ehci-pci
Mar 04 14:35:43 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detected
Mar 04 14:35:43 sparhawk-XPS-17 kernel: scsi host7: usb-storage 4-1.2:1.0
Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: checking bus 4, device 8: "/sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2"
Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: bus: 4, device: 8 was not an MTP device
Mar 04 14:35:44 sparhawk-XPS-17 kernel: scsi 7:0:0:0: Direct-Access              USB Flash Memory PMAP PQ: 0 ANSI: 4
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Write Protect is off
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Mode Sense: 23 00 00 00
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] No Caching mode page found
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Assuming drive cache: write through
Mar 04 14:35:45 sparhawk-XPS-17 kernel:  sdc: sdc1
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Attached SCSI removable disk
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8" has new interfaces: ("org.freedesktop.UDisks2.Drive")
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8"
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.PartitionTable")
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc"
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.Filesystem", "org.freedesktop.UDisks2.Part
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:45 sparhawk-XPS-17 udisksd[554]: Mounted /dev/sdc1 at /run/media/lee/Lee-key on behalf of uid 1000
Mar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/index.bdmv
Mar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/BACKUP/index.bdmv
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: true "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:45 sparhawk-XPS-17 polkitd[416]: Operator of unix-session:c2 FAILED to authenticate to gain authorization for action org.freedesktop.udisks2.filesystem-mount for system-bus-name::1.258 [kdeinit4: kded4 [
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 7 using ehci-pci
Mar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: checking bus 4, device 7: "/sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2"
Mar 04 14:35:34 sparhawk-XPS-17 mtp-probe[5109]: bus: 4, device: 7 was not an MTP device
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detected
Mar 04 14:35:34 sparhawk-XPS-17 kernel: scsi host6: usb-storage 4-1.2:1.0
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver usb-storage
Mar 04 14:35:34 sparhawk-XPS-17 kernel: usbcore: registered new interface driver uas
Mar 04 14:35:35 sparhawk-XPS-17 kernel: scsi 6:0:0:0: Direct-Access              USB Flash Memory PMAP PQ: 0 ANSI: 4
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Write Protect is off
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Mode Sense: 23 00 00 00
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] No Caching mode page found
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Assuming drive cache: write through
Mar 04 14:35:36 sparhawk-XPS-17 kernel:  sdc: sdc1
Mar 04 14:35:36 sparhawk-XPS-17 kernel: sd 6:0:0:0: [sdc] Attached SCSI removable disk
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8" has new interfaces: ("org.freedesktop.UDisks2.Drive")
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8"
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.PartitionTable")
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc"
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.Filesystem", "org.freedesktop.UDisks2.Part
Mar 04 14:35:36 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:39 sparhawk-XPS-17 kernel: usb 4-1.2: USB disconnect, device number 7
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1" lost interfaces: ("org.freedesktop.UDisks2.Partition", "org.freedesktop.UDisks2.Filesystem", "org.freedesktop.UDisks2.Blo
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc" lost interfaces: ("org.freedesktop.UDisks2.PartitionTable", "org.freedesktop.UDisks2.Block")
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: "/org/freedesktop/UDisks2/block_devices/sdc"
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8" lost interfaces: ("org.freedesktop.UDisks2.Drive")
Mar 04 14:35:39 sparhawk-XPS-17 baloo_file[640]: Found removable storage volume for Baloo undocking: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8"
Mar 04 14:35:39 sparhawk-XPS-17 systemd-udevd[212]: error opening USB device 'descriptors' file
Mar 04 14:35:43 sparhawk-XPS-17 kernel: usb 4-1.2: new high-speed USB device number 8 using ehci-pci
Mar 04 14:35:43 sparhawk-XPS-17 kernel: usb-storage 4-1.2:1.0: USB Mass Storage device detected
Mar 04 14:35:43 sparhawk-XPS-17 kernel: scsi host7: usb-storage 4-1.2:1.0
Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: checking bus 4, device 8: "/sys/devices/pci0000:00/0000:00:1d.0/usb4/4-1/4-1.2"
Mar 04 14:35:43 sparhawk-XPS-17 mtp-probe[5198]: bus: 4, device: 8 was not an MTP device
Mar 04 14:35:44 sparhawk-XPS-17 kernel: scsi 7:0:0:0: Direct-Access              USB Flash Memory PMAP PQ: 0 ANSI: 4
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] 15240576 512-byte logical blocks: (7.80 GB/7.26 GiB)
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Write Protect is off
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Mode Sense: 23 00 00 00
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] No Caching mode page found
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Assuming drive cache: write through
Mar 04 14:35:45 sparhawk-XPS-17 kernel:  sdc: sdc1
Mar 04 14:35:45 sparhawk-XPS-17 kernel: sd 7:0:0:0: [sdc] Attached SCSI removable disk
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8" has new interfaces: ("org.freedesktop.UDisks2.Drive")
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/drives/USB_Flash_Memory_00187D0F56A0EE214000ABF8"
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.PartitionTable")
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc"
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: QObject::connect: Cannot connect (null)::accessibilityChanged(bool,QString) to Baloo::StorageDevices::slotAccessibilityChanged(bool,QString)
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1" has new interfaces: ("org.freedesktop.UDisks2.Block", "org.freedesktop.UDisks2.Filesystem", "org.freedesktop.UDisks2.Part
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:45 sparhawk-XPS-17 udisksd[554]: Mounted /dev/sdc1 at /run/media/lee/Lee-key on behalf of uid 1000
Mar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/index.bdmv
Mar 04 14:35:45 sparhawk-XPS-17 org.gtk.Private.UDisks2VolumeMonitor[420]: index_parse.c:190: indx_parse(): error opening /run/media/lee/Lee-key/BDMV/BACKUP/index.bdmv
Mar 04 14:35:45 sparhawk-XPS-17 baloo_file[640]: true "/org/freedesktop/UDisks2/block_devices/sdc1"
Mar 04 14:35:45 sparhawk-XPS-17 polkitd[416]: Operator of unix-session:c2 FAILED to authenticate to gain authorization for action org.freedesktop.udisks2.filesystem-mount for system-bus-name::1.258 [kdeinit4: kded4 [


Q: Make checkbox.Checked = True whose corresponding PictureBox is clicked I have 28 CheckBoxes in a windows form. Each box has PictureBox above it. When the user clicks on a PictureBox, I want to change the BackColor of the PictureBox to green, and make its corresponding CheckBox.Checked = True
The code I am using:
Private Sub PictureBox1_Click
    PictureBox1.BackColor = Color. Green
    CheckBox1.Checked = true

For 28 it will be a lengthy process. Is there any easy solution?

A: Programmatically add MouseClick even handlers to all your PictureBoxes in Form_Load. The event handler will parse the sender (PictureBox) and find the CheckBox based on the fact that the corresponding controls' names end in the same index. Remove the handlers when the form closes.
Private pictureBoxPrefix As String = "PictureBox"
Private checkBoxPrefix As String = "CheckBox"

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        AddHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

Private Sub PictureBox_MouseClick(sender As Object, e As MouseEventArgs)
    Dim index = Integer.Parse(pb.Name.Replace(pictureBoxPrefix, ""))
    Dim pb = CType(sender, PictureBox)
    Dim cb = CType(Me.Controls.Find($"{checkBoxPrefix}{index}", True).First(), CheckBox)
    pb.BackColor = Color.Green
    cb.Checked = True
End Sub

Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
    For Each pb In Me.Controls.OfType(Of PictureBox).Where(Function(p) p.Name.Contains(pictureBoxPrefix))
        RemoveHandler pb.MouseClick, AddressOf PictureBox_MouseClick
    Next
End Sub

A: In the Load() event of your form, use Controls.Find() to get a reference to both the PictureBoxes and CheckBoxes.  Store the CheckBox reference in the Tag() property of each PictureBox.  Wire up the Click() event of you PB.  In that event, change the color of the PB, then retrieve the CheckBox from the Tag() property and check the box as well:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For i As Integer = 1 To 28
        Dim PB As PictureBox = Me.Controls.Find("PictureBox" & i, True).FirstOrDefault
        Dim CB As CheckBox = Me.Controls.Find("CheckBox" & i, True).FirstOrDefault
        If Not IsNothing(PB) AndAlso Not IsNothing(CB) Then
            PB.Tag = CB
            CB.Tag = PB
            AddHandler PB.Click, AddressOf PB_Click
            AddHandler CB.CheckedChanged, AddressOf CB_CheckedChanged
        End If
    Next
End Sub

Private Sub PB_Click(sender As Object, e As EventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    Dim cb As CheckBox = DirectCast(pb.Tag, CheckBox)
    If pb.BackColor.Equals(Color.Green) Then
        pb.BackColor = Color.Empty
        cb.Checked = False
    Else
        pb.BackColor = Color.Green
        cb.Checked = True
    End If
End Sub

Private Sub CB_CheckedChanged(sender As Object, e As EventArgs)
    Dim cb As CheckBox = DirectCast(sender, CheckBox)
    Dim pb As PictureBox = DirectCast(cb.Tag, PictureBox)
    pb.BackColor = If(cb.Checked, Color.Green, Color.Empty)
End Sub


Q: Какая сложность у этого блока кода? Не могу понять, почему тут сложность O(n^2)?
for(i = 0;i<n;i++){
    for(j = 0;j<i;j++){
      sequence of statements
    }
}

A: Считается, что у такого кода сложность O(n2).
Внутренний цикл на каждой итерации внешнего цикла выполняется сначала 0, потом 1, 2 и так далее до n−2 раз, пока выполняются условия j<i<n.
Общее количество выполнений внутреннего цикла равно 0 + 1 + 2 + ... + n−2. Это сумма членов арифметической прогрессии, которая считается по формуле S = (a1+am)×m/2, где m — общее количество элементов.
В вашем случае a1 = 0, am = n−2, m = n−1.
Итого, S = (n−1)(n−2)/2 = (n2-3n+2)/2.
В нотации О-большое мы оцениваем производительность алгоритмов на высоком уровне, не детальном. Поэтому отбрасываем все несущественные части суммы.
При больших значениях n, n2 несоизмеримо больше, чем просто n, и большее чем константа 2, поэтому от (n2-3n+2)/2 остаётся n2/2.
Точно также мы отбрасываем константные множители, у нас это 1/2. Таким образом, n2/2 превращается в n2.
Поэтому сложность O(n2).

A: В данном случае сложность действительно квадратичная О(n^2).
Строго говоря, количество итераций здесь:
0 + 1 + … + n-1 = n * (0 + n - 1) / 2 = (n^2 - n)/2
Это по формуле арифметической прогрессии.
Конечно это не ровно n^2, а слегка меньше. Но О-большое это верхняя граница, а не точная оценка. Под линейную или, скажем, логарифмическую сложности приведенный вами алгоритм явно не подходит.


Q: User List with Role in .Net Core 3.1 Identity Can I get a list of all the users with the associated roles in .Net Core 3.1 from Identity? I haven't found any solution that works.

A: You need to customize Identity Model and add navigation properties.
public class ApplicationUser : IdentityUser
{
    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }
}

and then add required configuration.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<ApplicationUser>(b =>
    {
        // Each User can have many entries in the UserRole join table
        b.HasMany(e => e.UserRoles)
            .WithOne(e => e.User)
            .HasForeignKey(ur => ur.UserId)
            .IsRequired();
    });

    modelBuilder.Entity<ApplicationRole>(b =>
    {
        // Each Role can have many entries in the UserRole join table
        b.HasMany(e => e.UserRoles)
            .WithOne(e => e.Role)
            .HasForeignKey(ur => ur.RoleId)
            .IsRequired();
    });
}

and then you can use joins to query users with roles. More information on adding navigation proprieties can be found here


Q: MomentJS - Intended for input validation? Is MomentJS intended for user input parsing?
I've got moderately close with the easy cases, having it accept dates in the DDMMYYYY order, and it handles some variation.
It doesn't handle invalid dates particularly well when specifying the format - Including having day values too high, or switching year values between 2 and 4 digit.
Examples of year interpretation:
var date1 = moment('30082012', 'DDMMYYYY');
var date2 = moment('30082012', 'DDMMYY'); // Gives wrong year - 2020
var date3 = moment('300812', 'DDMMYYYY'); // Gives wrong year - 1900
var date4 = moment('300812', 'DDMMYY');

Examples of what would hopefully be invalid dates:
var date5 = moment('08302012', 'DDMMYYYY'); // Gives Jun 08 2014
var date6 = moment('08302012', 'DDMMYY'); // Gives Jun 08 2022
var date7 = moment('083012', 'DDMMYYYY'); // Gives Jun 08 1902
var date8 = moment('083012', 'DDMMYY'); // Jun 08 2014

I have created a JS Fiddle with these examples: http://jsfiddle.net/cHRfg/2/
Is there a way to have moment accept a wider array of user input, and reject invalid dates? Or is the library not intended for this?

A: var parsed = moment(myStringDate, 'DD.MM.YYYY');

for Version >= 1.7.0 use:
parsed.isValid()

for Version <  1.7.0 create your own isValid() function:
function isValid(parsed) {
    return (parsed.format() != 'Invalid date');
}

checkout the docs:
http://momentjs.com/docs/#/parsing/is-valid/

A: You can try parsing multiple formats. Updated fiddle: http://jsfiddle.net/timrwood/cHRfg/3/
var formats = ['DDMMYYYY', 'DDMMYY'];
var date1 = moment('30082012', formats);
var date4 = moment('300812', formats);

Here are the relevant docs. http://momentjs.com/docs/#/parsing/string-formats/
There is development on adding moment.fn.isValid which will allow you to do validation like in examples 5-8. It will be added in the 1.7.0 release. https://github.com/timrwood/moment/pull/306


Q: All Params Not Being Passed I am using php to create a hyperlink, and pass 3 params when the hyperlink is clicked.  My issue with the syntax below is that only the 1st param is passsed, the other 2 are ignored.
What should I alter in the syntax below so that all 3 params are passed?
    if($number_of_rows > 0) {
    echo '
';
    echo '
';
    echo '  Name 	';
    echo '  User ID 	';
    echo '  Dollar Amt 	';
    echo '  Price 1 	';
    echo '  Price 2 	';
    echo '  Price 3 	';
    echo '  Price 4 	';
    echo '  Items Sold 	';
    echo '  Items On Sale	';
    echo '
';

while ($Row = mssql_fetch_assoc($result))
{
    echo '
' . $Row['Name'] . '	' . $Row['User ID'] .
    '	' . "$".round($Row['Dollar Amt']) . '	' . "$".round($Row['Price 1']) .
    '	'. "$".round($Row['Price 2']) . '	'. "$".round($Row['Price 3']) .
    '	'. "$".round($Row['Price 4']) . '	' . $Row['Items Sold'] .
    '	'.$Row['Items On Sale'].'
';
}

The above runs a sql server stored procedure and I am using echo to create a table and return to my page. That process works as it should. The only issue is that only name is passed into the url when clicked not the 2 dates that I also want to pass.
NOT a duplicate, that is pertinate to mysql and I am using mssql.  Also, the linked duplicate talks about returning rows, now passing parameters.  My issue is that only the name parameter is passed when clicked. Please remove the duplicate flag.
EDIT
The variables are defined like so:
$begin = $_GET['begin'];
$end = $_GET['end'];

A: You are mixing double-quote " and single-quote '. Replace last line of your code inside while loop with following and it should work as expected.
'	'.$Row['Items On Sale'].'
';

From your post edit, try this:
'	'.$Row['Items On Sale'].'
';


Q: Passing and accessing value in Django form I'm trying to pass info to my form and I have a bit of a struggle with that. My code looks as follows:
views.py
class ObjectUpdateView(UpdateView):

    template_name = 'manage/object_form.html'
    form_class = ObjectEditForm
    def get_success_url(self):
        #...
    def form_valid(self, form):
        return super(ObjectUpdateView, self).form_valid(form)
    def get_object(self):
        return get_object_or_404(Room, pk=self.kwargs['object_id'])
    def get_form_kwargs(self, **kwargs):
        objectid = self.kwargs['object_id']
        object = Object.objects.get(id = objectid)
        container = object.container
        kwargs['container_id'] = container.id
        return kwargs

forms.py
class ObjectEditForm(forms.ModelForm):
 class Meta:
     model = Object
     fields = ['TestField']

 def __init__(self, *args, **kwargs):
     super(ObjectEditForm, self).__init__(*args, **kwargs)
     self.Container_id = kwargs.pop('container_id')

form_page.html
{{fomr.kwarg.Container_id}}

As you can see I'd like to access Container_id value in my form_page.html. Unfortunately, nothing is there. What I also noticed, that with __init__ I had to add, now values are empty in my form. Before I added __init__ all values were properly passed (well, except Container_id).
Could you recommend how I can pass such value to be accessed in the form template?

A: You can render this with:
{{ form.Container_id }}
In your form you should first pop the container_id from the kwargs, like:
class ObjectEditForm(forms.ModelForm):

    class Meta:
        model = Object
        fields = ['TestField']

    def __init__(self, *args, **kwargs):
        # first pop from the kwargs
        self.Container_id = kwargs.pop('container_id', None)
        super(ObjectEditForm, self).__init__(*args, **kwargs)
Use the context over the form
That being said, it is a bit strange that you pass this to the form, and not add this to the context data. You can simplify your view a lot to:
class ObjectUpdateView(UpdateView):

    template_name = 'manage/object_form.html'
    pk_url_kwarg = 'object_id'
    form_class = ObjectEditForm

    def get_success_url(self):
        #...

    def get_context_data(self, **kwargs):
        objectid = self.kwargs['object_id']
        object = Object.objects.get(id = objectid)
        context = super().get_context_data()
        context.update(container_id=object.container_id)
        return context
Django automatically fetches a single element based on the pk_url_kwarg [Django-doc]. You only need to set it correctly, so here that is the object_id.
In that case, we can simply render this with:
{{ container_id }}
and you do not need to store this in the form.


Q: Hardware and Service for Voip What king of hardware/service do I need to create a voip system in my LAN ( only PC-to-PC call and without internet connection !! ) ?
1) Internet Connection
2) Voip phones
...
.
Help me to compile the above list ;)

A: Skype is a quick and easy way to get up and running with VOIP.
However, there are other things you can run like Asterisk server and have VOIP enabled phones, but is fairly advanced and requires a lot of time. It depends on what your goal is. Are you in a business, or just two roomates looking to chat from two floors?

A: PC - to - PC?
Why don't you use headsets and Skype or any SIP-compatible Client & Service?
[edit]
After telling us that skype is not an option you should go for Asterisk and evaluate if it's any use for you. Here are some virtual appliances i found using google:
http://www.vmware.com/appliances/directory/48
http://www.jumpbox.com/app/asterisk
AFAIK the hardware needn't be that strong for a simple setup. If you are working with a lot of clients (or active "telephone lines") you may need a bigger machine. But i'm just guessing and adding some bits of knowledge here.


Q: How do I update environment variable (System.getenv) (not Java system property) variable during runtime in Java U tried various solutions like ProcessBuilder and Runtime to update an environment variable, but none work. I have used reflection, but it does not seem to work as it's an unmodifiableMap.
private void updateEnvVars(Map<String, String> kafkaProps) {
    try {
        Class[] classes = Collections.class.getDeclaredClasses();
        System.out.println("Total Classes : " + classes.length);
        Map<String, String> env = System.getenv();
        for (Class cl : classes) {
            System.out.println("ClassName: " + cl.getFields().toString());
            if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                Field field = null;
                field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                final Map<String, String> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.putAll(System.getenv());
                objectObjectHashMap.putAll(kafkaProps);

                Map<String, String> map = (Map<String, String>) obj;
                //java.util.Collections.unmodifiableMap<String, String>
                //final Map<String, String> stringMap = Collections.unmodifiableMap(map);
                map.clear();
                map.putAll(objectObjectHashMap);
        }
    }


Q: Rewrite with proof-irrelevant equivalence relations in Agda? I am quite new to type theories and dependently typed programming and is recently experimenting with various features of Agda. The following is a very simplified example I wrote of a record type C which contains multiple component records and some constraints that we can prove things with.
open import Relation.Binary.PropositionalEquality

module Sample (α : Set) where
  record A (type : α) : Set where

  record B : Set where
    field
      type : α

  record C : Set where
    field
      b₁ : B
      b₂ : B
      eq : B.type b₁ ≡ B.type b₂

    conv : A (B.type b₁) → A (B.type b₂)
    conv a rewrite eq = a

It seems appealing to me that the constraint eq : B.type b₁ ≡ B.type b₂ should be declared irrelevant by adding a . in the front (or, in the latest dev version 2.6.0, to replace by an equivalence relation of sort Prop, e.g.
data _≡_ {ℓ} {α : Set ℓ} (x : α) : α → Prop ℓ where
  refl : x ≡ x

), so that two instances of type C with the same components can be directly unified via refl regardless of different proofs eq. However, either way, the program stops to compile because I cannot pattern match on an irrelevant value / Prop.
I would like to know whether it is possible for the same functionality to be implemented in Agda in any way, or that in general why it is impossible to rewrite with proof-irrelevant equivalence relations in Agda (technical support difficulties, or this breaks some parts of Agda's type theory, etc.)?

A: This is currently not yet possible in Agda due to technical limitations: 'rewrite' is just syntactic sugar for a pattern match on refl, and currently pattern matching on irrelevant arguments is not permitted. In our paper at POPL '19 we describe a criterion for which datatypes in Prop are 'natural' and can thus be pattern matched on. I hope to add this criterion to Agda before the release of 2.6.1, but I cannot make any promises (help on the development of Agda is always welcome).


Q: Microsoft word - conditional formatting in mail merge? Is it possible to use conditional formatting in Microsoft Word 2007 Mail merge? I would like it to color the font, depending on the field value, for instance:

*

*if "Priority" field equals 1, color the font to red

*if "Priority" field equals 2, color the font to yellow

*if "Priority" field equals 3, color the font to green

I've tried using the "Rules" -> "If... Then... Else" and this could probably work, but creating rules using it is a nightmare.... Is there a better way?

A: Using If..Then..Else is the right start as it inserts an IF field into the document which is what you need, however the dialog which comes up isn't powerful enough to do this kind of thing so you will need to edit the IF fields manually in the document.
What you will need to have is IF fields which compare the value of the field and will display the field with desired  color for the appropriate value. Don't forget the MERGEFORMAT switch so that this color is passed on to the merged text.

A: Normally you would need the { IF } as suggested by Adam, or you can use separate IF fields rather than nested ones if the test values are mutually exclusive.
Either way, trying to insert nested fields using the built-in dialogs can be difficult. It's usually simpler to work with the field code shortcut keys and enter them manually - on WIndows Word, ctrl-F9 to insert a pair of the special field code braces, alt-F9 to toggle between field code view and results view, F9 to update selected fields and so on.
In the specific case where there are three values to test, the text to be coloured is short and contains no single quote characters, then you could consider using something like this:
{ ={ MERGEFIELD Priority }-2 \#"'priority 3 text';'priority 1 text';'priority 2 text'" }
Then you apply the appropriate colour to each text.
The length limitation is that the text between the "" cannot exceed 64 characters.
You can bring the text in from a merge field by nesting the appropriate merge field, but the same limitations on single quote characters and total length apply.


Q: how to find the value of K in quadratic equations look at the following question

If one of the Zeros of polynomial $f(x)=Kx^2-17K+(3K-2)$ is reciprocal
  of other zero, then K is equal to:
(a) 1, (b) -1, (c) 2, (d)-2

i solve the above question as follows
let the one zero be $a$ then,
$a=1/a$ because one zero is reciprocal of another,
then
taking $x=a$,
=>   $k(a)^2-17k+(3k-2)=0$
=>   $a^2k-17k+3k-2=0$
=>  $a^2k-14k-2=0$.....(1)
now taking $x=1/a$
$k(1/a)^2-17k+(3k-2)=0$,
$k/a^2-14k-2=0$,
$k-14ka^2+2a^2/a^2=0$    .....(2)
since equation 1 and 2 are equal to same thing then (1)=(2)
therefore $a^2k-14k-2=k-14ka^2-2a^2/a^2$,
$a^2(a^2k-14k-2)=k-14ka^2-2a^2$,
$a^4k-14ka^2-2a^2=k-14ka^2-2a^2$,
$a^4k-14ka^2+14ka^2-2a^2+2a^2=k$,
$a^4k=k$,
$a^4=1$,
hence, $a=1$
fortunately the answer is correct but i had found the value of $a$ instead of $k$, then what is the mistake ?
thanks.

A: If one root is reciprocal of another,their product is $1$
So, using Vieta's formula we have $\displaystyle 1=\frac{3K-2}K$


Q: Why toast message are not show in android 4.1 operating system containing mobile I cant see the toast message in android 4.1 mobile. Upto yesterday I was able to see the toast message. From today only I can not see the message. Please help me.
Toast.makeText(getApplicationContext(), "hi", Toast.LENGTH_SHORT).show();

I have tried custom toast message also instead of toast message. But still not working.
Custom toast:
LayoutInflater inflater=getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,(ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Please fill Name");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

A: Change to this and check again.
if(first_name.length() == 0)
{
    Toast.makeText(NameOfYourActivity.this, "Please fill Name", Toast.LENGTH_SHORT).show();
    Utilities.writeIntoLog("Please fill Name");
}

A: just post the google code link here.
Since Jelly Bean, users can disable notifications for a given app via "app details" settings.
A very bad and unwanted side effect is that once notifs are disabled, Toast messages are also disabled, even when the user is running the app!
You encourage to use Toast in your design guidelines, but who will want to use it if the users have the possibility to remove them, especially if the toasted message is an important feedback to display to the user...
I understand at least that Toasts could be disabled when the app is in background, but not if it is the foreground Activity.

A: Toast was not showing with me in Android 4.1 because Show Notifications was checked off in my app's settings. I just went to Settings->Manage Applications->[My App] and toggled on Show Notifications and Toasts started to appear.

A: Toast is working fine in all the version of Android. There can be couple of issues in your code like

*

*Your context is not wrong

*You are trying to display toast in the background thread instead of worker thread.

Edit
In your custom toast don't set the parent in your layout inflater for example use like below
View layout = inflater.inflate(R.layout.toast_layout,null);

A: I had the same problem. When I invoked the code on UI thread the issue resolved for me
public void showToastMessage(final String msg) {

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    });
}


Q: Build and strengthen the Stack Exchange community with "crossover questions" between sites I've been a Stack Exchange contributor for a couple of years now, currently most active on travel.SE. One thing that keeps coming up is questions that would appeal to audiences on two different Stack Exchange sites but there are almost no features taking advantage of these questions.
On travel.SE we have crossover questions most often with outdoors.SE and possibly next most often with bicycles.SE - but it can happen with almost any SE site. Today alone we had a question that would cross over with money.SE and opendata.SE had a question that would cross over with us.
I am absolutely sure that this must happen all the time between arbitrary pairs of Stack Exchange sites but the only feature that takes advantage of it is the possibility of migrating off-topic questions which leaves the original question acting as a redirect across the two sites.
I think there is a missed opportunity to build the network between sites where users of one site don't realize they could make valuable contributions to a sister site they have had so far little to do with.
At the very least there could be a way to "advertise" a question on a second site that could be interested in it. Probably by listing it in the sidebar where there are also links to meta questions, linked questions, related questions, new blog posts, and
But there could also be some kind of features that make some sort of acceptable crossposting. There could be gamification/badges added around building cross-site questions or whatever else you can think up.
I think this is a great way for people to spread their expertise from their main site onto other sites, to make the network stronger and more cohesive, to bring more attention to questions that would have a divided audience between two sites. I can think only of positives and no negatives.
Does anyone else have some ideas to add or think this is a bad idea for any reason?

Example crossover questions:
Here are some links to some crossover questions I've been finding in the Stack Exchange network here. (This was previously posted as an answer, but more people wanted it to be part of the question.)

*

* ▶  : Stream Airfare data

* ▶  : Is it possible to “cook” pasta at room temperature with low enough pressure?

* ▶  : Is our mental lexicon structured like a tag-cloud system or hierarchical?

* ▶  : In Latent Semantic Analysis, how do you recombine the decomposed matrices after truncating the singular values?

* ▶  : If travelling through excessively cold regions, what steps should you take to keep your vehicle warm enough to drive?

* ▶  : What is usually an American breakfast outside of the US?

* ▶  : How Do Bicycle Spokes Work?

* ▶  : Where is a tripod allowed from high up in New York City?

* ▶  : Twitter image encoding challenge

* ▶  : If the letter J is only 400–500 years old, was there a J sound that preceded the design of the letter?

* ▶  : British Sunni Muslim visiting Iran with family

* ▶  : Why does Stack Exchange require you to click to be turned down?

* ▶  : Why does Obi-Wan say that he'll become more powerful if Vader kills him?

A: This has been roughly implemented on the international sites for the use case of linking from Stack Overflow in English to canonical questions written in other languages.
If you go to certain questions on Stack Overflow and your browser language is set to one of the non-English languages that we support, you might see a small banner letting you know that we have a nearly identical question on [language] site, with answers of comparable quality. This works by users on the international sites nominating pairs of links (originating from English site, landing on international sites) which are vetted and put in place.
All of this currently runs on stuff that isn't quite in the code base properly, and probably won't be until Channels is quite a bit more feature complete. But, some functionality does exist.
I'd personally like to have something similar to what has been proposed in various forms here eventually; it would be great to lessen the fragmentation between SO and sites like Software Engineering, for instance. However, I can't give a definitive timeline on an implementation, or what that might eventually look like.
I'm tagging this as deferred as it is something that I really want to explore, but I can't give any promises on when we'll be able to do it. I can say that getting the rough implementation that we have going for the international sites more 'properized' and supported with UI that doesn't require user scripts is a big priority for me once resources become available, so the idea as a whole is definitely near the top of the list of stuff I want to see get more attention as soon as we're able to provide it.

A: Cross-site question association
I suggest to extend question association mechanism to all StackExchange sites.
It's already working between mechanism between StackOveflow in Russian and StackOverlow in English.
Something like this
Text translation: This question has answers on StackOverflow in Russian.
 [link to associated question].

If very similar questions were asked on different StackExchange sites (that have some topic intersection) we can show link under associated questions This question has answers on [StackExchange site of associated question]. [link to associated question]..

A: I imagine this might be better if, instead of multi-posting the same question on multiple sites, allowing the same question to be shown on multiple sites, and show up in the search results for those sites, while remaining just one question in the database.
I understand that this would come with some challenges, such as determining which tags should and should not be used (per-site), but it would be a cool way to see how different communities can contribute to the same question.
Answers could then include an icon indicating which site the user answered from, and badges or reputation would be only for that site, simplifying this. Furthermore, it gives users of one site an idea of what the other communities are like, and may get more users on the sister sites.
This approach could also work either by letting the OP specify which sites to share on (and those sites can close it on their respective sites), or this could be something left to reviewers with high enough reputation - but either way I think both models would work.

A: I would support such a feature.
I feel the segmentation of SE sites has become a bit excessive (e.g. SO, Code Review, Programmers and CS). This causes the average user (like myself) to worry more about where to post than how post correctly (partially because of fear of being scolded by the more hard-core users). In my case it ends up with me completely giving up on the post and searching for answers elsewhere.
I think that cross posting would allow the average user to post the question in the most fitting site (without worrying about not reaching some potentially interested experts), and use the cross-post feature to try suggest that the question be published on another site where the question might also be relevant.
I do agree with some other answers here, that in some cases, a question that fits more than one SE site might be indicative of a bad question, but I believe that these cases are not the majority. In any case, I don't think that such feature, if moderated correctly, would contribute to more bad questions being posted.

A: I totally agree that as the number exchanges/communities have grown, a lot of overlapping questions are spreading across the lines between the communities.
I also agree Migrating a question that was posted in the "incorrect" Community is not really a good fit for these questions.

*

*The OP participates in and posted in the original Community because he thinks that is where it belongs.  He has already expressed what he thinks the "correct" Community it.

*Once the question is migrated (if that is possible), content that was posted in the originating community is often lost.

*Often the decision of which Community is the one-and-only-one "correct" Community is highly subjective,  a situation Stack Exchange generally tries to avoid.

I had noticed this and recently proposed a different way to addressing the problem - Let Communities refer questions to other communities.
I do like your solution as well; but, as a developer, it seems that it might be more complicated to implement.  I believe a lot of the problem could be addressed by allowing visibility of the referred questions to other Communities but still allowing them to remain in the original community.

A: To build on Phil's great start, here is how I think it should work.
Question is Asked
A user on physics asks:

How Do Bicycle Spokes Work?

This is assigned a post ID of #94,0001 on physics. It is a physics question.
Cross-site Users Show Interest
hippietrail with accounts on both sites is browsing physics and sees this question and thinks it would be great on bicycles too. So he clicks a button:
Recommend on Other Site
This brings up a list of the sites he is a member on and allows him to pick which one wants to suggest it as a good fit for. Other users can see this on the question as they would a close vote:

They can either up-vote or down-vote the cross-site recommendation perhaps along the lines of a review or somesuch.
Both suggesting cross-site posting and voting on existing suggestions should be only visible/available to high-rep users on the destination site
Review Gets Created
On both the target-site and the original-site a review task for trusted users gets created. For the original-site they are allowed to vote either:
Migrate or Cross-Post
For the destination-site they are allowed to vote either:
Accept or Reject
If the receiving-site votes 'Reject' it does not get sent regardless (it stays on the original site akin to a rejected migration). If the receiving-site votes 'Accept' then it gets Migrated or Cross-posted depending on the choice of the original-site voters.
Managing Post IDs
We know how migrations work, so let's ignore those for now. The original-question has an ID of #94,001 on Physics, and it and any answers get new IDs on Bicycles. Post-type in data.se could be set as 9 - Cross-post to be able to distinguish the origin of each post since it is existing in two time-stack continua at once.
Yes, continua is the plural of continuum apparently. Latin, it's dead for a reason folks.
Any additional answers tacked on would be automatically assigned an ID on any shared site(s) with the same cross-post PostTypeID while being assigned a proper answer ID on the site it originated from.
Voting on Cross-Posts
If you are on Physics when you vote:

*

*Votes/flags on Physics-originated posts are treated as normal

*Votes/flags on non-Physics posts have no impact on reputation/score, but impact display

If an answer accumulated too many downvotes/flags that originated on a different site, it will be hidden from people accessing the question from the physics side. The answer may be good for bicycles, but not have so much benefit to the physics readers. And that's fine. The same would happen the other way around too. So we hide any inappropriate answers that a site's community deems aren't right for them (but don't lose them from the other site).
Hiding Cross-Posts from New/Google Users
For new users (under the association bonus level) and for google crawlers, only answers originating from the site being browsed should be applied. This means that bicycles.se answers will be more bicycle-oriented for search terms, and physics.se answers will focus more on the physics and differentiate the search results (hopefully). New users will not be confused by the potential for very contrasting answers or other issues related to differing community standards without losing out on anything.
Moderating These Questions
Locks/Protects would be per site and not mirrored on the other site (no sense in preventing good answers to be given on Physics for issues with the popularity on Bicycles).
Close votes would work as follows:

*

*Closed on original site ▶ Migrated to target-site

*Closed on target-site ▶ Treat as rejected migration

Flags on questions by users of either site would only be shown to trusted users/moderators of that site (no moderation of the other communities' questions).
I think this is a tremendous idea and will reduce poor migrations as well as give people a much better resource for comprehensive information on a cross-discipline topic, improving the quality of SE as a resource.

A: I like this idea, and agree with the rationale insofar as it helps a question reach an interested audience (not creating clutter, iow).
Some potential challenges:

*

*User privileges -- ability to edit, delete, etc. -- greater on the shared-with site than the originator site...  Is that OK?

*Tags -- how would those be treated?

Implementation ideas:

*

*add this as a review category (?) -- for reviewers to include/exclude questions nominated for sharing?

*add a new privilege category (?) -- so a person who wants to nomiate a question to be shared with SO, for example, would have to have some level of rep on SO?

--EDIT--
Re-reading this post / some of the answers that have come-in later...
One perspective that I think hasn't received much attention here is the cross-suitability of the answer to the cross-posted question.  It's one thing for a question to be relevant to two sites (using the 'how bicycle spokes work' example on @jmac's great answer here); but it may be quite another thing for the answer to be relevant on both sites.  For example, I can imagine readers on the physics SE will be more interested in answers describing the different types for force and how they be modeled using physics formulas, etc.; and I can imagine the readers on the bicycle enthusiasts' SE site being interested in an entirely different sort of answer (maybe something more focused on performance comparisons with alternative wheel designs on/off road, etc.).
I don't have any great ideas for where to go with this, but it seems like something that should be part of the discussion / proposed solutions.

A: I don't think there should be any crossover feature that would allow posting a single question on multiple sites (how should edit/close priviledges be calculated for the users of both sites?). The sites should be designed so that the topic crossover should be an exception, not the rule.
However, there are many common interest areas, so I'd vote for the idea of stronger linking between sites. For example, by adding a network-wide linked and related questions section on the left side. The question would always belong to one site, but it would be easier to browse related questions on the other sites.
For example it could look like that:
Linked  (Travel)

*

*question 1

*question 2

*question 3

Linked (other SEs)

*

*question 4 (The Great Outdoors)

*question 5 (Physical Fitness)

*question 6 (Photography)

Related section would be more tricky to implement, because network-wide looking for duplicates must be something more intelligent than simply word-based (I don't think people on Pets would be happy seeing Python programming questions in every second raptiliae question).

A: You have some great points, however the reason it will not currently work is because of the point systems being individual to each site.
And the badges primarily being individual to each site.
I could see improved performance on users using multiple sites if there were more badges added to stack overflow that were based on the point/reputation of other sites.
I don't necessarily think it would be good to add a whole lot more badges, to the already numerous gold/silver/bronze badges there are. What I think would work, is to create a platinum badge or something, that is relative to how many sites you have a total rep score of over 1000 points or something.

A: I suggest that there be a Network tab, or similar options to display interesting questions from across the network.
Clicking on questions from this tab would take you to the orignal question on it's "Real" site.
This suggestion is otherwise very similar to https://meta.stackexchange.com/a/219824/144630
I suggest the list of questions to be shown on that list be manually curated.
With the curation being an unlockable privilege determined by reputation on both sites.
Possibly with:

*

*"Add to cross-site list for X", requiring some level of rep on both sites. Probably 100 would be good, since the assoication bonus kinda indicates "You get Stack Exchange enough to have some respect everywhere in the network".

*Removing being similar to close-voting, requiring 4 votes by people with a certain privilege on the receiving site (probably lower than close voting).

Mock-up:
Yes the mockup image is inconstant, in formatting, but it is just example.

I'm not entirely happy with the idea of it as a Tab,
but I think it does benefit somewhat from being on a separate list to the real questions on the site.
So users who just don't care can ignore it.
(I would expect a lot more cross-posts than migrations, so leaving it in the main lists might not be good. Or it might be Ok)

A: Crossposting is bad.
A question which could be answered on two different sites is not a good question. Perhaps it needs to be more reasonably scoped.  Perhaps the person asking needs to understand their problem a little better so they know who best to ask for a fix. Perhaps they need to understand the audience a bit better and reword the question so it's obvious what they need to know.

*

*Stream Airfare data --> This isn't about travelling.  It's about getting data from a specific database on the internet. A traveler might have this problem, but it isn't a traveler problem.

*Is it possible to “cook” pasta at room temperature with low enough pressure? --> This is two different questions.  "Does pasta need to be cooked, or just rehydrated?" and "Does cooking happen by temperature, or by the state change of water?" They both belong on cooking.

*If travelling through excessively cold regions, what steps should you take to keep your vehicle warm enough to drive? --> The author specifically states they do not want vehicle advice, they want general procedures for a specific type of emergency during a trip. You could post something similar to an emergency prepardeness/survival/wilderness site, but again you'd tailor it for that group of experts.

I could go on, but here's the key:
If a question is well-written for a specific group of experts, it will irritate the experts in the other group.  If it waffles or tries to address both groups, it will merely irritate both of them.  It will be given close votes, comments indicating it's inappropriate nature for the site, etc.
We already allow links in the questions.  So I've seen many questions that present the problem, then provide a link to a related question on another site.  The answers aren't the same, because the expertise on each site isn't the same and it shouldn't be.
It may be that there's some room for another sidebar, "Related questions on other SE sites" which links to explicitly linked questions, and uses keywords and tags to link to related questions elsewhere.
But we should not see the same exact question on two different sites.  It shows a lack of understanding about the group of experts the question is being addressed to. We don't want to encourage this behavior, because it requires bad questions that try to address two different groups of experts. If the user isn't sure, let them post it on the site they believe is best, and the moderators can move it, others can edit it, in order to make it work on the correct site.
Crossposting shouldn't be encouraged or supported.

A: I came across this question in during the process of writing a related question: Multi-Topic / Cross-Topic Question: Search Visibili...
This question is also very similar to 2012-META: Asking on Multiple Sites: “Soft-Migration”.
I'm wondering if a simple patch solution could be to fill out search results with Q&A from related topics/sites? I think this would help improve question visibility and also help provide more answering opportunities to casual users around StackExchange.
Take my example:

*

*diy_search=affinity+fan

*engineering_search=affinity+fan
As of April 2019 there are only ~4 search results total across both topics. wouldn't it make sense to supplement searches like this with possibly relevant material from related topics? Possible results could be limited to only questions with relevant tags, residing in specified coordinating topics...
It looks like some related work has been done on this within the past 2 years for foreign language topics/sites, as detailed in Vadim's answer, although I'm not sure exactly how it works, and if it is applicable more generally. Does it just put a note on the question itself? What if I don't open the question? what about question browsing?
I'd like to suggest modifying search results. Perhaps only for searches with fewer than 10 hits?
Also, side note, perhaps the association bonus could be replaced by bonus-points and badges existing between specific coordinating topics on a per-topic basis.


Q: Woocommerce REST API not considering discounts and coupons I am trying to create an order on my WooCommerce store from my mobile application using the REST API v2. The order is created successfully but I can't find any solution to the following issues.

*

*I send a coupon_lines array within the order object and when the order is viewed on the admin panel, it shows the coupon there but the order total is not affected at all.

*Then I decided to calculate the total and discounts based on the applied coupon manually. I tried to set discount_total within the order object equal to the amount which is the value of the coupon. I also update the total manually as well. But again, all the values that I pass are ignored and the order total is equal to the sum of the prices of all line items (ignoring discount_total).

Here is a sample JSON object that is sent to the API from my app.

What other options do I have to set an order total and discount manually? Any suggestions are welcome.

A: In your coupon_lines array, each item in the array needs 2 properties: code (the coupon code itself) and amount, which is either a flat fee (eg 50.00 off) or a discount (eg 10% off). Your structure ends up looking like:
"coupon_lines": [
    {
        "code": "MYCODE1",
        "amount": "10.00"
    },
    {
        "code": "MYCODE2",
        "amount": "25.00"
    }
]

If you're already doing this - consider posting an example request here.


Q: Evaluating Fourier Series
By evaluating the Fourier series of $g(x)$ at $x = 0$ show that:
  $$\dfrac{\pi^2}{12} = \sum_{n=1}^\infty\dfrac{(-1)^n+1}{n^2}$$

I have that $g(x)=f'(x)$ where $$f(x) = \dfrac \pi2 - \dfrac4\pi\sum_{n=1}^\infty \dfrac{\cos(nx)}{n^2}$$
I'm quite confused as subbing in $x=0$ obviously gets $0$.

A: If
$$g(x)=\frac12x(x-\pi)=a_0+\sum_{k=1}^{\infty}a_k\cos kx$$
For $0\le x\le\pi$, then
$$\int_0^{\pi}\frac12x(x-\pi)\cdot1dx=\left[\frac16x^3-\frac{\pi}4x^2\right]_0^{\pi}=-\frac{\pi^3}{12}=\pi a_0$$
$$\begin{align}\int_0^{\pi}\frac12x(x-\pi)\cos kx\,dx&=\left[\left(\frac1{2k}x(x-\pi)-\frac1{k^3}\right)\sin kx+\frac{x-\frac{\pi}2}{k^2}\cos kx\right]_0^{\pi}\\
&=\frac{\pi}{2k^2}\left[1+(-1)^k\right]=\frac{\pi}2a_k\end{align}$$
So
$$g(x)=-\frac{\pi^2}{12}+\sum_{k=1}^{\infty}\frac{1+(-1)^k}{k^2}\cos kx$$
And we have
$$g(0)=0=-\frac{\pi^2}{12}+\sum_{k=1}^{\infty}\frac{1+(-1)^k}{k^2}$$
So I think that expression for $f(x)$ was up there is wrong somehow -- there never was an assertion about the function the Fourier series was intended to represent was.

A: This is more of a comment than an actual answer

This is a graph of $f(x)$, so far I can tell $f(x)$ is not even differentiable at $x= 0$.


Q: "Connection failed" message when successfully connecting I have an annoying problem with my MacBook connecting to wireless routers. After typing in the password, it returns an error saying "Connection failed". However, it then goes on and connects fine. The dialog gives me 2 options, "Cancel" and "Join". Join keeps returning "connection failed" even after it has successfully connected.
It does this on multiple wireless networks whether I've remembered them or not, password protected or not.

A: To answer this topic, I took the MBP to the local Apple store where the tech found that I had 2 user accounts attempting to log into the router. I don't remember if one of them had the wrong password or if the second failed because it was already connected - probably the former.


Q: Post-request rejected by server Could anyone help to solve a problem? I'm trying to send data form from authorize user to protected controller method,   using fetch and getting  400 error. I'm using NET CORE 5 MVC  and on front-en  bootstrap 5. If I remove ValidateAntiForgeryToken from AddItemToStore method I'm getting 415 error
C# code
  [Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
    StoreUser str = new StoreUser
    {

        Id = 1,
        UserId = itemsStore.UserId,
        CatrgoryId = itemsStore.CatrgoryId
    };

    return Ok(str);
}

JS-code

var buttonAddOrder = document.getElementById("addToOrder");

buttonAddOrder?.addEventListener("click", function () {
    var catId = document.querySelector("#formToStore input[name = 'cardId']").value;
    var userId = document.querySelector("#formToStore input[name = 'userId']").value;
    var antiForgeryToken = document.querySelector("#formToStore input[name = '__RequestVerificationToken']").value;
    var itemsStore = {
        __RequestVerificationToken: antiForgeryToken,
        UserId: userId,
        CatrgoryId: catId,
        Payed: false
    };
    var url = "/CategoriesToUser/AddItemToStore";

    var response = fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
        },
        body: {

            itemsStore: itemsStore
        }
    })
        .then((response) => {
            return response.json();
        }).catch((e) => console.log(e.message));
    console.log('buttonAddOrder', response);

HTML

<form id="formToStore" method="post" enctype="multipart/form-data">
  <input type="hidden" name="cardId" id="cardId" /> @{ var getUser = await UserManager.GetUserAsync(User); }
  <input type="hidden" name="userId" asp-for="@getUser.Id" />

    <button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>

    <button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">
                        Add to Order
                    </button>

</form>

An attempt of using FormData  doesn't work, the same error.

buttonAddOrder?.addEventListener("click", function () {

    var url = "/CategoriesToUser/AddItemToStore";
    const  formToStore = document.getElementById('formToStore');
    var formOrder = new FormData(formToStore);

    let response = fetch(url, {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8;'
        },
        body: formOrder
    })
        .then((response) => {
            return response.json();
        }).catch((e) => console.log(e.message));
    console.log('buttonAddOrder', response);

});

But If I send data to anonymous post method without using  ValidateAntiForgeryToken on beck-end It's work.
Example:
[AllowAnonymous]
[HttpPost]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
    StoreUser str = new StoreUser
    {

        Id = 1,
        UserId = itemsStore.UserId,
        CatrgoryId = itemsStore.CatrgoryId
    };

    return Ok(str);
}

Screenshots

A: Before coding, you need be sure the following inputs contain value:
<input type="hidden" name="cardId" id="cardId" /> @{ var getUser = await UserManager.GetUserAsync(User); }
<input type="hidden" name="userId" asp-for="@getUser.Id" />

Two ways you could follow:
1.From Body:
View
<form id="formToStore" method="post" enctype="multipart/form-data">
  <input type="hidden" name="cardId" id="cardId" value="1" />
  <input type="hidden" name="userId" value="466788cb-6aab-4798-81f1-f6b05cb71e32"/>

    <button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>

    <button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">Add to Order</button>

</form>
@section Scripts
{

}

Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromBody] StoreUser itemsStore)
{
    //do your stuff....
    return Ok(itemsStore);
}

Startup.cs:
services.AddAntiforgery(x => x.HeaderName = "X-ANTI-FORGERY-TOKEN");

2.From Form:
View
<form id="formToStore" method="post" enctype="multipart/form-data">

                      @*change name="cardId" to name="CatrgoryId"*@
  <input type="hidden" name="CatrgoryId" id="cardId" value="1" />
  <input type="hidden" name="userId" value="466788cb-6aab-4798-81f1-f6b05cb71e32"/>

    <button type="button" id="buttonclose" name="buttonclose" class="buttonclose btn btn-secondary" data-bs-dismiss="modal">Close</button>
    <button type="button" id="addToOrder" name="addToOrder" class="btn btn-primary">Add to Order</button>

</form>
@section Scripts
{

}

Controller
Change [FromBody] to [FromForm].
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddItemToStore([FromForm] StoreUser itemsStore)
{
    //do your stuff...
    return Ok(itemsStore);
}


Q: Can't remove/purge a package due to a post-removal script error On accident, I previously removed Apache from an installation, in an attempt to remove unneeded packages on an LDAP Server. What I didn't realize is that I also had Fusion Directory installed as well, and now I cannot reinstall either Apache or Fusion Directory as I get an error any time I attempt an operation with apt/dpkg:
ckilgore@ubuntu-ldap-server:/etc/apache2/conf-available$ sudo apt install apache2
Reading package lists... Done
Building dependency tree
Reading state information... Done
apache2 is already the newest version (2.4.18-2ubuntu3.1).
The following packages will be REMOVED:
  fusiondirectory
0 upgraded, 0 newly installed, 1 to remove and 24 not upgraded.
1 not fully installed or removed.
After this operation, 6,822 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 98501 files and directories currently installed.)
Removing fusiondirectory (1.0.8.8-3ubuntu2) ...
apache2_invoke fusiondirectory postrm: No action required
apache2.service is not active, cannot reload.
invoke-rc.d: initscript apache2, action "reload" failed.
dpkg: error processing package fusiondirectory (--remove):
 subprocess installed post-removal script returned error exit status 1
Errors were encountered while processing:
 fusiondirectory
E: Sub-process /usr/bin/dpkg returned an error code (1)

What I would really like to do is simply uninstall Apache and Fusion Directory completely, reinstall, and re-import my config for Fusion Directory. However, with this issue in place I cannot. What is the best approach to fixing this issue?
Below are entries from syslog and apt log
syslog
Sep 17 09:26:50 ubuntu-ldap-server fusiondirectory: apache2_invoke fusiondirectory postrm: No action required
Sep 17 09:26:50 ubuntu-ldap-server systemd[1]: Reloading.
Sep 17 09:26:51 ubuntu-ldap-server systemd[1]: apt-daily.timer: Adding 8h 34min 29.316164s random time.
Sep 17 09:26:51 ubuntu-ldap-server systemd[1]: Started ACPI event daemon.
Sep 17 09:26:51 ubuntu-ldap-server systemd[1]: apache2.service: Unit cannot be reloaded because it is inactive.
Sep 17 09:29:53 ubuntu-ldap-server fusiondirectory: apache2_invoke fusiondirectory postrm: No action required
Sep 17 09:29:54 ubuntu-ldap-server systemd[1]: Reloading.
Sep 17 09:29:54 ubuntu-ldap-server systemd[1]: apt-daily.timer: Adding 6min 36.572554s random time.
Sep 17 09:29:54 ubuntu-ldap-server systemd[1]: Starting Daily apt activities...
Sep 17 09:29:54 ubuntu-ldap-server systemd[1]: Started ACPI event daemon.
Sep 17 09:29:54 ubuntu-ldap-server systemd[1]: apache2.service: Unit cannot be reloaded because it is inactive.
Sep 17 09:29:55 ubuntu-ldap-server systemd[1]: Started Daily apt activities.
Sep 17 09:29:55 ubuntu-ldap-server systemd[1]: apt-daily.timer: Adding 6h 12min 2.585803s random time.
Sep 17 09:29:55 ubuntu-ldap-server systemd[1]: apt-daily.timer: Adding 9h 49min 31.073000s random time.

term.log
Log started: 2016-09-17  09:29:52
(Reading database ... ^M(Reading database ... 5%^M(Reading database ... 10%^M(Reading database ... 15%^M(Reading database ... 20%^M(Reading database ... 25%^M(Reading database ... 30%^M(Reading database ... 35%^M(Reading database ... 40%^M(Reading database ... 45%^M(Reading database ... 50%^M(Reading database ... 55%^M(Reading database ... 60%^M(Reading database ... 65%^M(Reading database ... 70%^M(Reading database ... 75%^M(Reading database ... 80%^M(Reading database ... 85%^M(Reading database ... 90%^M(Reading database ... 95%^M(Reading database ... 100%^M(Reading database ... 98501 files and directories currently installed.)^M
Removing fusiondirectory (1.0.8.8-3ubuntu2) ...^M
apache2_invoke fusiondirectory postrm: No action required^M
apache2.service is not active, cannot reload.^M
invoke-rc.d: initscript apache2, action "reload" failed.^M
dpkg: error processing package fusiondirectory (--remove):^M
 subprocess installed post-removal script returned error exit status 1^M
Errors were encountered while processing:^M
 fusiondirectory^M

A: You can manually edit file /var/lib/dpkg/info/fusiondirectory.postrm to fix removal error.
Stop apache if it still running an then open that file with root privileges and find there section:
if [ -x /usr/sbin/apache2 ]; then
    if [ -x /usr/sbin/invoke-rc.d ]; then
        invoke-rc.d apache2 reload
    else
        /etc/init.d/apache2 reload
    fi
fi

Comment it and then try
sudo apt-get install -f

to fix errors or just
sudo apt-get remove fusiondirectory

to finally remove fusiondirectory.


Q: I can not get an image of the URL found with XmlHttpRequest Im trying to get a image url through XmlHttpRequest and use it like 'src' attribute of a 'img' tag. That is my plan:
function populaLista() {

var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://localhost:8080/artes');

ourRequest.onload = function() {
    var ourData = ourRequest.responseText.toString();
    var jsonResposta = JSON.parse(ourData);

    if (ourData.length > 0) {

        document.getElementById("paragrafo1").innerHTML = jsonResposta.url;

        var tabela = document.createElement("TABLE");
        var corpoTabela = document.createElement("TBODY");
        var tr = document.createElement("TR");
        var td = document.createElement("TD");
        var imagem = document.createElement("IMG");
        var urlImg = document.createTextNode(jsonResposta.url).toString();
    //  var urlImg = "https://mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg";

        document.getElementById("paragrafo").innerHTML = typeof urlImg;

        imagem.setAttribute("src",urlImg);
        td.appendChild(imagem);
        tr.appendChild(td);
        corpoTabela.appendChild(tr);
        tabela.appendChild(corpoTabela);

        document.getElementById("tabeladeImagens").appendChild(tabela);

    } else {
        document.getElementById("paragrafo").innerHTML = "item não encontrado";
    }

};
ourRequest.send();

The problem is: when I use the result of my request on my img tag, I can't see the image, but if I use the same url in a string var that I created I can see normally.

<meta charset="ISO-8859-1">

The json response:
{id : 38, url : "//mir-s3-cdn-cf.behance.net/projects/202/6310ed61231533.Y3JvcCwyNjM1LDIwNjIsMjI3LDA.jpg"}


Q: Retrieve all functions that called by a user mode process in kernel mode debug including kernels functions I am trying to find all the functions including both user mode functions and kernel mode functions that wmic.exe calls to execute the diskdrive command. In order to do this I opened wmic.exe in my virtual machine and set breakpoint in kernel mode windbg on WMIC!CParsedInfo::GetUser and WMIC!CExecEngine::ExecuteCommand.
As soon as I input diskdrive debugger breaks on ExecuteCommand, I am in kernel mode through COM port, but I cant use wt command, however I can run instructions line by line and step in to every call and track all function in stack call, but this will take lots of time and it’s not optimized. Is there any way to do something similar to the wt command in the kernel debugger?
Whenever I use the wt command it outputs ^ Unimplemented error in 'wt'.
Some extra info:

*

*I am running Windows 11 Enterprise Build 22000.856 on VMWare and connected to it through the COM port for kernel debugging and the host OS is the latest version of Windows 11 Enterprise.

*Windbg is also the latest version of windbg.

*Both windbg and vmware running as administrator.

*I am able to use all the usual commands I can see registers, see stack calls with single step, see threads and etc.

*wt runs normally on my main OS for user mode processes on my main OS without any problem


Q: Snowflake External Table Have a question regarding the Snowflake External Table. As we now the External Tables still a preview feature and still not a General Available. Hence have guys used External table in your production environment and you see any issue ? Snowflake do not recommend to use Preview feature in Production. Any thoughts?

A: External table feature is publicly available feature as per documentation
https://docs.snowflake.com/en/user-guide/tables-external-intro.html


Q: Azure DevOps Server 2020 - FilePath artifacts not always deleted from fileShare We are on ADS 2020.0.1
We are migrating to a new file server, we have noticed that drops on the new file server are not beeing deleted after the build run has been deleted.
I have created a test pipeline, where i drop to the old and new server.
After deleting the build, the artifacts are deleted on the old server, but not the new server.
old build path: 116 chars - new build path: 142 chars
The service account has modify permissions in both the old and new location. I am able to manually delete a file remotely while logged on as this account on one of the build servers.
I can see the cleanup job in the job history, it shows a red X, but i cannot see the details.
Question is, where can i see the logs of the delete artifacts task? i tried in the _oi page, but here it doesn't show anything.
We see this behaviour in classing and YAML pipelines


Q: positioning the child behind the parent of the parent element, ```z-index``` does not work I want the  to appear behind the #sideBar i tried z-index: -3 but that didn't work

body {
  margin: 0px;
  font-family: "Signika Negative", sans-serif;
  background-color: #252525;
  color: #f8f9fa;
  user-select: none;
}

#sideBar{
  width: 2vw;
  height: 100vh;
  background-color: rgb(15, 15, 15);
  opacity: .99;
}

.menuBtn{
  background: none;
  cursor: pointer;
  padding: .5vw;
  border: none;
  padding: none;
  color: white;
  font-weight: 600;
  font-size: 1vmax;
}

.menuBtn .label{
  transition: left .5s;
}

.label{
  position: absolute;
  font-size: .9vmax;
  opacity: 1;
  left: -2.2vw;
}

svg{
  transition: transform .5s;
}

.menuBtn:hover svg{
  transform: scale(1.2);
}

.menuBtn:hover .label{
  opacity: 1;
  left: 2.2vw;
}
<!DOCTYPE html>

    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link href="https://fonts.googleapis.com/css2?family=Fira+Mono&family=Signika+Negative:wght@300&display=swap" rel="stylesheet"/>

    <meta charset="UTF-8" />
    <link rel="stylesheet" href="styles.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>OverStat</title>

Clear all games and ranks<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path fill="lightgrey" d="M135.2 17.7C140.6 6.8 151.7 0 163.8 0H284.2c12.1 0 23.2 6.8 28.6 17.7L320 32h96c17.7 0 32 14.3 32 32s-14.3 32-32 32H32C14.3 96 0 81.7 0 64S14.3 32 32 32h96l7.2-14.3zM32 128H416V448c0 35.3-28.7 64-64 64H96c-35.3 0-64-28.7-64-64V128zm96 64c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16zm96 0c-8.8 0-16 7.2-16 16V432c0 8.8 7.2 16 16 16s16-7.2 16-16V208c0-8.8-7.2-16-16-16z"/></svg>

Prefrences<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="lightgrey" d="M0 416c0-17.7 14.3-32 32-32l54.7 0c12.3-28.3 40.5-48 73.3-48s61 19.7 73.3 48L480 384c17.7 0 32 14.3 32 32s-14.3 32-32 32l-246.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 448c-17.7 0-32-14.3-32-32zm192 0a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zM384 256a32 32 0 1 0 -64 0 32 32 0 1 0 64 0zm-32-80c32.8 0 61 19.7 73.3 48l54.7 0c17.7 0 32 14.3 32 32s-14.3 32-32 32l-54.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 288c-17.7 0-32-14.3-32-32s14.3-32 32-32l246.7 0c12.3-28.3 40.5-48 73.3-48zM192 64a32 32 0 1 0 0 64 32 32 0 1 0 0-64zm73.3 0L480 64c17.7 0 32 14.3 32 32s-14.3 32-32 32l-214.7 0c-12.3 28.3-40.5 48-73.3 48s-61-19.7-73.3-48L32 128C14.3 128 0 113.7 0 96S14.3 64 32 64l86.7 0C131 35.7 159.2 16 192 16s61 19.7 73.3 48z"/></svg>

How to use<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="lightgrey" d="M256 512A256 256 0 1 0 256 0a256 256 0 1 0 0 512zM216 336h24V272H216c-13.3 0-24-10.7-24-24s10.7-24 24-24h48c13.3 0 24 10.7 24 24v88h8c13.3 0 24 10.7 24 24s-10.7 24-24 24H216c-13.3 0-24-10.7-24-24s10.7-24 24-24zm40-208a32 32 0 1 1 0 64 32 32 0 1 1 0-64z"/></svg>

A: When you put opacity: .99 on the #sidebar, it forms a stacking context on #sidebar and everything inside it is stuck on it even if you put a z-index: -1000.
#sidebar {
   opacity: 1;
}
.label {
   z-index: -3;
}

Read more about the stacking context.


Q: How do I receive/send information from/to GitHub using android App I have a school project where I am supposed to create an Android application that can get notifications from a GitHub project and also be able to send comments to GitHub using the App. I don't really know where to start but I hope there is some API for Git that I can use.
I'm using Eclipse which is kinda new to me and would really appreciate some help!

A: Github has a number of apis that you can use and I'm sure there are many user created ones as well:
GitHub API
I know they recently rolled out
    Webhooks
Some developer guides


Q: Error nordvpn with ubuntu 22.10 I have to install nordvpn on my ubuntu 22.10 everything works well but when I connect to the server I got an error like this (Whoops! Connection failed. Please try again. If the problem persists, contact our customer support) I try to find any solution but it still doesn't work


Q: React Native FlatList Object displaying I have the below object that I am retrieving from the AsyncStorage, and I want to display it in a FlatList but I am getting the following error:
Invariant Violation: Invariant Violation: Invariant Violation: Invariant Violation: Tried to get frame for out of range index NaN
My JSON format is:
Object {
  "44": Object {
    "pro_id": "44",
    "pro_img": "url",
    "pro_name": " S4 ",
  },
  "52": Object {
    "pro_id": "52",
    "pro_img": "url",
    "pro_name": " S4 ",

  },
}

The JSON above is retrieved from AsyncStorage like so:
retrieveData = async () => {

    try {
       await AsyncStorage.getItem('userFavorites')
       .then(req => JSON.parse(req))
       .then(json => this.setState({ favPro:json }))

    } catch (error) {

    }
}

My method for rendering items in the FlatList is defined like this:
 fav = ({ item }) => {
    return (
      <View>
      <Text>{item.pro_id+ item.pro_name}</Text>
      </View>
    )
}

Finally, I render the FlatList as follows:
<FlatList
          data={this.state.favPro}
          renderItem={this.fav}
          keyExtractor={item => item.pro_id}
        />

How I can display my JSON data using the FlatList component?

A: The FlatList component expects an array input for the data prop. Based on your JSON format, it appears you're passing in an object rather than an array.
Consider the following adjustment to your render method:
// Convert object to array based on it's values. If favPro not
// valid (ie during network request, default to an empty array)
const data = this.state.favPro ? Object.values(this.state.favPro) : []

<FlatList
  data={data}
  renderItem={this.fav}
  keyExtractor={item => item.pro_id}
/>

A: You're using async / await incorrectly. Instead of calling .then you assign your call to await to a variable (or don't assign it if it does not return a value) and wrap the call (or calls) to await in a try / catch block. The await keyword will automatically handle resolve and reject so you get the appropriate information.
retrieveData = async () => {
  try {
    const data = JSON.parse(await AsyncStorage.getItem("userFavorites"))
    this.setState({ favPro: data })
  } catch (error) {
    console.error(error)
    this.setState({ favPro: [] })
  }
}

You also need to pass an array, the shape of your data looks like an object, but it should be an array of objects. This is not a terribly difficult transformation and I can provide a helper function if you need it.
edit: if you need to convert an object into an array, you can use the reduce function
const data = {
  '44': { a: 2 },
  '55': { b: 3 },
}

const dataArr = Object.keys(data).reduce(
  (arr, key) => arr.concat(data[key]),
  []
)

By using Object.keys we can each object by name. Then call reduce and the array returned by Object.keys, passing a function as the first argument, and an empty array as the second argument. The second argument is automatically passed to the function as the first argument, arr, and the second argument of the function we pass is the key of the object. Then it's just a matter of adding the objects to the array using concat.
Array.reduce can seem a little overwhelming at first but it's a very powerful method and you can get a lot done with it.


Q: Java: Two Scanners reading from the same input file. Doable? Useful? I have to read in integers from an input file based on whether or not a string that appears before them is a certain keyword "load". There is no key number telling how many numbers are about to be inputted. These numbers must be saved to an array. In order to avoid creating and updating a new array for each additional number scanned, I'd like to use a second scanner to first find the amount of integers, and then have the first scanner scan that many times before reverting back to testing for strings. My code:
public static void main(String[] args) throws FileNotFoundException{
    File fileName = new File("heapops.txt");
    Scanner scanner = new Scanner(fileName);
    Scanner loadScan = new Scanner(fileName);
    String nextInput;
    int i = 0, j = 0;
    while(scanner.hasNextLine())
    {
        nextInput = scanner.next();
        System.out.println(nextInput);
        if(nextInput.equals("load"))
        {
            loadScan = scanner;

            nextInput = loadScan.next();
            while(isInteger(nextInput)){
                i++;
                nextInput = loadScan.next();
            }

            int heap[] = new int[i];
            for(j = 0; j < i; j++){
                nextInput = scanner.next();
                System.out.println(nextInput);
                heap[j] = Integer.parseInt(nextInput);
                System.out.print(" " + heap[j]);
            }
        }

    }

    scanner.close();
}

My problem seems to be that scanning via loadscan, the secondary scanner only meant for integers, also moves the primary scanner forward. Is there any way to stop this from happening? Any way to make the compiler treat scanner and loadscan as separate objects despite them preforming the same task?

A: You may certainly have two Scanner objects read from the same File object simultaneously. Advancing one will not advance the other.
Example
Assume that the contents of myFile are 123 abc. The snippet below
    File file = new File("myFile");
    Scanner strFin = new Scanner(file);
    Scanner numFin = new Scanner(file);
    System.out.println(numFin.nextInt());
    System.out.println(strFin.next());

... prints the following output...
123
123

However, I don't know why you would want to do that. It would be much simpler to use a single Scanner for your purposes. I called mine fin in the following snippet.
String next;
ArrayList<Integer> readIntegers = new ArrayList<>();
while (fin.hasNext()) {
    next = fin.next();
    while (next.equals("load") {
        next = fin.next();
        while (isInteger(next)) {
            readIntegers.Add(Integer.parseInt(next));
            next = fin.next();
        }
    }
}


Q: How to use asyncio with a very long list of tasks (generator) I have a small program that loads a pretty heavy CSV (over 800MB, in chunks, using pandas.read_csv to limit memory usage) and performs a few API calls to servers "out in the wild", and finally builds a result object which is then stored in a database.
I have added caching for the network requests where possible, but even then, the code takes over 10 hours to complete. When I profile the code with PySpy, most of it is waiting for network requests.
I tried converting it to use asyncio to speed things up, and have managed to get the code to work on a small subset of the input file. However with the full file, the memory use become prohibitive.
Here is what I have tried:
import pandas as pd
import httpx

async def process_item(item, client):
    # send a few requests with httpx session
    # process results
    await save_results_to_db(res)

async def get_items_from_csv():
    # loads the heavy CSV file
    for chunk in pd.read_csv(filename, ...):
        for row in chunk.itertuples():
            item = item_from_row(row)
            yield item

async def main():
    async with httpx.AsyncClient() as client:
        tasks = []
        for item in get_items_from_csv():
            tasks.append(process_item(item, client))
        await asyncio.gather(*tasks)

asyncio.run(main())

Is there a way to avoid creating the tasks list, which becomes a very heavy object with over 1.5M items in it? The other downside of this is that no task seems to be processed until the entire file has been read, which is not ideal.
I'm using python 3.7 but can easily upgrade to 3.8 if needed.

A: I think what you are looking for here is not running in batches but running N workers which concurrently pull tasks off of a queue.
N = 10  # scale based on the processing power and memory you have

async def main():
    async with httpx.AsyncClient() as client:
        tasks = asyncio.Queue()
        for item in get_items_from_csv():
            tasks.put_nowait(process_item(item, client))

        async def worker():
            while not tasks.empty():
                await tasks.get_nowait()
            # for a server
            # while task := await tasks.get():
            #     await task

        await asyncio.gather(*[worker() for _ in range(N)])

I used an asyncio.Queue but you can also just use a collections.deque since all tasks are being added to the queue prior to starting a worker. The former is especially useful when running workers that run in a long running process (e.g. a server) where items may be asynchronously queued.


Q: SQL Count Data 1/2 hourly I have a stored procedure that counts data for each hour,
Declare @DateTimeToFilter DATETIME;
--set @DateTimeToFilter = GetDate();
set @DateTimeToFilter = '6/5/14'

SET NOCOUNT ON;

WITH H ([Hour]) AS
(   SELECT  7       UNION
    SELECT  8       UNION
    SELECT  9       UNION
    SELECT  10      UNION
    SELECT  11      UNION
    SELECT  12      UNION
    SELECT  13      UNION
    SELECT  14      UNION
    SELECT  15      UNION
    SELECT  16      UNION
    SELECT  17      UNION
    SELECT  18      UNION
    SELECT  19
)
SELECT  H.[Hour],
    COUNT(T.BookingID) AS NoOfUsers
FROM    H
    LEFT JOIN tbl_Visitor T
        ON H.[Hour] = DATEPART(HOUR, T.TimeofArrival) AND
        ((DATEDIFF(dd, T.TimeofArrival, @DateTimeToFilter) = 0) AND (DATEDIFF(mm, T.TimeofArrival, @DateTimeToFilter) = 0) AND
                  (DATEDIFF(yy, T.TimeofArrival, @DateTimeToFilter) = 0))
GROUP BY H.[Hour];

This forces the data returned for each hour irrespective of whether there is any data or not.
How could I add the half hourly data to be added also, so the returned data look like.
Hour Count
7   0
7.5 0
8   0
8.5 0
9   0
9.5 0
10  4
10.5    0
11  0
11.5    0
12  0
12.5    0
13  0
13.5    0
14  5
14.5    0
15  2
15.5    0
16  2
16.5    0
17  0
17.5    0
18  0
18.5    0
19  0
19.5    0

The data is stored in the database as a smalltimedate, i.e. 2014-06-05 14:00:00
Any help is appreciated.

A: You can use minutes instead of hours:
with h ([Minute]) as (
  select 420 union all
  select 450 union all
  select 480 union all
  select 510 union all
  select 540 union all
  ...

Divide the minutes to get fractional hours:
select h.[Minute] / 60.0 as [Hour], ...

Calculate the start and stop time for the interval to filter the data:
... on T.TimeofArrival >= dateadd(minute, h.[Minute], @DateTimeToFilter) and
       T.TimeofArrival < dateadd(minute, h.[Minute] + 30, @DateTimeToFilter)

A: Below is an example that groups by half-hour intervals and can easily be extended for other intervals.  I suggest you avoid applying functions to columns in the WHERE clause as that prevents indexes on those columns from being used efficiently.
DECLARE
      @DateTimeToFilter smalldatetime = '2014-06-05'
    , @IntervalStartTime time = '07:00:00'
    , @IntervalEndTime time = '20:00:00'
    , @IntervalMinutes int = 30;

WITH
      t4 AS (SELECT n FROM (VALUES(0),(0),(0),(0)) t(n))
    , t256 AS (SELECT 0 AS n FROM t4 AS a CROSS JOIN t4 AS b CROSS JOIN t4 AS c CROSS JOIN t4 AS d)
    , t64k AS (SELECT ROW_NUMBER() OVER (ORDER BY (a.n)) AS num FROM t256 AS a CROSS JOIN t256 AS b)
    , intervals AS (SELECT DATEADD(minute, (num - 1) * @IntervalMinutes, @DateTimeToFilter) AS interval
        FROM t64k
        WHERE num <= 1440 / @IntervalMinutes)
SELECT
      interval
    , CAST(DATEDIFF(minute, @DateTimeToFilter, interval) / 60.0 AS decimal(3, 1)) AS Hour
    , COUNT(T.BookingID) AS NoOfUsers
FROM intervals
LEFT JOIN dbo.tbl_Visitor T
    ON T.TimeofArrival >= intervals.interval
    AND T.TimeofArrival < DATEADD(minute, @IntervalMinutes, intervals.interval)
WHERE
    interval >= DATEADD(minute, DATEDIFF(minute, '', @IntervalStartTime), @DateTimeToFilter)
    AND interval < DATEADD(minute, DATEDIFF(minute, '', @IntervalEndTime), @DateTimeToFilter)
GROUP BY interval
ORDER BY Hour;


Q: Gradle circular dependency, force ignore I am trying to create a service registry where all the modules are added as compile(project(..)). The service registry module expose an unified function to call any function from any module. This is to reduce the direct coupling between two modules and to provide a proper separation of concern. To call any function from any module one can add dependency of service-registry as project and get the function. But if we do that the project has circular dependency.
Is there a way I can force gradle to ignore circular dependency,
project root
    project A
    -- compile(project(':SR'))
    project B
    -- compile(project(':SR'))
    project SR
    -- compile(project(':A')
    -- compile(project(':B')

I will be moving the dependencies to nexus and use versioning, but in initial phase it would be great if somehow I can force gradle not to do so.
Can it be done by doing some condition as
if(calling_project_name!=root) compile(project(':A'),project(':B'))exclude(project(':calling project name')

is it possible to do? Other suggestions are also welcome.
I am using gradle 2.7.


Q: reinstalling packages using the command line During installation of ubuntu on my chromebook certain packages were installed then removed...how do I reinstall them. Since several packages were removed at once can i reinstall them all at once, or one by oone, or is it possible to reinstall them at all. Thanks for any help you give.

A: Of course.
You can do
sudo apt install {package1} {package2} {package3} {package4}

where you replace {packageN} will the package names you want to install. This does depend on the packages being available in the repositories.
The same can be done with downloaded .DEB's with
sudo dpkg -i {package}

You can also search for the name in Ubuntu software center if you do not know the package name and install from there or write down the package name it shows and install it with above apt command.


Q: easyRTC has bad audio in low bandwith in tablet with 3G internet i create audio chat with easyRTC But it have noise and it work bad when I use tablet and 3g internet !
But in computer I work true !
How i can change audio quality in easyRTC ?

A: You should reduce quality of Video to improve audio quality.
By default, easyRTC config Video quality with resolution of 1280x720.
You could reconfig quality base on status of bandwidth or device and set quality on client side with:
easyrtc.setVideoDims(X, Y);

Given X and Y params are your intend res.
You should refer the detailed of setVideoDims function on easyrtc client as bellow:
easyrtc.setVideoDims = function(width, height) {
    if (!width) {
        width = 1280;
        height = 720;
    }
    easyrtc.videoFeatures = {
        mandatory: {
            minWidth: width,
            minHeight: height,
            maxWidth: width,
            maxHeight: height
        },
        optional: []
    };
};

A: I was actually exploring this same issue for a recent project!
Here's something that worked for us.
(1) First, pass an echoCancellation configuration option into MediaTrackConstraints: https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/echoCancellation - this is the built-in echo cancellation feature available natively in most browsers as part of their WebRTC support.
(2) Mute any video element where sound isn't needed - I don't need to hear my own video projecting sound, only the other, remote, user does. This applies only if you're using some video (or similar-enough audio) html element.
(3) EasyRTC supports: https://easyrtc.com/docs/client-api/Easyrtc_Rates.php - there's an example of how that can be used here: https://demo.easyrtc.com/demos/demo_lowbandwidth.html - play around with the options and you'll likely find a use-case specific setting that works for your needs!
Edit: (3) provides actual codec settings for video and audio!
Hope that helps!


Q: issues with center aligning content I've the below HTML.

SCHEDULE 1 [r.32]

PART I

and the below CSS
.para {
  text-indent: 0em;
  margin-bottom: 0.85em;
}
.para + .align-right {
  margin-top: 1.2em;
}
.align-center {
  text-align: center;
}
div.align-center span.align-right {
  float: right;
}

Here I'm trying to center align the SCHEDULE 1 word, it is in center but there is some left inclination, and the second div PART 1 is in the exact center. Please let me know how can I get the first div in center and the right aligned text has to be there in right on same line. When I delete that right aligned text, SCHEDULE 1 appears in exact center.

.para {
  text-indent: 0em;
  margin-bottom: 0.85em;
}
.para + .align-right {
  margin-top: 1.2em;
}
.align-center {
  text-align: center;
}
div.align-center span.align-right {
  float: right;
}

SCHEDULE 1 [r.32]

PART I

A: You can do it with using position field in CSS
HTML:

SCHEDULE 1 [r.32]

PART I

CSS:
.para {
  text-indent: 0em;
  margin-bottom: 0.85em;
}
.align-center {
  text-align: center;
}
div{
    position: relative;
}
div.align-center span.align-right {
  float: right;
}

div span.align-right{
    position: absolute;
    right: 0;
}

Please look at the demo code
DEMO

A: you can remove .para +  .align-right remove +
Css:

.para {
  text-indent: 0em;
  margin-bottom: 0.85em;

}
.align-center {
  text-align: center;

}

div.align-center span.align-right {
   float:right;
    margin-left:-38px;
}

DEMO


Q: Better performance and lower memory usage I am developing an application where I will store complex XMLs in Snappydata for future analysis.
For better analysis performance and lower memory consumption, what do you recommend? Store in xml, json or object?
Previously, thanks for your attention.

A: Obtain a DataFrame from your XML source and save into a Row or Column table in SnappyData.
Something like this if SQL is your preferred choice ....  (Refer to docs for DF API)
snappy> CREATE external TABLE myXMLTable USING com.databricks.spark.xml
   OPTIONS (path "pathToYourXML.xml", rowTag "Refer to docs link below");

snappy> create table myInMemoryTable using column as (select * from myXMLTable);

https://github.com/databricks/spark-xml