text:
Q: MacOS partition showing as "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFF" I tried to uninstall linux on my MBP 2014, accidentally corrupting my MacOS. Tried to fix it using this guide : Data Not Backed Up, Partition Type: FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF, did not work. Here's what I had done:
-bash-3.2# diskutil info disk0s2
   Device Identifier:        disk0s2
   Device Node:              /dev/disk0s2
   Part of Whole:            disk0
   Device / Media Name:      Customer

   Volume Name:              Not applicable (no file system)

   Mounted:                  Not applicable (no file system)

   File System:              None

   Partition Type:           FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF
   OS Can Be Installed:      No
   Media Type:               Generic
   Protocol:                 PCI
   SMART Status:             Verified
   Disk / Partition UUID:    AFF19235-7921-417B-8A73-EE26292C7C99

   Total Size:               218.8 GB (218774044672 Bytes) (exactly 427293056 512-Byte-Units)
   Volume Free Space:        Not applicable (no file system)
   Device Block Size:        512 Bytes

   Read-Only Media:          No
   Read-Only Volume:         Not applicable (no file system)
   Ejectable:                No

   Whole:                    No
   Internal:                 Yes
   Solid State:              Yes

-bash-3.2# diskutil list
/dev/disk0
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *251.0 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2: FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF               218.8 GB   disk0s2
   3: 0FC63DAF-8483-4772-8E79-3D69D8477DE4               28.0 GB    disk0s3
/dev/disk1
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     Apple_partition_scheme                        *1.3 GB     disk1
   1:        Apple_partition_map                         30.7 KB    disk1s1
   2:                  Apple_HFS OS X Base System        1.3 GB     disk1s2
/dev/disk2
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *5.2 MB     disk2
/dev/disk3
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk3
/dev/disk4
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk4
/dev/disk5
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk5
/dev/disk6
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk6
/dev/disk7
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk7
/dev/disk8
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *6.3 MB     disk8
/dev/disk9
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *2.1 MB     disk9
/dev/disk10
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *1.0 MB     disk10
/dev/disk11
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk11
/dev/disk12
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk12
/dev/disk13
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *1.0 MB     disk13
/dev/disk14
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *6.3 MB     disk14
-bash-3.2# gpt -r show disk0
gpt show: disk0: Suspicious MBR at sector 0
      start       size  index  contents
          0          1         MBR
          1          1         Pri GPT header
          2         32         Pri GPT table
         34          6
         40     409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
     409640  427293056      2  GPT part - FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF
  427702696    7870040
  435572736   54661120      3  GPT part - 0FC63DAF-8483-4772-8E79-3D69D8477DE4
  490233856        863
  490234719         32         Sec GPT table
  490234751          1         Sec GPT header
