text:
Q: unexpected crash of embedded-linux on Zynq-Device (Zybo) We have created, following the instruction on wiki-xilinx-linux web page, a system Zybo + embedded linux kernel (I want to remark that we didn't use PetaLinux but we have built all the file with the Xilinx tools).
When we turn on the system everything works fine and this is the output at the boot time:
 U-Boot 2016.07-03720-g95e11f6-dirty (Oct 17 2016 - 02:56:48 -0700)

Model: Zynq ZYBO Development Board
Board: Xilinx Zynq
I2C:   ready
DRAM:  ECC disabled 512 MiB
MMC:   sdhci@e0100000: 0
SF: Detected S25FL128S_64K with page size 256 Bytes, erase size 64 KiB, total 16 MiB
*** Warning - bad CRC, using default environment

In:    serial@e0001000
Out:   serial@e0001000
Err:   serial@e0001000
Model: Zynq ZYBO Development Board
Board: Xilinx Zynq
Net:   ZYNQ GEM: e000b000, phyaddr 0, interface rgmii-id
I2C EEPROM MAC address read failed
eth0: ethernet@e000b000
Hit any key to stop autoboot:  0
Device: sdhci@e0100000
Manufacturer ID: 3
OEM: 8368
Name: NCard
Tran Speed: 50000000
Rd Block Len: 512
SD version 3.0
High Capacity: Yes
Capacity: 3.7 GiB
Bus Width: 4-bit
Erase Group Size: 512 Bytes
reading uEnv.txt
** Unable to read file uEnv.txt **
Copying Linux from SD to RAM...
reading uImage
3843104 bytes read in 367 ms (10 MiB/s)
reading devicetree.dtb
10331 bytes read in 17 ms (592.8 KiB/s)
reading uramdisk.image.gz
5310018 bytes read in 504 ms (10 MiB/s)
## Booting kernel from Legacy Image at 02080000 ...
   Image Name:   Linux-4.6.0-xilinx-22285-g0e4e40
   Image Type:   ARM Linux Kernel Image (uncompressed)
   Data Size:    3843040 Bytes = 3.7 MiB
   Load Address: 00008000
   Entry Point:  00008000
   Verifying Checksum ... OK
## Loading init Ramdisk from Legacy Image at 04000000 ...
   Image Name:
   Image Type:   ARM Linux RAMDisk Image (gzip compressed)
   Data Size:    5309954 Bytes = 5.1 MiB
   Load Address: 00000000
   Entry Point:  00000000
   Verifying Checksum ... OK
## Flattened Device Tree blob at 02000000
   Booting using the fdt blob at 0x2000000
   Loading Kernel Image ... OK
   Loading Ramdisk to 1e601000, end 1eb11602 ... OK
   Loading Device Tree to 1e5fb000, end 1e60085a ... OK

Starting kernel ...

Uncompressing Linux... done, booting the kernel.
Booting Linux on physical CPU 0x0
Linux version 4.6.0-xilinx-22285-g0e4e407-dirty (leonardo@ubuntu) (gcc version 4.9.2 (Sourcery CodeBench Lite 2015.05-17) ) #1 SMP PREEMPT Mon Oct 17 03:54:44 PDT 2016
CPU: ARMv7 Processor [413fc090] revision 0 (ARMv7), cr=18c5387d
CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache
Machine model: xlnx,zynq-7000
bootconsole [earlycon0] enabled
cma: Reserved 16 MiB at 0x1f000000
Memory policy: Data cache writealloc
percpu: Embedded 12 pages/cpu @debcc000 s19776 r8192 d21184 u49152
Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 130048
Kernel command line: console=ttyPS0,115200 root=/dev/mmcblk0p2 rw earlyprintk rootfstype=ext4 rootwait devtmpfs.mount=1
PID hash table entries: 2048 (order: 1, 8192 bytes)
Dentry cache hash table entries: 65536 (order: 6, 262144 bytes)
Inode-cache hash table entries: 32768 (order: 5, 131072 bytes)
Memory: 489332K/524288K available (5304K kernel code, 230K rwdata, 1844K rodata, 1024K init, 222K bss, 18572K reserved, 16384K cma-reserved, 0K highmem)
Virtual kernel memory layout:
    vector  : 0xffff0000 - 0xffff1000   (   4 kB)
    fixmap  : 0xffc00000 - 0xfff00000   (3072 kB)
    vmalloc : 0xe0800000 - 0xff800000   ( 496 MB)
    lowmem  : 0xc0000000 - 0xe0000000   ( 512 MB)
    pkmap   : 0xbfe00000 - 0xc0000000   (   2 MB)
    modules : 0xbf000000 - 0xbfe00000   (  14 MB)
      .text : 0xc0008000 - 0xc07fb004   (8141 kB)
      .init : 0xc0800000 - 0xc0900000   (1024 kB)
      .data : 0xc0900000 - 0xc0939b60   ( 231 kB)
       .bss : 0xc0939b60 - 0xc09714e8   ( 223 kB)
Preemptible hierarchical RCU implementation.
    Build-time adjustment of leaf fanout to 32.
    RCU restricting CPUs from NR_CPUS=4 to nr_cpu_ids=2.
RCU: Adjusting geometry for rcu_fanout_leaf=32, nr_cpu_ids=2
NR_IRQS:16 nr_irqs:16 16
efuse mapped to e0800000
slcr mapped to e0802000
L2C: platform modifies aux control register: 0x72360000 -> 0x72760000
L2C: DT/platform modifies aux control register: 0x72360000 -> 0x72760000
L2C-310 erratum 769419 enabled
L2C-310 enabling early BRESP for Cortex-A9
L2C-310 full line of zeros enabled for Cortex-A9
L2C-310 ID prefetch enabled, offset 1 lines
L2C-310 dynamic clock gating enabled, standby mode enabled
L2C-310 cache controller enabled, 8 ways, 512 kB
L2C-310: CACHE_ID 0x410000c8, AUX_CTRL 0x76760001
zynq_clock_init: clkc starts at e0802100
Zynq clock init
sched_clock: 64 bits at 325MHz, resolution 3ns, wraps every 4398046511103ns
clocksource: arm_global_timer: mask: 0xffffffffffffffff max_cycles: 0x4af477f6aa, max_idle_ns: 440795207830 ns
Switching to timer-based delay loop, resolution 3ns
clocksource: ttc_clocksource: mask: 0xffff max_cycles: 0xffff, max_idle_ns: 551318127 ns
timer #0 at e080a000, irq=17
Console: colour dummy device 80x30
Calibrating delay loop (skipped), value calculated using timer frequency.. 650.00 BogoMIPS (lpj=3250000)
pid_max: default: 32768 minimum: 301
Mount-cache hash table entries: 1024 (order: 0, 4096 bytes)
Mountpoint-cache hash table entries: 1024 (order: 0, 4096 bytes)
CPU: Testing write buffer coherency: ok
CPU0: thread -1, cpu 0, socket 0, mpidr 80000000
Setting up static identity map for 0x100000 - 0x100058
CPU1: thread -1, cpu 1, socket 0, mpidr 80000001
Brought up 2 CPUs
SMP: Total of 2 processors activated (1300.00 BogoMIPS).
CPU: All CPU(s) started in SVC mode.
devtmpfs: initialized
VFP support v0.3: implementor 41 architecture 3 part 30 variant 9 rev 4
clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 19112604462750000 ns
pinctrl core: initialized pinctrl subsystem
NET: Registered protocol family 16
DMA: preallocated 256 KiB pool for atomic coherent allocations
cpuidle: using governor menu
hw-breakpoint: found 5 (+1 reserved) breakpoint and 1 watchpoint registers.
hw-breakpoint: maximum watchpoint size is 4 bytes.
zynq-ocm f800c000.ocmc: ZYNQ OCM pool: 256 KiB @ 0xe0880000
zynq-pinctrl 700.pinctrl: zynq pinctrl initialized
vgaarb: loaded
SCSI subsystem initialized
usbcore: registered new interface driver usbfs
usbcore: registered new interface driver hub
usbcore: registered new device driver usb
media: Linux media interface: v0.10
Linux video capture interface: v2.00
pps_core: LinuxPPS API ver. 1 registered
pps_core: Software ver. 5.3.6 - Copyright 2005-2007 Rodolfo Giometti <giometti@linux.it>
PTP clock support registered
EDAC MC: Ver: 3.0.0
Advanced Linux Sound Architecture Driver Initialized.
clocksource: Switched to clocksource arm_global_timer
NET: Registered protocol family 2
TCP established hash table entries: 4096 (order: 2, 16384 bytes)
TCP bind hash table entries: 4096 (order: 3, 32768 bytes)
TCP: Hash tables configured (established 4096 bind 4096)
UDP hash table entries: 256 (order: 1, 8192 bytes)
UDP-Lite hash table entries: 256 (order: 1, 8192 bytes)
NET: Registered protocol family 1
RPC: Registered named UNIX socket transport module.
RPC: Registered udp transport module.
RPC: Registered tcp transport module.
RPC: Registered tcp NFSv4.1 backchannel transport module.
Trying to unpack rootfs image as initramfs...
rootfs image is not initramfs (no cpio magic); looks like an initrd
Freeing initrd memory: 5188K (de601000 - deb12000)
hw perfevents: enabled with armv7_cortex_a9 PMU driver, 7 counters available
futex hash table entries: 512 (order: 3, 32768 bytes)
workingset: timestamp_bits=28 max_order=17 bucket_order=0
jffs2: version 2.2. (NAND) (SUMMARY)  © 2001-2006 Red Hat, Inc.
io scheduler noop registered
io scheduler deadline registered
io scheduler cfq registered (default)
dma-pl330 f8003000.dmac: Loaded driver for PL330 DMAC-241330
dma-pl330 f8003000.dmac:    DBUFF-128x8bytes Num_Chans-8 Num_Peri-4 Num_Events-16
e0001000.serial: ttyPS0 at MMIO 0xe0001000 (irq = 143, base_baud = 6250000) is a xuartps
�console [ttyPS0] enabled
console [ttyPS0] enabled
bootconsole [earlycon0] disabled
bootconsole [earlycon0] disabled
xdevcfg f8007000.devcfg: ioremap 0xf8007000 to e086c000
[drm] Initialized drm 1.1.0 20060810
brd: module loaded
loop: module loaded
CAN device driver interface
libphy: MACB_mii_bus: probed
macb e000b000.ethernet eth0: Cadence GEM rev 0x00020118 at 0xe000b000 irq 145 (00:0a:35:00:01:22)
RTL8211E Gigabit Ethernet e000b000.etherne:00: attached PHY driver [RTL8211E Gigabit Ethernet] (mii_bus:phy_addr=e000b000.etherne:00, irq=-1)
e1000e: Intel(R) PRO/1000 Network Driver - 3.2.6-k
e1000e: Copyright(c) 1999 - 2015 Intel Corporation.
ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver
ehci-pci: EHCI PCI platform driver
usbcore: registered new interface driver usb-storage
mousedev: PS/2 mouse device common for all mice
i2c /dev entries driver
EDAC MC: ECC not enabled
Xilinx Zynq CpuIdle Driver started
sdhci: Secure Digital Host Controller Interface driver
sdhci: Copyright(c) Pierre Ossman
sdhci-pltfm: SDHCI platform and OF driver helper
mmc0: SDHCI controller on e0100000.sdhci [e0100000.sdhci] using DMA
ledtrig-cpu: registered to indicate activity on CPUs
usbcore: registered new interface driver usbhid
usbhid: USB HID core driver
NET: Registered protocol family 10
sit: IPv6 over IPv4 tunneling driver
NET: Registered protocol family 17
can: controller area network core (rev 20120528 abi 9)
NET: Registered protocol family 29
can: raw protocol (rev 20120528)
can: broadcast manager protocol (rev 20120528 t)
can: netlink gateway (rev 20130117) max_hops=1
Registering SWP/SWPB emulation handler
hctosys: unable to open rtc device (rtc0)
ALSA device list:
mmc0: new high speed SDHC card at address b368
  No soundcards found.
mmcblk0: mmc0:b368 NCard 3.72 GiB
 mmcblk0: p1 p2
RAMDISK: gzip image found at block 0
EXT4-fs warning (device ram0): ext4_update_dynamic_rev:746: updating to rev 1 because of new feature flag, running e2fsck is recommended
EXT4-fs (ram0): mounted filesystem without journal. Opts: (null)
VFS: Mounted root (ext4 filesystem) on device 1:0.
Starting rcS...
++ Mounting filesystem
mount: mounting /dev/mmcblk0p1 on /mnt failed: No such file or directory
mount: mounting /dev/mmcblk0 on /mnt failed: No such file or directory
++ Setting up mdev
++ Starting telnet daemon
++ Starting http daemon
++ Starting ftp daemon
++ Starting ssh daemon
random: sshd urandom read with 1 bits of entropy available
rcS Complete
zynq>
zynq>
zynq>

The problem is that, after some instructions, the system crash with this output:
zynq> EXT4-fs (mmcblk0p2): mounted filesystem with ordered data mode. Opts: (null)
VFS: Mounted root (ext4 filesystem) on device 179:2.
Trying to move old root to /initrd ... /initrd does not exist. Ignored.
Unmounting old root
Trying to free ramdisk memory ... failed
devtmpfs: error mounting -2
Unable to handle kernel NULL pointer dereference at virtual address 00000020
pgd = c0004000
[00000020] *pgd=00000000
Internal error: Oops - BUG: 17 [#1] PREEMPT SMP ARM
Modules linked in:
CPU: 0 PID: 10 Comm: migration/0 Not tainted 4.6.0-xilinx-22285-g0e4e407-dirty #1
Hardware name: Xilinx Zynq Platform
task: de060040 ti: de06a000 task.ti: de06a000
PC is at set_section_perms+0x8c/0x110
LR is at set_section_perms+0x18/0x110
pc : [<c0113404>]    lr : [<c0113390>]    psr: 80000093
sp : de06bec0  ip : dc4f3018  fp : 00000600
r10: 00000000  r9 : 00000000  r8 : 00000001
r7 : 00000003  r6 : c0902468  r5 : 00000000  r4 : c0908508
r3 : 00000000  r2 : c0000000  r1 : 00000003  r0 : 00000009
Flags: Nzcv  IRQs off  FIQs on  Mode SVC_32  ISA ARM  Segment none
Control: 18c5387d  Table: 1c4f804a  DAC: 00000051
Process migration/0 (pid: 10, stack limit = 0xde06a210)
Stack: (0xde06bec0 to 0xde06c000)
bec0: c0908508 00000003 00000001 de0db780 de0db780 de0db998 00000003 c0908508
bee0: c09065c0 00000000 00000000 c01134f4 de04df70 00000001 a0000013 de04df84
bf00: 00000003 00000000 00000000 c011355c c011354c c017c420 de04df30 debccf64
bf20: de06a000 debccf68 00000000 c017c4f8 c017c478 de06a000 de02db40 c090cd94
bf40: 00000001 c0135454 de060040 de02d9c0 00000000 de02db40 c0135218 00000000
bf60: 00000000 c0132a40 4dff1176 00000001 00000000 de02db40 00000000 00030003
bf80: de06bf80 de06bf80 00000000 00000000 de06bf90 de06bf90 de06bfac de02d9c0
bfa0: c0132968 00000000 00000000 c0106ef8 00000000 00000000 00000000 00000000
bfc0: 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
bfe0: 00000000 00000000 00000000 00000000 00000013 00000000 dfefe0f2 77e519c8
[<c0113404>] (set_section_perms) from [<c01134f4>] (update_sections_early+0x6c/0xc4)
[<c01134f4>] (update_sections_early) from [<c011355c>] (__fix_kernmem_perms+0x10/0x1c)
[<c011355c>] (__fix_kernmem_perms) from [<c017c420>] (multi_cpu_stop+0xb0/0x108)
[<c017c420>] (multi_cpu_stop) from [<c017c4f8>] (cpu_stopper_thread+0x80/0xb0)
[<c017c4f8>] (cpu_stopper_thread) from [<c0135454>] (smpboot_thread_fn+0x23c/0x254)
[<c0135454>] (smpboot_thread_fn) from [<c0132a40>] (kthread+0xd8/0xec)
[<c0132a40>] (kthread) from [<c0106ef8>] (ret_from_fork+0x14/0x3c)
Code: e1520003 2a00001b e5943014 e1a0baa2 (e599a020)
---[ end trace 07a0838423ee7708 ]---
note: migration/0[10] exited with preempt_count 2

It is clear that there is an error with the "mounted filesystem":
zynq> EXT4-fs (mmcblk0p2): mounted filesystem with ordered data mode. Opts: (null)
VFS: Mounted root (ext4 filesystem) on device 179:2.
Trying to move old root to /initrd ... /initrd does not exist. Ignored.
Unmounting old root
Trying to free ramdisk memory ... failed
devtmpfs: error mounting -2

Why does this happen? Why before I can do everything with the system and, suddenly, I have a crash? Yes, the system crashes when I am doing nothing on it and not when I am working with it.
Are there some advice to solve this? to not to have anymore these crashes?

A: From the Linux Kernel Command line I can see "root=/dev/mmcblk0p2" and also the target is started with initial ramdisk image "uramdisk.image.gz". So the init process or scripts inside ramdisk image should be responsible to mount the real file system from SD i.e. from /dev/mmcblk0p2 and remove the used memory of ramdisk. To narrow down the problem, you need to analyze the steps taken in ramdisk image to mount the real filesystem and make sure you have the proper RFS flashed inside SD in /dev/mmcblk0p2. I can also seen some missing directories to mount the /dev/mmcblk0p1 and /dev/mmcblk0.
++ Mounting filesystem
mount: mounting /dev/mmcblk0p1 on /mnt failed: No such file or directory
mount: mounting /dev/mmcblk0 on /mnt failed: No such file or directory

In simple words, check the init scripts inside the ramdisk image and make sure the RFS is mounted properly.


text:
Q: Trying to open a file from command line So i wanted to write some code that work like type in command line
meaning when I write the text file name it displays the content of it.
I wrote this:
int main(int argc, char* argv[])
{
    FILE *t;
    t = fopen(argv[1], "r");        // tring to open file from command line
    if (t == NULL){
        cout << "the file doesnt exists\n";
        return 0;
    }
    else{
        fseek(t, 0, SEEK_END);
        int size = ftell(t);
        fseek(t, 0, SEEK_SET);

        char* x = new char[size];

        fread(x, size, 1, t);

        for (int i = 0; i<size; i++)
        {
            cout << x[i];

        }

        delete[] x;
    }

      return 0;
  }

I got Debug Assertion Failed Error
Exppression:file!=NULL <br>

A: Before using arguments from argv, make sure that there are enough for your needs:
if (argc > 1) {
    // We have enough args in argv, go for it
    t = fopen(argv[1], "r");
} else {
    /* do something else that doesn't need argv[1] i.e. ask the user */
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: When to use different forms of the similar looking uncertainity equations? I usually find two different forms of Heisenberg's uncertainty principle equations as in follows:

*

*$$ \Delta x \cdot \Delta p \ge h$$

*$$ \Delta x \cdot \Delta p \ge (\frac{h}{2\pi})$$
Some text books have used the first one and the others have used the second one. How is dividing Planck's constant by $2\pi$ going to make the equation different? Under what conditions should one use the first equation and under what conditions one should use the second one?

A: It's all about orders of magnitude. Heisenberg's uncertainity principal is really given by: $$\Delta x \Delta p \geq \frac{h}{4\pi}=\frac{\hbar}{2}$$ Where $\hbar=\frac{h}{2\pi}$. But sometimes the right hand side is replaced by $h$ or $\hbar$, this is simply an approximation, just to make our lives easier. So formally you should always use $\Delta x \Delta p \geq \frac{h}{4\pi}$ but if it is easier and you don't think $\Delta x \Delta p$ is going to be near $\frac{h}{4\pi}$ then you can change the RHS to something of roughly the same order of magnitude such as $h$ or $\hbar$.


text:
Q: F# build a list/array of values + consecutive duplicates I need to pack data like this:
let data = [1; 2; 2; 3; 2; 2; 2; 4]
let packed = [(1, 1); (2, 2); (3, 1); (2, 3); (4, 1)]

Where each item say how much times it exist before the next. However, it must work with non-adjacent duplications.
I can work this with classical imperative code, but wonder how do this functionally.
Also, Seq.countBy not work because it take in account all the values

A: If you already have an imperative version, you can follow a set of small steps to refector to a recursive implementation.
Recursion
While I don't know what your imperative version looks like, here's a recursive version:
let pack xs =
    let rec imp acc = function
    | [] -> acc
    | h::t ->
        match acc with
        | [] -> imp [(h, 1)] t
        | (i, count) :: ta ->
            if h = i
            then imp ((i, count + 1) :: ta) t
            else imp ((h, 1) :: (i, count) :: ta) t
    xs |> imp [] |> List.rev

This function has the type 'a list -> ('a * int) list when 'a : equality. It uses a private 'implementation function' called imp to do the work. This function is recursive, and threads an accumulator (called acc) throughout. This accumulator is the result list, having the type ('a * int) list.
If the accumulator list is empty, the head of the original list (h), as well as the count 1, is created as a tuple as the only element of the updated accumulator, and the imp function is recursively called with that updated accumulator.
If the accumulator already contains at least one element, the element is extracted via pattern matching, and the element in that tuple (i) is compared to h. If h = i, the accumulator is updated; otherwise, a new tuple is consed on acc. In both cases, though, imp is recursively called with the new accumulator.
You can call it with a list equivalent to your original tuple like this:
> pack [1; 2; 2; 3; 2; 2; 2; 4];;
val it : (int * int) list = [(1, 1); (2, 2); (3, 1); (2, 3); (4, 1)]

Fold
Once you have a recursive version, you often have the recipe for a version using a fold. In this case, since the above pack function has to reverse the accumulator in the end (using List.rev), a right fold is most appropriate. In F#, this is done with the built-in List.foldBack function:
let pack' xs =
    let imp x = function
        | (i, count) :: ta when i = x -> (i, count + 1) :: ta
        | ta -> (x, 1) :: ta
    List.foldBack imp xs []

In this case, the function passed to List.foldBack is a bit too complex to pass as an anonymous function, so I chose to define it as a private inner function. It's equivalent to the recursive imp function used by the above pack function, but you'll notive that it doesn't have to call itself recursively. Instead, it just has to return the new value for the accumulator.
The result is the same:
> pack' [1; 2; 2; 3; 2; 2; 2; 4];;
val it : (int * int) list = [(1, 1); (2, 2); (3, 1); (2, 3); (4, 1)]

A: My solution assumes the data collection is a list. If having it as a tuple (as per your example) was intentional then for my solution to work the tuple has to be converted to a list (an example how to do it can be found here).
let groupFunc list =
    let rec groupFuncRec acc lst init count =
        match lst with
        | [] -> List.rev acc
        | head::[] when head = init
            -> groupFuncRec ((init, count)::acc) [] 0 0
        | head::[] when head <> init
            -> groupFuncRec ((head, 1)::acc) [] 0 0
        | head::tail when head = init
            -> groupFuncRec acc tail head (count+1)
        | head::tail when head <> init
            -> groupFuncRec ((init, count)::acc) tail head 1
    let t = List.tail list
    let h = List.head list
    groupFuncRec [] t h 1

When I run the function on your sample data I get back the expected result:
 list = [(1, 1); (2, 2); (3, 1); (4, 1)]

A: You can get Seq.countBy to work by including some positional information in its argument. Of course, you need then to map back to your original data.
[1; 2; 2; 3; 2; 2; 2; 4]
|> Seq.scan (fun (s, i) x ->
    match s with
    | Some p when p = x -> Some x, i
    | _ -> Some x, i + 1 ) (None, 0)
|> Seq.countBy id
|> Seq.choose (function
| (Some t, _), n -> Some(t, n)
| _ -> None )
|> Seq.toList
// val it : (int * int) list = [(1, 1); (2, 2); (3, 1); (2, 3); (4, 1)]


text:
Q: Cuál sería la manera mas óptima de crear las tablas en la base de datos? Estoy realizando un proyecto en el que consiste en ver el proceso de empaquetado de los productos, mi pregunta es como son varios productos de diferentes categorías o tipos, están los de tipo syrup (toda medicina para la tos), cremas, píldoras, cápsulas y pastillas, que sería lo más óptimo?, registrar todos los productos en una misma tabla con su nombre, cantidad y tipo y a la hora de hacer la consulta hacer select * from productos where tipo = al tipo que el usuario necesite o registrar cada producto en su respectiva tabla dependiendo de su tipo y hacer el select en la tabla de los productos del tipo que seleccione el usuario?, para mi sería la segunda opción ya que con la primera si tienes 1mil productos registrados y le dices que te los devuelva dependiendo de su tipo este tiene que recorrer sin embargo con el segundo ya te devuelve todos, espero haberme explicado bien :)

