text:
Q: memory leak while using udev functions I wrote a function to check whether the USB device connected is my product or not by using PID value and vid value. I did that using udev functions. when I run the code using Valgrind, it shows memory leak in the udev functions... I have attached the code and the error it shows. please help me out.
here is my code
The function calling:
video_node_dir = opendir("/sys/class/video4linux/");
    if(video_node_dir == NULL)
     {
        printf("%s():opendir failed\n", __func__);
     }
else
{
    while((video_node = readdir(video_node_dir))!= NULL)
    {
       if(video_node->d_type == DT_LNK)
        {
            strcpy(video_node_name,video_node->d_name);
         if(enumerateDevices(video_node_name))
            {
              printf("%s",DeviceName);
            }
        }
     }
 }

Function definition:
This function only has a memory leak.
bool enumerateDevices(char* dev_name)
{
   bool mydevice=false ;
   struct udev *udev;
   struct udev_enumerate *enumerate;
   struct udev_list_entry *devices, *dev_list_entry;
   struct udev_device *dev,*pdev;
   char parameter[32] = "video4linux";
   /* Create the udev object */
   udev = udev_new();
   if (!udev) {
     return false;
   }

enumerate = udev_enumerate_new(udev);
udev_enumerate_add_match_subsystem(enumerate, parameter);
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);

udev_list_entry_foreach(dev_list_entry, devices) {
const char *path;
path = udev_list_entry_get_name(dev_list_entry);
dev = udev_device_new_from_syspath(udev, path);
pdev = udev_device_get_parent_with_subsystem_devtype(
                dev,
                "usb",
                "usb_device");

char *vidValue = "2560",*pidValue = "c1d4";
if(strstr(path,dev_name)!=NULL)
{
    if (strcmp(udev_device_get_sysattr_value(pdev,"idVendor"),vidValue) == 0)
    {
        if (strcmp(udev_device_get_sysattr_value(pdev,"idProduct"),pidValue) == 0){
              mydevice=true;
              const char* productName = udev_device_get_sysattr_value(pdev,"product");
              strcpy(DeviceName, productName);
        }
          else{
                  mydevice=false;
                  break;
          }
    }
    else
    {
      mydevice=false;
      break;
    }
 }
 else{
  continue;
 }
udev_device_unref(dev);
 }
  udev_enumerate_unref(enumerate);
  udev_unref(udev);
  return mydevice;
 }