-bash-3.2# diskutil umountDisk disk0
Unmount of all volumes on disk0 was successful
-bash-3.2# dd if=/dev/disk0s2 count=3 | vis -c
3+0 records in
3+0 records out
1536 bytes transferred in 0.013231 secs (116091 bytes/sec)
\^W\M-?C\M-@b\^\\M^I\^]\^A\0\0\0\0\0\0\0\M-j\M-9*\0\0\0\0\0\^A\0\0\M^@\0\0\0\0NXSB\0\^P\0\0000\M^?.\^C\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\^B\0\0\0\0\0\0\0-\a\M-E\M^P\M-f\M^L@8\M^C\M-0\M-Q~\M-u\M-5A\M^[ToF\0\0\0\0\0\M-k\M-9*\0\0\0\0\0\^X\^A\0\0 l\0\0\M-^\M-,\^B\0\0\0\0\0}-\^B\0\0\0\0\0 \0\0\0[5\0\0\^^\0\0\0\^B\0\0\0L5\0\0\^O\0\0\0\M-W\^_F\0\0\0\0\0004/  \0\0\0\0\0\^A\^D\0\0\0\0\0\0\0\0\0\0d\0\0\0\^C\^D\0\0\0\0\0\0Z \^D\0\0\0\0\0\\ \^D\0\0\0\0\0 \M-F\^D\0\0\0\0\0.\^O?\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\-bash-3.2# diskutil umountDisk disk0
Unmount of all volumes on disk0 was successful
-bash-3.2# gpt remove -i 3 disk0
gpt remove: disk0: Suspicious MBR at sector 0
disk0s3 removed
-bash-3.2# diskutil umountDisk disk0
Unmount of all volumes on disk0 was successful
-bash-3.2# gpt remove -i 2 disk0
gpt remove: disk0: Suspicious MBR at sector 0
disk0s2 removed
-bash-3.2# gpt add -i 3 -b 227212504 -s 1269536 -t 426F6F74-0000-11AA-AA11-00306543ECAC disk0
gpt add: disk0: Suspicious MBR at sector 0
gpt add: disk0: error: no space available on device
-bash-3.2# gpt add -i 3 -b 435572736 -s 1269536 -t 426F6F74-0000-11AA-AA11-00306543ECAC disk0
gpt add: disk0: Suspicious MBR at sector 0
gpt add: disk0: error: no space available on device
-bash-3.2# gpt -r show /dev/disk0
gpt show: /dev/disk0: Suspicious MBR at sector 0
      start       size  index  contents
          0          1         MBR
          1          1         Pri GPT header
          2         32         Pri GPT table
         34          6
         40     409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
     409640  427293056      2  MBR part 218
  427702696    7870040
  435572736   54661120      3  MBR part 131
  490233856        863
  490234719         32         Sec GPT table
  490234751          1         Sec GPT header
-bash-3.2# gpt add -b diskutil umountDisk /dev/disk0
usage: gpt add [-b lba] [-i index] [-s lba] [-t uuid] device ...
-bash-3.2# diskutil umountDisk /dev/disk0
Unmount of all volumes on disk0 was successful
-bash-3.2# gpt add -b 409640 -s 427293056 -i 2 -t 53746F72-6167-11AA-AA11-00306543ECAC
usage: gpt add [-b lba] [-i index] [-s lba] [-t uuid] device ...
-bash-3.2# gpt add -b 409640 -s 427293056 -i 2 -t 53746F72-6167-11AA-AA11-00306543ECAC /dev/disk0
gpt add: /dev/disk0: Suspicious MBR at sector 0
gpt add: /dev/disk0: error: no space available on device
-bash-3.2# gpt -r show /dev/disk0
gpt show: /dev/disk0: Suspicious MBR at sector 0
      start       size  index  contents
          0          1         MBR
          1          1         Pri GPT header
          2         32         Pri GPT table
         34          6
         40     409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
     409640  427293056      2  MBR part 218
  427702696    7870040
  435572736   54661120      3  MBR part 131
  490233856        863
  490234719         32         Sec GPT table
  490234751          1         Sec GPT header
-bash-3.2# diskutil umountDisk /dev/disk0
Unmount of all volumes on disk0 was successful
-bash-3.2# gpt destroy /dev/disk0
gpt destroy: /dev/disk0: Suspicious MBR at sector 0
-bash-3.2# gpt create -f /dev/disk0
gpt create: /dev/disk0: Suspicious MBR at sector 0
-bash-3.2# fdisk -i -a hfs /dev/disk0
fdisk: could not open MBR file /usr/standalone/i386/boot0: No such file or directory

    -----------------------------------------------------
    ------ ATTENTION - UPDATING MASTER BOOT RECORD ------
    -----------------------------------------------------

Do you wish to write new MBR and partition table? [n] n
MBR is unchanged
-bash-3.2# fdisk -i -a hfs /dev/disk0
fdisk: could not open MBR file /usr/standalone/i386/boot0: No such file or directory

    -----------------------------------------------------
    ------ ATTENTION - UPDATING MASTER BOOT RECORD ------
    -----------------------------------------------------

Do you wish to write new MBR and partition table? [n] y
-bash-3.2# gpt -r show /dev/disk0
gpt show: error: bogus map
gpt show: unable to open device '/dev/disk0': Undefined error: 0
-bash-3.2# gpt create -f /dev/disk0
gpt create: error: bogus map
gpt create: unable to open device '/dev/disk0': Undefined error: 0
-bash-3.2# diskutil umountDisk /dev/disk0
Unmount of all volumes on disk0 was successful
-bash-3.2# info disk0
-bash: info: command not found
-bash-3.2# diskutil info disk0
   Device Identifier:        disk0
   Device Node:              /dev/disk0
   Part of Whole:            disk0
   Device / Media Name:      APPLE SSD SM0256F Media

   Volume Name:              Not applicable (no file system)

   Mounted:                  Not applicable (no file system)

   File System:              None

   Content (IOContent):      FDisk_partition_scheme
   OS Can Be Installed:      No
   Media Type:               Generic
   Protocol:                 PCI
   SMART Status:             Verified

   Total Size:               251.0 GB (251000193024 Bytes) (exactly 490234752 512-Byte-Units)
   Volume Free Space:        Not applicable (no file system)
   Device Block Size:        512 Bytes

   Read-Only Media:          No
   Read-Only Volume:         Not applicable (no file system)
   Ejectable:                No

   Whole:                    Yes
   Internal:                 Yes
   Solid State:              Yes
   OS 9 Drivers:             No
   Low Level Format:         Not supported

-bash-3.2# diskutil list
/dev/disk0
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     FDisk_partition_scheme                        *251.0 GB   disk0
   1:                  Apple_HFS                         251.0 GB   disk0s1
/dev/disk1
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     Apple_partition_scheme                        *1.3 GB     disk1
   1:        Apple_partition_map                         30.7 KB    disk1s1
   2:                  Apple_HFS OS X Base System        1.3 GB     disk1s2
/dev/disk2
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *5.2 MB     disk2
/dev/disk3
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk3
/dev/disk4
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk4
/dev/disk5
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk5
/dev/disk6
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk6
/dev/disk7
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk7
/dev/disk8
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *6.3 MB     disk8
/dev/disk9
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *2.1 MB     disk9
/dev/disk10
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *1.0 MB     disk10
/dev/disk11
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk11
/dev/disk12
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *524.3 KB   disk12
/dev/disk13
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *1.0 MB     disk13
/dev/disk14
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               *6.3 MB     disk14
-bash-3.2# gpt -r show disk0
gpt show: error: bogus map
gpt show: unable to open device 'disk0': No such file or directory
-bash-3.2# gpt -r show /dev/disk0
gpt show: error: bogus map
gpt show: unable to open device '/dev/disk0': Undefined error: 0
-bash-3.2#

I haven't backed up my files, but I read that this process should not erase any data from the original disk. Is there anything that can fix this?
Update
I have managed to boot into macOS, but the last step was not working for me. 32 GB was also missing. Here are the output of diskutil list and gpt -r show /dev/disk0.
-bash-3.2# diskutil list
/dev/disk0 (internal, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        *251.0 GB   disk0
   1:                        EFI EFI                     209.7 MB   disk0s1
   2:                 Apple_APFS Container disk2         218.8 GB   disk0s2

/dev/disk1 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      GUID_partition_scheme                        +2.1 GB     disk1
   1:                  Apple_HFS macOS Base System       2.0 GB     disk1s1

/dev/disk2 (synthesized):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:      APFS Container Scheme -                      +218.8 GB   disk2
                                 Physical Store disk0s2
   1:                APFS Volume Macintosh HD - Data     188.8 GB   disk2s1
   2:                APFS Volume Preboot                 81.7 MB    disk2s2
   3:                APFS Volume Recovery                528.7 MB   disk2s3
   4:                APFS Volume VM                      1.1 GB     disk2s4
   5:                APFS Volume Macintosh HD            11.1 GB    disk2s5

/dev/disk3 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +10.5 MB    disk3

/dev/disk4 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +10.5 MB    disk4

/dev/disk5 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk5

/dev/disk6 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk6

/dev/disk7 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk7

/dev/disk8 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +2.1 MB     disk8

/dev/disk9 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk9

/dev/disk10 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk10

/dev/disk11 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +12.6 MB    disk11

/dev/disk12 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +4.2 MB     disk12

/dev/disk13 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +1.0 MB     disk13

/dev/disk14 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +2.1 MB     disk14

/dev/disk15 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk15

/dev/disk16 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +2.1 MB     disk16

/dev/disk17 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk17

/dev/disk18 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +1.0 MB     disk18

/dev/disk19 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk19

/dev/disk20 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +6.3 MB     disk20

/dev/disk21 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +6.3 MB     disk21

/dev/disk22 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +524.3 KB   disk22

/dev/disk23 (disk image):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:                            untitled               +2.1 MB     disk23

/dev/disk24 (external, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     FDisk_partition_scheme                        *30.8 GB    disk24
   1:             Windows_FAT_32 NO NAME                 30.8 GB    disk24s1

-bash-3.2# gpt -r show /dev/disk0
      start       size  index  contents
          0          1         PMBR
          1          1         Pri GPT header
          2         32         Pri GPT table
         34          6
         40     409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
     409640  427293056      2  GPT part - 7C3457EF-0000-11AA-AA11-00306543ECAC
  427702696   62532023
  490234719         32         Sec GPT table
  490234751          1         Sec GPT header
-bash-3.2#

A: You almost got it right. After you used gpt create, you should have gone back to gpt add. Try the sequence below.

Note: I omitted any diskutil unmountdisk /dev/disk0 commands you may need to enter.

dd if=/dev/zero of=/dev/disk0 bs=512 count=1
gpt destroy /dev/disk0
gpt create -f /dev/disk0
gpt add -b 40 -s 409600 -t C12A7328-F81F-11D2-BA4B-00A0C93EC93B /dev/disk0
gpt add -b 409640 -s 427293056 -t 7C3457EF-0000-11AA-AA11-00306543ECAC /dev/disk0

If successful, you can then enter the command given below to add the free space back to macOS. (You may need to reboot to macOS before entering the command.)
sudo diskutil apfs resizeContainer disk0s2 0


text:
Q: Android AVD - Faster On Windows Or On Ubuntu VM? My Android emulator runs painfully slow on my PC so I was thinking about installing Ubuntu on a virtual machine and running the AVD there. Do you think it would be faster if I did so?

A: you have two solution.
one, you install AndroVM on VirtualBox.
AndroVM
this way is very faster, but bit difficult to setup and controll.
other way is create AVD which is made in Intel x86.
Configuring the x86 Emulator
this way is very fast too.and setup and controll is very easy compare to general emulator.
but this way require CPU which support Intel VT / AMD-V
both way is good,please choose you like :)

A: I would put my money on Linux - as it has less of a footprint OS wise.
On the other hand, Windows is by far more used, so if they've developed it and put time into the one that is used the most, it could be Windows.
As a side note: there are several new android emulators that run on windows, some I've seen actually interface with the hardware (this avoids a layer of abstraction).
If your concerned with speed, you will get better performance with less programs running as the emulator is process intensive. (My i7, 8gb ram, is usable for developing - though nothing beats a device... Or nexus for that matter)
To connect to your computer: Debugging on my phone (Eclipse, Android)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery serialize collecting multiples form which group values by name How to collect multiples form input and group the output into string which combines values by name
For example:
<div class="register">
    <input type="text" name="full_name">
    <textarea name="address"></textarea>
    <input type="radio" name="sex" value="male">
    <input type="radio" name="sex" value="female">
    <input type="checkbox" name="hobies" value="foodball">
    <input type="checkbox" name="hobies" value="basketball">
    <input type="button" class="submit" value="Submit">
</div>

how to get the output will be string or something like this

// field_name: [values]

i'm trying like this:
$('.submit').click(function(){
    var InputCollect = $('.register').find(':input');

    $(InputCollect).each(function(){
        names = $(this).attr('name');
        values = $(this).attr('value');

        // the output will be string or something like this:

        // full_name: jhon doe
        // address: some street
        // gender: male
        // hobies: football, basketball (combine multiple values:not if checked)
    });
});

i don't know how to group multiple values by it's name

what is the best way to make that output.. use jQuery serialize or each
function ??
thanks for attention

A: You can find the checked checkboxes with :checked. You can then put them into a key-value store where the key is the name of the checkbox, and the value is an array of selected checkboxes :
$('.submit').click(function(){
    var InputCollect = $('.register').find(':input');
    let form = {}
    $('input[type=text], textarea, input[type=radio]:checked', '.register').each(function(){
        const name = $(this).attr('name');
        const value = $(this).val();
        if(value.trim() !== '') {
            form[name] = value;
        }
    });

    $('input[type=checkbox]:checked', '.register').each(function(){
        const name = $(this).attr('name');
        const value = $(this).val();
        if(form[name] === undefined) {
            form[name] = [value];
        } else {
            form[name].push(value);
        }
    });

    console.log(form);
});

Here I had to split the logic into two callbacks because handling textual inputs and radios is different from handling checkboxes, although you can still merge them in a single callback if you want.
JS fiddle link


text:
Q: Reading environment variables in SymmetricDS engine properties I'm using the Gradle Application plugin to create a zip distribution of SymmetricDS. It would be nice to have a simple way of switching between environments (test, staging, production, whatever).
The SymemtricDS User Guide says
SymmetricDS will automatically create a node for each Node Properties
File configured in the engines directory

So, it will probably not be possible to define engines for all environments and choose which one to start, without doing this manually.
A better way would probably be to have SymmetricDS read some environment variables and use these to define e.g. db.url in the engine files. This way the same config could be used for all environments. Is this possible?

A: There have been several requests for something like this.  I noticed someone setting up docker images also would benefit from being able to specify dynamic properties.  I'm adding the ability to do token replacement with environment variable or system properties in 3.8.12.
Here is the issue to track it: https://www.symmetricds.org/issues/view.php?id=2945

A: Use Gradle Resource filtering to replace variable placeholders in your symmetric-ds.properties file. For example
db.url=${env.db.url}
db.user=${env.db.user}
db.password=${env.db.password}

then create as many config files as there are environments where the actual values of placeholders would be saved, for example dev.conf:
env.db.url=jdbc://db_host:1520
env.db.user=my_user
env.db.user=p4$$vv0rd

use a command line parameter to choose an environment to gradle assembly command which will choose one of conf files


text:
Q: default behaviour for (bool) cast classes in the stl, such as unique_ptr will occasionally show examples such as:
// unique_ptr constructor example
#include <iostream>
#include <memory>

int main () {
  std::default_delete<int> d;
  std::unique_ptr<int> u1;
  std::unique_ptr<int> u2 (nullptr);
  std::unique_ptr<int> u3 (new int);
  std::unique_ptr<int> u4 (new int, d);
  std::unique_ptr<int> u5 (new int, std::default_delete<int>());
  std::unique_ptr<int> u6 (std::move(u5));
  std::unique_ptr<void> u7 (std::move(u6));
  std::unique_ptr<int> u8 (std::auto_ptr<int>(new int));

  std::cout << "u1: " << (u1?"not null":"null") << '\n';
  std::cout << "u2: " << (u2?"not null":"null") << '\n';
  std::cout << "u3: " << (u3?"not null":"null") << '\n';
  std::cout << "u4: " << (u4?"not null":"null") << '\n';
  std::cout << "u5: " << (u5?"not null":"null") << '\n';
  std::cout << "u6: " << (u6?"not null":"null") << '\n';
  std::cout << "u7: " << (u7?"not null":"null") << '\n';
  std::cout << "u8: " << (u8?"not null":"null") << '\n';

 *emphasized text* return 0;
}

The line:
 std::cout << "u1: " << (u1?"not null":"null") << '\n';

shows the unique_ptr u1 being directly cast to false if it is tracking a null pointer.
I have seen this behaviour used in other custom classes. How is this managed and what operator decides whether a direct cast to bool such as this returns true or false?

A: It is implemented as a member conversion operator of the form explicit operator bool() const;. Whether it returns true or false is implemented in the logic of the class itself. For example, this class has an bool conversion operator that returns true if it's data member has value 42, and false otherwise:
struct Foo
{
  explicit operator bool() const { return n==42; }
  int n;
};

#include <iostream>

int main()
{
  Foo f0{12};
  Foo f1{42};

  std::cout << (f0 ? "true\n" : "false\n");
  std::cout << (f1 ? "true\n" : "false\n");
}

A: operator bool();

It's a standard cast-operator to type bool.
Here's an example of how to use it:
class Checked
{
    bool state;

public:
    Checked(bool _state) : state(_state) { }

    explicit operator bool() const {
        return state;
    }
};

Checked c (true);
if (c)
    cout << "true";

Note the explicit keyword. It appeared in C++11 and allows safe conversion of the class to bool, which happens, in short, in the logical context such as if(), while() etc. Without the explicit, bad things could happen, as there's an implicit conversion of bool to numeric types. In C++03 and older it's safer to overload operator ! (), which then is tested as if (!!c).

A: A conversion operator is used for this functionality:
operator bool(){ return false; }

In C++11 you can also make them explicit
explicit operator bool(){ return true; }

Implicit conversion operators are an error prone endeavour. Consider if unique_ptr had an implicit conversion operator to bool, you could do nonsensical things like...
std::unique_ptr<Thing> x;
int y = 7 + x;

In the above case y would equal 7 + (0 if x is null or 1 if x is non-null)


text:
Q: rsstail Not Printing Output I've installed rsstail 1.8 on my linux box and everything seems to be going smoothly, knock on wood, except for the part where rsstail isn't printing the streams. Running the command, I see that it's retrieving the feed, but nothing ever happens and I'm flummoxed as to why.
rsstail -i 300 -t -d -v -u http://www.nu.nl/feeds/rss/algemeen.rss -n 20
Monitoring RSS feeds:
        http://www.nu.nl/feeds/rss/algemeen.rss
Check interval: 300
Retrieving RSS feed 'http://www.nu.nl/feeds/rss/algemeen.rss'...

Edit: I'm looking for this to do two things. Given a RSS feed, I'd like to go pull the last N entries for display and second track the feed and update with new articles. Despite pointing at feeds (I've tried CNN and others) it never displays the previous listings, even though browser eyeballing says stuff is there.


text:
Q: How to convert json into csv file using jq? This is my json file:
{
  "ClientCountry": "ca",
  "ClientASN": 812,
  "CacheResponseStatus": 404,
  "CacheResponseBytes": 130756,
  "CacheCacheStatus": "hit"
}
{
  "ClientCountry": "ua",
  "ClientASN": 206996,
  "CacheResponseStatus": 301,
  "CacheResponseBytes": 142,
  "CacheCacheStatus": "unknown"
}
{
  "ClientCountry": "ua",
  "ClientASN": 206996,
  "CacheResponseStatus": 0,
  "CacheResponseBytes": 0,
  "CacheCacheStatus": "unknown"
}

I want to convert these json into csv like below.
"ClientCountry", "ClientASN","CacheResponseStatus", "CacheResponseBytes", "CacheCacheStatus"
"ca", 812, 404, 130756, "hit";
"ua", 206996, 301, 142,"unknown";
"ua", 206996, 0,0,"unknown";

Please let me know how to achieve this using jq?
I just tried below. But its not working.
jq 'to_entries[] | [.key, .value] | @csv'

Regards
Palani

A: Since you want all the key-values,
then assuming that the keys are presented in a consistent order in the input file, you can simply write:
jq -r '[.[]] | @csv' palanikumar.json

With the given input, this produces the following CSV:
"ca",812,404,130756,"hit"
"ua",206996,301,142,"unknown"
"ua",206996,0,0,"unknown"

Adding the headers and the trailing semicolons (if you really want them) is left as a (very easy) exercise.
Inconsistent ordering
If the ordering of the keys varies or might vary, then the following could be used to produce suitable CSV, assuming that the ordering of the keys in the first object in the input stream should be used:
input
| . as $first
| keys_unsorted as $keys
| $keys, [$first[]], (inputs | [.[$keys[]]]) | @csv

The appropriate invocation of jq would include both the -n and -r command-line options.

A: Look at these links
How to convert arbirtrary simple JSON to CSV using jq?
http://bigdatums.net/2017/09/30/convert-json-to-csv-with-jq/
( jq -r '.myarray | @csv' )


text:
Q: Regular expression route constraint for a resource route Laravel offers the possibility to add regular expression constraint to a route like this:
Route::get('user/{name}', function($name)
{
    //
})
->where('name', '[A-Za-z]+');

it is also possible to create multiple routes for a resource:
Route::resource('photo', 'PhotoController');

I want to add regular expression constraint only to the route GET /photo/{id}
is that possible?

A: As far as I know you can't but you may mimic that using something like this (route filtering):
public function __construct()
{
    $this->beforeFilter('checkParam', array('only' => array('getEdit', 'postUpdate')));
}

This is an example of route filtering using the constructor and here I've filtering only two methods (you may use except or nothing at all) and declared the filter in filters.php file as given below:
Route::filter('checkParam', function($route, $request){
    // one is the default name for the first parameter
    $param1 = $route->parameter('one');
    if(!preg_match('/\d/', $param1)) {
        App::abort(404);
        // Or this one
        throw new Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
    }
});

Here, I'm checking the first parameter manually (parameters method returns an array of all parameters passed to the route) and if it's not a digit then throwing NotFoundHttpException exception.
You may also catch the exception by registering a handler like this:
App::missing(function($exception){
    // show a user friendly message or whatever...
});

A: In Laravel 5 resourceful route parameters can be named like this:
Route::resource('user', 'UserController', ['parameters' => [
   'user' => 'id'
]]);

This can be combined with route patterns:
Route::pattern('id', '[0-9]+');

So you can easily define a single global constraint for route parameters and use if for all of your resourceful routes.

A: In your RouteServiceProvider boot() method, just reference the parameter name using Route::pattern('parameter', 'regex'). Note: the parameter name is the singular (if path is plural) of the path.
public function boot()
{
    Route::pattern('photo', '[0-9]+');

    parent::boot();
}

This would work for both:
Route::resource('photo', 'PhotoController');

and
Route::resource('photos', 'PhotoController');

Note: if you typehint your parameter to the model, this is not necessary. For example:
public function show(Photo $photo)
{
    //
}

Now, if a non-matching parameter is passed, a 404 | Not Found will be returned. But if you are using Route::fallback() to handle unmatched routes, you should keep Route::pattern('parameter', 'regex').

A: You should overwrite IlluminateFoundation\Exceptions\Handler :
if ($exception instanceof QueryException) {
            if (str_contains($exception->getMessage(), "Invalid text representation:")) {
                $requestId = $exception->getBindings()[0] ?? "";
                App::abort(404);
               // Or this one
               throw new Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
            } else {
               throw $exception;
            }
        }


text:
Q: Using custom Data Service Providers, do I have any control over URLs that are returned? I'm implementing several custom Data Service Providers in WCF Data Services:

*

*IDataServiceMetadataProvider

*IDataServiceQueryProvider

*IDataServiceUpdateProvider
To illustrate the point of my question consider this made-up example:
I have a resource called "Employee," which can be addressed in the following ways:
MyDataService.svc/Employees(1)
or
MyDataService.svc/Employees?$filter=FirstName eq 'John'
The results that are returned automatically include URLs for each resource, like:
http://localhost:1337/MyDataService.svc/Employees(5), and so on.
Is it possible to, instead, have Data Services return People(5) instead of Employees(5)?
In short, I need some control over URLs that Data Services generates. Is that possible?

A: This does not seem possible at this time.


text:
Q: Default text not generating I am learning C# and just started with VScode and it does not generate any of the defualt text my tutorial showed me such as this
using System;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");
    }
  }
}