A: Para decidir la disgregación de una tabla entre varias según el valor de un atributo hay que tener en cuenta cuantos valores nulos nos ahorra la nueva estructura.
Si los distintos tipos de productos no son más que eso, el valor que identifica el tipo, pero no tiene más consecuencias, es conveniente poner todos los productos en la misma tabla. Si para ciertos tipos hay que registrar valores adicionales, entonces conviene la disgregación para evitar los nulos que supondrían esos atributos específicos para los productos de otros tipos.
Muchos tiene que haber para que se note el incremento de tiempo en un select. Si efectivamente estamos hablando de decenas de miles de productos, y la consulta por tipo es frecuente, entonces vale la pena añadir un índice en esa columna, de forma que NO DEBERÁ RECORRER TODA LA TABLA para hacer el select, sino que lo hará en un tiempo proporcional al número de cifras de la cantidad de productos que haya, es decir, en log(n), ya que para eso sirve la indexación.
Espero que sirva.

A: En mi caso, escogería una sola tabla para los productos, ya que si un tipo de producto sale del modelo de negocio la tabla sería obsoleta. Si el tipo de producto esta representado mediante un numero realmente el tiempo de la consulta sera muy bajo, no llegará a notarse hasta que sea una cantidad realmente enorme de registros y aún entonces, me parece mas que justificado dada la simplicidad que se aportaría al diseño, reduciendo los costos de mantenimiento de la base de datos y aumentando su mantenibilidad y escalabilidad. Ahora que si un producto se diferencia radicalmente de los otros tipos y es fundamental para el negocio si valdría la pena hacer otra tabla independiente.