The error shown is
==4845== HEAP SUMMARY:
==4845==     in use at exit: 39,336 bytes in 114 blocks
==4845==   total heap usage: 809 allocs, 695 frees, 707,030 bytes allocated
==4845==
==4845== 8 bytes in 2 blocks are still reachable in loss record 1 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052D9E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40535AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 8 bytes in 2 blocks are still reachable in loss record 2 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052DB4: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40535AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 12 bytes in 2 blocks are still reachable in loss record 3 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052D9E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40535AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 12 bytes in 2 blocks are still reachable in loss record 4 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052DB4: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40535AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 16 bytes in 2 blocks are still reachable in loss record 5 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056103: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405669E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4047E61: udev_device_new_from_syspath (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x400FFC: enumerateDevices (deviceenum.c:33)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 16 bytes in 2 blocks are still reachable in loss record 6 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056103: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405669E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052C74: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CBE8: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 16 bytes in 2 blocks are still reachable in loss record 7 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056103: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405669E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052C74: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC5C: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 16 bytes in 2 blocks are still reachable in loss record 8 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052FCB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4053721: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 16 bytes in 4 blocks are still reachable in loss record 9 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405272A: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052994: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC1D: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 16 bytes in 4 blocks are indirectly lost in loss record 10 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x405270C: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052994: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC1D: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 32 bytes in 4 blocks are still reachable in loss record 11 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405319A: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40536CA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 40 bytes in 4 blocks are still reachable in loss record 12 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405272A: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052994: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC1D: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 42 bytes in 2 blocks are still reachable in loss record 13 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-    amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052FCB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4053721: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype     (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
        ==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 42 bytes in 2 blocks are indirectly lost in loss record 14 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4F52A17: __vasprintf_chk (vasprintf_chk.c:80)
==4845==    by 0x4F528F1: __asprintf_chk (asprintf_chk.c:32)
==4845==    by 0x4052FB0: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4053721: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 50 bytes in 4 blocks are still reachable in loss record 15 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
    ==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405319A: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40536CA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 50 bytes in 4 blocks are indirectly lost in loss record 16 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x405317C: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40536CA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
    ==4845==
==4845== 84 bytes in 2 blocks are still reachable in loss record 17 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056103: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405669E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
    ==4845==    by 0x4052C74: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC5C: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
    ==4845==
==4845== 100 bytes in 2 blocks are still reachable in loss record 18 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056103: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405669E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
    ==4845==    by 0x4052C74: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CBE8: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 138 bytes in 2 blocks are still reachable in loss record 19 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056103: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x405669E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4047E61: udev_device_new_from_syspath (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x400FFC: enumerateDevices (deviceenum.c:33)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 146 bytes in 20 blocks are still reachable in loss record 20 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AACB: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4053779: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
    ==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 236 bytes in 20 blocks are still reachable in loss record 21 of 32
==4845==    at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4EC5489: strdup (strdup.c:42)
==4845==    by 0x404AADF: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4053779: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 768 bytes in 2 blocks are indirectly lost in loss record 22 of 32
==4845==    at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x40516F7: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056689: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4047E61: udev_device_new_from_syspath (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x400FFC: enumerateDevices (deviceenum.c:33)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 768 bytes in 2 blocks are indirectly lost in loss record 23 of 32
==4845==    at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x40516F7: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056689: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052C74: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CBE8: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
    ==4845==
==4845== 768 bytes in 2 blocks are indirectly lost in loss record 24 of 32
==4845==    at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x40516F7: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4056689: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4052C74: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC5C: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 1,088 bytes in 4 blocks are indirectly lost in loss record 25 of 32
==4845==    at 0x4C2FB55: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x4047547: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4047A7B: udev_device_get_parent (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC8D: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== 1,536 bytes in 4 blocks are still reachable in loss record 26 of 32
==4845==    at 0x4C2FD5F: realloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4845==    by 0x404FEF5: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4054656: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404AB0E: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x4053779: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x40537AA: ??? (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x404CC3F: udev_device_get_parent_with_subsystem_devtype (in /lib/x86_64-linux-gnu/libudev.so.1.6.4)
==4845==    by 0x401016: enumerateDevices (deviceenum.c:35)
==4845==    by 0x401200: list_and_select_device (deviceenum.c:95)
==4845==    by 0x40141D: storagecam_init (deviceenum.c:147)
==4845==    by 0x4015F2: main (deviceenum.c:175)
==4845==
==4845== LEAK SUMMARY:
==4845==    definitely lost: 544 bytes in 2 blocks
==4845==    indirectly lost: 28,076 bytes in 26 blocks
==4845==      possibly lost: 0 bytes in 0 blocks
==4845==    still reachable: 10,716 bytes in 86 blocks
==4845==         suppressed: 0 bytes in 0 blocks
==4845==
==4845== For counts of detected and suppressed errors, rerun with: -v
==4845== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)


text:
Q: Does a nucleus in a lattice emit thermal radiation? Does a single nucleus in a lattice emit thermal radiation?
https://www.youtube.com/watch?v=TPxhIRLW7G8
If so, how many photons are emitted, one (or more) for each proton? one or more for each proton on same axis? Is the frequency of the photon(s) exactly the number of oscillations per second?
For example, does an atom of golt emit 79 photons ? Consider the oscillation of a nucleus on the z- axis, in what direction travel(s) photon(s)?
Edit
The answer excludes the contribution of nuclei in thermal radiation, yet wiki says...

Thermal radiation is a direct result of the random movements of atoms
  and molecules in matter. Since these atoms and molecules are composed
  of charged particles (protons and electrons), their movement results
  in the emission of electromagnetic radiation, which carries energy
  away from the surface.

...that protons are actively involved. Can anyone explain what produces thermal radiation?

A: Atoms emit radiation, and absorb it, thermally.   The nuclear PART of an atom, however, is not easily excited, in the sense of deformation of the nucleus.  Such an 'excited state' for a nucleus, because of the strong nuclear forces, is unlikely to be as small as (typical) thermal energies.  At room temperature (0.02 electron volt, roughly) the chance of making a nucleus transition to its lowest
excited state (200,000. electron volt, order of magnitude) is very small.
Thermal photons (infrared) and nuclear excitation transitions (gamma rays) are
just too different.
For practical purposes, at 'normal' temperatures, nuclei are noninteracting
with thermal radiation, basically meaning that they're transparent.
Simple kinetic energy of a molecule in a gas IS mainly the kinetic energy of
one or a few nuclei, and there IS some interaction with radiation, but it is largely due to the electrons.   It is electronic states that are seen in thermal radiation in gasses.  The nucleus just wanders slowly as it is attracted by the thermal  motion of negative charges around it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Open with difftool" doesn't do anything I have a file with local changes. I right-click and select "Open with difftool" from Git Extensions and nothing happens. Difftool opens fine for some other files. This file is not shown neither in the Commit window and in git status.

A: I had my file marked with --skip-worktree. To fix, run the following (mind the case in the filepath):
git update-index --no-skip-worktree <filepath>

Git GUI allows adding custom commands. I now have one command to --skip-worktree and the other to revert this change.


text:
Q: calulator errors My Sharp EL-531XH calculator appears to have a bug in the decimal to hex conversion, where any number with more than nineteen bits (>2^19) is in error. A few minutes produced the following table ...
Power   Hex
 (2^x)
20      1001A8
21      1FFF68
22      3FFED0
23      800188
24      FFFF28
25     1FFFE50
26     4000088
27     8000110
28     FFFFE38
29    20000058
30    4003F080
31    7FF89EC0
32   100007FC0
My questions: can anybody suggest a fix or workaround, or must I toss the device? If I need to buy a new one, are all Sharp calculators likely to be the same, or did I just get a bad model/batch/whatever?
All suggestions welcome.


text:
Q: Reducing the number of columns using a condition in R I have a big matrix with more than 1000 rows and 100 columns. In each row ONLY 6-10 columns having values and the rest are zeros. I want to create a matrix has only 5 columns that taking the values of the 5 consecutive columns in each row. For example:
A = structure(c(0, 1L, 6L, 0, 2L, 0, 2L, 0, 1L, 4L, 1L, 3L, 7L, 2L, 6L, 2L, 4L, 0, 3L, 0, 3L, 5L, 1L, 4L, 0, 4L, 6L, 2L, 0, 0, 5L, 0, 3L, 5L, 0, 0, 0, 4L, 6L, 7L, 0, 7L, 5L, 7L, 8L, 6L, 0, 0, 8L, 9L, 0, 0, 0, 9L, 1L, 0 , 0, 0, 0, 2L, 7L, 0, 2L, 0, 0, 1L, 8L, 4, 0, 0), .Dim = c(5L, 14L))

#A =
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#[1,]    0    0    1    2    3    4    5    0    0     6     0     0     7     1
#[2,]    1    2    3    4    5    6    0    0    7     0     0     0     0     8
#[3,]    6    0    7    0    1    2    3    4    5     0     0     0     2     4
#[4,]    0    1    2    3    4    0    5    6    7     8     9     0     0     0
#[5,]    2    4    6    0    0    0    0    7    8     9     1     2     0     0

I want this matrix:
B = structure(c(1L, 1L, 1L, 5L, 7L, 2L, 2L, 2L, 6L, 8L, 3L, 3L, 3L, 7L, 9L, 4L, 4L, 4L, 8L, 1L, 5L, 5L, 5L, 9L, 2L), .Dim = c(5L, 5L))

#B =
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    1    2    3    4    5
#[3,]    1    2    3    4    5
#[4,]    5    6    7    8    9
#[5,]    7    8    9    1    2

My code:
df = data.frame(A)
B = do.call(rbind, lapply(1:NROW(df), function(i) df[i,][(df[i,])!=0][1:5]))
# or
B = t(apply(X = df, MARGIN = 1, function(x) x[x!=0][1:5]))

My code works fine for the first two rows of A but fails for the rest of the rows. I also thought about getting the columns indexes that are none zeros and then to see if there are 5 consecutive columns (without any gap between them) and retrieve their values. Any help much appreciated!

A: you can use rollapply:
library(zoo)
t(apply(A,1,function(x) {x[match(T,rollapply(!!x,5,all)) + (0:4)]}))

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    1    2    3    4    5
# [2,]    1    2    3    4    5
# [3,]    1    2    3    4    5
# [4,]    5    6    7    8    9
# [5,]    7    8    9    1    2

If you have rows without any sequence of 5 it will crash, please update your post if you want it to be handled.
Or the same but prettier:
library(purrr)
Adf       <- as.data.frame(t(A)) # data.frame fits more this data conceptually, you have different series, and it's better to put them in columns
res_df  <- map_df(Adf,~ {.x[match(T,rollapply(.x!=0,5,all))+(0:4)]})
res_mat <- as.matrix(t(unname(res_df))) # if you want to go back to ugly :)

A: Here is an option using rle
t(apply(A, 1, function(x) {
      rl <- rle(x !=0)
    head(x[inverse.rle(within.list(rl, values[!(values & lengths >= 5)] <- FALSE))], 5)}))
#      [,1] [,2] [,3] [,4] [,5]
#[1,]    1    2    3    4    5
#[2,]    1    2    3    4    5
#[3,]    1    2    3    4    5
#[4,]    5    6    7    8    9
#[5,]    7    8    9    1    2

A: EDIT: missed some details, here is my new attempt in using apply and the base library:
cumfun <- function(x){
  y<-ifelse(x>0,1,0)
  tmp<-cumsum(y)
  pos<-which(tmp-cummax((!y)*tmp)==5)
  x[(pos-4) : pos]
}

B<-t(apply(A,1,cumfun))

> B
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    1    2    3    4    5
[4,]    5    6    7    8    9
[5,]    7    8    9    1    2

A: library(zoo)
t(apply(A, MAR = 1, function(x, n = 5) x[which(rollsum(!!x, n)==n)[1]+seq_len(n)-1]))

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    1    2    3    4    5
[4,]    5    6    7    8    9
[5,]    7    8    9    1    2


text:
Q: Obtaining table names for sqlite SQL join in android I have a need to join standard android's tables (like contacts and call log) using SQL. It is possible using the rawQuery or query methods of SQLiteDatabase class. But for the methods to work properly I need to know table names that I can provide in a raw SQL query.
Example. I want to execute query like this:
SELECT * FROM Contacts as c INNER JOIN Call_Log as l ON c.number=l.number
I know how to get field names (like CallLog.Calls.NUMBER), but I don't know how to get the name of a standard table that every android has. It is possible to hardcode the name, but the way with something like CallLog.TABLE_NAME looks much more reliable. So, where can I find an analogue of CallLog.TABLE_NAME?

A: Your asking for a lot of info, but this is a good summation of how to access the contacts table and how to create your own SQL table and update it with information you get from other tables.
To do any type of search of the Contacts Provider, your app must have READ_CONTACTS permission. To request this, add this  element to your manifest file as a child element of :
<uses-permission android:name="android.permission.READ_CONTACTS" />

To do any type of search of the Call Log, your app must have READ_CALL_LOG permission. To request this, add this  element to your manifest file as a child element of :
    <uses-permission android:name="android.permission.READ_CALL_LOG" />

Code below on how to access Phone Call History
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);

String num= c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for  number
String name= c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going.

This technique tries to match a search string to the name of a contact or contacts in the Contact Provider's ContactsContract.Contacts table. You usually want to display the results in a ListView, to allow the user to choose among the matched contacts.
Saving data to a database is ideal for repeating or structured data, such as contact information. This class assumes that you are familiar with SQL databases in general and helps you get started with SQLite databases on Android. The APIs you'll need to use a database on Android are available in the android.database.sqlite package.
One of the main principles of SQL databases is the schema: a formal declaration of how the database is organized. The schema is reflected in the SQL statements that you use to create your database. You may find it helpful to create a companion class, known as a contract class, which explicitly specifies the layout of your schema in a systematic and self-documenting way.
A contract class is a container for constants that define names for URIs, tables, and columns. The contract class allows you to use the same constants across all the other classes in the same package. This lets you change a column name in one place and have it propagate throughout your code.
A good way to organize a contract class is to put definitions that are global to your whole database in the root level of the class. Then create an inner class for each table that enumerates its columns.
public final class FeedReaderContract {
  // To prevent someone from accidentally instantiating the contract class,
  // make the constructor private.
  private FeedReaderContract() {}

  /* Inner class that defines the table contents */
  public static class FeedEntry implements BaseColumns {
      public static final String TABLE_NAME = "entry";
      public static final String COLUMN_NAME_TITLE = "title";
      public static final String COLUMN_NAME_SUBTITLE = "subtitle";
    }
}

Once you have defined how your database looks, you should implement methods that create and maintain the database and tables. Here are some typical statements that create and delete a table:
 private static final String TEXT_TYPE = " TEXT";
 private static final String COMMA_SEP = ",";
 private static final String SQL_CREATE_ENTRIES =
   "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
    FeedEntry._ID + " INTEGER PRIMARY KEY," +
    FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
    FeedEntry.COLUMN_NAME_SUBTITLE + TEXT_TYPE + " )";

  private static final String SQL_DELETE_ENTRIES =
  "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;

Just like files that you save on the device's internal storage, Android stores your database in private disk space that's associated application. Your data is secure, because by default this area is not accessible to other applications.
A useful set of APIs is available in the SQLiteOpenHelper class. When you use this class to obtain references to your database, the system performs the potentially long-running operations of creating and updating the database only when needed and not during app startup. All you need to do is call getWritableDatabase() or getReadableDatabase().
To use SQLiteOpenHelper, create a subclass that overrides the onCreate(), onUpgrade() and onOpen() callback methods. You may also want to implement onDowngrade(), but it's not required.
For example, here's an implementation of SQLiteOpenHelper that uses some of the commands shown above:
  public class FeedReaderDbHelper extends SQLiteOpenHelper {

// If you change the database schema, you must increment the database           version.
      public static final int DATABASE_VERSION = 1;
      public static final String DATABASE_NAME = "FeedReader.db";
  public FeedReaderDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
 }
 public void onCreate(SQLiteDatabase db) {
    db.execSQL(SQL_CREATE_ENTRIES);
 }
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // This database is only a cache for online data, so its upgrade policy is
    // to simply to discard the data and start over
    db.execSQL(SQL_DELETE_ENTRIES);
    onCreate(db);
 }
 public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)     {
    onUpgrade(db, oldVersion, newVersion);
}

}
To access your database, instantiate your subclass of SQLiteOpenHelper:
FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());
Put Information into a Database
Insert data into the database by passing a ContentValues object to the insert() method:
// Gets the data repository in write mode
SQLiteDatabase db = mDbHelper.getWritableDatabase();

// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_SUBTITLE, subtitle);

// Insert the new row, returning the primary key value of the new row
long newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
The first argument for insert() is simply the table name.

The second argument tells the framework what to do in the event that the ContentValues is empty (i.e., you did not put any values). If you specify the name of a column, the framework inserts a row and sets the value of that column to null. If you specify null, like in this code sample, the framework does not insert a row when there are no values.
To read from a database, use the query() method, passing it your selection criteria and desired columns. The method combines elements of insert() and update(), except the column list defines the data you want to fetch, rather than the data to insert. The results of the query are returned to you in a Cursor object.
SQLiteDatabase db = mDbHelper.getReadableDatabase();

// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
   FeedEntry._ID,
   FeedEntry.COLUMN_NAME_TITLE,
   FeedEntry.COLUMN_NAME_SUBTITLE
};

// Filter results WHERE "title" = 'My Title'
String selection = FeedEntry.COLUMN_NAME_TITLE + " = ?";
String[] selectionArgs = { "My Title" };

// How you want the results sorted in the resulting Cursor
String sortOrder =
FeedEntry.COLUMN_NAME_SUBTITLE + " DESC";

Cursor c = db.query(
   FeedEntry.TABLE_NAME,                     // The table to query
   projection,                               // The columns to return
   selection,                                // The columns for the WHERE      clause
   selectionArgs,                            // The values for the WHERE clause
   null,                                     // don't group the rows
   null,                                     // don't filter by row groups
   sortOrder                                 // The sort order
 );

To look at a row in the cursor, use one of the Cursor move methods, which you must always call before you begin reading values. Generally, you should start by calling moveToFirst(), which places the "read position" on the first entry in the results. For each row, you can read a column's value by calling one of the Cursor get methods, such as getString() or getLong(). For each of the get methods, you must pass the index position of the column you desire, which you can get by calling getColumnIndex() or getColumnIndexOrThrow(). For example:
cursor.moveToFirst();
  long itemId = cursor.getLong(
  cursor.getColumnIndexOrThrow(FeedEntry._ID)
);


text:
Q: C Programming - Split an array element into separate chars Lets say I have an array = {2, 3, ABCD}
First, I need to make the third element equal to a new Array. And I know char newArr [] = array [2] wont work, so how do I go about this?
Second, I need to print out the characters of the newArr one by one. So my output should be
A
B
C
D
They should be separated from each other. I know how to do this in java, but I have no idea what the syntax is in C. Your help is greatly appreciated.

A: Something like:
char *array[] = {"2", "3", "ABCD"}; // your existing array.
char n        = strlen(array[2]);   // size of 2nd element.
char *newArr  = malloc(n);          // create new array.
int i;

// populate the new array.
for(i=0;i<n;i++) {
        newArr[i] = array[2][i];
}

// print.
for(i=0;i<n;i++) {
        printf("%c\n",newArr[i]);
}

A: No extra library needed:
  typedef struct {char x[100];}helper;
  char *a[]={"2","3","ABCD"}, b[100];
  *(helper*)b=*(helper*)a[2];
  puts(b);


text:
Q: How to start a Python Integer WITH leading 0s? I have a web scraper, and I need the number to start at 000000001 as that's how the URL starts, however whenever I run it I get the "leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers" error - which I tried to use but that doesn't solve my issue.
Is there any way around this?
Excerpt:
results = []
START = 000000001
LIMIT = 100
END = START + LIMIT + 1
row = 1

for i in range(START, END):
    URL = f"{url}{i}"
    result = parse(URL)
    if not result:
        print("this url doesn't exist: ", URL)
        continue
    for column_number, column_value in enumerate(result):
        worksheet.write(row, column_number, column_value)
    row += 1

A: You need str values that contain fixed-width representations of integers.
start = 1
limit = 100
end = start + limit + 1
row = 1

for i in range(start, end):
    url = f'{url}{i:09}'
    ...
Following the :, the 0 indicates the string should be padded with leading zeros to fill a string with length 9.


text:
Q: Power BI: Calculate sum of variance based on the variance % of last year I have a requirement where I need to calculate the sum(term reductions) of all the [variance] for which the [variance %] of the last year-end is less than or equal to -1.
For this, I'm using this formula:
Term Reductions =
var _date = MAX('Date-Processing'[Date])
var _month = MONTH(_date)
var _prior_year_end_date = IF(_month=1,EOMONTH(_date,-13),EOMONTH(_date,-_month))
var _prior_year_end_variance = CALCULATE([Variance %],FILTER(ALL('Date-Processing'),'Date-Processing'[Date]=_prior_year_end_date),FILTER(AccountLoan,AccountLoan[RiskRatingCategoryCode]<>"S" && AccountLoan[RiskRatingCategoryCode]<>"W"))

return SUMX(SUMMARIZE(Customer,Customer[CustomerName],"Variance",if(_prior_year_end_variance<=-1,[Variance],BLANK())),[Variance])

The formula is showing value if overall(all customers) [variance %] is less than or equal to -1, or else it is showing blank.
Can anyone please help me to understand, how can I calculate [variance %] at the customer level, so that even if the overall [variance %] is greater than -1, but any customer has [variance %] less than or equal to -1, then the output should be the sum of [variance] of those customers

A: If I understood your question correctly I think you just need to move your prior year calculation into the SUMX table:
Term Reductions =
var _date = MAX('Date-Processing'[Date])
var _month = MONTH(_date)
var _prior_year_end_date = IF(_month=1,EOMONTH(_date,-13),EOMONTH(_date,-_month))

return SUMX(
  SUMMARIZE(Customer,
    Customer[CustomerName],
    "PriorEnd", CALCULATE([Variance %],FILTER(ALL('Date-Processing'),'Date-Processing'[Date]=_prior_year_end_date),FILTER(AccountLoan,AccountLoan[RiskRatingCategoryCode]<>"S" && AccountLoan[RiskRatingCategoryCode]<>"W")),
    "Variance", [Variance]),
  IF([PriorEnd]<=-1,[Variance],BLANK()))


text:
Q: cannot find an initializer for type 'String' that accepts an argument list of type '(format: String, argument: UInt32 I created a playground in Xcode 6.3 (6D570) and input these following code:
import UIKit
var randum_num = arc4random_uniform(13) + 1
String(format: "card%i", arguments: randum_num)

And I got this error:
cannot find an initializer for type 'String' that accepts an argument list of type '(format: String, argument: UInt32

Sorry I'm complete new in Swift, thanks for any advices!
P.S. I'm following this tutorial: link

A: You just have to omit "arguments:". Try like this:
let randum_num = arc4random_uniform(13) + 1
String(format: "card%i",  randum_num)

or simply
String(format: "card%i",  arc4random_uniform(13) + 1)


text:
Q: How to overcome the git error `Unknown SSL protocol error in connection` I'm trying to git clone some repository, but then I get the error:
$ git clone --recursive https://some-url.git
Cloning into 'project'...
fatal: unable to access 'https://https://some-url.git/': Unknown SSL protocol error in connection to
some-url.git:443

I've read that the git repositories moved to force the TLS1.0 and no more support SSLv3 communication due to the POODLE vulnerability. But I don't know whether this error message means that my git client only knows to talk SSLv3 and the server denies or that the server only knows to talk SSLv3 and my client denies. If the problem is in my client, how can I configure it to use TLS; on the other hand, if it is the server, how can I resolve?
The error is received on both SourceTree and scm git (console and gui).

A:
how can I configure it to use TLS?

Git 2.5 (August 2015) already allows to specify a list of ciphers to use when negotiating SSL connections, with http.sslCipherList and GIT_SSL_CIPHER_LIST.
(See Cannot communicate securely with peer: no common encryption algorithm(s))
Starting Git 2.6+ (Q3 2015), it will be possible to specify the SSL version explicitly:

http: add support for specifying the SSL version

See commit 01861cb (14 Aug 2015) by Elia Pinto (devzero2000).
Helped-by: Eric Sunshine (sunshineco).
(Merged by Junio C Hamano -- gitster -- in commit ed070a4, 26 Aug 2015)
http.sslVersion

The SSL version to use when negotiating an SSL connection, if you want to force the default.
  The available and default version depend on whether libcurl was built against NSS or OpenSSL and the particular configuration of the crypto library in use. Internally this sets the 'CURLOPT_SSL_VERSION' option; see the libcurl documentation for more details on the format of this option and for the ssl version supported.
  Actually the possible values of this option are:

*

*sslv2

*sslv3

*tlsv1

*tlsv1.0

*tlsv1.1

*tlsv1.2

  Can be overridden by the 'GIT_SSL_VERSION' environment variable.
  To force git to use libcurl's default ssl version and ignore any explicit http.sslversion option, set 'GIT_SSL_VERSION' to the empty string.

The setting above is important since GitHub now (Feb. 2018) forces disabling weak cryptographic standards.

On February 8, 2018 we'll start disabling the following:

*

*TLSv1/TLSv1.1: This applies to all HTTPS connections, including web, API, and git connections to https://github.com and https://api.github.com.

*diffie-hellman-group1-sha1: This applies to all SSH connections to github.com

*diffie-hellman-group14-sha1: This applies to all SSH connections to github.com

Git 2.18 (Q2 2018) can now use TLSv1.3:
When built with more recent cURL, GIT_SSL_VERSION can now specify
"tlsv1.3" as its value.
See commit d81b651 (29 Mar 2018) by Loganaden Velvindron (loganaden).
(Merged by Junio C Hamano -- gitster -- in commit 9b59d88, 11 Apr 2018)

http: allow use of TLS 1.3
Add a tlsv1.3 option to http.sslVersion in addition to the existing
  tlsv1.[012] options.
libcurl has supported this since 7.52.0.
This requires OpenSSL 1.1.1 with TLS 1.3 enabled or curl built with
  recent versions of NSS or BoringSSL as the TLS backend.

With Git 2.21 (Q1 2019), a new "http.version" configuration variable can be used with recent enough cURL library to force the version of HTTP used to talk when fetching and pushing.
See commit d73019f (09 Nov 2018) by Force Charlie (fcharlie).
(Merged by Junio C Hamano -- gitster -- in commit 13d9919, 04 Jan 2019)

http: add support selecting http version
Usually we don't need to set libcurl to choose which version of the
  HTTP protocol to use to communicate with a server.
  But different versions of libcurl, the default value is not the same.

CURL >= 7.62.0: CURL_HTTP_VERSION_2TLS
CURL < 7.62: CURL_HTTP_VERSION_1_1

In order to give users the freedom to control the HTTP version, we need to add a setting to choose which HTTP version to use.

The git config man page now shows:
http.version:

Use the specified HTTP protocol version when communicating with a server.
  If you want to force the default.
  The available and default version depend on libcurl.
  Actually the possible values of this option are:

*

*HTTP/2

*HTTP/1.1


text:
Q: AWS Amplify and AWS Cognito Android (Native), token expiration issue after 30 days I have an Android(Native) app with Amplify Backend(amplify SDK version 1.6.4)
The Refresh Token from AWS-Cognito UserPool is expiring after 30 days, as mentioned in
AWS Amplify "Refresh Token has expired" after less than configured time (30 days)
The doc mentions that we can set between 60 minutes and 10 years
https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-the-refresh-token.html
From the UserPool I tried updating it (900 days), but still the refresh token seems to be expiring after 30 days (And this is causing problems in the App).
So, the question is How do I increase the Refresh Token Expiration Time ??
Steps that i followed to update the Refresh Token Expiration time:

*

*Select the User Pool (Switch to New Amazon Cognito Console)

*Goto "App Integration"

*Goto  "App clients and analytics">"App client name"

*"App client information",Click Edit, Update the "Refresh token expiration"

Another question that i have related to this is, when the refresh token expires (assuming that it is expiring after 30 days), inside the function Amplify.Auth.fetchAuthSession(), result.isSignedIn returns True, but Amplify.Auth?.currentUser returns Null (and hence the Amplify.Auth?.currentUser?.userId is empty)
enter code here
Amplify.Auth.fetchAuthSession(
        { result ->
            runOnUiThread {
                Toast.makeText(this, "fetchAuthSession success", Toast.LENGTH_SHORT).show()
            }

            val refreshToken = (result as AWSCognitoAuthSession).userPoolTokens.value?.refreshToken ?: "empty"
            val accessToken = (result as AWSCognitoAuthSession).userPoolTokens.value?.accessToken ?: "empty"
            val idToken = (result as AWSCognitoAuthSession).userPoolTokens.value?.idToken ?: "empty"

            runOnUiThread {
                Toast.makeText(this, "fetchAuthSession success: RT: $refreshToken, AT: $accessToken, IT: $idToken", Toast.LENGTH_SHORT).show()
            }

            if (result.isSignedIn) {
                runOnUiThread {
                    Toast.makeText(this, "isSignedIn True", Toast.LENGTH_SHORT).show()
                }

                val currentUser = Amplify.Auth?.currentUser?.userId ?: "userId empty"
                runOnUiThread {
                    Toast.makeText(this, "fetchAuthSession isSignedIn: $currentUser", Toast.LENGTH_SHORT).show()
                }
                //
            } else {
                runOnUiThread {
                    Toast.makeText(this, "isSignedIn False", Toast.LENGTH_SHORT).show()
                }
                //

            }
        },
        { error ->

            runOnUiThread {
                Toast.makeText(this, "fetchAuthSession error", Toast.LENGTH_SHORT).show()
            }

        }
)

So should i logout the User from the App when userId is null/empty or when refresh token is null/empty ?? Or Can't we update the refresh token ??


text:
Q: How to Read KeyStore File Path From standalone.xml wildfly First of all i am sorry if my question is not valid because i don't have any idea on the SSL implementation and validating the request from a trusted certificate authority.
Basically we are using .jks file to validate the request and we are using JAX-RS deployed on wildfly.
In the standalone.xml we have done the configuration like this:
<management>
 <security-realms>
**<security-realm name="SslRealm">
  <server-identities>
    <ssl>
      <keystore path="../../../ssl/keystore.jks" relative-to="jboss.server.config.dir" keystore-password="changeme"/>
    </ssl>
  </server-identities>
</security-realm>**
</security-realms>

Now in the java code we need to read the .jks file , username and password:
 public static Response getArtifactsHttps(String authInfo, String area) {
        String username = "username";
        String password1 = "password";
        StringBuilder authorization = new StringBuilder();
        authorization.append(username).append(":").append(password1);

        // String authHeader = "Basic " + Base64.getEncoder().encodeToString(authorization.toString().getBytes());
        Response response = RestAssured
                .given()
                .keyStore("pathOffile\\DemoTrust.jks", "DemoTrustKeyStorePassPhrase")
                .when()
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .header(Constant.HTTP_HEADERS.AUTHORIZATION, "Basic " + authInfo)
                .header(Constant.HTTP_HEADERS.MODULETYPE, Constant.AC_MODULETYPE.CLIENT)
                .get("login").thenReturn();

        System.out.println("RESPONSE" + response);
        return response;
    }

In the above you can see i have hardcoded the path of the .jks file
  pathoffile\DemoTrust.jks also username and password i have hardcoded.

Now i want to read all these value from the standalone.xml file. Can anybody suggest me how i can do this using java?

A: Use System.getProperty("jboss.server.config.dir") to get the root of the configuration path.


text:
Q: Converting block body method with out parameter to expression body method causes out parameter to be null I have the following method which is covered by passing unit tests;
    public static bool TryGetInstance<T>(out T config) where T : class
    {
        return Instance.TryGetInstance(out config);
    }

When I convert this to expression body syntax the unit tests fail?
    public static bool TryGetInstance<T>(out T config) where T : class =>
        Instance.TryGetInstance(out config);

The failing tests are asserting that the method returns true and that the instance returned for config is not null. I had presumed that these compiled to exactly the same IL?
Why might this be happening?

A: They are semantically identical, as shown here
the IL is identical:
    .method public hidebysig static
        bool TryGetInstance1<class T> (
            [out] !!T& config
        ) cil managed
    {
        // Method begins at RVA 0x2050
        // Code size 12 (0xc)
        .maxstack 8

        IL_0000: call class Foo P::get_Instance()
        IL_0005: ldarg.0
        IL_0006: callvirt instance bool Foo::TryGetInstance<!!T>(!!0&)
        IL_000b: ret
    } // end of method P::TryGetInstance1

    .method public hidebysig static
        bool TryGetInstance2<class T> (
            [out] !!T& config
        ) cil managed
    {
        // Method begins at RVA 0x205d
        // Code size 12 (0xc)
        .maxstack 8

        IL_0000: call class Foo P::get_Instance()
        IL_0005: ldarg.0
        IL_0006: callvirt instance bool Foo::TryGetInstance<!!T>(!!0&)
        IL_000b: ret
    } // end of method P::TryGetInstance2

so: one of two things:

*

*you've broken the compiler or the JIT

*the error isn't where you think it is

The second option is far more common. Try reverting just this method change, and see if the problem goes away.
If it does: the folks at Microsoft will be interested in a repro.


text:
Q: How do I set a name_scope in a graph to be removed from main graph in python I'm trying to organize my TensorBoard graph such that a certain component is automatically placed on the side when I first initiate TensorBoard.

I want the save node to be on the right, like this:

I can right click on save in the graph itself, But I'd rather have it waiting for me this way when I get there.

A: This isn't currently possible, although we are planning to do this as part of a broader push to improve the graph visualizer in the next few months.
If you want, you can file a GitHub issue for tracking (but we will do this either way).


text:
Q: SQL - Insert using Column based on SELECT result I currently have a table called tempHouses that looks like:
avgprice | dates | city

dates are stored as yyyy-mm-dd
However I need to move the records from that table into a table called houses that looks like:
city | year2002 | year2003 | year2004 | year2005 | year2006

The information in tempHouses contains average house prices from 1995 - 2014.
I know I can use SUBSTRING to get the year from the dates:
SUBSTRING(dates, 0, 4)

So basically for each city in tempHouses.city I need to get the the average house price from the above years into one record.
Any ideas on how I would go about doing this?

A: This is an SQL Server approach, and a PIVOT may be a better, but here's one way:
 SELECT City,
        AVG(year2002) AS year2002,
        AVG(year2003) AS year2003,
        AVG(year2004) AS year2004
   FROM (
         SELECT City,
                CASE WHEN Dates BETWEEN '2002-01-01T00:00:00' AND '2002-12-31T23:59:59' THEN avgprice
                     ELSE 0
                END AS year2002,
                CASE WHEN Dates BETWEEN '2003-01-01T00:00:00' AND '2003-12-31T23:59:59' THEN avgprice
                     ELSE 0
                END AS year2003
                CASE WHEN Dates BETWEEN '2004-01-01T00:00:00' AND '2004-12-31T23:59:59' THEN avgprice
                     ELSE 0
                END AS year2004
                -- Repeat for each year
        )
  GROUP BY City

The inner query gets the data into the correct format for each record (City, year2002, year2003, year2004), whilst the outer query gets the average for each City.
There many be many ways to do this, and performance may be the deciding factor on which one to choose.

A: The best way would be to use a script to perform the query execution for you because you will need to run it multiple times and you extract the data based on year. Make sure that the only required columns are city & row id:
http://dev.mysql.com/doc/refman/5.0/en/insert-select.html
INSERT INTO <table> (city) VALUES SELECT DISTINCT `city` from <old_table>;

Then for each city extract the average values, insert them into a temporary table and then insert into the main table.
SELECT avg(price), substring(dates, 0, 4) dates from <old_table> GROUP BY dates;

Otherwise you're looking at a combination query using joins and potentially unions to extrapolate the data. Because you're flattening the table into a single row per city it's going to be a little tough to do. You should create indexes first on the date column if you don't want the database query to fail with memory limits or just take a very long time to execute.


text:
Q: Is it correct to say "are you logged in" or "have you logged in"? Which is the correct way of asking the question
"Are you logged in"?
Or
"Have you logged in"?

A: Both are correct - it ultimately depends on the question that you wish to ask.
If you were to ask:

Are you logged in?

Then you are asking whether the user is currently logged into a particular system at the present moment.
Whereas, if you were to ask:

Have you logged in?

Then you are asking whether, at some point in time, the user has performed the action of logging into a particular system.


text:
Q: How can I edit a non-string data value in a data frame? Consider a data set with a number of columns.
> data <- import.csv("data.csv")
> head(data[1])

> Output:

    Sex
1   M
2   M
3   F
4   M
5   I
6   I

(Isolating the first column of my data set.) I want to change the F to M in all cases.
So I try the following:
> for (i in 1:6) {
      if (data[i, 1] == F) {
          data[i, 1] = M)
      }
  }

This leaves the data unchanged. So I tried to import the data like so:
> data <- import.csv("data.csv", stringsAsFactors = FALSE)

The loop method works now, but this is not OK because with the F, M, and I as strings I cannot perform the logistic regression that I need to.
Any suggestions on changing F to M but not introducing strings?

A: Change all rows in data where Sex is equal to the string 'F':
data[data$Sex == 'F',] <- 'M'
You haven't told us what these variable types should be. Are they objects? Should they be of a certain type?

A: Try

Df$column <- ifelse(df$var== "F","M",df$var)


text:
Q: mySQL get the next and previous dates to the date of the current row I have table with a date column which I am using to query to get a set of rows back from.
I am not storing any time value just the date and T:00:00:00
I need to workout what is the next and previous days that I have data for.
I would love to be able to do a single Query and the dates to use the next and back UI nav with the Query to select the current data set
so  start with this to get the last set of data
SELECT *
FROM  `newco_bh_price_data`
WHERE  `manager_id` =960
AND  `currency_id` =0
AND  `class_id` =  'A'
AND  `price_date`
IN (SELECT MAX(  `price_date` )
FROM  `newco_bh_price_data`
)

I now need to know what the next date will be so I can query on it
SELECT *
FROM  `newco_bh_price_data`
WHERE  `manager_id` =960
AND  `currency_id` =0
AND  `class_id` =  'A'
AND  `price_date` = '2002-09-19'

Mant thanks for any help and comments
Here is a sample of the data
id  price_date  manager_id  currency_id class_id    value   v_change
554 2002-09-19  960 0   A   8.631   0
553 2002-09-19  960 0   A   9.5635  0
552 2002-09-18  960 0   A   9.1068  0
551 2002-09-18  960 0   A   8.9351  0
550 2002-09-18  960 0   A   9.61    0
549 2002-09-17  960 0   A   9.1868  0
548 2002-09-17  960 0   A   9.0201  0
547 2002-09-17  960 0   A   9.6425  0
546 2002-09-16  960 0   A   9.3377  0
545 2002-09-16  960 0   A   9.3317  0
544 2002-09-16  960 0   A   9.6902  0
543 2002-09-13  960 0   A   9.418   0
542 2002-09-13  960 0   A   9.3669  0
541 2002-09-13  960 0   A   9.7125  0
540 2002-09-12  960 0   A   9.4463  0
539 2002-09-12  960 0   A   9.4383  0
538 2002-09-12  960 0   A   9.7474  0
537 2002-09-11  960 0   A   9.5303  0
536 2002-09-11  960 0   A   9.6592  0
535 2002-09-11  960 0   A   9.8041  0
534 2002-09-10  960 0   A   9.4666  0
533 2002-09-10  960 0   A   9.5878  0
532 2002-09-10  960 0   A   9.7651  0
531 2002-09-09  960 0   A   9.3104  0
530 2002-09-09  960 0   A   9.4841  0
529 2002-09-09  960 0   A   9.7498  0
528 2002-09-06  960 0   A   9.2462  0
527 2002-09-06  960 0   A   9.3823  0
526 2002-09-06  960 0   A   9.7501  0
525 2002-09-05  960 0   A   9.0465  0

A: The functions that you really want are lag() and lead().  But, alas, these are not available in MySQL.  I think the easiest way to implement them is using correlated subqueries.
Here is an example:
SELECT *,
       (select price_date
        from newco_bh_price_data pd1
        where pd1.manager_id = pd.manager_id and
              pd1.currency_id = pd.currency_id and
              pd1.class_id = pd.class_id and
              pd1.price_date > pd.price_date
        order by price_date
        limit 1
       ) as next_price_date,
       (select price_date
        from newco_bh_price_data pd1
        where pd1.manager_id = pd.manager_id and
              pd1.currency_id = pd.currency_id and
              pd1.class_id = pd.class_id and
              pd1.price_date < pd.price_date
        order by price_date desc
        limit 1
       ) as prev_price_date
FROM  `newco_bh_price_data` pd
WHERE  `manager_id` =960
AND  `currency_id` =0
AND  `class_id` =  'A'
AND  `price_date` = '2002-09-19';

This assumes that you want manager, currency, and class to be the same when looking for the next and previous date.

A: Query:
SQLFIDDLEExample
SELECT t1.*,
       (SELECT MIN(t2.`price_date`)
        FROM `newco_bh_price_data` t2
        WHERE t2.`price_date`> t1.`price_date`
        AND t2.`manager_id`= t1.`manager_id`
        AND t2.`currency_id` = t1.`currency_id`
        AND t2.`class_id` = t1.`class_id`
        ) AS NextDate,
       (SELECT MAX(t2.`price_date`)
        FROM `newco_bh_price_data` t2
        WHERE t2.`price_date`< t1.`price_date`
        AND t2.`manager_id`= t1.`manager_id`
        AND t2.`currency_id` = t1.`currency_id`
        AND t2.`class_id` = t1.`class_id`
        ) AS PreviousDate
FROM  `newco_bh_price_data` t1
WHERE  t1.`manager_id` =960
AND  t1.`currency_id` =0
AND  t1.`class_id` =  'A'