What am I supposed to do?


text:
Q: How to draw text with in a specified rect in android? Is there a method to draw text  with in a  specified rectangle?
I am drawing directly to a canvas(ImageView) using
canvas.drawText(text,x,y,paint)

But this drew the entire text in a single line. I want to wrap the text with in the specified (x,y) ,(x1,y1) limit. I don't want to use textviews or any other views.
I just want to draw the text over an image.
Is there any method to do this?
Thanks in Advance

A: Firstly you have to determine the text size. The width of each character could be get by getTextWidths(), the height is same with text size. Try to estimate a initial text size, and use the height and width of text to adjust the final value.
Secondly you need to break lines. Paint.getTextWidths() or Paint.breakText() can all achieve this target.
Edit: add the code example.
public static class RectTextView extends View {
    private int mWidth = 200;
    private int mHeight = 100;
    private String mText = "Hello world. Don't you know why, why you and I.";
    private Paint mPaint;
    private List<Integer> mTextBreakPoints;

    public RectTextView(Context context) {
        this(context, null);
    }

    public RectTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mPaint.setColor(Color.WHITE);
        mPaint.setAntiAlias(true);
        setSuitableTextSize();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int start = 0;
        int x = 0;
        int y = 0;
        for (int point : mTextBreakPoints) {
            y += mPaint.getTextSize();
            canvas.drawText(mText, start, point, x, y, mPaint);
            start = point;
        }
    }

    private void setSuitableTextSize() {
        int textSize = getEstimateTextSize();
        for (; textSize > 0; textSize--) {
            if (isTextSizeSuitable(textSize))
                return;
        }
    }

    private boolean isTextSizeSuitable(int size) {
        mTextBreakPoints = new ArrayList<Integer>();
        mPaint.setTextSize(size);
        int start = 0;
        int end = mText.length();
        while (start < end) {
            int len = mPaint.breakText(mText, start, end, true, mWidth,
                    null);
            start += len;
            mTextBreakPoints.add(start);
        }
        return mTextBreakPoints.size() * size < mHeight;
    }

    private int getEstimateTextSize() {
        return (int) Math.sqrt(mWidth * mHeight / mText.length() * 2);
    }
}


text:
Q: Is every knot unavoidable in the embeddings of some graph?
Is it the case that, for any given knot $K$,
  there exists some graph $G$ whose every embedding into $\mathbb{R}^3$
  (or into $\mathbb{S}^3$)
  contains a cycle that realizes $K$?

I know the famous Conway-Gordon result that the complete graph
on seven vertices $K_7$ is intrinsically knotted in that every
embedding contains a knotted cycle.
And Joel Foisy proved that $K_{3,3,1,1}$ is also intrinsically knotted
(J. Graph Theory, 2002, ACM link).
Instead, I am asking a Ramsey-like question:
Whether it's known that, for every particular knot, there exists some
graph for which that particular knot is unavoidable.

A: The answer is no for the following silly reason.  Take any graph $G$ and some embedding into $\mathbb R^3$.  To any edge, we may perform the connected sum with a fixed knot $K'$ (that is, take a small straight part of the edge and connect sum to it $K'$ there).  Do this operation separately to all of the edges.  Then any cycle in $G$ has knot type of the form $K'\#(\text{something})$.  We just need to pick a knot $K'$ so that the given $K$ is not of this form.
We could modify the question and ask whether a fixed knot $K$ exists in some weaker sense in any given embedding of $G$.  One such (very) weak sense could be that there exists a knotted torus $T$ in knot type $K$ and a cycle in $G$ which is contained in $T$ and cannot be made disjoint from a compressing disk for $T$.  I suspect this may also have a negative answer, however.  It seems one can probably always find embeddings of $G$ which are arbitrarily complicated, and in particular which are not related in any way to the given knot $K$.