text:
Q: Check if a .txt file exists. FileWriter.exists method not working SOLVED!!! Thanks for the hand guys got it working. Appreciate it!
I'm writing a program that has user name and password input. I am trying to check if a file exists for a user if the user puts in a user name that already exists when they create a user name and password.
The .exists method isn't working and I cant figure it out. Error cannot find symbol comes back. I've changed things, moved things around and got it down to one error. Tried using loops as well as if statements but using if gets me to only one error .Any help would be great.
import java.util.Scanner;
import java.io.*;

class UserData
{
  public static void main ( String[] args ) throws IOException
  {
  Scanner kb = new Scanner(System.in);

  System.out.println("Do you have an account? Yes or No: ");
  String answer = kb.next().trim();

  if ((answer.startsWith("N")) || (answer.startsWith("n")))
  {

System.out.println("Create user name: ");
String user = kb.next().trim();

String fileName = user + ".txt";
FileWriter userData = new FileWriter(fileName);

 if (userData.exists())
 {
   System.out.println("User already exists");
   System.out.println("Create user name: ");
   user = kb.next().trim();

   fileName = user + ".txt";
   userData = new FileWriter(fileName);
 }

System.out.println("Create Password: ");
String ps = kb.next().trim();

userData.write(user + " ");
userData.write(ps);
userData.close();

  }

  else if ((answer.startsWith("Y")) || (answer.startsWith("y")))
  {
System.out.println("Enter user name: ");
String user = kb.next().trim();

System.out.println("Enter Password: ");
String ps = kb.next().trim();

String fileName = user + ".txt";
Scanner inFile = new Scanner(new File(fileName));

String userName = inFile.next();
String password = inFile.next();

//     If ((userName != user) || (password != ps))
//     {
//       System.out.println("User Not Found");
//       System.out.println("Enter user name: ");
//       String user = kb.next().trim();
//
//       System.out.println("Enter Password: ");
//       String ps = kb.next().trim();
//
//       String fileName = user + ".txt";
//       Scanner inFile = new Scanner(new File(fileName));
//
//       String userName = inFile.next();
//       String password = inFile.next();
//     }
//     else
//     {
   System.out.println("User Found");
//     }
}

}}

A: You have compilation error here:
FileWriter userData = new FileWriter(fileName);
if (userData.exists())

Change it to:
File userDataFile = new File(fileName);
if (userDataFile.exists())

and of course:
FileWriter userData = new FileWriter(userDataFile);
userData.write(user + " ");
userData.write(ps);
userData.close();

If file doesn't exist anyway, you might be looking in a wrong directory. Try to add this:
System.out.println(new File(fileName).getAbsolutePath());

And check yourself if the file available on the printed path.


text:
Q: List Certain Columns in Pandas I have this List

And I want t list The name and short name of every airfield & display the results
I have tried
df1 = df['Name':'ShortName']
df1 = df.ix[:, 'Name':'ShortName']

newdf = df[df.columns[9:12]]

I have also tried other commands, and none seem to work. Any ideas would help thanks.


text:
Q: Django Rest Framework Filter not Working, The filter button is not showing on browsable API Good day I am new with django and django rest framework. I am trying to do some filtering. I followed the steps on the docs https://www.django-rest-framework.org/api-guide/filtering/ but nothing is working, it doesnt even show the filter button on browsable api. hope someone can help. thank you
settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_filters',
    'rfproducts',
    'frontend'
]

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 15,
}

views.py
class ProductsView(generics.ListAPIView):
    queryset = Products.objects.all()
    serializer_class = ProductsSerializers
    filterset_fields = ['category']