Result:
|  ID |                       PRICE_DATE | MANAGER_ID | CURRENCY_ID | CLASS_ID | VALUE | V_CHANGE |                         NEXTDATE |                     PREVIOUSDATE |
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| 554 | September, 19 2002 00:00:00+0000 |        960 |           0 |        A |     9 |        0 |                           (null) | September, 18 2002 00:00:00+0000 |
| 553 | September, 19 2002 00:00:00+0000 |        960 |           0 |        A |    10 |        0 |                           (null) | September, 18 2002 00:00:00+0000 |
| 552 | September, 18 2002 00:00:00+0000 |        960 |           0 |        A |     9 |        0 | September, 19 2002 00:00:00+0000 | September, 17 2002 00:00:00+0000 |
| 551 | September, 18 2002 00:00:00+0000 |        960 |           0 |        A |     9 |        0 | September, 19 2002 00:00:00+0000 | September, 17 2002 00:00:00+0000 |
| 550 | September, 18 2002 00:00:00+0000 |        960 |           0 |        A |    10 |        0 | September, 19 2002 00:00:00+0000 | September, 17 2002 00:00:00+0000 |
| 549 | September, 17 2002 00:00:00+0000 |        960 |           0 |        A |     9 |        0 | September, 18 2002 00:00:00+0000 | September, 16 2002 00:00:00+0000 |
| 548 | September, 17 2002 00:00:00+0000 |        960 |           0 |        A |     9 |        0 | September, 18 2002 00:00:00+0000 | September, 16 2002 00:00:00+0000 |