A: Yes. See this paper of Negami.  The main result is that for any fixed knot (or link) of type $k$, there is a constant $R(k)$ such that every straight line embedding of $K_{R(k)}$ in $\mathbb{R}^3$ contains a knot (or link) equivalent to $k$.


text:
Q: What goes on behind the curtains during disk I/O? When I seek to some position in a file and write a small amount of data (20 bytes), what goes on behind the scenes?
My understanding
To my knowledge, the smallest unit of data that can be written or read from a disk is one sector (traditionally 512 bytes, but that standard is now changing).  That means to write 20 bytes I need to read a whole sector, modify some of it in memory and write it back to disk.
This is what I expect to be happening in unbuffered I/O.  I also expect buffered I/O to do roughly the same thing, but be clever about its cache.  So I would have thought that if I blow locality out the window by doing random seeks and writes, both buffered and unbuffered I/O ought to have similar performance...  maybe with unbuffered coming out slightly better.
Then again, I know it's crazy for buffered I/O to only buffer one sector, so I might also expect it to perform terribly.
My application
I am storing values gathered by a SCADA device driver that receives remote telemetry for upwards of a hundred thousand points.  There is extra data in the file such that each record is 40 bytes, but only 20 bytes of that needs to be written during an update.
Pre-implementation benchmark
To check that I don't need to dream up some brilliantly over-engineered solution, I have run a test using a few million random records written to a file that could contain a total of 200,000 records.  Each test seeds the random number generator with the same value to be fair.  First I erase the file and pad it to the total length (about 7.6 meg), then loop a few million times, passing a random file offset and some data to one of two test functions:
void WriteOldSchool( void *context, long offset, Data *data )
{
    int fd = (int)context;
    lseek( fd, offset, SEEK_SET );
    write( fd, (void*)data, sizeof(Data) );
}

void WriteStandard( void *context, long offset, Data *data )
{
    FILE *fp = (FILE*)context;
    fseek( fp, offset, SEEK_SET );
    fwrite( (void*)data, sizeof(Data), 1, fp );
    fflush(fp);
}

Maybe no surprises?
The OldSchool method came out on top - by a lot.  It was over 6 times faster (1.48 million versus 232000 records per second).  To make sure I hadn't run into hardware caching, I expanded my database size to 20 million records (file size of 763 meg) and got the same results.
Before you point out the obvious call to fflush, let me say that removing it had no effect.  I imagine this is because the cache must be committed when I seek sufficiently far away, which is what I'm doing most of the time.
So, what's going on?
It seems to me that the buffered I/O must be reading (and possibly writing all of) a large chunk of the file whenever I try to write.  Because I am hardly ever taking advantage of its cache, this is extremely wasteful.
In addition (and I don't know the details of hardware caching on disk), if the buffered I/O is trying to write a bunch of sectors when I change only one, that would reduce the effectiveness of the hardware cache.
Are there any disk experts out there who can comment and explain this better than my experimental findings? =)

A: Indeed, at least on my system with GNU libc, it looks like stdio is reading 4kB blocks before writing back the changed portion. Seems bogus to me, but I imagine somebody thought it was a good idea at the time.
I checked by writing a trivial C program to open a file, write a small of data once, and exit; then ran it under strace, to see which syscalls it actually triggered. Writing at an offset of 10000, I saw these syscalls:
lseek(3, 8192, SEEK_SET)                = 8192
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 1808) = 1808
write(3, "hello", 5)                    = 5

Seems that you'll want to stick with the low-level Unix-style I/O for this project, eh?

A: The C standard library functions perform additional buffering, and are generally optimized for streaming reads, rather than random IO. On my system, I don't observe the spurious reads that Jamey Sharp saw I only see spurious reads when the offset is not aligned to a page size - it could be that the C library always tries to keep its IO buffer aligned to 4kb or something.
In your case, if you're doing lots of random reads and writes across a reasonably small dataset, you'd likely be best served using pread/pwrite to avoid having to make seeking syscalls, or simply mmaping the dataset and writing to it in memory (likely to be the fastest, if your dataset fits in memory).


text:
Q: Sequelize v5 underscored option is not working I am using node.js with sequelize and typescript on vs code.
Recently migrated to sequelize v5 for using typescript.
So I removed "underscoredAll" option because it is no more supported on sequelize v5.
But problem is here.
My MySQL table definition is still works. I already defined all columns using underscore and sequelize loaded data well.
I've been using this system for eight months, before upgrade to sequelize v5.

Please check this image, "Auth" is instance of sequelize model.
"ChannelId" is a foreignKey and "createdAt" is timestamp, which created by sequelize.
Yes, Instance's member is not underscored field.
That fields still camelCased.
I already tried set underscored option to each model init function option.
Nevertheless, It didn't work.
What can I do for this problem T.T
Please Help Me... I want to go home...
const database = new Sequelize('db_name', 'username', 'pwd', {
    host: 'localhost',
    dialect: 'mysql',
    dialectOptions: {
        connectTimeout: 30000
    },
    define: {
        underscored: true,
        // underscoredAll: true /* removed on v5 */
    },
    pool: {
        max: 100,
        idle: 30000,
        acquire: 60000,
    },
    logging: false
});


text:
Q: CakePHP 3 is NOT able to connect to the database due to a missing PHP extension I am trying to install cakePHP 3.0.0 with WT-NMP, but i got this message:

CakePHP is NOT able to connect to the database.
Database driver Cake\Database\Driver\Mysql cannot be used due to a
  missing PHP extension or unmet dependency

my php.ini has this:
extension = php_bz2.dll
extension = php_curl.dll
extension = php_gd2.dll
extension = php_imap.dll
extension = php_mbstring.dll
extension = php_exif.dll
extension = php_mysql.dll
extension = php_mysqli.dll
extension = php_pdo_mysql.dll
extension = php_pdo.dll
extension = php_soap.dll
extension = php_sockets.dll
extension = php_sqlite3.dll
extension = php_openssl.dll
extension = php_fileinfo.dll
extension = php_intl.dll

the app.php has this
    'default' => [
        'className' => 'Cake\Database\Connection',
        'driver' => 'Cake\Database\Driver\Mysql',
        'persistent' => false,
        'host' => 'localhost',
        /**
         * CakePHP will use the default DB port based on the driver selected
         * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
         * the following line and set the port accordingly
         */
        'port' => '3306',
        'username' => 'root',
        'password' => '',
        'database' => 'test',
        'encoding' => 'utf8',
        'timezone' => 'UTC',
        'cacheMetadata' => true,

What am I missing? or this is cakePHP 3.0 bug? OR anything to do with WT-NMP.
I have been stuck for whole day.

A: Try this:
For PHP 7.0
sudo apt-get install php7.0-mysql

For PHP 5:
sudo apt-get install php5-mysql

A: The error message is because of extension = php_pdo_mysql.dll not being installed and enabled in php.ini. If you don't have php_intl.dll enabled you will get an error before checking the database connection.
Your php.ini indicates that you have got php_pdo_mysql.dll enabled, however it may have been that you needed to restart the CakePHP server bin/cake server.

A: Solved this by luck!:
extension = php_intl.dll
extension = php_pdo_mysql.dll
intl.default_locale = en_utf8
intl.error_level = E_WARNING

A: Installing the modules for MySQL database connections solved it for me:
#Install the package
sudo apt-get install php5-mysql
#Restart Apache
sudo service apache2 restart

Source: http://guru4cakephp.blogspot.nl/2015/04/install-cakephp-3-on-ubuntu.html
Package details: https://packages.debian.org/sid/php5-mysql

A: Don't just depend on the php.ini reading. Just check if you have installed php[v]-mysql extension. You can check if php_mysql.dll exist in the php extension directory(most probably <path to your php installation>/ext) in your windows based server. In linux you can use the following command check if it is installed.
yum list installed | grep php

It will list down all the php extensions installed.


text:
Q: FITS Image Array Pixel out of bounds I am attempting to set a threshold for pixels in a FITS file using the code below. However, I get an error that says that:
IndexError: Index 2620 is out of bounds for axis 0 with size 2620

Any ideas on how to fix this?
This is the code:
from astropy.io import fits
import numpy as np
hdulist = fits.open("12ratio.fits")
origImData = hdulist[0].data
newImData = origImData*0

for x, y in np.nditer(origImData.shape):
        curPixel = origImData[x, y]
        if curPixel > 0.28 or curPixel < 3.11:
                newImData[x, y] = curPixel
        else:
                newImData[x, y] = 0
newhdu = fits.PrimaryHDU(newImData)
newhdulist = fits.HDUList([newhdu])
newhdulist.writeto('modifiedratio12.fits')

A: The problem is your iteration scheme.  You're iterating over the shape of the array, not the pixel indices.
In general there is a better approach for masking:
mask = (origImData > 0.28) & (origImData < 3.11)
newImData[mask] = origImData[mask]

will accomplish what you seem to be aiming for.
Or just as effective:
from astropy.io import fits
import numpy as np
hdulist = fits.open("12ratio.fits")
origImData = hdulist[0].data
mask = (origImData > 0.28) & (origImData < 3.11)
origImData[~mask] = 0

newhdu = fits.PrimaryHDU(data=origImData, header=hdulist[0].header)
newhdu.writeto('modifiedratio12.fits')

Here I've used the numpy array boolean not operation (~) to invert the mask.  I've also skipped making an HDUList since that is not needed for a single-extension FITS file.
There are two errors in the code you've shown:
for x, y in np.nditer(origImData.shape):

will assign x and y the values of origImData.shape, i.e. x=2640 and y=(something else), it will not assign them the values 0,1,...,2640 as you intend.
The comparison operation:
    if curPixel > 0.28 or curPixel < 3.11:

will always be true for real numbers:  all numbers are either greater than 0.28 or less than 3.11.


text:
Q: Get back full URI from Addressable object? If I have an addressable object like this:
uri = Addressable::URI.parse("http://example.com/path/to/resource/")

How would I get back the "http://example.com/path/to/resource/" - I have looked at uri.methods, but I fail to see which one would I use to get back the full URI.

A: Use to_s method:
uri = Addressable::URI.parse("http://example.com/path/to/resource/")
uri.to_s
# => "http://example.com/path/to/resource/"

See URI - basic example.


text:
Q: TypeError: cannot call method 'forEach' of undefined When I try to add static dirs to my code, I get this error :
TypeError: cannot call method 'forEach' of undefined
Can anyone help me with this ?
['adobeair','applewebkit','bs3','chrome','css','font-awesome','hpwos','images','img','js', 'Opera', 'plugins'].forEach(function (dir)
{
    app.use('/template/'+dir, connect.static(__dirname+'/template/'+dir));
});

Thanks

A: Best way -
var dirs = ['adobeair','applewebkit','bs3','chrome','css','font-awesome','hpwos','images','img','js', 'Opera', 'plugins'];

dirs.forEach(function(dir) {

console.log('dir name : '+dir);

});

It is working or me :)