models.py
class Products(models.Model):
    product_partnumber = models.CharField(max_length=255)
    image_link = models.URLField()
    pdf_link = models.URLField()
    manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    subcategory = models.ForeignKey(Subcategory, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

serializers.py
class ProductsSerializers(serializers.ModelSerializer):

    specifications = ProductSpecificationSerializers(many=True)
    manufacturer_details = ManufacturerSerializers(source='manufacturer', read_only=True)
    category_details = CategorySerializers(source='category', read_only=True)

    class Meta:
        model = Products
        fields = ['id', 'product_partnumber', 'image_link', 'pdf_link', 'manufacturer', 'manufacturer_details', 'category', 'category_details', 'subcategory', 'specifications']

    def create(self, request):
        specs_data = request.pop('specifications')
        product = Products.objects.create(**request)

        for spec_data in specs_data:
            ProductSpecification.objects.create(product=product, **spec_data)

        return product

when I try to access some parameters in the url like
api/products?category=2

url.py
from django.urls import path, include
from .api import ProductsView, ManufacturerView, SpecificationView, CategoryView, SubcategoryView
from rest_framework import routers

router = routers.DefaultRouter()
router.register('api/products', ProductsView, 'products' )
router.register('api/manufacturers', ManufacturerView, 'manufacturers')
router.register('api/specifications', SpecificationView, 'specification')
router.register('api/category', CategoryView, 'category')
router.register('api/subcategory', SubcategoryView, 'subcategory')

urlpatterns = [
    path('', include(router.urls))
]

it retruns a blank page with status 200 response. Category field cointains a foreign key.
I am using react for my frontend, does it affect the issue?
In the image the filter button is not showing on the browsable API and also the category value in the url parameters is also existing
sample broswsable api

A: The filter button is a part of the django-crispy-forms module, and is NOT built-in to the django-filter module.
Installation for the django-crispy-forms module:

*

*Run pip install django-crispy-forms

*Add 'crispy_forms', to your INSTALLED_APPS in the settings.py file

If installed correctly with proper use of the django-filter module, the "Filters" button should now show up on your browsable API page.

A: I came into the same question today and it took me a while to make it display. We don't need to install the crispy-forms. The filter button will display when we define the filterset_fields here. Tutorial defines it as filterset_fields = (...) not [...]. But even if I changed my code to ['sku', 'name'] it still works. Reference: https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html

class ProductView(ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    pagination_class = StandardResultsSetPagination

    # filterset_class = [ProductFilter]
    filterset_fields = ('sku', 'name')

enter image description here
enter image description here


text:
Q: File System Usage Indicator I am unable to find a suitable utility to just indicate the file system usage (% space free for partitions) on the panel.
And I am not looking forward to install any bad kinds of desktop management tool, but a simple indicator.
I appreciate all your suggestions.

A: Install Sysmonitor Indicator:
sudo add-apt-repository ppa:fossfreedom/indicator-sysmonitor
sudo apt-get update
sudo apt-get install indicator-sysmonitor

and it has "Available Space in File System" option.

A: EDIT:
1. NEW ANSWER
While the answer at the bottom of this one can be used (see [2.]), it lead to a ppa -version with additional options, to be set in a preferences window.

Options include:

*

*Setting all aliases in one window

*Setting theme colors for the panel icon:

*Setting threshold for warnings

*Show info on newly mounted / connected volumes in a notification:

*Run on Startup
Furthermore, the indicator now includes a smaller (width) icon set for other distro's (like xfce), which will be automatically applied, depending on the window manager.

To install:
sudo add-apt-repository ppa:vlijm/spaceview
sudo apt-get update
sudo apt-get install spaceview

2. OLD ANSWER
The script below is an indicator that lists your devices and shows their usage. The information is updated (if necessary) once per ten seconds.

Furthermore

*

*While the indicator is running, you can choose a device to be represented in the icon. The device will be remembered on the next time you run the indicator:

*For one or more (or all) devices, you can set an alternative name ("custom name"), to be set in the head of the script
As an example, this:
alias = [
    ["sdc1", "stick"],
    ["sdb1", "External"],
    ["sda2", "root"],
    ["sda4", "ntfs1"],
    ["sda5", "ntfs2"],
    ["//192.168.0.104/media", "netwerk media"],
    ["//192.168.0.104/werkmap_documenten", "netwerk docs"],
    ]

Will show:

*You can set a threshhold; if the free space of either one of your devices is below that, you'll get a warning:

*Plugged/unplugged devices will be added/removed from the menulist within 10 seconds.
The script
#!/usr/bin/env python3
import subprocess
import os
import time
import signal
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3, GObject
from threading import Thread

#--- set alias names below in the format [[device1, alias1], [device2, alias2]]
#--- just set alias = [] to have no custom naming
alias = []
#--- set the threshold to show a warning below
#--- set to 0 to have no warning
threshold = 17
#---
currpath = os.path.dirname(os.path.realpath(__file__))
prefsfile = os.path.join(currpath, "showpreferred")

class ShowDevs():
    def __init__(self):
        self.default_dev = self.get_showfromfile()
        self.app = 'show_dev'
        iconpath = currpath+"/0.png"
        self.indicator = AppIndicator3.Indicator.new(
            self.app, iconpath,
            AppIndicator3.IndicatorCategory.OTHER)
        self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
        self.indicator.set_menu(self.create_menu())
        self.indicator.set_label("Starting up...", self.app)
        self.update = Thread(target=self.check_changes)
        self.update.setDaemon(True)
        self.update.start()

    def check_changes(self):
        state1 = None
        while True:
            self.state2 = self.read_devices()
            if self.state2 != state1:
                self.update_interface(self.state2)
            state1 = self.state2
            time.sleep(10)

    def update_interface(self, state):
        warning = False; self.newmenu = []
        for dev in state:
            mention = self.create_mention(dev)
            name = mention[0]; deci = mention[2]; n = mention[1]
            if n <= threshold:
                warning = True
            try:
                if self.default_dev in name:
                    newlabel = mention[3]
                    newicon = currpath+"/"+str(10-deci)+".png"
            except TypeError:
                pass
            self.newmenu.append(name+" "+str(n)+"% free")
        if warning:
            newlabel = "Check your disks!"
            newicon = currpath+"/10.png"
        try:
            self.update_indicator(newlabel, newicon)
        except UnboundLocalError:
            labeldata = self.create_mention(state[0])
            newlabel = labeldata[3]
            newicon = currpath+"/"+str(10-labeldata[2])+".png"
            self.update_indicator(newlabel, newicon)
        GObject.idle_add(self.set_new,
            priority=GObject.PRIORITY_DEFAULT)

    def update_indicator(self, newlabel, newicon):
        GObject.idle_add(self.indicator.set_label,
            newlabel, self.app,
            priority=GObject.PRIORITY_DEFAULT)
        GObject.idle_add(self.indicator.set_icon,
            newicon,
            priority=GObject.PRIORITY_DEFAULT)

    def set_new(self):
        for i in self.initmenu.get_children():
            self.initmenu.remove(i)
        for item in self.newmenu:
            add = Gtk.MenuItem(item)
            add.connect('activate', self.change_show)
            self.initmenu.append(add)
        menu_sep = Gtk.SeparatorMenuItem()
        self.initmenu.append(menu_sep)
        self.item_quit = Gtk.MenuItem('Quit')
        self.item_quit.connect('activate', self.stop)
        self.initmenu.append(self.item_quit)
        self.initmenu.show_all()

    def change_show(self, *args):
        index = self.initmenu.get_children().index(self.initmenu.get_active())
        self.default_dev = self.newmenu[index].split()[0]
        open(prefsfile, "wt").write(self.default_dev)
        self.update_interface(self.read_devices())

    def create_mention(self, dev):
        name = dev[1] if dev[1] else dev[0]
        n = dev[2]; deci = round(dev[2]/10)
        newlabel = name+" "+str(n)+"% free"
        return (name, n, deci, newlabel)

    def create_menu(self):
        # create initial basic menu
        self.initmenu = Gtk.Menu()
        self.item_quit = Gtk.MenuItem('Quit')
        self.item_quit.connect('activate', self.stop)
        self.initmenu.append(self.item_quit)
        self.initmenu.show_all()
        return self.initmenu

    def read_devices(self):
        # read the devices, look up their alias and the free sapace
        devdata = []
        data = subprocess.check_output(["df", "-h"]).decode("utf-8").splitlines()
        relevant = [l for l in data if all([
                    any([l.startswith("/dev/"), l.startswith("//")]),
                    not "/loop" in l])
                    ]
        for dev in relevant:
            data = dev.split(); name = data[0]; pseudo = None
            free = 100-int([s.strip("%") for s in data if "%" in s][0])
            for al in alias:
                if al[0] in name:
                    pseudo = al[1]
                    break
            devdata.append((name, pseudo, free))
        return devdata

    def get_showfromfile(self):
        # read the preferred default device from file
        try:
            defdev = open(prefsfile).read().strip()
        except FileNotFoundError:
            defdev = None
        return defdev

    def stop(self, source):
        Gtk.main_quit()

ShowDevs()
GObject.threads_init()
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()

The icons
 0.png
 1.png
 2.png
 3.png
 4.png
 5.png
 6.png
 7.png
 8.png
 9.png
 10.png
Setting up
Setting up is simple:

*

*Copy the script into an empty file, save it as showusage.py

*Save the icons above, exactly named as in their label, into one and the very same directory as the script (right- click > Save as)

*In the headsection of the script, set (possible) alternative names (aliasses). Below an example:
alias = [
    ["sda2", "root"],
    ["sdb1", "External"]
    ]

If you want to display the devices unchanged, use:
alias = []

...and if you want, change the threshold to show a warning:
#--- set the threshold to show a warning below (% free, in steps of 10%)
#--- set to 0 to have no warning
threshold = 10

That's it
Running it
To use the indicator, run the command:
python3 /path/to/showusage.py

To add it to Startup Applications, use the command:
/bin/bash -c "sleep 10 && python3 /path/to/showusage.py"

Choose Applications: Dash > Startup Applications > Add, add the command above.

A:  disclaimer: I am author of this indicator and it is written for this specific question
Update Oct 23,2018
The indicator now supports  listing network shares.  Thanks to mihaigalos
Update Oct 29, 2016
The indicator now has unmount functionality and aliases have been made unique by referring to UUID of each partition instead of block device name such as sda1.  See the related bug report
Update , Oct 8,2016
The indicator is now in version 2.0, has added a few features and has its own PPA.
To install from PPA, use the following steps in terminal:

*

*sudo apt-add-repository ppa:udisks-indicator-team/ppa

*sudo bash -c 'apt-get update && apt-get install udisks-indicator'
As mentioned in the release notes the features include:

*

*Icons for menu entries: each partition/device has appropriate icon attached to it. If the device is usb disk , removable media icon is used, if it's iso image - the optical disk icon is used, and obviously hard drive/SSD partitions have drive icons.

*Usage is now shown in percentage and human-readable values ( powers of 1024 ).

*Graphical representation of usage via usage bar ( big thanks to Mateo Salta for the idea )

*Preferences dialog : users can turn off certain fields that they do not want to see per each menu entry. This allows keeping indicator menu clean if there is a large amount of partitions attached. ( Thanks to Zacharee's request)

*Text spacing: with default Ubuntu font and Monospace fonts, the text entries are nicely spaced to have cleaner look and enhance readability of the information.

*Notification bubbles in case partition cannot be mounted

Below is the screenshot with default Ubuntu icon theme:

Ubuntu Kylin icon theme

With all optional fields off

Design choices and additional thoughts:
In the making of this indicator , I hoped to achieve a utility that would be suitable for advanced and casual users alike. I tried to address some of the issues that I've noticed the new users may have with handling command line tools. In addition, the utility strives to be multipurpose.
The Preferences dialog allows making the indicator as complex and/or as simple as the user desires. It was also a specific design decision to avoid having label in the top panel so that it doesn't take up too much of user's top panel space. In addition, this indicator strives to be multipurpose utility that allows mounting partitions as well as opening their respective directories. This can be used not just as disk usage utility , but also as navigation utility for quick opening of the directories.
It is also convenient for users to know which partition inhabits which disk, thus avoiding frequent confusion with mounting via command line utilities such as mount. Instead it employs udisksctl for that purpose ( as well as obtaining the information from UDisks2 daemon, hence the naming ). The only task that it does not perform is unmounting , and or this reason the Open Disks Utility menu entry is included.
While originally I strived to make it similar to iStat menulet , the project diverged from this goal - the indicator is unique in it's design and purpose. I hope it will be found useful for many users and make their Ubuntu experience much more pleasant.

udisks-indicator (original answer)
Indicator for Ubuntu with Unity desktop to show disk usage

Overview
This indicator for Ubuntu with Unity allows easily view information about your mounted partitions. It strives to be visually similar to iStat Menu 3 menulet from OS X.
Entries are organized in order:

*

*Partition

*Alias ( if set by user )

*Disk Drive to which partition belongs

*Mountpoint of the partition ( directory )

*% Usage

Clicking on each partition entry will open the partition's mountpoint in the default file manager
The "Unmounted Partitions" menu lists all the partitions not currently mounted by the system. Clicking on any entry in that submenu will mount that partition automatically, typically to /media/username/drive-id folder
The indicator uses default icons provided with the system, so the icon should be changing as you change the icon theme using Unity Tweak Tool or other methods
NOTE: if you want to add multiple aliases at the same time, instead of one by one via "Make Alias" option, you can do so via editing the ~/.partition_aliases.json configuration file. The format is as follows:
{
    "sda1": "Alias 1",
    "sda2": "Alias 2",
    "sdb1": "Alias 3"
}

Installation
PPA for easy installation is coming soon . . .
In the mean time, here are alternative steps:

*

*cd /tmp

*wget https://github.com/SergKolo/udisks-indicator/archive/master.zip

*unzip master.zip

*sudo install udisks-indicator-master/udisks-indicator /usr/bin/udisks-indicator

*sudo install udisks-indicator-master/udisks-indicator.desktop /usr/share/applications/udisks-indicator.desktop
All these steps can be put into a nice little installation script:

#!/bin/bash

cd /tmp
rm master.zip*
wget https://github.com/SergKolo/udisks-indicator/archive/master.zip
unzip master.zip
install udisks-indicator-master/udisks-indicator /usr/bin/udisks-indicator
install udisks-indicator-master/udisks-indicator.desktop /usr/share/applications/udisks-indicator.desktop

Source code
Original source code (Version v1.0) with basic functionality of this indicator can be found below. For newest features , check GitHub repository for this project. Please report any feature requests as well as errors on GitHub.
The /usr/bin/udisks-indicator:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
# Author: Serg Kolo , contact: 1047481448@qq.com
# Date: September 27 , 2016
# Purpose: appindicator for displaying mounted filesystem usage
# Tested on: Ubuntu 16.04 LTS
#
#
# Licensed under The MIT License (MIT).
# See included LICENSE file or the notice below.
#
# Copyright © 2016 Sergiy Kolodyazhnyy
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import gi
gi.require_version('AppIndicator3', '0.1')
from gi.repository import GLib as glib
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Gtk as gtk
from os import statvfs
#from collections import OrderedDict
import subprocess
import shutil
import dbus
import json
import os

class UdisksIndicator(object):

    def __init__(self):
        self.app = appindicator.Indicator.new(
            'udisks-indicator', "drive-harddisk-symbolic.svg",
            appindicator.IndicatorCategory.HARDWARE
            )

        if not self.app.get_icon():
           self.app.set_icon("drive-harddisk-symbolic")

        self.app.set_status(appindicator.IndicatorStatus.ACTIVE)

        filename = '.partition_aliases.json'
        user_home = os.path.expanduser('~')
        self.config_file = os.path.join(user_home,filename)
        self.cache = self.get_partitions()
        self.make_menu()
        self.update()

    def update(self):
        timeout = 5
        glib.timeout_add_seconds(timeout,self.callback)

    def callback(self):
        if self.cache != self.get_partitions():
            self.make_menu()
        self.update()

    def make_menu(self,*args):
        """ generates entries in the indicator"""
        if hasattr(self, 'app_menu'):
            for item in self.app_menu.get_children():
                self.app_menu.remove(item)

        self.app_menu = gtk.Menu()

        partitions = self.get_partitions()
        for i in partitions:

            part = "Partition: " + i[0]
            alias = self.find_alias(i[0])
            drive = "\nDrive: " + i[1]
            mount = "\nMountPoint: " + i[2]
            usage = "\n%Usage: " + i[3]

            item = part + drive + mount + usage
            if alias:
                alias = "\nAlias: " + alias
                item = part + alias + drive + mount + usage

            self.menu_item = gtk.MenuItem(item)
            self.menu_item.connect('activate',self.open_mountpoint,i[2])
            self.app_menu.append(self.menu_item)
            self.menu_item.show()

            self.separator = gtk.SeparatorMenuItem()
            self.app_menu.append(self.separator)
            self.separator.show()

        self.unmounted = gtk.MenuItem('Unmounted Partitions')
        self.unmounted_submenu = gtk.Menu()
        self.unmounted.set_submenu(self.unmounted_submenu)

        for i in self.get_unmounted_partitions():

            # TODO: add type checking, prevent swap

            part = "Partition: " + i[0]
            alias = self.find_alias(i[0])
            drive = "\nDrive: " + i[1]
            label = part + drive
            if alias:
               alias = "\nAlias: " + alias
               label = part + alias + drive

            self.menu_item = gtk.MenuItem(label)
            self.menu_item.connect('activate',self.mount_partition,i[0])
            self.unmounted_submenu.append(self.menu_item)
            self.menu_item.show()

            self.separator = gtk.SeparatorMenuItem()
            self.unmounted_submenu.append(self.separator)
            self.separator.show()

        self.app_menu.append(self.unmounted)
        self.unmounted.show()

        self.separator = gtk.SeparatorMenuItem()
        self.app_menu.append(self.separator)
        self.separator.show()

        self.make_part_alias = gtk.MenuItem('Make Alias')
        self.make_part_alias.connect('activate',self.make_alias)
        self.app_menu.append(self.make_part_alias)
        self.make_part_alias.show()

        user_home = os.path.expanduser('~')
        desktop_file = '.config/autostart/udisks-indicator.desktop'
        full_path = os.path.join(user_home,desktop_file)

        label = 'Start Automatically'
        if os.path.exists(full_path):
           label = label + ' \u2714'
        self.autostart = gtk.MenuItem(label)
        self.autostart.connect('activate',self.toggle_auto_startup)
        self.app_menu.append(self.autostart)
        self.autostart.show()

        self.open_gnome_disks = gtk.MenuItem('Open Disks Utility')
        self.open_gnome_disks.connect('activate',self.open_disks_utility)
        self.app_menu.append(self.open_gnome_disks)
        self.open_gnome_disks.show()

        self.quit_app = gtk.MenuItem('Quit')
        self.quit_app.connect('activate', self.quit)
        self.app_menu.append(self.quit_app)
        self.quit_app.show()

        self.app.set_menu(self.app_menu)

    def mount_partition(self,*args):
        # TODO: implement error checking for mounting
        return self.run_cmd(['udisksctl','mount','-b','/dev/' + args[-1]])

    def get_mountpoint_usage(self,mountpoint):
        fs = statvfs(mountpoint)
        usage = 100*(float(fs.f_blocks)-float(fs.f_bfree))/float(fs.f_blocks)
        return str("{0:.2f}".format(usage))

    def get_partitions(self):
        objects = self.get_dbus('system',
                           'org.freedesktop.UDisks2',
                           '/org/freedesktop/UDisks2',
                           'org.freedesktop.DBus.ObjectManager',
                           'GetManagedObjects',
                           None)

        partitions = []
        for item in objects:
            try:
                if 'block_devices'  in str(item):

                       drive = self.get_dbus_property('system',
                                        'org.freedesktop.UDisks2',
                                        item,
                                        'org.freedesktop.UDisks2.Block',
                                        'Drive')
                       if drive == '/': continue

                       mountpoint = self.get_mountpoint(item)
                       if not mountpoint: continue
                       mountpoint = mountpoint.replace('\x00','')

                       drive = str(drive).split('/')[-1]
                       usage = self.get_mountpoint_usage(mountpoint)

                       part = str(item.split('/')[-1])
                       partitions.append((part,drive,mountpoint,usage))

            except Exception as e:
                #print(e)
                pass

        # returning list of tuples
        partitions.sort()
        return partitions

    def get_mountpoint(self,dev_path):
        try:
            data = self.get_dbus_property(
                             'system',
                             'org.freedesktop.UDisks2',
                             dev_path,
                             'org.freedesktop.UDisks2.Filesystem',
                             'MountPoints')[0]

        except Exception as e:
            #print(e)
            return None
        else:
            if len(data) > 0:
                return ''.join([ chr(byte) for byte in data])

    def get_unmounted_partitions(self):
        objects = self.get_dbus('system',
                           'org.freedesktop.UDisks2',
                           '/org/freedesktop/UDisks2',
                           'org.freedesktop.DBus.ObjectManager',
                           'GetManagedObjects',
                           None)

        partitions = []
        for item in objects:
            try:
                if 'block_devices'  in str(item):
                       drive = self.get_dbus_property('system',
                                        'org.freedesktop.UDisks2',
                                        item,
                                        'org.freedesktop.UDisks2.Block',
                                        'Drive')
                       if drive == '/': continue

                       mountpoint = self.get_mountpoint(item)
                       if  mountpoint: continue

                       drive = str(drive).split('/')[-1]
                       part = str(item.split('/')[-1])
                       if not part[-1].isdigit(): continue
                       partitions.append((part,drive))
                       #print(partitions)

            except Exception as e:
                #print(e)
                pass

        partitions.sort()
        return partitions

    def get_dbus(self,bus_type,obj,path,interface,method,arg):
        if bus_type == "session":
            bus = dbus.SessionBus()
        if bus_type == "system":
            bus = dbus.SystemBus()
        proxy = bus.get_object(obj,path)
        method = proxy.get_dbus_method(method,interface)
        if arg:
            return method(arg)
        else:
            return method()

    def get_dbus_property(self,bus_type,obj,path,iface,prop):

        if bus_type == "session":
           bus = dbus.SessionBus()
        if bus_type == "system":
           bus = dbus.SystemBus()
        proxy = bus.get_object(obj,path)
        aux = 'org.freedesktop.DBus.Properties'
        props_iface = dbus.Interface(proxy,aux)
        props = props_iface.Get(iface,prop)
        return props

    def make_alias(self,*args):
        partitions = [ i[0] for i in self.get_partitions() ]

        combo_values = '|'.join(partitions)
        #print(combo_values)
        command=[ 'zenity','--forms','--title','Make Alias',
                  '--add-combo','Partition','--combo-values',
                  combo_values,'--add-entry','Alias'    ]
        user_input = self.run_cmd(command)
        if not user_input: return

        alias = user_input.decode().strip().split('|')

        existing_values = None

        if os.path.isfile(self.config_file):
            with open(self.config_file) as conf_file:
                try:
                    existing_values = json.load(conf_file)
                except ValueError:
                    pass

        with open(self.config_file,'w') as conf_file:
             if existing_values:
                 existing_values[alias[0]] = alias[1]
             else:
                 existing_values = {alias[0]:alias[1]}

             #print(existing_values)
             json.dump(existing_values,conf_file,indent=4,sort_keys=True)

    def find_alias(self,part):
        if os.path.isfile(self.config_file):
            with open(self.config_file) as conf_file:
                try:
                    aliases = json.load(conf_file)
                except ValueError:
                    pass
                else:
                    if part in aliases:
                       return aliases[part]
                    else:
                       return None

    def toggle_auto_startup(self,*args):
        user_home = os.path.expanduser('~')
        desktop_file = '.config/autostart/udisks-indicator.desktop'
        full_path = os.path.join(user_home,desktop_file)

        if os.path.exists(full_path):
           os.unlink(full_path)
        else:
           original = '/usr/share/applications/udisks-indicator.desktop'
           if os.path.exists(original):
               shutil.copyfile(original,full_path)

        self.make_menu()

    def open_mountpoint(self,*args):
        pid = subprocess.Popen(['xdg-open',args[-1]]).pid

    def open_disks_utility(self,*args):
        pid = subprocess.Popen(['gnome-disks']).pid

    def run_cmd(self, cmdlist):
        """ Reusable function for running external commands """
        new_env = dict(os.environ)
        new_env['LC_ALL'] = 'C'
        try:
            stdout = subprocess.check_output(cmdlist, env=new_env)
        except subprocess.CalledProcessError:
            pass
        else:
            if stdout:
                return stdout

    def run(self):
        """ Launches the indicator """
        try:
            gtk.main()
        except KeyboardInterrupt:
            pass

    def quit(self, data=None):
        """ closes indicator """
        gtk.main_quit()

def main():
    """ defines program entry point """
    indicator = UdisksIndicator()
    indicator.run()

if __name__ == '__main__':
    main()

The /usr/share/applications/udisks-indicator.desktop
[Desktop Entry]
Version=1.0
Name=Udisks Indicator
Comment=Indicator for reporting partition information
Exec=udisks-indicator
Type=Application
Icon=drive-harddisk-symbolic.svg
Terminal=false

Additional Info:
Ubuntu Mate 16.04 test:

Gnome users need an extension (KStatusNotifierItem/AppIndicator Support) to make the indicator behave properly:

A: There is another answer using basic Sysmonitor Indicator but you can create your own custom panel with as much information as you like.
Google (well search at least) is your friend
First step is to figure out how to calculate partition use percentage:
$ percentage=($(df -k --output=pcent /dev/sda1))
$ echo "${percentage[1]}"
13%

Create bash script to echo to panel
Here is a bash script to use as "custom" option in Sysmonitor Indicator. It will  show the percentage used on the first three partitions on /dev/sda:
#!/bin/bash
echo "sda1: "
percentage=($(df -k --output=pcent /dev/sda1))
echo "${percentage[1]}"
echo " | sda2: "
percentage=($(df -k --output=pcent /dev/sda2))
echo "${percentage[1]}"
echo " | sda3: "
percentage=($(df -k --output=pcent /dev/sda3))
echo "${percentage[1]}"

Sample output
When running it will look like this:

Install and configure custom scripts in Sysmonitor Indicator
For detailed instructions on installing Sysmonitor Indicator and assigning a custom script see this answer: Can BASH display in systray as application indicator?


text:
Q: Why have I counted wrong? The question is:
There are 10 questions in an exam. At least 4 of the first 5 questions  must be answered. Then how many ways (combinations) are there to answer 7 questions?
I thought it should be
${5 \choose 4}{6 \choose 3}$ because there are ${5 \choose 4}$ ways to decide which 4 of the first 5 questions to answer. After that choice is made, we still need to choose 3 more questions to answer from the remaining 6 questions. The number of ways to do this is ${6 \choose 3}$ . Hence I get my answer via the counting principal.
However I think I've overcounted but I don't see how my application of the counting principle is wrong. The counting principal I'm given says that  if there're $m$ ways to do task 1 and after task 1 is done, there're $n$ ways to do task 2 then the total number of ways to do task 1 and task 2 is $mn$.
I now think the answer should in fact be ${5 \choose 4}{5 \choose 3}+{5 \choose 5}{5 \choose 2}$. But I still don't really see why I've counted wrong earlier and why my use of the counting principal is incorrect. Any help greatly appreciated.

A: Every set of $7$ questions that includes all of the first $5$ has been counted $5$ times in your original calculation. Take the set consisting of the first $7$ questions. You've counted it once with questions $1,2,3$, and $4$ as the $4$ chosen from the first $5$, once again with questions $1,2,3$, and $5$ as the $4$ chosen from the first $5$, yet again with questions $1,2,4$, and $5$ as the $4$ chosen from the first $5$, once more with questions $1,3,4$ and $5$ as the $4$ chosen from the first $5$, and a fifth and final time with questions $2,3,4$, and $5$ as the $4$ chosen from the first $5$.


text:
Q: How to write addressToLocations onError? How can I write a code for checking the error condition in Javascript (ArcGIS) for
addressToLocations(params, callback?, errback?).
if somebody entered an invalid address- how can I call error function?
Please share your thoughts!
my code below:-
-->

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<title>Find Address</title>
<link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.2/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/3.2/js/esri/css/esri.css" />

A: Just change your:
locator.addressToLocations(options);

to:
locator.addressToLocations(options,cBack,errBack);

The cBack, would actually be the same as the showResults call at:
  dojo.connect(locator, "onAddressToLocationsComplete", showResults);

The errBack, is what you are looking for! If there will be an error during the "addressToLocations", this method will be called. You can then process the error within this function:
function errBack(error){
    console.log("Error - "+error)
    console.log("Error code - "+error.code)
}


text:
Q: Matching the impedance of a filter? Currently designing a circuit consisting of 50 Ohm rated ICs. Between two ICs (switches), I will place a BP-filter made out of discrete components (high-Q inductors and capacitors). The filter will probably be 7th order.
My question:
Is it necessary to match the impedance of the filter to the ICs, or to the characteristic impedance of the circuit? If so, how can it be done?
Oh, and the frequencies will be in the 100-300 MHz area.
Thanks.

A: You WILL have to consider the output impedance of the driving chip AND the input impedance of the receiving chip when you design your filter or you will likely get disappointing filter performance. All your good work using high Q inductors could be ruined with an output impedance as high as 50 ohms - this resistor is in series with the output effectively and, if you are using series inductors in your design, the first stage will be massively affected if not taken into account.
On your last filter stage, the effective parallel resistance of the receiving chip being 50 ohms may also ruin that stage's abilty to be high Q.
Regards matching the nominal pass band impedance of the filter to the two IC's 50 ohm impedance I'd be less worried. 300MHz has a wavelength of 1m and you are not going to get standing wave problems on a few inches of circuit or bread board. Clearly don't make the filter's input impedance too low and don't make its output impedance too high or you'll have significant insertion losses (irrespective of whether the chips "ruin" the filter characteristics).


text:
Q: QDataStream allocation between members class ReadFile {
  public:
    void init();
    QList<double> getData();
  private:
    QFile file;
    QDataStream read;
    double bufferFloat;
    quint32 bufferInteger
}

The idea is now that when init() is called, the a file should be opened and navigated into a location where the data starts. Now, every time getData() is called, a chunk of bytes should be read from the file.
Pseudo-code looks like this:
void ReadFile::init()
{
  file.setFileName("...");
  file.open(QIODevice::ReadOnly);
  QDataStream read(&file);

  // This chunk does some magic to find correct location by applying
  // a readout (read >> bufferInteger) and check the result

  // I can verify that at this point, if doing a readout (read >> bufferFloat)
  // I get good data (i.e. corresponding to the file).
}

and
QList<double> ReadFile::getData()
{
  // Doing a (read >> bufferFloat) at this point will result in zeros.
}

I understand why this happens, since the read in init is declared locally. But how should I allocate the data stream so getData can pick up where init left off? And the next getData can pick up where the previous left off. A call sequence would look like:
ReadFile file();
file.init();
file.readData();
file.readData();
file.readData();
file.readData();
//etc...

A: There is an error in your code. This line:
QDataStream read(&file);

defines a local variable, which overrides class member. Instead you should do this:
read.setDevice(&file);


text:
Q: How do I return a list of tuples containing a phrase, and the number of times it appears in descending order? The following is the prompt for my homework:
"Write a function called phrase_freq that takes as input two file name strings.  The
first file name refers to a file containing a book. The second file name contains
phrases, one phrase to a line. The function uses a dictionary to map each
phrase in the second file to an integer representing the number of times the phrase
appears in the first file.  Phrases should be counted regardless of their capitalization
(e.g., if the phrase is "The Goops", then the phrases "The goops", "the Goops", and
"the goops", should be counted).  The function returns a list of tuples containing the phrase and the number of times the phrase appears, sorted from largest number of appearances
to the smallest."
I think my thought process is along the right track, but I am not quite there.
The following is the current code that I have:

def phrase_freq(file1, file2):
#1. Initialize a dictionary.
    a_dict = {}
#2. Open the file containing the phrases from the book.
    in_file = open(file1)
#3. Iterate though the data in the phrases file.
    for data in in_file:
#4. Add this data into the dictionary.
        a_dict = data
#5. Close this file.
    in_file.close()
#6. Open the file containing text from book.
    in_file_2 = open(file2)
#7. Assign values to key and val variables in dict.
    key = data
    val = 0
#8. Iterate through second file of book text.
    for other_data in in_file_2:
#9. Determine if phrases from file1 are in the book text.
        if key in file2:
#10. Add 1 to the instance which the phrase is found in text.
            a_dict[key] = a_dict[key] + 1
#11. If not found more than once, keep freq. value at one.
        else:
             a_dict[key] = 1
#Above giving me error. "TypeError: 'str' object does not support item assignment."
#12. Close the book text file.
    in_file_2.close()
#13. Return the list of phrases and their frequency in text.
    return list(a_dict.items())

The output should appear like the following test cases:
>>> phrase_freq("goops.txt","small_phrase.txt")
[('The Goops', 11)]
>>> phrase_freq("goops.txt","large_phrase.txt")
[('The Goops', 11), ('a Goop', 9), ('your mother', 5), ('you know', 3), ('your father', 3), ('never knew', 2), ('forget it', 1)]

A: You should create the dictionary from the phrase file, not the book file. The book may not contain each phrase alone on a line.
You need to strip the line when reading from the phrase file, to remove the newlines.
You have to convert everything to a common case so that you can compare phrases with the book case-insensitively.
You have to test whether a phrase is in the line, not the other way around.
Finally, the requirements say that the list that's returned should be sorted by the number of times the phrase was found.
import operator

def phrase_freq(file1, file2):
    a_dict = {}
    # initialize dictionary with all the phrases
    with open(file2) as phrases:
        for phrase in phrases:
            a_dict[phrase.strip().lower()] = 0
    with open(file1) as book:
        # check for each phrase on each line of the book
        for line in book:
            line = line.lower()
            for phrase in a_dict:
                if phrase in line:
                    a_dict[phrase] += 1
    # Return sorted list
    return sorted(a_dict.items(), key=operator.itemgetter(1), reverse=True)


text:
Q: показать символы unicode без преобразования в эмодзи ☺ html есть символ ☺, если его вставить без css стиля, то он отображается черно-белым, так как мне нужно.
А если он стоит на странице, где есть css стиль, то символ преобразуется в цветной эмодзи.
Я пробовал удалять части css, но только полное его отсутствие решает проблему.
Подскажите пожалуйста как можно отобразить символ ☺ так что бы он не преобразовывался в эмодзи на html странице.

.wrap {background: #EEEEEE; font-size: 20px; font-family: sans-serif, Tahoma; color: #333333; padding: 18px; margin: 1px;}
p {margin: 4px 0 4px 0;}
h1 {font-size: 20px; margin: 4px 0 4px 0;}
h2 {font-size: 20px; margin: 4px 0 4px 0;}
hr {margin: 4px 0 4px 0;}
input {margin: 0 0 0 0; padding: 0 0 0 0; border-radius: 3px;}
form {margin: 0 0 0 0; padding: 0 0 0 0;}

.line {background-color: #333333;}
.time {color: #EEEEEE; margin: 5px; font-size: 120%; font-style: italic;}
.text {text-align: center;}
.button {cursor: pointer; border: none; background-color: #EEEEEE; font-size: 20px; text-decoration: underline; color: #0000FF; display: inline-block; margin: 0.2em 0.05em;}

.border {border-bottom-width: 2px; border-left-width: 2px; border-right-width: 2px; border-top-width: 2px; color: #000000; font-size: 13px; font-weight: 400; padding: 1px;text-transform: none;}
.border_button {border-style: solid; border-width: 1px 1px 1px 1px; border-color: #333333; text-decoration: underline; }
a {text-decoration: none}
a:visited {text-decoration: none}
.grecaptcha-badge {visibility: hidden; }
.reCAPTCHA {font-size: 10px;}
.inp{display:flex;}
.mark
{
    background-color: #feeff4;
    border-left: 6px solid #e04386;
    color: #49152c;
    padding: 1px 2px;

}

@media screen and (max-width: 600px) {
    .line {
        display: none;
    }
    body{background: #EEEEEE;}
    .wrap {font-size: 18px; font-family: sans-serif, Tahoma; color: #333333; line-height: 1.2; padding: 5px; margin: 1px;}
    h1 {font-size: 20px; margin: 4px 0 4px 0;}
    h2 {font-size: 20px; margin: 4px 0 4px 0;}
    p {margin: 4px 0 4px 0;}
    hr {margin: 4px 0 4px 0;}
    input {margin: 0 0 0 0; padding: 0 0 0 0;}
    form {margin: 0 0 0 0; padding: 0 0 0 0;}
}


text:
Q: One project having two different apk I'm new to Android development. I crated a project with two packages, each having their own launcher activities i.e, its kind of each package can be a separate application. Now is it possible to create a apk file for each package separately?

A:
Now is it possible to create a apk file for each package separately?

Sorry but what you asking is not possible. Every project has always built only one apk.
but you can archive this by creating two different project with different Package Name.

A: You can create a library project, that contains the main logic of your app.
And then you create two seperate projects that contain the application specific logic, launcher activities, icons, etc.
The application package's rely on the library for shared logic, and you compile them to their own apk.

A: When using the new build system you can create a separate apk for each buildType and flavor with different package identifiers.
This is kind of a steep learning curve for a beginner, but definitely worth it as it reduces the overall overhead for your purpose. Also it's the future.


text:
Q: How to read a plist of array and dictionary in swift I'm following the apple example project TVAnimationsGestures but applying it to one of my own projects. I need to load data from a plist into my classes but i cant seem to figure out how to do it in swift. Here is an image of the plist in trying to read.

The example project reads the plist using this method
- (NSArray *)plays {

if (_plays == nil) {

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"PlaysAndQuotations" withExtension:@"plist"];
    NSArray *playDictionariesArray = [[NSArray alloc ] initWithContentsOfURL:url];
    _plays = [NSMutableArray arrayWithCapacity:[playDictionariesArray count]];

    for (NSDictionary *playDictionary in playDictionariesArray) {

        APLPlay *play = [[APLPlay alloc] init];
        play.name = playDictionary[@"playName"];

        NSArray *quotationDictionaries = playDictionary[@"quotations"];
        NSMutableArray *quotations = [NSMutableArray arrayWithCapacity:[quotationDictionaries count]];

        for (NSDictionary *quotationDictionary in quotationDictionaries) {

            APLQuotation *quotation = [[APLQuotation alloc] init];
            [quotation setValuesForKeysWithDictionary:quotationDictionary];

            [quotations addObject:quotation];
        }
        play.quotations = quotations;

        [_plays addObject:play];
    }
}

return _plays;

}
I've looked around and managed to get most of it to not display any errors but I don't think it's done properly because there's a lot of casting. Here's how far I've got:
    func loadFoodCategoryData() ->[Any] {
    // foodCategoryData is declared outside the function
    if foodCategoryData == nil {

        var url = NSBundle.mainBundle().URLForResource("Items", withExtension: "plist")!
        var categoryDictionaryArray = NSArray(contentsOfURL: url) as! [[String:AnyObject!]]
        foodCategoryData = Array()

        for foodDictionary:Dictionary in categoryDictionaryArray {

            var foodCat = FoodCategories()
            foodCat.foodCategoryName = foodDictionary["categoryName"] as! String

            var foodItemsDict = foodDictionary["items"]
            var foodItemsArray = [AnyObject]()

            for foodItems in foodDictionary {

                var foodItem:FoodItems = FoodItems()
                foodItem.setValuesForKeysWithDictionary(foodItems as! Dictionary)

                foodItemsArray.append(foodItem)

            }
        }
    }

    return foodCategoryData
}

Anyone have any better and more efficient ways to load this plist into my classes?

A: lazy initialized variables have a specific syntax in Swift. The equivalent to the ObjC code is (body simplified)
  lazy var plays : [AnyObject] = {
    var foodCategoryData = [AnyObject]()
    // do things
    foodCategoryData.append("something")
    return foodCategoryData
  }()

The down-casting from AnyObject is a pain but necessary
Edit
Your code is quite close. Try this (untested)
lazy var foodCategoryData : [AnyObject] = {

  let url = NSBundle.mainBundle().URLForResource("Items", withExtension: "plist")!
  var categoryDictionaryArray = NSArray(contentsOfURL: url) as! [[String:AnyObject!]]
  var foodItemsArray = [FoodItems]()

  for foodDictionary in categoryDictionaryArray {

    var foodCat = FoodCategories()
    foodCat.foodCategoryName = foodDictionary["categoryName"] as! String

    var foodItemsDict = foodDictionary["items"] as! [String:AnyObject]

    for foodItems in foodDictionary {

      var foodItem:FoodItems = FoodItems()
      foodItem.setValuesForKeysWithDictionary(foodItems as! Dictionary)

      foodItemsArray.append(foodItem)

    }
  }
  return foodItemsArray
 }()


text:
Q: Iterate in specific portion of numpy array and add values Probably this is a very easy and silly fix, but I cannot think of anyway to solve this issue.
I have a three column array with 2000 elements like so where each column represent x, y, z coordinates.
Final_array =np.zeros([2000,3])

Through some for loops I am trying to populate this array's columns. I was able to populate the first 1000 rows of the y values (second column) with the information of another array y_coords1, but I don't know how to populate the remaining 1000 bottom rows with another array y_coords2. Can someone please help?
# putting y values
for y in range(len(y_coords1)):
    Final_array[y, 1] = y_coords1[y]
for w in Final_array[999:2000]:
    for y in range(len(y_coords2)):
        Final_array[y,1] = y_coords2[y]

print(Final_array)

I have tried some variations on the for loops but I get errors.

A: I was looking for a different approach to answer this question, but the solution provided by Ulises Bussi worked to solve the issue
FinalArray[:,1] = np.concatenate([y_coords1 ,y_coords2 ],axis=0)


text:
Q: How to add more data into LocalStorage instead of overwriting it in contenteditable attribute? I want to create contenteditable in div when user add something in it then it should add in local storage. but right now it is overwrite when add another data.
HTMl code
<!DOCTYPE html>

        Here is the element's original content

    <input type="button" value="save my edits" onclick="saveEdits()" />

 - Edit the text and click to save for next time

Your Name

JS code
function saveEdits() {

    //get the editable element
    var editElem = document.getElementById("edit");

    //get the edited element content
    var userVersion = editElem.innerHTML;

    //save the content to local storage
    localStorage.userEdits = userVersion;

    //write a confirmation to the user
    document.getElementById("update").innerHTML = "Edits saved!";

}

function checkEdits() {

    //find out if the user has previously saved edits
    if (localStorage.userEdits != null)
        document.getElementById("edit").innerHTML = localStorage.userEdits;
}

A: You need to change your saveEdits function to check is there anything saved on storage with the same key or not. To achieve it I will recommend you to use get and set item from API here some example how you can do it.
function saveEdits() {

  //get the editable element
  var editElem = document.getElementById("edit");

  //get the edited element content
  var userVersion = editElem.innerHTML;

  //get previously saved
  const previousEditsStr = localstorage.getItem('userEdits');

  // parse allready saved edits or create empty array
  const savedEdits = previousEditsStr ? JSON.parse(previousEditsStr) : [];

  // push the latest one
  savedEdits.push(userVersion);

  //stringify and save the content to local storage
  localStorage.setItem('userEdits', JSON.stringify(savedEdits));

  //write a confirmation to the user
  document.getElementById("update").innerHTML = "Edits saved!";
}

Please be noticed that the memory here is limited and you need to take it under your control. For example you can limit previously saved comments.
Since we are saving an array thats men you need to change your reading part as well
function checkEdits() {
  const userEdits = localStorage.getItem('userEdits');

  //find out if the user has previously saved edits
  if (userEdits) {

    // here is the saved edits
    const comments = JSON.parse(userEdits);

    // showing previously saved message
    document.getElementById("edit").innerHTML = comments[comments.length - 1];
  }
}


text:
Q: How to detect a person when he/she is near an object? I have a python script which will open my webcam and detect object using yolov3.
But when the person is near a specific object (for example a rack), I need to identify the person and compute how long the person spent in that place.
What should I do in order to make it work?

A: using yolov3 is a bit tough, so I suggest you to use a more easy and clean module, the opencv module. It's not compulsory which module you use, but for better experience, use OpenCV.
First install it :
pip install opencv-python
OpenCV already contains many pre-trained classifiers for face, eyes, smiles, etc.. I will be using classifier. You can experiment with other classifiers as well.
You need to download the trained classifier XML file (haarcascade_frontalface_default.xml), which is available in OpenCv's GitHub repository. Save it to your working location.
In the below code, I am converting the colourful image to black and white image.
THE CODE :
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('img', img)
cv2.waitKey()

We can do it for videos too because videos are actually many frames per second, so we can take it as image, so for videos you can use the following CODE:
import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# To capture video from webcam.
cap = cv2.VideoCapture(0)
# now we will use an infinitive loop to read for each frames per second
while True:

    _, img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.1, 4)
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
    cv2.imshow('img', img)

    # Stop if escape key is pressed

    k = cv2.waitKey(30) & 0xff
    if k==27:
        break
# Release the VideoCapture object
cap.release()

But if you still want to use yolov3, then go through the documentation, but again, you might probably lacking some skills so use OpenCV for getting experience.
GOOD LUCK!!


text:
Q: Insert multiple columns and rows into SQL Server with node js I'm trying to to make a script that reads from a nosql and inserts into a SQL Server database.
That said I'm reading collections dynamically, so I need something to do things like
var columns = [ 1, 2, 3, 4 ...]
var values = [a, b, c ,4 ...]
request.query("INSERT INTO TABLE (" + [columns] + ") VALUES ( " [values] ");"

I have some collections with up to like 27 columns and I can't hog the database by inserting each value as I have like 20.000.000 registers to do... can't find anything that can do that inside a transaction, so I would appreciate any suggestions

A: var columns = [ 1, 2, 3, 4 ...]
var values = [a, b, c ,4 ...]
request.query(`INSERT INTO TABLE (${columns}) VALUES ?`), [[values]])

columns is an array so will have convert into a string for removing '[' and ']' brackets.


text:
Q: Using Jmeter how extracted values can be inserted to different columns of a database table Using JMeter-Bean shell sampler, I have extracted and split(with ',' delimiter) dynamic string. Currently I got stuck how this split values can be inserted to different columns of a database table.

A: Here is the code snippet which prints all the values after split. After splitting the string, each value will store into an array. You can retrieve by specifying the array position.
You can use the variable name e.g. aftersplit[0], aftersplit[1], and so on in the insert query.
String mystring = "here is my, dynamic, random, and unique string";
String[] aftersplit = mystring.split(",");

System.out.println(aftersplit[0]);
System.out.println(aftersplit[1]);
System.out.println(aftersplit[2]);

//To print all the values after splitting

for (int i=0; i < aftersplit.length; i++){
 System.out.println(aftersplit[i]);
}

A: I would recommend the following approach: store your dynamic values into JMeter Variables having number postfix, example code:
String source = "foo,bar,baz";

int counter = 1;

for (String token : source.split(",")) {
    vars.put("token_" + counter, token);
    counter++;
}

It produces the following JMeter Variables:
token_1=foo
token_2=bar
token_3=baz

Then add ForEach Controller to iterate the generated variables and JDBC Request sampler as a child of the ForEach Controller to insert them into the database. See The Real Secret to Building a Database Test Plan With JMeter to learn how to establish database connection and execute arbitrary SQL queries using JMeter


text:
Q: Keras ImageDataGenerator Predicts More Than The Prediction Set I am trying to make a CNN model that classifies American Sign Language. I already created and trained my model. Now I am trying to predict classes. My prediction set has 7250 unlabeled images however when I do the prediction, the model performs 587250 predictions while I need it to do 7250 predictions. I am providing the code below. What is the reason for this? Am I doing something wrong?
Code Block 1:
predict_set = data.flow_from_directory('/content/gdrive/MyDrive/test_data/')

Output 1:
Found 7250 images belonging to 1 classes.

Code Block 2:
import numpy as np
predictions = model.predict_classes(predict_set)
print(len(predictions),"\n", predictions)

Output 2:
587250
[27 27 27 ... 27  6 12]

Edit:
CNN Model:
model = Sequential()

# First Layer
model.add(Conv2D(filters = 64, kernel_size = (4, 4), input_shape = (64, 64, 3), activation = 'relu'))
model.add(Conv2D(filters = 64, kernel_size = (4, 4), strides = 2,  activation = 'relu'))
model.add(Dropout(0.5))
model.add(BatchNormalization(axis = 3, momentum = 0.8))

# Second Layer
model.add(Conv2D(filters = 128, kernel_size = (4, 4), activation = 'relu'))
model.add(Conv2D(filters = 128, kernel_size = (4, 4), strides = 2,  activation = 'relu'))
model.add(Dropout(0.5))
model.add(BatchNormalization(axis = 3, momentum = 0.8))

# Third Layer
model.add(Conv2D(filters = 256, kernel_size = (4, 4), activation = 'relu'))
model.add(Conv2D(filters = 256, kernel_size = (4, 4), strides = 2,  activation = 'relu'))
model.add(Dropout(0.5))
model.add(BatchNormalization(axis = 3, momentum = 0.8))

# Flattening
model.add(Flatten())
model.add(Dropout(0.5))

model.add(Dense(units = 512, activation = 'relu')) # Hidden Layer
model.add(Dense(units = 29, activation = 'softmax')) # Output Layer

#Compiling the CNN
model.compile(optimizer= 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])

model.fit_generator(training_set, steps_per_epoch = 350, epochs = 15, validation_data = test_set, validation_steps = 100)

The batch size of test_set and training_set is 64
Model Summary:
Model: "sequential_24"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_142 (Conv2D)          (None, 61, 61, 64)        3136
_________________________________________________________________
conv2d_143 (Conv2D)          (None, 29, 29, 64)        65600
_________________________________________________________________
dropout_90 (Dropout)         (None, 29, 29, 64)        0
_________________________________________________________________
batch_normalization_69 (Batc (None, 29, 29, 64)        256
_________________________________________________________________
conv2d_144 (Conv2D)          (None, 26, 26, 128)       131200
_________________________________________________________________
conv2d_145 (Conv2D)          (None, 12, 12, 128)       262272
_________________________________________________________________
dropout_91 (Dropout)         (None, 12, 12, 128)       0
_________________________________________________________________
batch_normalization_70 (Batc (None, 12, 12, 128)       512
_________________________________________________________________
conv2d_146 (Conv2D)          (None, 9, 9, 256)         524544
_________________________________________________________________
conv2d_147 (Conv2D)          (None, 3, 3, 256)         1048832
_________________________________________________________________
dropout_92 (Dropout)         (None, 3, 3, 256)         0
_________________________________________________________________
batch_normalization_71 (Batc (None, 3, 3, 256)         1024
_________________________________________________________________
flatten_21 (Flatten)         (None, 2304)              0
_________________________________________________________________
dropout_93 (Dropout)         (None, 2304)              0
_________________________________________________________________
dense_42 (Dense)             (None, 512)               1180160
_________________________________________________________________
dense_43 (Dense)             (None, 29)                14877
=================================================================
Total params: 3,232,413
Trainable params: 3,231,517
Non-trainable params: 896
_________________________________________________________________

A: There is very limited documentation for predict_classes. It may not work if you are using a generator based on the documentation shown below
x: input data, as a Numpy array or list of Numpy arrays (if the model has multiple inputs).

so I do not think it works with a generator. So you will have to use model.predict.
predictions=model.predict(predict_set)
for p in predictions:
    class_index=np.argmax(p) # this is the integer value assogned to a class.

if you used a generator to train your model (I will call it train_gen) then you can get the class_indices dictionary which is of the for (class name, class_index)
as follows
class_dict=train_gen.class_indices
# reverse the dictionary
for key,value in class_dict.items():
        new_dict[value]=key
````
now you can use the new_dict to get the class name with the code below
````
for p in predictions:
    class_index=np.argmax(p)
    class_name=new_dict[class_index]
````


text:
Q: If $f_n$ converges uniformly then $\cos(t)f_n$ converges uniformly? In my Fourier Series course, it seems the following result is used:

If a series of function $\sum a_n(t)$ converges uniformly then the sequence of functions $\cos(t)\sum a_n(t)$ converges uniformly as well.

I doubt this is true in general. However it is valid when the series $\sum a_n(t)$ converges normally .
Can someone share thoughts about this ?

A: Note that
$$
|\cos(x)f_n(x)-\cos(x)f(x)|\leq|f_n(x)-f(x)|,
$$
since $\cos$ is bounded, so if the right hand side goes to 0 uniformly, so does the left hand side.
In general: If $f_n$ converges uniformly to some $f$, and if $g$ is bounded, then $gf_n$ converges uniformly to $gf$.


text:
Q: How to save the 'this' variable in JS?

function Device(socket) {

  this.imei = false;
  this.status = false; //maintaining the logged in status
  let self = this; //saving this variable

  this.on('data', function() { //Event on the device object

    //I want to access self.imei

  });

  Device.prototype.saveLocation = function(parts) {
    //Here the value of self changes to the value of self of the recent object created
    console.log("In save location : IMEI " + self.imei);

  };
}

I am creating new objects of the device class and wanted to save the 'this' value of every object to self variable so that I can use that in callbacks without any hassle. But what is happening is that when two objects a and b are created, the value of self of object a also changes to that of b which produces ambigous results. Can someone explain why?
New devices that connect to the server, changes the self value of every previous object.
const server = net.createServer(function (socket) {
    socket.name = socket.remoteAddress + ":" + socket.remotePort;
    socket.device = new Device(socket);
    clients.push(socket);
    let bufferString = 'cddwcdc';
    socket.emit('data',bufferString);
});

A: The problem is that there's only one Device.prototype.saveLocation function. Every time you create a new device, you're overwriting this function with the most recent one, which has the last value of self in it.
Prototype functions should not be created in the constructor, they should be defined just once. It doesn't need to use self, because it receives the object it's called on as this.
You only need to use self in callback functions that are defined in the constructor, not methods of the object or prototype.
So it should be like this.

function Device(socket) {

  this.imei = false;
  this.status = false; //maintaining the logged in status
  let self = this; //saving this variable

  this.on('data', function() { //Event on the device object

    //I want to access self.imei

  });
}

Device.prototype.saveLocation = function(parts) {
  //Here the value of self changes to the value of self of the recent object created
  console.log("In save location : IMEI " + this.imei);
};

You can also define the callback function using an arrow function, then it inherits this from where it was defined.

function Device(socket) {

  this.imei = false;
  this.status = false; //maintaining the logged in status
  let self = this; //saving this variable

  this.on('data', () => { //Event on the device object

    //You can access this.imei here

  });
}

Device.prototype.saveLocation = function(parts) {
  //Here the value of self changes to the value of self of the recent object created
  console.log("In save location : IMEI " + this.imei);
};


text:
Q: vertical centering of a div in responsive design I'm just starting to study responsive web designing. In my situation, I have a <wrapper> that is needed to be in the center of the screen in any kind of mobile device. I have managed to center it horizontally, but the vertical position can't be centered. Is it possible to center a div vertically?
These are my codes:
CSS
@media (max-width: 480px) and (min-width: 320px) {
    #wrapper{
        top: 10%;
        left: 5%;
        padding-bottom: 3%;
        position: relative;
        width: 90%;
    }

HTML

 O N L I N E
R E S U M E

Sample

Sample

E-mail Address: sample@yahoo.com.ph

        R E S U M E
        P O R T F O L I O
        C O N T A C T

A: Apply this style:
div.center{
   position: absolute;
   margin: auto;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
}

A: Hey try with below code at @media ()
 /* Parent */
 body {
     position: absolute;
     display: table;
     width: 100%;
     height:100%;
 }

 /* Child */
 #wrapper {
     display: table-cell;
     vertical-align: middle;
 }

Good Luck

A: HTML

  testing!

CSS
div{
  background: #222;
  color:#FFF;
  bottom: 0;
  height: 100px;
  left: 0;
  margin: auto;
  position: absolute;
  top: 0;
  right: 0;
  width: 100px;
}