text:
Q: Unable to get header to fall under my menu via Flexbox Working on flexboxes and I'm unable to get my Awesome Logo header to fall underneath the very top menu which includes the date, login, etc
How it should look:
Actual Image
How my layout is:
My Funky Garbage
I'm assuming it's something with the formatting of my divs from my .html because after placing the header-container and head classes around differently, the header moves :(
html code:

Subscribe ▾

Feb 7, 2023

Sign Up

Login

CSS:
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.menu-container {
    color: #fff;
    background-color: #5995da;
    padding: 20px;
    display: flex;
    justify-content: center;
}

.menu {
    width: 900px;
    display: flex;
    justify-content: space-between;
}

.links {
    display: flex;
    justify-content: flex-end;
}

.login {
    margin-left: 20px;
}

.header-container {
    color: #5995DA;
    background-color: #D6E9FE;
    display: flex;
    justify-content: center;
  }

.header {
    width: 900px;
    height: 300px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

I'm on the cross axis section of this website: https://www.internetingishard.com/html-and-css/flexbox/
Thanks!

A: Try adding flex-direction: column-reverse; to .menu-container.
For cleaner code you can also get rid of .header-container and add its css properties to header, change the order of the menu and header divs, and use flex-direction: column;. Like the code below.

Feb 7, 2023

Sign Up

Login

Subscribe ▾

A: You should move your .header-container out of .menu-container, so they're sibling elements. If needed, create a wrapper for them.
Your .links div is also unclosed, which might be causing you issues.
So your HTML should look something like this:

Feb 7, 2023

Sign Up

Login

Subscribe ▾


text:
Q: Group case in a Switch/Case statement in objective-c I have a switch case where at different case may correspond the same fragment of code.
Is there an elegant alternative, rather than duplicating all the code ?
switch(expression) {

  case firstCase:
      // do something
      break;

  case secondCase:
      // do exactly the same of first case
      break;

  case otherCase:
      // do anything else
      break;

  case etceteraCase:
      .......

  default:
      break;

}

I know that as an alternative I could create a method to be called within the case, but this could lead to proliferation of methods hard to maintain.

A: Yes:
switch(expression) {

  case firstCase:
  case secondCase:
      // do exactly the same of first case
      break;

  case otherCase:
  case yetAnotherCase:
      // do anything else
      break;

  case etceteraCase:
      .......

  default:
      break;

}

A: Remove break after first case:
switch(expression) {

  case firstCase:

  case secondCase:
      // do the same of first case
      break;

  case otherCase:
      // do anything else
      break;

  case etceteraCase:
      .......

  default:
      break;

}

A: switch(expression) {

  case firstCase:
  case secondCase:
      // do exactly the same of first case
      break;

  case otherCase:
      // do anything else
      break;

  case etceteraCase:
      .......

  default:
      break;

}

excluding break; will produce your expected result.


text:
Q: Script Deployment Management Tool for NetSuite We are looking at removing developers from production and want a simple kind of deployment management tool. One suggestion that some members are using with SalesForce is Jenkins. I have never used Jenkins or any kind of deployment tool before. I normally just copied my code from IDE and updated the file in the SuiteScript file cabinet.
Does Jenkins work for NetSuite? Or what do you recommend for this purpose?
We are planning to use Bit Bucket (which runs Git in the background) as our version control in case that matters.
Thank you for any help

A: IMO the greatest challenge in integrating with any CI environment(be it Jenkins or any other) is the fact that you can move code files from one system to another using code/APIs but, NOT things like scripts, custom records, fields its deployments , etc. for which you need a bundling process and hence, manual intervention.
NetSuite in recent Suiteworld 2015 said that its coming up "Change Management" which would allow you to put everything that is part of your app to version control system such as git. Please see SuiteAnswer Id 42387, when this feature is rolled out, you can integrate with your CI tool to automatically copy/deploy your app details to an another NetSuite account and run your tests there and accordingly pass/fail your build.

A: Why do you want to remove developers from Production? This will severely hamper their ability to create solutions for your NetSuite account and will create a ton of overhead for them.
If you must have them out of Production, then probably your "best" option would be to have them build their solutions in Sandbox and then use SuiteBundles for deployment to Production. A Production Admin would need to update the appropriate Bundle(s) for all Production migrations.
NetSuite has also built a SuiteCloud IDE plugin for Eclipse which allows uploading and downloading files (no copy-paste necessary), so if you're not using that I would recommend it.
We are using Jenkins for our own internal automated testing, but not for deployment into NetSuite. I do not know if someone has already built a NetSuite plugin for Jenkins; it is likely you would have to build your own file upload mechanism using the NetSuite Web Services SOAP API, but that would still only allow deployment of source files. Developers will most likely also need to be creating and updating custom records, fields, lists as well as Script records and Script Deployment records, which you will not be able to do through Jenkins or any other tool that I know of.


text:
Q: R convert raw data to character I try to use R load data from mongodb with package "mongolite", and the code like this:
df <- db$find('{}', '{"CurrentId":1,"_id":0}')

Which I want to extract the "CurrentId" of collection, and variable "CurrentId" is ObjectId in mongodb, which may contains several ObjectId.
and the df look like this:
[[1]]
list()

[[2]]
list()

[[3]]
list()

[[4]]
list()

[[5]]
list()

[[6]]
[[6]][[1]]
[1] 56 cd 5f 02 b8 9b 5b d0 26 cb 39 c9

[[6]][[2]]
[1] 56 cd 6c 13 b8 9b 5b d0 26 cb 39 d5

[[6]][[3]]
[1] 56 cd 6f c6 b8 9b 5b d0 26 cb 39 de

And df[[6]][[1]]  is :
 [1] 56 cd 5f 02 b8 9b 5b d0 26 cb 39 c9

the type of typeof(df[[6]][[1]]) is :
 [1] "raw"

I use paste(dc3[[6]][[1]],collapse = '') convert the raw type to string, just like mongodb ObjectId format:
 [1] "56cd5f02b89b5bd026cb39c9"

And then I try to convert all the raw data in df to string like above. So I use sapply function:
sapply(df, function(x) paste(as.character(x),collapse = ''))
and got this :
[1] ""
[2] ""
[3] ""
[4] ""
[5] ""
[6] "as.raw(c(0x56, 0xcd, 0x5f, 0x02, 0xb8, 0x9b, 0x5b, 0xd0, 0x26, 0xcb, 0x39, 0xc9))as.raw(c(0x56, 0xcd, 0x6c, 0x13, 0xb8, 0x9b, 0x5b, 0xd0, 0x26, 0xcb, 0x39, 0xd5))as.raw(c(0x56, 0xcd, 0x6f, 0xc6, 0xb8, 0x9b, 0x5b, 0xd0, 0x26, 0xcb, 0x39, 0xde))"

But I want to get something like this:
[[1]]
list()

[[2]]
list()

[[3]]
list()

[[4]]
list()

[[5]]
list()

[[6]]
[[6]][[1]]
[1] "56cd5f02b89b5bd026cb39c9"

[[6]][[2]]
[1] "56cd6c13b89b5bd026cb39d5"

[[6]][[3]]
[1] "56cd6fc6b89b5bd026cb39de"

Could anyone know how to handle this? And could there be more efficient way to do the whole work?
Update:
I should give some code to reproduce my origin dataset:
test = as.raw(as.hexmode(x = c("56","cd","5f","02","b8","9b","5b","d0","26","cb","39","c9")))
df = lapply(1:10,function(x) test)

although this code produce this:
[[1]]
list()

[[2]]
[[2]][[1]]
[1] 5f

[[2]][[2]]
[1] d0

[[3]]
[[3]][[1]]
[1] 26

[[3]][[2]]
[1] 56

[[4]]
list()

[[5]]
[[5]][[1]]
[1] cb

[[6]]
list()

It's not like original df, but I really don't know how to paste Raw data in nested list, hope this may help you!
the result of  sapply(df, function(x) paste(x,collapse = '')) is just like this:
[1] ""
[2] ""
[3] ""
[4] ""
[5] ""
[6] "as.raw(c(0x56, 0xcd, 0x5f, 0x02, 0xb8, 0x9b, 0x5b, 0xd0, 0x26, 0xcb, 0x39, 0xc9))as.raw(c(0x56, 0xcd, 0x6c, 0x13, 0xb8, 0x9b, 0x5b, 0xd0, 0x26, 0xcb, 0x39, 0xd5))as.raw(c(0x56, 0xcd, 0x6f, 0xc6, 0xb8, 0x9b, 0x5b, 0xd0, 0x26, 0xcb, 0x39, 0xde))"

A: just use paste() without calling as.character() within your sapply() call.
Short example:
convertRaw = function(x) paste(x,collapse = '') # works identical in sapply
test = as.raw(as.hexmode(x = c("56","cd","5f","02","b8","9b","5b","d0","26","cb","39","c9"))) # line copied from your sample
convertRaw(test)
[1] "56cd5f02b89b5bd026cb39c9"

Update
actually there is another issue that results from using a nested list. Because of you dealing with a nested list your sapply call needs to be nested too. You can i.e. call it via lapply(). Here is a short example hope that finally resolves your issue:
test = as.raw(as.hexmode(x = c("56","cd","5f","02","b8","9b","5b","d0","26","cb","39","c9")))
testList = list(list(),list(test,test)) # here I create a short nested list
res = lapply(testList,function(y) sapply(y,function(x) paste(x,collapse = '')))
print(res)

the result is:
[[1]] list()

[[2]] [1] "56cd5f02b89b5bd026cb39c9" "56cd5f02b89b5bd026cb39c9"

if you prefer this:
[[1]] list()

[[2]] [[2]][[1]]
[1] "56cd5f02b89b5bd026cb39c9"

[[2]][[2]]
[1] "56cd5f02b89b5bd026cb39c9"

simply call, lapply() nested:
lapply(testList,function(y) lapply(y,function(x) paste(x,collapse = '')))


text:
Q: fancybox use divs instead of a href How can I use FancyBox or JQuery to create multiple pop-up DIVs that all use the same class (no IDs) on one page? For example, I have 50 products on a single page that all have the same class names.

This IS A Cool PopUp 1

Close

Sample 1

This IS A Cool PopUp 2

Close

Sample 2

This IS A Cool PopUp 3

Close

Sample 3

THE CSS

It should work like this example (please click on the product to test pop-up):
http://www.grubhub.com/order.jsp?custId=263838&cityId=5&orderId=18429055&searchable=true&deliverable=true&verified=false&poiSearchTerm=null

A: You should do something like this:
$('.container_header').click( function() {
    $(this).parent().prev().prev('.popup_box').fadeIn("slow");
});

$('.closePopup').click( function(){
    $('.popup_box').fadeOut("slow");
    $('.overlay_box ').fadeOut("slow");
});

SEE DEMO (Result Only)
SEE CODE HERE


text:
Q: Trying to calculate the average in an ArrayList I'm trying to write some code which takes in any number of entries and stores it in an ArrayList given a specific condition. What I'm not able to do is find the average of the values stored in the ArrayList. Here's the code written so far:
import java.util.ArrayList;
import java.util.Scanner;

public class App {
    private ArrayList<Integer> temp;
    private int t;
    private int count = 0;

    public void main() {
        Scanner input = new Scanner(System.in);
        temp = new ArrayList<>();
        System.out.println("Enter temperatures: ");
        do {
            t = input.nextInt();
            if (t == -99) {
                System.out.println("Program Terminating..");
                break;
            } else {
                temp.add(t);
            }
        } while (t != -99);
        for (int i = 0; i < temp.size(); i++) {
            if (temp.get(i) > 40) {
                count++;
            }

        }
        System.out.println(count);

    }
}

A: You have a funky condition there; you're only doing operations if the value is greater than 40.  The code below takes those into account; if you don't desire that, then remove the conditional.
In a traditional manner, you can use an enhanced-for with a counter to get all of the values greater than 40 and average those...
double sum = 0;
for(Integer i : temp) {
    if(i > 40) {
        sum += i;
        count++;
    }
}

if(count != 0) { // avoid divide-by-zero error here
    System.out.println(sum / count);
}

...or with Java 8, you can use streams, filter out those that are less than 40, and get the average as a double instead:
System.out.println(temp.stream()
                       .filter(x -> x > 40)
                       .mapToInt(Integer::intValue)
                       .average()
                       .getAsDouble());

A:  long total =0;
  for(int i=0;i < temp.size(); i++){
    if(temp.get(i) > 40){
        count++;
        total+=temp.get(i);
    }
   }

    double mean=0;
   if(count!=0)
        mean = total/count;


text:
Q: CE Update Event: any way to pass before/after property values to a workflow? I've configured a FileNet workflow subscription on Add, Update and Delete events.  The workflow calls a Java component to send a notification message (to a third party).
We would like to see "before" and "after" property values in the notification message for "Update" events.
The "Event" object that triggers the subscription has a "Modified Properties" member, so I was hoping I could just create a corresponding "ModifiedProperties" string array in the workflow, and have the subscription map "Update.ModifiedProperties = ModifiedProperties".  Unfortunately, the Event's "ModifiedProperties" only gives the NEW value, not the "before" value.
  <= So I don't see any way to get "before/after" values directly from the subscription...
It looks like the "UpdateEvent" object also has an "OriginalObject" member ... and I might be able to use the Java API to get the "before" value from the OriginalObject.
Q: Does this sound plausible method for getting the before/after document property values?
Q: Any ideas how to pass the "OriginalObject" object from the subscription to the workflow, so the Java component can use it?
The target platform is P8 5.2.1; I'm developing on P8 5.5.

A: You are right, the only way to the original values is through the OriginalObject object. And the quickest way to get data to a workflow is using a subscribable object.
Therefore, a solution to your problem is to define a custom object containing the properties describing the new and the old property values. You create this custom object in a custom event handler triggered on an update event from the document. Here you can populate the properties of the custom object using the original object:
Document document = (Document) event.get_OriginalObject();;
Iterator<?> iterator = event.get_ModifiedProperties().iterator();
while (iterator.hasNext()) {
    String modifiedProperty = (String) iterator.next();

    // TODO: Fetch the values from the original object
    // and set them on the custom object. The details depend
    // on the data structure you choose.
}

Next you create a Workflow subscription triggered on the creation of the custom object. You can map the properties of your custom object to the data fields of your workflow. In the workflow that is started you can define an attachment and specify that the custom object is the initiating attachment. Using the CE_Operation queue methods you can now and delete the custom object when your processing is finished.

A: if(objEvent instanceof UpdateEvent) { try { String strModifiedProperties = ""; UpdateEvent updateEvent = (UpdateEvent) objEvent; StringList propertyNames = updateEvent.get_ModifiedProperties(); Iterator iterModifiedProps = propertyNames.iterator(); while(iterModifiedProps.hasNext()) { String modifiedProperty = (String) iterModifiedProps.next(); strModifiedProperties = strModifiedProperties+modifiedProperty+","; } strModifiedProperties = strModifiedProperties.substring(0, strModifiedProperties.lastIndexOf(",")); } catch (Exception e) { System.out.println("onEvent : Exception while executing UpdateEvent: "+e.getMessage()); } }


text:
Q: Singular of "folks"? It has been suggested to me that "fellow" is the corresponding singular version of the word "folks" in the context of "hey folks" or "listen folks" but it doesn't have the same gender neutrality.

A: There is no direct singular word for folks. It is almost like the word "guys" (but more gender neutral).
If an announcer comes out and says, "Howdy folks!" They are speaking to a group or crowd.  You do not say folks when speaking to one person nor do you say folk.  You would simply say "Howdy Mister/Madame/Whatever".  Folks is usually a very friendly word that conveys a down to earth attitude.  I think the closest word to takes its singular place would be friend.
If you see a group of people walking by that you know- "Howdy folks".
If you see a person walking by that you know - "Howdy friend" or just "Howdy".  When you gave the "Howdy Folks" to the group walking by the use of folks noted that there was an individual howdy for everyone.

A: Maybe this link can help you.  http://en.wikipedia.org/wiki/Folk
folks in the plural form means "people".  The singular of "people" is person, not "fellow".


text:
Q: Where can I find all android.os.Build.MODEL value for all phone? As the question stated, is there anyway I can get these values for every smartphone?

A: You can get a very long list of device makes and models from Google's list of Supported Devices. As of January 2022, there are over 35,000 devices listed. The device list can be downloaded as a CSV file (very useful) or as PDF.

A: it's not possible to list all smart phones details. By using android.os.Build.MODEL we can find which device we are using. please refer this site for smart phone details (http://en.wikipedia.org/wiki/Comparison_of_Android_devices)

A: It's not complete, but you can try https://github.com/mataanin/android-devices


text:
Q: jQWidgets datatable and columns on demand I am building POC module on jqxdatatable where user will have flexibility to add/remove optional columns.
Let me elaborate in details, For example following is my table initially loads with default 6 columns.I would like to give an option with 2 more columns Department and country with check-box so if user wants to add any of these two optional columns they can just select/deselect the check-box and that column will appear/disappear on the grid.

Please note I would prefer to have XML data source.
Is it possible with jqxdatatable ?

A: jQWidgets Team just confirmed it's not possible :( . I would love to hear if someone could suggest same can be achieved by any other JS library.
http://www.jqwidgets.com/community/topic/jqwidgets-datatable-and-columns-on-demand/


text:
Q: JSON-data from iOS into PHP-script How can I access json data within a php-script, which it received via http-post?
I'm doing the following on the iOS-side:
NSData *data = [NSJSONSerialization dataWithJSONObject:object options:0 error:NULL];

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/script.php"]];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:data];

[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];

How do I access this data in the php-script? In other words, when I call json_decode(...) in the php-script, what is ...?

A: If your are sending your JSON in POST method , It can be received in PHP with the below code
<?php $handle = fopen('php://input','r');
                $jsonInput = fgets($handle);
                // Decoding JSON into an Array
                $decoded = json_decode($jsonInput,true);
?>

A: The post request when sent using iOS does not works with $_POST. If similar request is issued using js the json in post does works.

A: In the php script you take the POST data and do
json_decode($data);

and that will give you an object you can work with.

A: NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody: jsonData];
    [request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];

This code can be used to send a response


text:
Q: Starting a new web application project with IntelliJ IDEA I am using the latest version of IntelliJ IDEA. My first project went fine. I was able to create a simple hello world with some parameters. Now, I have decided to create a new project to test JAX-RS and some JSPs. Everything runs fine on my TomEE server.
Though, the problem I am currently facing is really weird. request.getParameter() is no longer recognized and similar elements. I have compared both of the old project and new project, and discovered that that new project is missing libs folder with the javax* files in it.
I do not know why IntelliJ no longer generates the libs files into the new projects. I would appreciate it if someone could share any helpful information.


text:
Q: How to extract a visible scatterplot matrix from Rstudio when you have many variables? I'm doing the chemical analysis and trying to make a scatterplot matrix based on my chemistry data. I was able to create a matrix that I wanted but each scatterplot is not visible enough to read on my screen. I am planning to print this matrix on a huge scientific poster, however, I don't know how am I going to export this matrix with visible plots. Are there any ways that I can get these plots visible?
I used this code for a matrix:
scatterFull <- pairs(springwater[,1:53], panel=panel.smooth)
Here is a matrix that I got in a plot box from Rstudio. I know the monitor screen size matters which is why I am not able to see each plot clearly but is there a way to figure this out without changing monitor size?

I want to see this matrix visible as much as the matrix below (this matrix contains only 10 elements but I need all of 53 elements in my matrix).

Please help me with this problem. Thank you!

A: I have had to deal with this problem for decades.  By far the best way (in terms of ease and quality) in R is to output the graphic in PDF format.  When you specify a large paper size, the graphic can be readable.  It will be of higher quality than exporting the graphic shown in RStudio.  Even so, you will likely have to experiment and possibly tinker with graphical elements such as text sizes and symbol sizes.
Here's an example showing how the plot looks by default on a poster-size sheet (44 by 32 inches).  The figure displays a portion of the output (as rendered in Acrobat Reader at 200% magnification: click on it to see it at its original size on the screen).

#
# Generate sample data.
#
n <- 1e2                 # Number of points
d <- 53                  # Number of variables
mu <- runif(d)           # Variable log means
sigma <- rbeta(d, 2, 2)  # Variable log sds
X <- matrix(exp(rnorm(n*d, mu, sigma)), n, byrow=FALSE)
X <- ifelse(X < 1, 0, X) # Censor all values at a detection limit of 1
colnames(X) <- paste0("X", seq_len(ncol(X)))
#
# The proposed solution.
#
pdf("Pairs.pdf", width=44, height=32)
pairs(X)
dev.off()

After running this code, open the output file Pairs.pdf in a pdf reader to view it.
If even this doesn't work, you will need to tile the output by looping over disjoint subsets of the variables and outputting a scatterplot matrix for each ordered pair of those subsets.  But with 53 variables it ought to be good enough.

If you wish to identify and display a subset of these panels, here's some basic code you can emulate.  It uses a hard-coded threshold of 0.3 for the correlation coefficient; in practice, you would likely adjust this according to the data and your objectives.
#
# Display highly correlated pairs of variables.
#
R <- abs(cor(X))          # The correlation matrix
i <- which(R > 0.3) - 1   # Indexes of large absolute correlations
p <- rbind(i %% ncol(X), i %/% ncol(X)) + 1 # Indexes into the variable names
p <- p[, p[1,] != p[2,]]  # Remove the diagonals

m <- ncol(p)
if (m > 0) {
  nrow <- min(4, ceiling(sqrt(m/1.6)))
  ncol <- min(5, ceiling(sqrt(m*1.6)))
  par(mfrow = c(nrow, ncol))
  apply(p, 2, function(j) {
    plot(X[, j[1]], X[, j[2]], xlab=colnames(X)[j[1]], ylab=colnames(X)[j[2]])
  })
  par(mfrow=c(1,1))
}


text:
Q: How gzip file gets stored in HDFS HDFS storage support compression format to store compressed file. I know that gzip compression doesn't support splinting. Imagine now the file is a gzip-compressed file whose compressed size is 1 GB. Now my question is:

*

*How this file will get stored in HDFS (Block size is 64MB)

From this link I came to know that The gzip format uses DEFLATE to store the compressed data, and DEFLATE stores data as a series of compressed blocks.
But I couldn't understand it completely and looking for broad explanation.
More doubts from gzip compressed file:

*How many block will be there for this 1GB gzip compressed file.

*Will it go on multiple datanode ?

*How replication factor will be applicable for this file ( Hadoop cluster replication factor is 3.)

*What is DEFLATE algorithm?

*Which algorithm is applied while reading the gzip compressed file?

I am looking here broad and detailed explanation.

A:
How this file will get stored in HDFS (Block size is 64MB) if splitting does not supported for zip file format?

All DFS blocks will be stored in single Datanode. If your block size is 64 MB and file is 1 GB, the Datanode with 16 DFS blocks ( 1 GB / 64 MB = 15.625) will store 1 GB file.

How many block will be there for this 1GB gzip compressed file.

1 GB / 64 MB = 15.625 ~ 16 DFS blocks

How replication factor will be applicable for this file ( Hadoop cluster replication factor is 3.)

Same as of any other file. If the file is splittable, no change. If the file is not splittable, Datanodes with required number of blocks will be identified. In this case, 3 datanodes with 16 available DFS blocks.
From source code of this link : http://grepcode.com/file_/repo1.maven.org/maven2/com.ning/metrics.action/0.2.7/org/apache/hadoop/hdfs/server/namenode/ReplicationTargetChooser.java/?v=source
and
http://grepcode.com/file_/repo1.maven.org/maven2/org.apache.hadoop/hadoop-hdfs/0.22.0/org/apache/hadoop/hdfs/server/namenode/BlockPlacementPolicyDefault.java/?v=source
/** The class is responsible for choosing the desired number of targets
 * for placing block replicas.
 * The replica placement strategy is that if the writer is on a datanode,
 * the 1st replica is placed on the local machine,
 * otherwise a random datanode. The 2nd replica is placed on a datanode
 * that is on a different rack. The 3rd replica is placed on a datanode
 * which is on the same rack as the first replca.
 */

What is DEFLATE algorithm?

DELATE is the algorithm to uncompress zipped files of GZIP format.
Have a look at this slide to have understanding of other algorithms for different variants of zip files.

Have a look at this presentation for more details.


text:
Q: Zend_Form radio element Below is sample code to create a radio button element with Yes/No options in Zend_Form. Any ideas on how to set the required answer to Yes, so if No is selected, it'll fail validation? The code below will accept either Yes or No.
    $question= new Zend_Form_Element_Radio('question');
    $question->setRequired(true)
        ->setLabel('Are you sure?')
        ->setMultiOptions(array('Yes', 'No'));

A: Not sure if this is the best way, but it worked for me:
$questionValid = new Zend_Validate_InArray(array('Yes'));
$questionValid->setMessage('Yes is required!');

$question = new Zend_Form_Element_Radio('question');
$question->setRequired(true)
    ->setLabel('Are you sure?')
    ->setMultiOptions(array('Yes'=>'Yes', 'No'=>'No'))
    ->addValidator($questionValid);

A: A quicker way, though this wouldn't work for other situations:
$question = new Zend_Form_Element_Radio('question');
$question->setRequired(true)
    ->setLabel('Are you sure?')
    ->setMultiOptions(array('Yes'=>'Yes', 'No'=>'No'))
    ->addValidator('StringLength', false, array('min' => 3, 'messages' => "You must be sure."));

Since "no" is less than 3 characters, this will fail unless "yes" is selected.  It's a little "hacky", but I like this way because it uses less code and also makes use of the built-in validators.


text:
Q: Laravel validation required rule not working I need to add required rule if one field is available. Also need to check if it is an integer and 10 digit. So I added the rule like below.
'id_number' => 'sometimes|required|digits:10|integer'

Validations works only when the field is available. But here required rule is not working. It directly shows integer error even if the field is empty.
I use Laravel 5.1

A: Finally I figured it!
You need to change the order of required rule to last. It works when I add rule like this,
'id_number' => 'sometimes|digits:10|integer|required'