text:
Q: Novel search: A man searching for his brother in Africa starts a chase through different realities/dimensions I might be mixing up several books, I hope I'm not, it's been 20 years since I read the books.
I want to say it was a series of books.
Each book could have been written by a different writer.
From memory it starts off in the late 1800's/early 1900's a man has gone to Africa to search for his lost brother. Weird/implausible stuff starts happening as they travel up a river, I want to say the Congo, and eventually they enter another realm. As they chase after clues to his brother they traverse a reality roughly each book.
At some point I want to say there is train imagery used as well as an iceberg with reference to Mary Shelly's monster(I could be mixing this up with another book)

A: I'm guessing Philip Jose Farmer's shared world series "The Dungeon", six novels by four authors who are not Farmer.

The books follow nineteenth century explorer Clive Folliot as he
  travels through a multilayered dungeon world attempting to find his
  twin brother Neville. Along the way, he forms a group of similarly
  lost creatures and persons, and must battle the pawns and agents of
  the Dungeon's mysterious alien masters.

Volume One, The Black Tower by Richard Lupoff


text:
Q: How to check user's input data type in C? #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
void main()
{
int userNum;
int count=0;

printf("Please enter a whole number: ");
scanf("%i", &userNum);

while (userNum != 999)
{
    if (userNum > 0)
    {
        printf("Factors: ");
        for (count = 1; count <= userNum; count++)
        {
            if ((userNum % count) == 0)
            {
                printf("%i ", count);
            }
        }
    }
    else
    {
        printf("You input a negative number");
    }
    printf("\nPlease enter a whole number: ");
    scanf("%i", &userNum);
}
printf("\n");
system("pause");

}
Hey guys, that is my code for finding factors of a number given by the user. I have a problem: the program will run into an infinite loop if the user inputs a  character or a double number. So, I want to ask how to solve that problem. I really like coding. Please help. Thank you so much.


text:
Q: AS3 multiple starling custom event dispatcher error I am having an issue with custom events when I have more than 1.
Currently I have 2 custom events:

*

*Navigation event

*Friend action event

They are both pretty much the same as:
package events
{
import starling.events.Event;

public class NavigationEvent extends Event
{
    public static const SHOWSCREEN:String = "";
    public var params:Object;

    public function NavigationEvent(type:String, _params:Object = null, bubbles:Boolean=false, data:Object=null)
    {
        super(type, bubbles, data);
        this.params = _params;
    }
}
}

however the other is
public class FriendActionEvent extends Event

on the main class I have 2 listeners
this.addEventListener(events.NavigationEvent.SHOWSCREEN, onNavigationScreen);
this.addEventListener(events.FriendActionEvent.ACTION, onFriendAction);

and the methods however when I add the second listener I get the error
TypeError: Error #1034: Type Coercion failed: cannot convert events::NavigationEvent@fe5ee21 to events.FriendActionEvent.

so I am guessing there is an issue with 2 custom events but unsure how to work around it.
Cheers

A: I think onNavigationScreen is taking FriendActionEvent in parameter (possibly a case of bad copy-paste from the other event handler).


text:
Q: Web Service Deployment Descriptor What is the purpose of Web Service Deployment Descriptor (wsdd) configuration file.
If I didn't configure this file explicitly it doesn't create any issue in my application (as I am using a .jws file to do some web service related processes). But, for the first time the application runs, an error is logged in the error log file. The error is as follows:
"Unable to find config file. Creating new servlet engine config file: /WEB-INF/server-config.wsdd". And when the page refreshes or even the application is re-logged in (still the server is running), there won't be any such error log further times. When I use a sample wsdd file in my application, the error is not at all logged in the error log file. I want to know the purpose of this wsdd file and how to configure it based on our application.
Any suggestions would be appriciated.
Marshal.

A: Just do a google on "server-config.wsdd".
e.g. http://axis.apache.org/axis/java/integration-guide.html
It looks like your container or framework is generating a default file if you don't specify one, which is useful, but if you wish to add additional customisations such as handlers, security and logging (etc) then you can specify your own file.
It might be best to use a "bare minimum" file so you can customise it later.


text:
Q: How to improve performance of an Abstract Factory when all the time appears to be spent in memory allocation The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory).  It's too slow.  Profiling says all the time is spent in operator new.
Notes: The application already uses a custom memory allocator that does pooling.  The compiler is VC++ 6.0 and the code uses the old RogueWave collections rather than the STL.
The only idea I have right now is to introduce Object Pooling.  I'd maintain large collections of pre-allocated objects for each type and re-use them.  But this will be a lot of work in this old code, and I'm not yet sure there's enough re-use that it would even help.  I was hoping someone smarter than me has an idea.

A: The only way is to reduce the number of memory allocations. Have you used a profiler that will tell you exactly what is doing the allocation?  Are you possibly doing some string manipulation?
If all the time is spent allocating the objects the factory is creating, you may need to go to a pool.

A: Have you tried using a custom allocator for objects of known size? This is a good technique for speeding up allocations.

A: I'll assume that most allocations relate to the list of objects you're talking about. If you're actually allocating a bunch of other objects as part of the parsing that's too slow, then you need more information to optimize.

*

*I don't know anything about the RogueWave collections, but if their linked list allocates an external node, then you should be able to halve the number of allocations by using an intrusive list - write your own container if necessary. This assumes that you don't need to put the same objects on multiple lists at once (or in the same list more than once).

*If your app is multi-threaded, then the memory allocator will likely be doing some synchronization. But if you can arrange for these objects to be freed in the same thread they're allocated, then they could be allocated off a per-thread heap by overloading operator new. This might be faster: synchronization isn't necessarily all that slow provided there isn't contention, but it takes more time than none, and if other threads in your process are allocating at the same time then there will be contention.

*For even more limited use-cases, if you find that you allocate a whole load of these things and then always free them all at once when you're done with the list, you can write an even faster "gc-style" allocator.
Operator new/delete would call functions like these (and size might be a constant rather than a parameter, if there's only one class you use the pool for):
char *alloc(POOL *pool, size_t size) {
    // if size is a parameter, and may be a non-multiple the max alignment
    // requirement on your system, and you want this to work in general:
    // size = (size + MAX_ALIGNMENT - 1) % ALIGNMENT;
    char *block = pool.current;
    char *next = block + size;
    if (next > pool.limit) throw std::bad_alloc();
    pool.current = next;
    return block;
}

void free(char *block) {
    return;
}

void freeAll(POOL *pool) {
    pool.current = pool.start;
    return;
}

This should ensure that operator new takes trivial time compared with what you spend parsing the objects you're creating. But it does require the application to identify the times at which it should create, destroy, and clear pools, and to to use a suitable new operator taking the pool pointer as a parameter, so it's not a drop-in replacement.

A: Just some ideas...

*

*What are you doing in your ctors? Maybe they are slow? Large objects, file access, etc?

*How much memory is available for your application? Are you close to the physical limits so the OS busy is swapping?

*Be cache friendly by localizing your memory access patterns. If the RogueWave collections won't do that for you, maybe it's time to look for something else.

*Are you sure your custom allocator isn't the culprit?

A: You can replace operator new, even per class. In your particular case, you'll be allocating and deallocatin many objects of a single class. That means you will have quite a few allocations with identical size. That's a pattern which is easy to optimize. Basically, keep a raw block of memory, N*sizeof(T) and a bitmap with N/8 bits to indicate free status. This refits quite easily; your old code doesn't need to change.


text:
Q: Displaying data json , into web pages with JavaScript I found the problem will display the results jSon to a web page at run time data is empty or blank web page, if anyone could help me ?
This my variable declare

var xmlhttp = new XMLHttpRequest();
var url = "http://adisapu10022.besaba.com/smsVerify/json.php";

xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        myFunction(xmlhttp.responseText);
    }
}
xmlhttp.open("GET", url, true);
xmlhttp.send();

This my function

  function myFunction(response) {
        var arr = JSON.parse(response);
        var i;
        var out = "
";

        for(i = 0; i < arr.length; i++) {
            out += "
" +
            arr[i].Foto +
            "	" +
      arr[i].Komoditas +
            "	" +
            arr[i].Harga +
            "	" +
      arr[i].Pengunggah +
            "	" +
            arr[i].Telp +
            "	" +
            arr[i].Unggah +
            "
";
        }
        out += "
";
        document.getElementById("id01").innerHTML = out;
    }

A: I thing your json string is invalid. Check at

"Komoditas":"Sepatu Nike",{"Harga":"900 Ribu /kg"

The right format is

"Komoditas":"Sepatu Nike","Harga":"900 Ribu /kg"


text:
Q: Tooltip for jqgrid column I have jqgrid coloumn on which I want to customize my tooltip just for one column while for others I need default tooltip.
Any leads ?
My column is something like the below
....
{
                            name : 'title',
                            index : 'title',
                            width : '20%',
                            align : 'center',
                            sorttype : false,
                            sortable : false
                        }

A: Tooltip for Header
If you want tooltip for header of column you can just add title attribute with jquery like this:
if your grid container this:

then yout js will be like this:
$("#jqgh_myJqgrid_title").attr("title", "Can't sort my title!");

Header name selector id forms like this:

jqgh_<<grid_div_name>>_<<column_name>>

Tooltip for cell in column
If you need tooltip for column you can use cellattr function.
You can even create different tooltip for each cell in column base on cell or row value, becouse function have optional parameters: rowId, cellValue, rawObject  etc (documentation)
In your case you can do like this:
{
   name : 'title',
   index : 'title',
   width : '20%',
   align : 'center',
   sorttype : false,
   sortable : false,
   cellattr: function () { return ' title="Here is my tooltip on colCell!"'; }
}

A: The version 3.8.2 of jqGrid was published in 2010. It's really very old. The features like cellattr was introduced later in jqGrid 4.0 (see here).
I would strictly recommend you to update it to jqGrid 4.7.0 or jqGrid 4.6.0.

A: Assuming you already have the data (xml, json ...) you could have hidden values in a column and used cellattr to indicate the value of each column.
For example if you have three columns:
//tooltip obtained from hidden column for the first column
{
    name : 'title',
    index : 'title',
    width : '20%',
    align : 'center',
    sorttype : false,
    sortable : false,
    cellattr: function (rowId, cellValue, rowObject) {
                   return ' title="' + $(rowObject).find('cell:eq(3)').text() + '"';
              }
},
//default tooltip obtained from hidden column
{
    name : 'subtitle',
    index : 'subtitle',
    width : '20%',
    align : 'center',
    sorttype : false,
    sortable : false,
    cellattr: function (rowId, cellValue, rowObject) {
                   return ' title="' + $(rowObject).find('cell:eq(4)').text() + '"';
              }
},
//here you can set as in the column subtitle or put the default tooltip that you want
{
    name : 'subtitle2',
    index : 'subtitle2',
    width : '20%',
    align : 'center',
    sorttype : false,
    sortable : false,
    cellattr: function (rowId, cellValue, rowObject) {
                   return ' title=" My default tooltip "';
              }
},
//hidden columns
{
    name : 'hiddenColumn1',
    index : 'hiddenColumn1',
    hidden: true,
},
{
    name : 'hiddenColumn2',
    index : 'hiddenColumn2',
    hidden: true,
},

A: You would need to use jquery to create "title" HTML attribute for tooltips.
jQuery(document).ready(function($){
jQuery("tr.ui-jqgrid-labels th:eq(0)").attr("title", "Column 1 header title");

jQuery("tr.ui-jqgrid-labels th:eq(1)").attr("title", "Column 2 header title");

jQuery("tr.ui-jqgrid-labels th:eq(2)").attr("title", "Column 3 header title");

});

A: I use this code for a set custom tooltip:
{
name : 'title',
index : 'title',
width : '20%',
align : 'center',
sorttype : false,
sortable : false,
cellattr: function (rowId, cellValue, rowObject) {
               return ' title="' + $(rowObject)[3] + '"';
          }

},


text:
Q: Different htaccess directory and subdirectory redirect I am trying to have clean urls on my site and here is the mapping I'm trying to achieve:

*

*mysite.tld/directory/ is going to > mysite.tld/page.php?q=directory

*mysite.tld/tags/directory/ is going to > mysite.tld/tag.php?q=directory

I have made an htaccess file at the root of my site wiht the folling code:
RewriteEngine On
RewriteRule ^([^\/]+)\/?$ pages.php?q=$1 [L,QSA]
RewriteRule ^tags/([^/d]+)/?$ tags.php?q=$1 [L,QSA]

For some reason, the tag redirect works but is then "eaten" by the other rule of redirection. Not sure what to do to prevent second rule from doing this.

A: Answer is as follow:
RewriteEngine On
RewriteRule ^tags/([^/d]+)\/? /tags.php?q=$1 [L,QSA]
RewriteCond %{REQUEST_URI} !/tags
RewriteRule (.*) pages.php?q=$1 [L,QSA]


text:
Q: regex for swap info in SunOs swap command : /usr/sbin/swap  -s
I even tried something like awk '/total/ {print $2}' /usr/sbin/swap -s but gives me error
swap output :
total: 12417784k bytes allocated + 2705800k reserved = 15123584k used, 45459976k available

I need to get used an available values i.e., 15123584k and 45459976k respectively.

A: Use a pipe to pass the output of swap to awk
/usr/sbin/swap -s | awk '/total/ {print $2}'

To get the value of 15123584k and 45459976k, we print out column 9 and column 11 using
/usr/sbin/swap -s | awk '/total/ {print $9" "$11}'


text:
Q: Why RSACryptoServiceProvider VerifyData method is taking 30 seconds when deployed on server The rsa1.VerifyData() method is taking 30 seconds to return the result. The parameter calculation is completed within few milliseconds. I have tried adding the OID mappings in machine.config but no benefit.
    public bool VerifyData(string publicKeyXml, string plainData, string base64Signature)
    {
        try
        {

            RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(1024);

            rsa1.FromXmlString(publicKeyXml);

            bool isVerified = rsa1.VerifyData(Encoding.UTF8.GetBytes(plainData), CryptoConfig.MapNameToOID("SHA256"), Convert.FromBase64String(base64Signature));

            return isVerified;
        }
        catch (Exception ex)
        {
            Logger.CreateLogInFileS(ex, "VerifyHash", "Exception");
            return false;
        }
    }


text:
Q: How to display string in a listbox using C++? I am trying to extract the content of a .txt file and then display it in a listbox, my developing environment is VC++ 2010.
listBox1,button1 are elements of my Windows form appliaction.
This is what i got so far:
         private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
          {
             ifstream ss_dfs_output("C:\\Users\\...\\Sampletext.txt");
             string TempStoreToDisp;
             vector<string> VecToDisp;
             vector<string>::iterator ToDisp_ptr;
             string OutToDisp;
             while (getline(ss_dfs_output,TempStoreToDisp,'\n'))
             {
                 VecToDisp.push_back(TempStoreToDisp);
             }
             for (ToDisp_ptr=VecToDisp.begin();ToDisp_ptr!=VecToDisp.end();ToDisp_ptr++)
             {
                 OutToDisp = *ToDisp_ptr;
                 String ^sss = Convert::ToString(OutToDisp.c_str());
                 this->listBox1->Items->Insert(0,sss);
             }
           }

The compiling was successfull but the output seems strange. Seems sss returns "true" but shoudn't it be a string?

A: How about
this->listBox1->Items->Add(gcnew String(OutToDisp.c_str())); // you can still Insert if you want

MSDN SByte* constructor reference


text:
Q: How to programatically open a folder in android? I am working on an Android application which opens folders,
My question is how can I open a folder programmatically in Android? .
I tried all the solutions available in stack-overflow and searched in Google but I couldn't find a solution. Can someone please provide me an answer?
Thanks in advance.

A: you can open folder with use of following code
File file = new File(path);
        Uri uri_path = Uri.fromFile(file);
        String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension
                (MimeTypeMap.getFileExtensionFromUrl(path));

        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        intent.setType(mimeType);
        intent.setDataAndType(uri_path, mimeType);
        startActivity(intent);


text: Q: Unique ergodicity a spectral invariant? Suppose $f:X\to X$ and $g:Y\to Y$ are two automorphism of measure spaces. Suppose there is an unitary operator $V:L^2(X)\to L^2(Y)$ satisfying $VU_fV^*=U_g$, here $U_f$ and $U_g$ are the Koopman operators corresponding to $f$ and $g$. Additionally we know $f$ is uniquely ergodic. Can we say $g$ is uniquely ergodic? I suspect no. Counterexample?


text:
Q: Optimizing MySQL FULLTEXT and proximity search query Consider the following table of adverts (creation using Laravel, but the code is pretty self explanatory):
Schema::create('adverts', function (Blueprint $table) {
   $table->increments('id');      //PRIMARY KEY
   $table->string('name', 150);   //VARCHAR
   $table->text('description');   //TEXT

   $table->integer('city_id')->nullable();
   $table->foreign('city_id')->references('id')->on('cities');

   $table->timestamps();
});

The adverts table has more columns, but these are the ones necessary right now imo. I want users to be able to find adverts with a text-search function so I added the following FULLTEXT index:
ALTER TABLE posts ADD FULLTEXT search(name, description)

As you can see each advert also has a city_id foreign key, that allows the user to search for adverts in a city, as well as in cities within a given radius. For this purpose I have a radius table, which contains records of pairs of cities and their distance from one another:
|  city_A  |   city_B   |distance|
----------------------------------
|    1     |     2      |  30    |
|    2     |     1      |  30    |

The radius table holds around 7 000 000 records and all of its columns are indexed. I have seeded the adverts table with around 100 000 fake records (descriptions are around 700 chars). When searching for adverts I execute the following Laravel query:
Advert::whereRaw('MATCH(name, description) AGAINST(? IN BOOLEAN MODE)', [$term])
       ->join('radius', function ($join) use ($radius, $id){
             $join->on('radius.secondary_id','=', 'posts.city_id');
        })->where('radius.primary_id', $id)
        ->whereBetween('radius.radius', [0,$radius]);

In SQL this translates to:
SLECT * FROM `adverts`
INNER JOIN `radius` on `radius`.`city_B` = `posts`.`city_id`
WHERE MATCH(name, description) AGAINST(? IN BOOLEAN MODE)
AND `radius`.`city_A` = ?
AND `radius`.`radius` between ? and ?
ORDER BY `created_at` desc
LIMIT 20

Ok so as I said the adverts table has a few more columns, but those don't seem to be causing major problems when performing a search query. However once I combine the FULLTEXT term search with the city proximity search the query takes a fairly long time to execute on my localhost - somewhere around 10-15 seconds. It seems like doing a MATCH on the entire adverts table works fine, radius search works fine but combined like this they result in a rather slow response.
Is there something I can do to improve the tables or the query statements or is this a case where MySQL just wouldn't keep up?
My specs for the record:
CPU: Intel Core i5 3450 @ 3.10GHz Quad
RAM: 8,00GB Dual-Channel DDR3 @ 665MHz
HDD: Seagate ST3320613AS ATA Device (SATA) 7200RPM 16MB Cache

EDIT: MySQL Explain of the inner join query:
+----+-------------+-------+------+---------------+-----+---------+-----+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+-----+---------+--------+---+--+
| 1  |    SIMPLE   |adverts|fulltxt|adverts_city_id_foreign,| search | 0 |  | 1 | Using where; Using filesort |
|    |             |       |       | search                 |        |   |
------------------------------------------------------------------------------------------
| 1  |   SIMPLE   | radius | ref  | city_A_index,| city_A_index| 5 | test_db.adverts.city_id | 1417 | Using where |
|    |            |        |      | city_B_index,|             |   |
|    |            |        |      | distances_ind|             |   |
+----+------------+--------+------+--------------+-------------+---+---+---+---+


text:
Q: Terminal long line wrapping I got a small issue with line wrapping on a custom linux and I'm not sure where this is set.
When on serial console or using SSH login i get the following:
Cursor at start of line
[user@myhost ~]$ dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd>

Cursor at end of line
<ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

So instead of breaking into multiple lines it continues into described by the angle brackets.
Can anybody point me into the direction where I can change this behaviour? Tried messing with inputrc for readline and something like "set horizontal-scroll-mode" but I'm not sure that this is the right place

A: If your shell is bash, try
bind 'set horizontal-scroll-mode off'

and if that fixes it, add a set horizontal-scroll-mode off line to your ~/.inputrc file.
Also, check if there's an entry in the terminfo database for the terminal from the TERM variable by running infocmp. If readline (as used by bash) is not able to find an entry for it, it will fall back to horizontal-scroll-mode (since it cannot assume that the terminal has automatic margins).
You can always export a terminfo definition from one machine to another with:
infocmp termname | ssh user@host tic -

That will create a per-user entry inside ~/.terminfo/. If you omit termname, infocmp value will use the content of TERM.

That's also the behavior of the mksh (the default shell on Android) and of OpenBSD's ksh (with the difference that the < is on the right side). For that case, I don't think that it's possible to configure it away.


text:
Q: What does "Failed to provision bridges" mean? Google search doesn't seem to have heard of this error, but I'm unable to escape it:
ERROR: (gcloud.preview.app.deploy) Server responded with code [400]:
  Bad Request Unexpected HTTP status 400.
  Failed Project Preparation (app_id='s~rrowland-test-project-2').
  Error "Failed to provision bridges." during VmProvisionBridges.

I have followed the instructions at https://cloud.google.com/appengine/docs/managed-vms/nodejs/hello-world exactly. I have tried new projects. I've tried clearing out the VM buckets.
This appears during the deploy process after running
gcloud preview app deploy

From the sample app's root directory:
nodejs-docs-samples/appengine/hello-world

A: Launching a permanent VM instance myself fixed this for me.
https://console.cloud.google.com/compute/instances
Edit: lol! Never mind. It built for 10 minutes and then ultimately ended in the same error.

A: I managed to get it working. I think there may be a bad state in the project. Here are the steps I went through to get it working.

*

*create a new project

*enable billing for that project

*LEAVE CLOUD CONSOLE (if you attempt to navigate around it starts enabling API's I.E Compute Engine)

*Go to command line and run gcloud init

*create a new config for your new project

*when it asks if you want to use repositories say no

*attempt to deploy the application gcloud preview app deploy

*this may result in a timeout and a message saying try again try again

*if all went well it will say it is enabling the remote build service

*the app might take some time to build the docker image but it should deploy at this point

Hopefully, this will help someone else get past this issue.


text:
Q: PyQt5 and persistent DB with QtSql Fairly new to PyQt5 and in setting up a sample application I ran into an issue with QtSql.  All of the examples I have found show a single class using the database connection but none show how to use the QtSql classes persistently over many different classes that require a DB connection.  Almost all of the MDI subwindows in my application require a connection to the database but when I setup the connection I get errors that the connection is "duplicate".  My question is:
If I have an MDI application with several dialogs that require a DB connection, How do I set up the database connection persistently so all my dialogs can access the database?

A: If you are going to connect to the same database it is not necessary that you create several connections, only one since qt manages those connections globally as indicated by the docs:

QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const
QString &connectionName = QLatin1String(defaultConnection))
Adds a database to the list of database connections using the driver type and
the connection name connectionName. If there already exists a database
connection called connectionName, that connection is removed.
The database connection is referred to by connectionName. The newly
added database connection is returned.
If type is not available or could not be loaded, isValid() returns
false.
If connectionName is not specified, the new connection becomes the
default connection for the application, and subsequent calls to
database() without the connection name argument will return the
default connection. If a connectionName is provided here, use
database(connectionName) to retrieve the connection.
Warning: If you add a connection with the same name as an existing
connection, the new connection replaces the old one. If you call this
function more than once without specifying connectionName, the default
connection will be the one replaced.

Example:
.
├── connection.py
├── main.py
└── views.p

connection.py
from PyQt5 import QtWidgets, QtSql

def createConnection():
    db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
    db.setDatabaseName(":memory:")
    if not db.open():
        QtWidgets.QMessageBox.critical(None, "Cannot open database",
                             "Unable to establish a database connection.\n"
                             "This example needs SQLite support. Please read "
                             "the Qt SQL driver documentation for information how "
                             "to build it.\n\n"
                             "Click Cancel to exit.", QtWidgets.QMessageBox.Cancel)
        return False

    query = QtSql.QSqlQuery()
    query.exec_("""CREATE TABLE IF NOT EXISTS person (id int primary key,
                                                     firstname VARCHAR(20),
                                                    lastname VARCHAR(20))""")
    query.exec_("insert into person values(101, 'Danny', 'Young')")
    query.exec_("insert into person values(102, 'Christine', 'Holand')")
    query.exec_("insert into person values(103, 'Lars', 'Gordon')")
    query.exec_("insert into person values(104, 'Roberto', 'Robitaille')")
    query.exec_("insert into person values(105, 'Maria', 'Papadopoulos')")

    query.exec_("""CREATE TABLE IF NOT EXISTS  items (id INT primary key,
                                       imagefile INT,
                                       itemtype varchar(20),
                                       description varchar(100))""");
    query.exec_("insert into items "
               "values(0, 0, 'Qt',"
               "'Qt is a full development framework with tools designed to "
               "streamline the creation of stunning applications and  "
               "amazing user interfaces for desktop, embedded and mobile "
               "platforms.')");
    query.exec_("insert into items "
               "values(1, 1, 'Qt Quick',"
               "'Qt Quick is a collection of techniques designed to help "
               "developers create intuitive, modern-looking, and fluid "
               "user interfaces using a CSS & JavaScript like language.')");
    query.exec_("insert into items "
               "values(2, 2, 'Qt Creator',"
               "'Qt Creator is a powerful cross-platform integrated "
               "development environment (IDE), including UI design tools "
               "and on-device debugging.')");
    query.exec_("insert into items "
               "values(3, 3, 'Qt Project',"
               "'The Qt Project governs the open source development of Qt, "
               "allowing anyone wanting to contribute to join the effort "
               "through a meritocratic structure of approvers and "
               "maintainers.')");
    return True

views.py
from PyQt5 import QtWidgets, QtSql

class PersonWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(PersonWidget, self).__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        view = QtWidgets.QTableView()
        lay.addWidget(view)
        model = QtSql.QSqlTableModel(self)
        model.setTable("person")
        model.select()
        view.setModel(model)

class ItemsWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ItemsWidget, self).__init__(parent)
        lay = QtWidgets.QVBoxLayout(self)
        view = QtWidgets.QTableView()
        lay.addWidget(view)
        model = QtSql.QSqlTableModel(self)
        model.setTable("items")
        model.select()
        view.setModel(model)

main.py
from PyQt5 import QtWidgets, QtSql

from connection import createConnection
from views import PersonWidget, ItemsWidget

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.mdiarea = QtWidgets.QMdiArea()
        self.setCentralWidget(self.mdiarea)

        sub1 = QtWidgets.QMdiSubWindow()
        sub1.setWidget(PersonWidget())
        self.mdiarea.addSubWindow(sub1)
        sub1.show()

        sub2 = QtWidgets.QMdiSubWindow()
        sub2.setWidget(ItemsWidget())
        self.mdiarea.addSubWindow(sub2)
        sub2.show()

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)

    if not createConnection():
        sys.exit(-1)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

In the previous example, there is the createConnection() method that establishes the connection and creates the tables if necessary. And the views that use the data of the database without indicating the connection and consequently use the default connection, that is, the one that was established in createConnection().


text:
Q: facebook app not working on mobiles I have a Facebook app (canvas app), let's say https://apps.facebook.com/test, that redirects and works as expected on the desktop (on all browsers that I have tested).
On mobile phones (both from the FB app and the browser) the path gets redirected to https://m.facebook.com/apps/test/?ref=web_canvas, which gives a "This page cannot be found" error. Why?

A: This has been reported as a bug to Facebook and Facebook has confirmed it as a bug.  They have not provided a date on when the fix will be ready.
You can follow the status of the bug here:
https://developers.facebook.com/bugs/1051463851558493/

A: Update: Facebook have (since the information struck-out below) completely removed support for this. The thread about this is here:
https://developers.facebook.com/bugs/1051463851558493/
The top-level information is:

We have now deprecated Mobile Canvas URL. This means that you will no
  longer be able to direct to a website/app directly within the Facebook
  mobile web based upon the external destination URL you have specified
  in the 'Mobile Site URL' field for the app on developers.facebook.com.
  Furthermore, we have removed the 'Mobile Site URL' field from the app
  setup going forward. This deprecation also applies to apps that were
  previously whitelisted.

So it's time to move away from this functionality, and either integrate the newer FB Instant Games functionality or just link to an external website as having your canvas app hosted inside the FB mobile app simply isn't possible as it was in years gone by.
Facebook has disabled mobile URLs working by default:

We recently identified a handful of apps misusing our mobile App Center to redirect people to unauthorized sites. As a precaution, we have temporarily turned off the ability for developers to direct to a destination URL for any app in the "Mobile Site URL" field on the dev site.

Now if you wish for this functionality to work, you need to be logged into Facebook and then go to the following URL:
https://www.facebook.com/help/contact/588209321338256
This URL will effectively put your request in a queue, for someone at Facebook to manually verify your app configuration isn't malicious, and then enable the redirection. I do not like posting this answer, as I know it will eventually become invalid, but as of today it is the only answer. As stated by Scott, you can follow progress on this issue here:
https://developers.facebook.com/bugs/1051463851558493/
Please ignore the fact it claims the issue has been 'Fixed' as Facebook count the above workaround as a fix. If you read through the comments on the bug you can note the waiting time to get the URL fixed (on a per app basis) is typically several weeks.

A: On May 28th, 2017, Facebook confirmed that the Mobile Canvas URL has now been deprecated. Any apps already using (and white listed) will stop working, and no new apps will be accepted.

Hi everyone,
First, please accept my sincere apologies for the delay in getting
  back to you with an update on the status of Mobile Canvas URL. I
  understand your frustrations, particularly if you submitted your
  details via the form and were waiting on a response.
We have now deprecated Mobile Canvas URL. This means that you will no
  longer be able to direct to a website/app directly within the Facebook
  mobile web based upon the external destination URL you have specified
  in the 'Mobile Site URL' field for the app on developers.facebook.com.
  Furthermore, we have removed the 'Mobile Site URL' field from the app
  setup going forward. This deprecation also applies to apps that were
  previously whitelisted.
The Mobile Canvas URL feature is a vestige of a long ago deprecated
  product called Mobile Canvas. Facebook maintains a high commitment to
  quality, so we don't want to leave unsupported products active —
  especially when they continue to cause bugs for our developers. Going
  forward, we're recommending you take advantage of the well-supported
  Facebook Games on Web product to drive traffic to your app.
We've also introduced Instant Games which lets people play mobile
  games within Messenger and Facebook News Feed. We invite you to sign
  up for our closed beta program. We believe letting people play games
  together on Facebook is a powerful experience for both players and
  developers.
If your app is still set up to rely on Mobile Canvas URL
  functionality, we recommend taking the following actions:

*

*If you're using Mobile Canvas to link to a page on mobile web, you need to update your app to handle the redirection in the desktop
  iframe. User interaction is required to redirect away from web canvas
  as our Platform Policy does not allow automated redirects from canvas.

*If your app was previously whitelisted, you will need to take action as this deprecation supersedes any workarounds you have in place.
Thank you for your understanding as we continually improve the
  products and services we offer to both developers and players. Again,
  please accept my apologies for the wait in getting back to you with
  this information
Best regards,
Tim

See this thread https://developers.facebook.com/bugs/1051463851558493/


text:
Q: Excel Interop Workbooks.Open inconsistencies I have a process that is opening multiple workbooks
var exApp = new Excel.Application();
Excel.Workbook ONE;
Excel.Workbook TWO;
Excel.Workbook THREE;
ONE = exApp.Workbooks.Open(ONELocation);
TWO = exApp.Workbooks.Open(TWOLocation);
THREE = exApp.Workbooks.Open(THREELocation);
Console.WriteLine("All Excel workbooks opened successfully\n");

Sometimes it runs with no issues.
Sometimes though I get the following exception on crash

System.Runtime.InteropServices.COMException: 'The remote procedure call failed. (Exception from HRESULT: 0x800706BE)'

The exception happens on different workbooks and sometimes not at all. When it happens after rerunning a few times the process goes through successfully and all data is processed correctly.
Why does it work sometimes and not others? Is there a better way to open these workbooks? How do I stop this from happening?

A: RPC_S_CALL_FAILED was indeed the root cause as pointed out by the question user xxbbcc linked to as a possible duplicate.
However, that just told me the cause and did not solve the problem.
I googled RPC_S_CALL_FAILED with the word excel and found this SuperUser question
I disabled the "FoxitReader PDF Creator COM Add-in" as described in the question and my program now runs consistently without error.

How to disable the plugin: Excel > File > Options > Add-ins > Manage, then choose "COM add-ins" > Go. And then untick the problematic plugin.


text:
Q: Filter table with multiple dropdowns with jquery I have been trying to use multiple dropdowns to filter my table with the hide() and show() functions in jQuery and not just filter if the table contains a string, but if it equals to a certain string.
Image:
Until now I was able to just use 2 dropdowns and make them able to filter the first two columns. I don't know how I can make it work properly with all 8. Maybe I am just thinking a bit to complicated.
I want all dropdowns to work properly and filter the table.

    Hersteller:
    <select class='fstdropdown-select' id='first'>
      <option value=''>Auswählen</option>
      <option value=". ++$a .">".$row['Hersteller']."</option> .
    </select>

    Artikel:
    <select class='fstdropdown-select' id='second'>
      <option value=''>Auswählen</option>";
      <option value=". ++$a .">".$row['Artikel']."</option> .
    </select>

//this is the first dropdown menu seen on the picture
$("#first").change(function() {
  // .rows is the class of the tr 's
  $('.rows:not(:contains(' + firstDropVal + '))').show();
  var end = this.value;
  var firstDropVal = $('#first .fstselected').text();

  if (firstDropVal == "Auswählen") {
    $('.rows:not(:contains(' + firstDropVal + '))').show();
    firstDropVal = $('#second .fstselected').text();
    if (firstDropVal == "Auswählen") {
      $('.rows:not(:contains(' + firstDropVal + '))').show();
    } else {
      $('.rows:not(:contains(' + firstDropVal + '))').hide();
    }
  } else {
    $('.rows:not(:contains(' + firstDropVal + '))').hide();
    firstDropVal = $('#second .fstselected').text();
    if (firstDropVal == "Auswählen") {
      firstDropVal = $('#first .fstselected').text();
      $('.rows:not(:contains(' + firstDropVal + '))').hide();
    } else {
      $('.rows:not(:contains(' + firstDropVal + '))').hide();
    }
  };
});

//this is the second dropdown menu seen on the picture
$("#second").change(function() {
  $('.rows:not(:contains(' + firstDropVal + '))').show();
  var end = this.value;
  var firstDropVal = $('#second .fstselected').text();
  if (firstDropVal == "Auswählen") {
    $('.rows:not(:contains(' + firstDropVal + '))').show();
    firstDropVal = $('#first .fstselected').text();
    if (firstDropVal == "Auswählen") {
      $('.rows:not(:contains(' + firstDropVal + '))').show();
    } else {
      $('.rows:not(:contains(' + firstDropVal + '))').hide();
    }
  } else {
    $('.rows:not(:contains(' + firstDropVal + '))').hide();
    firstDropVal = $('#first .fstselected').text();
    if (firstDropVal == "Auswählen") {
      firstDropVal = $('#second .fstselected').text();
      $('.rows:not(:contains(' + firstDropVal + '))').hide();
    } else {
      $('.rows:not(:contains(' + firstDropVal + '))').hide();
    }
  };
});

A: Make you filter with one class and add name element relevant to your column
here mitarbeitertable-filter as filter class

   <select class="form-control bottomborder mitarbeitertable-filter input-small" name="k_kollegetyp">
       <option value="">Bitte Auswählen</option>
       <option value="1">Festangestellter</option>
       <option value="2">Freie Mitarbeiter</option>
       <option value="3">Kunde</option>
       <option value="4">Lizenzbenutzer</option>
     </select>

      <select class="form-control bottomborder mitarbeitertable-filter input-small" name="id_unit">
       <option value="">Bitte Auswählen</option>
       <option value="1">Consulting GmbH</option>
       <option value="2">Communication GmbH</option>
       <option value="3">Promotion GmbH</option>
       <option value="5">Sales GmbH</option>
       <option value="6">AG</option>
  </select>

in JS , and if you are using ajax based the you will receive it as filter column in your post
$('.mitarbeitertable-filter').on('keyup change input', function (e) {
  var searchArray = {};
  $('.mitarbeitertable-filter:visible').each(function( index )
   {
       var name = $(this).attr('name');
        searchArray[name] = $(this).val();
   }
  $("#table").dataTable().fnMultiFilter(searchArray)
})

PS:fix it according to your needs


text:
Q: Python - Splitting numbers and letters into sub-strings with regular expression I am creating a metric measurement converter. The user is expected to enter in an expression such as 125km (a number followed by a unit abbreviation). For conversion, the numerical value must be split from the abbreviation, producing a result such as [125, 'km']. I have done this with a regular expression, re.split, however it produces unwanted item in the resulting list:
import re
s = '125km'
print(re.split('(\d+)', s))

Output:
['', '125', 'km']

I do not need nor want the beginning ''. How can I simply separate the numerical part of the string from the alphabetical part to produce a list using a regular expression?

A: What's wrong with re.findall ?
>>> s = '125km'
>>> re.findall(r'[A-Za-z]+|\d+', s)
['125', 'km']

[A-Za-z]+ matches one or more alphabets. | or \d+ one or more digits.
OR
Use list comprehension.
>>> [i for i in re.split(r'([A-Za-z]+)', s) if i]
['125', 'km']
>>> [i for i in re.split(r'(\d+)', s) if i]
['125', 'km']

A: Split a string into list of sub-string (number and others)
Using program:
s = "125km1234string"
sub = []
char = ""
num = ""
for letter in s:
    if letter.isdigit():
        if char:
            sub.append(char)
            char = ""
        num += letter
    else:
        if num:
            sub.append(num)
            num = ""
        char += letter
sub.append(char) if char else sub.append(num)
print(sub)

Output
['125', 'km', '1234', 'string']


text:
Q: React Router access params from another component I am currently looking into React.js & Redux and was playing around with react-router. My question is: Is there a way to access url params from another Component?
For example:
I have a Foo component which displays the :bar param (via props.match.params.bar), but I also want to display the value of :bar in the Header Component. With ReactRouterDOM.withRouter I can get access to props.match. The Problem is that this is not the same as in the Foo Component (it contains the information about the parent route '/'). So how do I get the value in the Header Component and am I even on the right track?
Thanks in advance

const Foo = (props) => {
    return (

 Foo {props.match.params.bar}

);
};

const App = (props) => {
    return (

            <HeaderWrapper />

 Hello App

<ReactRouterDOM.Link to='/foo/bar'>Foo Bar</ReactRouterDOM.Link>

            <ReactRouterDOM.Route path='/foo/:bar' component={Foo} />

);
};

// Header
const Header = (props) => {
    console.log(props);
    return (  You are here: {}  );
};
const HeaderWrapper = ReactRouterDOM.withRouter(Header);

// Router
ReactDOM.render((
        <ReactRouterDOM.MemoryRouter>
            <ReactRouterDOM.Route path='/' component={App} />
        </ReactRouterDOM.MemoryRouter >
 ), document.getElementById('root'));

A: As far as I know, react-router doesn't have any standard way to achieve what you need. But you can use regular expression with path-to-regexp library to do that manually. You will always get the correct result as react-router it self internally use this library to match routes.
const re = pathToRegexp('/foo/:bar')
const result = re.exec(props.location.pathname)
if(result){
    console.log(result[1]); //bar
}