Irreducibility of polynomials over finite field

Question: If I want to show that a certain polynomial is irreducible over a finite field, which methods do I have?
In particular how can I show that $X^4-3$ is irreducible over $\mathbb F_5$
The idea which I posted here does not work very well for me.
Its not hard to see that the polynomial has no roots in the finite field. So the only possibility being reducible is that I can split it into two polynomials with degree $2$.
Should I try it as usual with $x^4-3=x^4-2x^2+9=(a_1x^2+b_1x+c_1)(a_2x^2+b_1x+c_1)$?
I tried it, but didn't came to a solution. Can someone help me?
Comment: There are fortunately not many irreducible polynomials of degree 2 over this field.
Comment: Duke, take a look at [this thread](http://math.stackexchange.com/q/353233/11619). That polynomial remains irreducible over the bigger field $\Bbb{F}_{125}$. Fortunately the proof of irreduciblity is the same: The zeros of this quartic are of order sixteen, and the field $\Bbb{F}_{5^4}$ is the smallest extension containing such elements. The usefulness of that argument depends on you being familiar with a few things about finite fields. Therefore I won't mark this as a duplicate. At least not yet.
Answer: Hint:
You have that $-3=2$ in $\mathbb F_5$. Therefore you just have to try to find $b,c\in\mathbb F_5$ such that
$$X^4-3=X^4+2=(X^2+bX+1)(X^2+cX+2),$$
or
$$X^4-3=X^2+2=(X^2+bX+3)(X^2+bX+4),$$
and if you get a contradiction, $X^4-3$ is not a product of two polynomial of degree 2. To check that it's not a product of polynomials of degree 1 and 3, you just have to show that for all $a\in \mathbb F_5$,
$$a^4+2\neq 0,$$
which is very quick.
Added
$$X^4+2=(X^2+bX+1)(X^2+cX+2)$$
$$\iff X^4+2=X^4+(b+c)X^3+(3+bc)X^2+(2b+c)X+2$$
$$\iff\begin{cases}b+c=0\\ 3+bc=0\\2b+c=0\end{cases}$$
$$\iff\begin{cases}b=-c\\c^2=3\\c=0\end{cases}$$
$$\iff\begin{cases}b=c=0\\
c^2=3\end{cases}$$
The contradiction is that if $c=0$, $c^2\neq 3$.
Now do the same reasoning with $X^4-3=(X^2+bX+3)(X^2+cX+4)$ and you'll get a contradiction too (if it's really irreducible).
Comment: Hello. Thanks for the answer. I know this, but I was not able to get a contradiction.
Comment: I completed my answer.


How do I get Windows XP IIS to handle more than 2 concurrent requests?

Question: Microsoft has intentionally crippled IIS in XP to keep people from using it as a web server platform. It defaults to handling only two simultaneous incoming requests. Is there any way to tweak this without serious system file abuse? If so, is there an easy way to test that the change was successful?
I found a suggestion from Tess Ferrandez's debugging blog about some registry settings but all the tests I run after-the-fact seem to indicate nothing has changed (even after an IIS reset and, ultimately, a system restart). In the case of her ASP.NET debugging labs, there is a test page that does a five-second sleep and logs the start and completion of the request but multiple requests to that page on this test system all start five seconds after each other instead of starting around the same time and simply taking five seconds longer from start to completion.
Answer: Here is a post by Jeff Atwood on how you can increase the limit to 10 or 40 connections. One way to possibly test would be to use a load tester like Microsoft Application Center Test that comes with Visual Studio 2003 or the Microsoft Application Stress Tool that you can download. This tools will allow you to simulate multiple users hitting your site. I would test it it before you make the change and after to see if it makes a difference.


Getting INT 16h key scancode instead of character

Question: I'm writing a simple bootloader, and I have a getch function.
char getch()
{
   uint16_t inchar;

   __asm__ __volatile__ ("int $0x16\n\t"
                        : "=a"(inchar)
                   : "0"(0x0));

   return (char)inchar;
}

I tried the first obvious solution, which is remove the casting to char of the inchar variable, but when I print it still returning a char instead of code.
My println implementation:
void println(char *str)
{
    while (*str)
    {
        // AH=0x0e, AL=char to print, BH=page, BL=fg color
        __asm__ __volatile__ ("int $0x10"
                              :
                              : "a" ((0x0e<<8) | *str++),
                                "b" (0x0000));

    }

}

Linker script:
ENTRY(start);
SECTIONS
{
    . = 0x7C00;
    .text : {
        /* Place the code in hw.o before all other code */
        boot.o(.text);
        *(.text);
    }

    /* Place the data after the code */
    .data : SUBALIGN(4) {
        *(.data);
        *(.rodata);
    }

    /* Place the boot signature at VMA 0x7DFE */
    .sig : AT(0x7DFE) {
        SHORT(0xaa55);
    }

    /* Place the uninitialised data in the area after our bootloader
     * The BIOS only reads the 512 bytes before this into memory */
    . = 0x7E00;
    .bss : SUBALIGN(4) {
        __bss_start = .;
        *(COMMON);
        *(.bss)
        . = ALIGN(4);
        __bss_end = .;
    }
    __bss_sizeb = SIZEOF(.bss);

    /* Remove sections that won't be relevant to us */
    /DISCARD/ : {
        *(.eh_frame);
        *(.comment);
        *(.note.gnu.build-id);
    }
}

My intention is to implement the scanf function and need to know the scancode of the Enter key. When scanf encounters an Enter it should stop reading the keyboard and return what is written as a string, or integer depending on whether you write a number or a character.
My attempt at implementing scanf:
char* readln()
{
    char *s[255];
    for (int i = 255; i <= 255; ++i) {
        char a[] = {0, 0};
        a[0] = getch();
        s[i] = a[0];
        //println(a);
        if (a[0] == '\r') {
            break;
            return s;
        }
    }
}

When I try to link, it doesn't work. It should return a string with characters entered from the keyboard. I get this error from the linker:

ld: section .sig loaded at [0000000000007dfe,0000000000007dff] overlaps section .data loaded at [0000000000007dd8,0000000000007e15]
Comment: The scancode can be found in `ah`, so try `inchar >> 8` to get it.  That said, pressing return should yield a carriage return (`\r`) or line feed (`\n`) character, forgot which one of these exactly.  See [here](http://www.ctyme.com/intr/rb-1754.htm) for documentation.
Comment: This error tells you that your code is too long for a boot sector.  More specifically, it tells you that the data segment overflowed the available space into the `0xaa55` signature you placed at the end.  A boot sector is only 512 bytes, that's very little space for the amount of code you want to cramp into it.  The usual approach is to write a tiny boot sector that loads some payload from the next few sectors and jumps to it.  This payload could be the rest of your bootloader; you can make it as large as needed.
Comment: That linker script and code was to build a small 512 byte boot sector. It wasn't designed for doing a complete kernel (as @fuz pointed out).The linker script is one of mine, so I happen to know what it was to be used for. If you wish I can create something that is probably more in lines with what you want to do.
Comment: No, you can still use realmode. You will be constrained with the size of the kernel. In the most simplistic case you can load the kernel into memory at 0x7E00 and go all the way to 0xFFFF allowing you 32kb for a kernel.You can get more if you create a more sophisticated loader that relocates to the memory above the interrupt table. Loading at 0x7e00 is the easiest.
Comment: Well, here's my implementation of scanf: char* readln()
{
 char *s[255];
 for (int i = 255; i <= 255; ++i)
 {
  char a[] = {0, 0};
  a[0] = getch();
  s[i] = a[0];
  //println(a);
  if (a[0] == '\r')
  {
   break;
   return s;
  }
 }
} but It does not work. Should return a string with readed data from keyboard. I get this error from the linker: ld: section .sig loaded at [0000000000007dfe,0000000000007dff] overlaps section .data loaded at [0000000000007dd8,0000000000007e15]
Comment: If you get a linker error, that means your linker script has been written incorrectly.  Are you putting this into the boot sector by chance?
Comment: I added the linker file
Comment: That's means that I need to jump to unreal mode?
Answer: Int 0x16/AH=0 returns the scan code in the upper 16-bits of the returned value. inchar was actually defined as a 16-bit uint16_t type. All you need to do is shift the value of inchar to the right 8 bits to place the BIOS scan code in the upper 8 bits into the lower 8 bits.
The function could look like:
/* getch that returns the scancode and not the ASCII character */
char getch_scancode()
{
   uint16_t inchar;

   /* upper 8 bits of inchar are the scancode in AH. */
   __asm__ __volatile__ ("int $0x16\n\t"
                        : "=a"(inchar)
                        : "0"(0x0));

   /* Shift right 8 bits to move scan code to the lower 8-bits */
   return ((char)(inchar>>8));
}

You don't need the scancode to determine if the ENTER key was pressed. You can test the ASCII character from getch for the value 0x0d (carriage return). You can also test the character against the C escape sequence \r.

The linker error you are getting:

ld: section .sig loaded at [0000000000007dfe,0000000000007dff] overlaps section .data loaded at [0000000000007dd8,0000000000007e15]

Is saying that your .data section has begun overlapping the .sig section. The linker script you are using was designed for a limited 512 byte bootloader. The error is occurring because you now have more code and data than can fit in 512-bytes. Using a new linker script and a more complex technique you get the bootloader to read the rest of the kernel into memory and then transfer control to it. The code below is an example that:

The bootloader and kernel files are combined with a linker script. The boot signature 0xaa55 is generated by the linker.
Relocates the bootloader to low memory just above the interrupt vector table and the BIOS Data Area (BDA) at 0x0600.
A FAR JMP is used to transfer control to the relocated bootloader.
The kernel is read into memory at 0x800 just after the relocated bootloader.
Disk reads are retried in the event of error.
The kernel is read 1 sector at a time using LBA to CHS translation. This allows it to be used on floppy disk images. The number of sectors to read is generated by the linker.
The kernel is stored on disk in the sectors right after the bootloader.
The code assumes a 1.44MB floppy with 18 sectors per track and 2 heads. It is suggested that floppy disk images contain a proper BIOS Parameter Block (BPB) for compatibility with USB Floppy/FDD emulation.
The stack is set to 0x0000:0x0000. This means it will wrap to the top of the first 64kb of memory. After the first push the stack address will be 0x0000:0xfffe.
The BSS segment is zeroed out. We can't assume memory will be zero.
Prior to calling the kernel the segment registers are set to zero. CS=DS=ES=FS=GS=0 and the direction flag for string instructions is cleared for forward movement.
Control is transferred to the kernelmainentry point in the C code using a 32-bit (DWORD) offset to be compatible with the way GCC handles return addresses when using the -m16 option.
I've provided a few improved and changed functions. printchar for printing a single character, printstring for printing a NUL terminated string, and getstring that starts accepting user input from the keyboard.
getstring take a buffer and a maximum number of characters to read. It ends when the user presses ENTER. TAB are ignored and thrown away. BACKSPACE prevents backspacing past the beginning of the buffer and treats backspace as destructive, as it backs up the cursor and replaces it with a space.
The sample kernel prompts for the user's name and displays it back to the user on the console.

link.ld:
OUTPUT_FORMAT("elf32-i386");
ENTRY(boot_start);

BOOTLOADER_BASE  = 0x7c00;
BOOTLOADER_RELOC = 0x600;
SECTOR_SIZE      = 512;
KERNEL_BASE      = BOOTLOADER_RELOC + SECTOR_SIZE;

SECTIONS
{
    __boot_reloc_addr = BOOTLOADER_RELOC;
    __boot_base_addr  = BOOTLOADER_BASE;
    __sector_sizew    = SECTOR_SIZE>>1;

    . = BOOTLOADER_RELOC;

    /* Code and data in boot.o placed between 0x7c00 and 0x7e00 */
    .boot : SUBALIGN(0) {
        boot.o(.text*)
        boot.o(.rodata*)
        boot.o(.data)
    }

    . = BOOTLOADER_RELOC + 0x200 - 2;
    /* Boot signature at 510th byte from beginning of bootloader's base */
    .sig : {
        SHORT(0xaa55);
    }

    KERNEL_ADJ = KERNEL_BASE - .;
    . = KERNEL_BASE;

    __disk_load_start = .;
    __disk_load_seg   = (__disk_load_start) >> 4;

    /* Kernel code and data */
    .kernel : AT(ADDR(.kernel) - KERNEL_ADJ) SUBALIGN(4) {
        *(.text*)
        *(.rodata*)
        *(.data)
    }
    __disk_load_end = .;
    __disk_load_num_sectors = (__disk_load_end - __disk_load_start + (SECTOR_SIZE - 1)) / SECTOR_SIZE;

    .kernel.bss : SUBALIGN(4) {
        __bss_start = .;
        *(COMMON);
        *(.bss)
        . = ALIGN(4);
        __bss_end = .;
    }
    __bss_sizew = SIZEOF(.kernel.bss)>>1;

    /* Remove unnecessary sections */
    /DISCARD/ : {
        *(.eh_frame);
        *(.comment);
    }
}

bpb.inc:
global bpb_disk_info

    jmp boot_start
    TIMES 3-($-$$) DB 0x90   ; Support 2 or 3 byte encoded JMPs before BPB.

bpb_disk_info:
    ; Dos 4.0 EBPB 1.44MB floppy
    OEMname:           db    "mkfs.fat"  ; mkfs.fat is what OEMname mkdosfs uses
    bytesPerSector:    dw    512
    sectPerCluster:    db    1
    reservedSectors:   dw    1
    numFAT:            db    2
    numRootDirEntries: dw    224
    numSectors:        dw    2880
    mediaType:         db    0xf0
    numFATsectors:     dw    9
    sectorsPerTrack:   dw    18
    numHeads:          dw    2
    numHiddenSectors:  dd    0
    numSectorsHuge:    dd    0
    driveNum:          db    0
    reserved:          db    0
    signature:         db    0x29
    volumeID:          dd    0x2d7e5a1a
    volumeLabel:       db    "NO NAME    "
    fileSysType:       db    "FAT12   "

boot.asm:
; These symbols are defined by the linker. We use them to zero BSS section
extern __bss_start
extern __bss_sizew

; These symbols are length (in sectors) of the kernel,
; and segment in memory to start reading to
extern __disk_load_num_sectors
extern __disk_load_seg

extern __sector_sizew;

; Mmory address to relocate the bootsector from / to
extern __boot_base_addr
extern __boot_reloc_addr

; This is the C entry point defined in kmain.c
extern kernelmain               ; kernelmain is C entry point
global boot_start               ; Make this global to suppress linker warning

KERNEL_LBA_START equ 1          ; Logical Block Address(LBA) kernel starts on
                                ;     LBA 1 = sector after boot sector
KERNEL_LBA_END   equ KERNEL_LBA_START + __disk_load_num_sectors
                                ; Logical Block Address(LBA) kernel ends at
DISK_RETRIES     equ 3          ; Number of times to retry on disk error

section .text
bits 16

; Include a BPB (1.44MB floppy with FAT12)
%include "bpb.inc"

boot_start:
    ; This code up until label .reloc must be position independent
    xor eax, eax                ; DS=0 since we use ORG 0x7c00. 0x0000<<4+0x7c00=0x7c00
    mov ds, ax
    mov es, ax
    mov ss, ax                  ; Stack at 0x0000:0x0000
    mov esp, eax                ; After first push will be 0x0000:0xfffe at top of 64kb

    ; Copy bootloader from  __boot_base_addr (0x7c00) to __boot_reloc_addr (0x600)
    ; We copy the bootloader to low memory above the BIOS Data Area (BDA) to allow
    ; more space for the kernel.
    cld
    mov cx, __sector_sizew
    mov si, __boot_base_addr
    mov di, __boot_reloc_addr
    rep movsw

    ; Jump to the relocated boot sector and set CS=0
    jmp 0x0000:.reloc
.reloc:

    ; Read kernel 1 sector at a time until kernel loaded
load_kernel:
    mov [bootDevice], dl        ; Save boot drive
    mov di, __disk_load_seg     ; DI = Current segment to read into
    mov si, KERNEL_LBA_START    ; SI = LBA that kernel starts at
    jmp .chk_for_last_lba       ; Check to see if we are last sector in kernel

.read_sector_loop:
    mov bp, DISK_RETRIES        ; Set disk retry count

    call lba_to_chs             ; Convert current LBA to CHS
    mov es, di                  ; Set ES to current segment number to read into
    xor bx, bx                  ; Offset zero in segment

.retry:
    mov ax, 0x0201              ; Call function 0x02 of int 13h (read sectors)
                                ;     AL = 1 = Sectors to read
    int 0x13                    ; BIOS Disk interrupt call
    jc .disk_error              ; If CF set then disk error

.success:
    add di, 512>>4              ; Advance to next 512 byte segment (0x20*16=512)
    inc si                      ; Next LBA

.chk_for_last_lba:
    cmp si, KERNEL_LBA_END      ; Have we reached the last kernel sector?
    jl .read_sector_loop        ;     If we haven't then read next sector

.kernel_loaded:
    jmp launch_kernel           ; Do realmode initialization and run kernel

.disk_error:
    xor ah, ah                  ; Int13h/AH=0 is drive reset
    int 0x13
    dec bp                      ; Decrease retry count
    jge .retry                  ; If retry count not exceeded then try again

error_end:
    ; Unrecoverable error; print drive error; enter infinite loop
    mov si, diskErrorMsg        ; Display disk error message
    call print_string
    cli
.error_loop:
    hlt
    jmp .error_loop

; Function: print_string
;           Display a string to the console on display page 0
;
; Inputs:   SI = Offset of address to print
; Clobbers: AX, BX, SI

print_string:
    mov ah, 0x0e                ; BIOS tty Print
    xor bx, bx                  ; Set display page to 0 (BL)
    jmp .getch
.repeat:
    int 0x10                    ; print character
.getch:
    lodsb                       ; Get character from string
    test al,al                  ; Have we reached end of string?
    jnz .repeat                 ;     if not process next character
.end:
    ret

;    Function: lba_to_chs
; Description: Translate Logical block address to CHS (Cylinder, Head, Sector).
;              Works for all valid FAT12 compatible disk geometries.
;
;   Resources: http://www.ctyme.com/intr/rb-0607.htm
;              https://en.wikipedia.org/wiki/Logical_block_addressing#CHS_conversion
;              https://stackoverflow.com/q/45434899/3857942
;              Sector    = (LBA mod SPT) + 1
;              Head      = (LBA / SPT) mod HEADS
;              Cylinder  = (LBA / SPT) / HEADS
;
;      Inputs: SI = LBA
;     Outputs: DL = Boot Drive Number
;              DH = Head
;              CH = Cylinder (lower 8 bits of 10-bit cylinder)
;              CL = Sector/Cylinder
;                   Upper 2 bits of 10-bit Cylinders in upper 2 bits of CL
;                   Sector in lower 6 bits of CL
;
;       Notes: Output registers match expectation of Int 13h/AH=2 inputs
;
lba_to_chs:
    push ax                     ; Preserve AX
    mov ax, si                  ; Copy LBA to AX
    xor dx, dx                  ; Upper 16-bit of 32-bit value set to 0 for DIV
    div word [sectorsPerTrack]  ; 32-bit by 16-bit DIV : LBA / SPT
    mov cl, dl                  ; CL = S = LBA mod SPT
    inc cl                      ; CL = S = (LBA mod SPT) + 1
    xor dx, dx                  ; Upper 16-bit of 32-bit value set to 0 for DIV
    div word [numHeads]         ; 32-bit by 16-bit DIV : (LBA / SPT) / HEADS
    mov dh, dl                  ; DH = H = (LBA / SPT) mod HEADS
    mov dl, [bootDevice]        ; boot device, not necessary to set but convenient
    mov ch, al                  ; CH = C(lower 8 bits) = (LBA / SPT) / HEADS
    shl ah, 6                   ; Store upper 2 bits of 10-bit Cylinder into
    or  cl, ah                  ;     upper 2 bits of Sector (CL)
    pop ax                      ; Restore scratch registers
    ret

; Set up segments so they are 0, zero out the BSS memory and transfer
; control to the function kernelmain
launch_kernel:
    xor ax, ax
    mov es, ax
    mov fs, ax
    mov gs, ax                  ; ES=FS=GS=0 (we set DS=SS=0 previously)

    ; We need to zero out the BSS section. We'll do it a WORD at a time
    mov edi, __bss_start        ; Start address of BSS
    mov ecx, __bss_sizew        ; Length of BSS in WORDS
                                ; Clear memory with value in AX (0x0000)
    rep stosw                   ; Do clear using string store instruction
                                ;     Clear 2 bytes at a time
    call dword kernelmain       ; Call kernel's "C" main entry point

.end_loop:                      ; Loop forever to terminate when kernel main is finished
    hlt
    jmp .end_loop

section .data
; Uncomment these lines if not using a BPB (via bpb.inc)
; numHeads:        dw 2         ; 1.44MB Floppy has 2 heads & 18 sector per track
; sectorsPerTrack: dw 18

bootDevice:      db 0x00
diskErrorMsg:    db "Unrecoverable disk error!", 0

kmain.c:
#include <stdint.h>

int getch()
{
   uint16_t inchar;

   __asm__ __volatile__ ("int $0x16\n\t"
                        : "=a"(inchar)
                        : "0"(0x0));

   return ((unsigned char)inchar);
}

/* getch that returns the scancode and not the ASCII character */
int getch_scancode()
{
   uint16_t inchar;

   /* upper 8 bits of inchar are the scancode in AH. */
   __asm__ __volatile__ ("int $0x16\n\t"
                        : "=a"(inchar)
                        : "0"(0x0));

   /* Shift right 8 bits to move scan code to the lower 8-bits */
   return ((unsigned char)(inchar>>8));
}

void printchar(int chr)
{
    /* AH=0x0e, AL=char to print, BH=page, BL=fg color */
    __asm__ __volatile__ ("int $0x10"
                          :
                          : "a" ((0x0e<<8) | (unsigned char)chr),
                            "b" (0x0000));
}

void printstring(char *str)
{
    while (*str)
        printchar (*str++);
}

/* Get NUL terminated string of maximum number of chars. The maximum
 * number of characters doesn't include the NULL terminator. Make sure the
 * str buffer passed can hold the maximum number characters plus an additional
 * byte for the NUL */
char *getstring(char *str, int maxnumchars)
{
    char inchar;
    int curpos = 0;

    /* Do nothing if NULL string or length is 0 */
    if (!maxnumchars || !str) return str;

    /* Continue string editing until ENTER (\r) is hit */
    while ((inchar = getch()) != '\r') {
        /* Process backspace, and do not allow backspacing past beginning of string.
         * Printing backspace using the BIOS is non-destructive. We must backspace,
         * print a space and then backspace once more to simulate a destructive
         * backspace */
        if (inchar == '\b') {
            if (curpos > 0) {
                curpos--;
                printstring("\b \b");
            }
            continue;
        }
        /* Toss away the tab character and do nothing */
        else if (inchar == '\t')
            continue;

        /* Store the keystroke pressed if we haven't reached end of buffer */
        if (curpos < maxnumchars) {
            str[curpos++] = inchar;
            printchar(inchar);
        }
    }
    /* Advance the cursor to the beginning of the next line with
     * Carriage return & Line Feed */
    printstring ("\r\n");
    /* Null terminate the string */
    str[curpos] = 0;

    return str;
}
    char str[41];

void kernelmain()
{
    /* Array to receive 40 characters + room for NUL terminator */

    printstring("\r\nEnter your name: ");
    getstring (str, sizeof(str)-1);
    printstring("Your name is: ");
    printstring(str);
    printstring("\r\n");
    return;
}

To compile/assemble and link you can do this:
nasm -f elf32 -Fdwarf -g boot.asm -o boot.o
i686-elf-gcc -g -c -m16 -ffreestanding -Os -Wall -fomit-frame-pointer kmain.c -o kmain.o
i686-elf-gcc -nostartfiles -nostdlib -Tlink.ld -o os.elf \
    boot.o kmain.o

# Convert os.elf to flat binary file os.bin
objcopy -Obinary os.elf os.bin

# Build 1.44MB disk image
dd if=/dev/zero of=disk.img bs=1024 count=1440
dd if=os.bin of=disk.img conv=notrunc

# Split the boot sector from the complete os.bin file
# These files may not be needed, generate them anyway
dd if=os.bin of=boot.bin bs=512 count=1
dd if=os.bin of=kernel.bin bs=512 seek=1

disk.img will be a 1.44MB floppy image with bootloader and kernel on it. boot.bin will be the binary file with the 512-byte boot sector, and kernel.bin is the kernel. You may not need boot.bin and kernel.bin but I generate them just in case.
You should be able to run it in QEMU like this:
qemu-system-i386 -fda disk.img

The output in QEMU would look similar to:

I recommend using a cross compiler, but you can modify the commands above to compile/link with your native compiler. I don't recommend it, but it should work:
gcc -fno-PIC -g -c -m16 -ffreestanding -Os -Wall -fomit-frame-pointer kmain.c -o kmain.o
ld -melf_i386 -nostartfiles -nostdlib -Tlink.ld -o os.elf \
    boot.o kmain.o

Comment: Nice and extremely helpful answer.  This should be turned into a canonical duplicate.
Comment: Very useful answer. Thanks for your patience with me. :)


What's the difference between "Artificial neuron" and "Perceptron"?

Question: The basic building block of a neural network are artificial neurons as you can see in the picture below the circles represent the artificial neurons.
What's a Perceptron? How it is different from the artificial neuron?
Answer: Perceptron is an early type of a neural network for binary classification without hidden layers. It is a model of the form
$$
y=\sigma(\mathbf w^T \mathbf x)
$$
where $\sigma$ is the Heaviside step function. It can be trained using the perceptron algorithm.
You could say that perceptron is a neural network with a single neuron.

Image from https://towardsdatascience.com/what-the-hell-is-perceptron-626217814f53
Comment: That makes sense. Can we have more than one neurons?


Mac Catalyst app: how to close a window without terminating the app?

Question: I'm developing an app by using Mac Catalyst.
When user has closed the window on Mac version, the app is terminated.
It was possible to change this behavior in Cocoa by using:
applicationShouldTerminateAfterLastWindowClosed

method or by setting NSSupportsAutomaticTermination to NO in plist file.
How can I get the same in a Mac Catalyst app?
Comment: Well, by my findings even injecting at AppKit level in macCatalyst mode, the `applicationShouldTerminateAfterLastWindowClosed` callback is not used. They terminate directly via private document controller. The only possible to do is prevent termination by `applicationShouldTerminate`, but in this case window is not closed.
Comment: @asperi yes. I also tried similar workarounds but still didn't have a chance to make it working. By the way, how do you inject Appkit?
Answer: I've discussed the problem with Apple technical developer support. After a long discussion, they accepted that this is a bug on Apple side. It's escalated to the engineering team.
UPDATE:
Apple Engineering team has provided the following information regarding this issue and it worked for me:
We were able to prevent the quitting behavior by adding NSSupportsAutomaticTermination = NO to info.plist
Comment: Thank you! I hope, that there will be soon a lot of bugfixing and improvements to SwiftUI and Catalyst. Please let us know, if there is a final solution, I will need it as well.
Comment: Doesn't work for me.
Comment: Makes no difference here either.
Answer: EDIT
This answer is not working, see the comments.
EDIT END
This is only possible, if you activate "Supports multiple windows":

My thoughts, why it is like this: macOS differentiates between applications and windows. So if your application can open only one window, closing that will tell macOS to close the application.
PS: I experienced some bugs in the "supports multiple windows" mode. I hope, that they will be removed soon.
Comment: This is also what I'd expected but not. When you enabled this option, the app icon is not visible in the dock and for sure, this is not the expected behavior.
Comment: Can you try it with a new clean project? For me it works.
Comment: I tried. When I enabled multiple window support in a clean macCatalyst project, when the user has closed the window and then clicked on somewhere on the screen, the app icon is not visible anymore on the dock.
Comment: Aaah, you're right, the icon will be gone, when you click somewhere else, sorry, I didn't check that. Then please forget my answer, I think that is something that Apple has to fix in Catalyst. Maybe you should file a bug.
Comment: I've opened a support request but no valid anser until now. Thanks for your replies
Comment: I'm not a macOS developer (iOS and used to be Windows too), so please forgive me for wondering out loud... as a workaround, could you (a) say the app supports multiple windows, then (b) throw up and minimize an "empty" window? By empty I'm thinking anything from an invisible window that only the OS sees to an visible window with a "close app" button - an yes, a minded window fits in between these. Absolutely it's a workaround, but until something better comes along from Apple, would this be technically feasible?
Comment: @dfd: I had the same idea, but I couldn't find a way to hide the window. Unfortunately requesting a new `UIScene` will instantly open a new window.
Answer: Here is my solution, maybe someone is still looking for this :)
1st we need to have access to AppKit. In this link you can find a good explanation of how to do it, as well as some sneak peek on the next step. link
Once we have an AppKit bundle ready, and read the explanation of how to disable the zoom button on the window (on the link above), we are ready to do what we actually want; which is to avoid the app termination when the Close button is clicked. For that we will simply hijack the Close button and tell it to do what we need...
- (void) tweakWindowButtons
{
    NSArray *windows = NSApplication.sharedApplication.windows;

    NSWindowCollectionBehavior behavior = NSWindowCollectionBehaviorFullScreenAuxiliary | NSWindowCollectionBehaviorFullScreenNone;

    for (NSWindow *window in windows) {
        [window setCollectionBehavior:behavior];

        //-- Hijack close button action
        NSButton *button = [window standardWindowButton:NSWindowCloseButton];
        [button setTarget:self];
        [button setAction:@selector(closeButtonAction)];

        button = [window standardWindowButton:NSWindowZoomButton];
        [button setEnabled:NO];
    }
}

- (void) closeButtonAction
{
        NSApplicationActivationPolicy policy = NSApplicationActivationPolicyAccessory;

        //-- hide app icon and window
        NSApplication.sharedApplication.activationPolicy = policy;
    }
}

To bring the view back, set the policy to NSApplicationActivationPolicyRegular
BTW, I'm assuming we also have a statusbar icon that will be working as an anchor to the app.


Wait for providers constructor to be ready before using it

Question: In my application I am using a provider for authentication and one for loading the applications config file. The auth provider uses data from the config provider, though. So I would like the auth provider to wait for the config providers constructor to be ready, before calling it's getSelectedConfig() method. Right now I implemented the following mechanism
// AuthProvider
@Injectable()
export class AuthProvider {

  private url:string;
  private token:string;

  constructor(
    public http: HttpClient,
    public config: ConfigProvider
  ) {
    this.loadParams();
  }

  private loadParams() {
    this.config.ready().subscribe(
      ready => {
        this.config.getSelectedConfig().subscribe(
          config => {
            this.url = config.endpoint;
            this.token = config.token;
          }
        );
      }
    )
  }
}

// ConfigProvider (in seperate file, of course)
@Injectable()
export class ConfigProvider {

  private selectedConfig:Config = null;
  private configStorageKey:string = "selected_config";
  public readyObservable:Observable<boolean>;

  constructor(
      public storage: Storage,
      public http: HttpClient
    ) {
    this.checkStorageForConfig();
  }

  public ready(){
    return this.readyObservable;
  }

  public checkStorageForConfig() {
    this.readyObservable = Observable.create(
      observer => {
        this.storage.get(this.configStorageKey).then(
          config => {
            if(config){
              this.selectedConfig = config;
            }
            observer.next();
          }
        )
      }
    )
  }
}

So I create an Observable that can be given to auth to know whether config provider can be used already.
This method works, but I don't think it is a good solution. Yet I can't come up with a better one. I generally don't know how to handle such a situation.
In my mind I would like to simply call something like this.config.ready().then( ... ) without introducing other Observables. But maybe this is the right way, after all.
Comment: Have a look at APP_INITIALIZER to load your config service before the app is loaded
Answer: You can simplify it by using await async/await maybe, if the logic started to increase much further i'd recommend having a separate service to handle onReady issues. This is just a simple rework:
// AuthProvider
@Injectable()
export class AuthProvider {

private url: string;
private token: string;

constructor(
    public http: HttpClient,
    public config: ConfigProvider
) {
    this.loadParams();
}

private loadParams() {
    this.config.readyObservable.subscribe(
        ready => {
            if (ready) {
                this.config.getSelectedConfig().subscribe(
                    config => {
                        this.url = config.endpoint;
                        this.token = config.token;
                    }
                );
            }
        }
    )
}

// ConfigProvider (in seperate file, of course)

@Injectable()
export class ConfigProvider {

private selectedConfig: Config = null;
private configStorageKey: string = "selected_config";
public readyObservable: ReplaySubject<boolean> = new
ReplaySubject(1);

constructor(
    public storage: Storage,
    public http: HttpClient
) {
    waitForStuffInConstructor()
}

public ready() {
    return this.readyObservable;
}
public async waitForStuffInConstructor() {
    await this.checkStorageForConfig();
    this.readyObservable.next(true);
}
public checkStorageForConfig() {
    this.storage.get(this.configStorageKey).then(
        config => {
            if (config) {
                this.selectedConfig = config;
            }
            observer.next();
        }
    )
}

Comment: This looks helpful, But it seems my `readyObservable` does not have the method `.next()` ?
Comment: Also `waitForStuffInConstructor` is not called, but I guess it should be called in the constructor, right?
Comment: Sorry was in a rush while answering as i was at work, i've edited it a bit so your using a replay subject which only emits when a next() value is given. and yes you call waitForStuffInConstructor() in the constructor. hope this helps.
Comment: Yes, that's reasonable. Thank you. I'm fairly new to development with ionic/angular. Is doing this actually good practice or are there better ways?
Comment: I think as a method of communication between services it's absolutely fine. its also great because you can monitor changes in your config with your Observable and make changes based on it.


Increment counter sequentially in Node.js

Question: I want to know how can I ensure that I increment counter correctly in Node.js environment.
If I understand correctly, async functions are processed by non-main threads that are instantiated by 4 libuv library threads, and the callbacks are executed by the main thread (event loop).
If above is true, then below code can result in incorrect updates to counter because f1() & f2() can try to update counter at the same time giving a final result of 1 instead of 2.
How do I rewrite the code below to ensure correct update to counter?
var counter = 0

async function f1() {
  // do something

  counter++
}

async function f2() {
  // do something

  counter++
}
f1()
f2()

Comment: Maybe this: [How to lock on object which shared by multiple async method in nodejs?](https://stackoverflow.com/questions/38802959/how-to-lock-on-object-which-shared-by-multiple-async-method-in-nodejs) ??
Comment: @LinDu There is no guarantee that f1 will be called before f2.
Comment: @Luuk cannot use 3rd party libraries. Only vanilla APIs.
Comment: What do you call "a final result"? No, there is no way that `f1` and `f2` access the same `counter` variable at the same time, so the "final" result will be `2`. However which of `f1` or `f2` would have set it to `1` or `2` is unsure. Async funtions are still ran by the one and only JS processing. You'd have such issues only with `SharedArrayBuffer` objects, but for these, we have `Atomics`.
Comment: @Kaiido That is what I want to clarify. Can you explain why `f1()` & `f2()`cannot access counter variable at the same time if they are being processed by background threads? The final result in this case is expected to be `2`
Comment: "Async fun[c]tions are still ran by the one and only JS processing." They're not processed by background threads. Maybe they're themselves waiting for some tasks that are processed by other processes, but the JS part is ran by the one and only JS processing that has access to `counter`. So there is no risk of clashing here. Once again, the only case where you could have such an issue is with `SharedArrayBuffer` shared across different JS contexts (e.g with web workers). Here `counter` is a number and can't be shared across contexts.
Comment: @Kaiido When do libuv threads come into picture if async functions are processed by main threads?
Comment: When you do something like `fs.readFile(url, cb)`, the filesystem io will be handled by another thread, but the callback `cb` will be ran by the one and only JS processing. That's just the same with `async` functions. Whatever API uses another thread will still use that other thread, but the JS execution will get ran by the JS processing.
Answer: No, there is no way that f1 and f2 do access the same counter variable at the same time, so the "final" result will be 2.
However which of f1 or f2 would have set it to 1 or 2 is unsure.
Async functions are still ran by the one and only JS processing, not by background threads. Maybe they will themselves be waiting for some tasks that are processed by other processes, depending on the API calls they'll make, but the JS part is still ran by the one and only JS processing that has access to the counter variable.
So there is no risk of clashing here.
The only case where you could have such an issue is with SharedArrayBuffer objects, when shared across different JS contexts (e.g with web workers). Though for this case we have Atomics.
But here the counter variable is not a SharedArrayBuffer, and can't be shared across contexts. So once again, when f1 and f2 will both have resolved in an undetermined order, counter will hold the value 2.
Answer:
If I understand correctly, async functions are processed by non-main threads

This is not true. All async functions are processed in the main thread. Therefore calling f1() and f2() will always result in counter being incremented twice. It will never fail. This is because javascript is single threaded.
It is important to know that javascript is single threaded. Even operations that are performed in multiple threads by Node.js such as calling web workers or performing file I/O are serialized back to the main thread by the event loop.
Unless you're using non-standard 3rd party threading libraries variable access in node.js are never simultaneous. This is because variables cannot be shared between workers in node.js (that is, if you use worker_threads - in normal coding you're not even executing your own code in separate threads). Data is exchanged between threads via messages - similar to the way client and servers on the internet share data with each other: they never access each other's variables.
Comment: YOu mean the callbacks are serialized to the main thread, not the I/O call itself. Right?
Comment: Yes. The code that runs on the threads are C++ code written by node developers. All your own code from requesting the read to the callback are handled in the main thread. The event loop is basically a giant state machine
Comment: For worker_threads you execute your own code in the other threads but the threads don't share variables. They execute in their own javascript interpreters. They can communicate the usual ways using sockets or pipes though the API give you high level functions to pass messages between threads that handles the low level details for you
Comment: Requesting reads and other I/O operations are handled by background threads, not main thread.
Comment: The C code requesting the read are done in the background thread. However, the code you typed (eg: `fs.readFile(...)`) is executed in the main thread.
Comment: Yup, thats what I said
Comment: Do note though that this applies only for file I/O. Network I/O are handled by the main thread. One way to think about it is that node cannot run code in parallel but can wait for events in parallel.
Comment: A language like JS is neither multi or single threaded, that doesn't mean anything. If anything, it does acknowledge that it can be running in a multi-threaded environment since it does provide [Atomics operations](https://tc39.es/ecma262/multipage/structured-data.html#sec-atomics-object).
Comment: No network & disk IO both are background threads. You will find this helpful: https://www.geeksforgeeks.org/libuv-in-node-js/
Comment: No. Network I/O is handled in the main thread. Look at the link you provided: https://www.geeksforgeeks.org/libuv-in-node-js. See the diagram that shows that only File I/O and DNS are handled by the thread pool while everything else is handled by the event loop of the main thread. That bit showing user code in the thread pool is probably referencing worker_threads. Reading about node.js form blogs can sometimes give you wrong information because some people don't understand it. Read the node documentation for better understanding: https://nodejs.org/en/docs/guides/dont-block-the-event-loop
Comment: Quoting you: "See the diagram that shows....oop of the main thread". You mean the diagram titled "libuv" ? Yeah thats for background threads. They are showing that Network I/O is handled by libuv thread pool.
Comment: libuv also handles async I/O. It's main purpose is to standardise async I/O functions across different OSes (select, kqueue, epoll etc.). It's secondary purpose is to manage thread pools. That's for the async I/O, not background threads
Comment: Please read the definitive documentation written by node.js developers that explains that network I/O is handled in the main thread: https://nodejs.org/en/docs/guides/dont-block-the-event-loop


Remove rows from dataframe that don't contain any numeric values

Question: I have an example dataframe as follows:
x <- data.frame(Var1 = c(NA,Inf,7,NA), Var2 = c(1,61, -Inf, -Inf), Var3 = c(12, 31, 49, Inf))
x
 Var1 Var2 Var3
1   NA    1   12
2  Inf   61   31
3    7 -Inf   49
4   NA -Inf  Inf

I would like to remove rows from this data frame that do not have at least one numeric value. So in this example, I'd like to only remove row 4, leaving a final data frame:
Var1 Var2 Var3
1   NA    1   12
2  Inf   61   31
3    7 -Inf   49

Comment: `Inf` is numeric
Answer: We may use is.finite in filter with if_any to subset data having any finite values in a row
library(dplyr)
x %>%
   filter(if_any(everything(), is.finite))
  Var1 Var2 Var3
1   NA    1   12
2  Inf   61   31
3    7 -Inf   49


what is the difference between mixture of two normal distributions and sum of two independent variables

Question: The following denotes a mixture of a standard normal with a
normal with the same mean but 100 times the variance:
$0.95 \mathrm{~N}(0,1)+ 0.05 \mathrm{~N}(0,100)$
Let Y = 0.95 X + 0.05 Z with X,Z are independent normal distribution with X ~ N(0,1) Z~N(0,100)
I remember Y = X + Z if X ~ N(u1,s1) and Z ~ N(u2,s2), then Y would follow N(u1 + u2,s1+s2)
These two conclusions seems different and makes me confused.
Hope someone can explain
Answer: If $X_1 \sim \mathsf{Norm}(\mu_1,\sigma_1)$ and, independently,
$X_2 \sim \mathsf{Norm}(\mu_1,\sigma_2)$ then
$$X_1+X_2 \sim \mathsf{Norm}\left(\mu_1+\mu_2,\sqrt{\sigma_1^2+\sigma_2^2}\right).$$
In other words, it is the variances that add,
not the standard deviations.
Also, there are some things about mixture distributions you may not understand. Although
I try to illustrate a 50-50 mixture of two
normal distributions (with different standard
deviations) below, you might want to look at the
Wikipedia page on 'mixture distributions' and
the 'Related' links in the margin of this page
that mention 'mixture' in their titles.
[The Wikipedia page gives examples of mixture
distributions with different means, but the formulas for PDFs, means, and variances are relevant.]
Because it is easier to visualize a 50:50 mixture
graphically than a 95:5 mixture, I use a 50:50 mixture below. [In the R functions for normal
distributions, the parameters are mean and SD.]
set.seed(2022); n = 10^5
p = rbinom(n, 1, .5)     # for 50:50 mixture
x1 = rnorm(n, 0, 1)
x2 = rnorm(n, 0, 10)
y.mix = p*x1 + (1-p)*x2
y.sum = x1 + x2

For samples of size $n = 100,000,$ sample means
and standard deviations should match population means and SDs to a couple of significant digits.
summary(y.mix); var(y.mix)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
-40.11645  -1.52578   0.00029   0.01102   1.53021  48.13074
[1] 50.40555   # sample SD

summary(y.sum); var(y.sum)
     Min.   1st Qu.    Median      Mean   3rd Qu.      Max.
-42.67832  -6.75347   0.00270  -0.00142   6.81791  48.53083
[1] 100.6077

In the figure below the (blue) histograms nearly
approximate the (black) density curves of the
distributions for the mixture and the sum.
par(mfrow=c(2,1))
hist(y.mix, prob=T, br=100, col="skyblue2")
 curve(.5*dnorm(x,0,1)+.5*dnorm(x,0,10), add=T, lwd=3)
hist(y.sum, prob=T, br=100, col="skyblue2")
 curve(dnorm(x, 0, sqrt(1+100)), add=T, lwd=3)
par(mfrow=c(1,1))

If you have two independent normal random variables, then their sum is normal, as shown at the beginning of this Answer. However, the mixture of two independent
normal random variables need not be even nearly normal.
Answer: Another way to think about it: if $X$ is generated from one distribution and $Y$ from another, then $X+Y$ is a sample from the distribution of the sum.  To get a sample from the mixture, you pick either $X$ or $Y$, with probabilities given by the mixing proportions.
The distribution of the sum is 'more Normal' than either of the component distributions: adding two distributions tends to smooth out their special features.  The distribution of the mixture isn't; a mixture of two Normals is bimodal, because you get an observation from one or the other.
Comment: I don't understand what you mean when you say that the sum of two independent normal random variables is "more normal" than either of the component distributions (which are themselves normal distributions.  Are some normal distributions "more normal" than others? If so, _how_?
Comment: The sum of two random variables *in general* is more Normal than the two components (which is how the maximum-entropy proof of the CLT works). Obviously if they are exactly Normal already, they can't get any more Normal than that.
Comment: The mixture of two normal distributions having different means and the same standard deviation is bimodal if the means are several standard deviations apart.
Comment: Different standard deviations, too -- they don't have to be the same
Answer: Adding another answer to the mix, in case it helps.
The random variable $Z = X + Y$ has a CDF of $P(Z\le z) = P(X+Y\le z)$.
On the other hand, if you have a mixture distribution $Z\sim 0.5X + 0.5Y$, then it
has PDF of $0.5f_X+0.5f_Y$, and CDF of $0.5F_X + 0.5F_Y$. That is, the first deals
with the actual event: we are asking, "what is the chance that the sum of a random
variable $X$ and $Y$ is a certain value?" The second has to do with likelihood.
We are asking, "what would happen if we added these likelihoods to construct
a new one?" As an example, if I had $X\sim N(0,1), Y\sim N(1000,1)$, then the
mixture distribution would look like two mountains. On the other hand, the
sum of the two would not have any peak at 0. Why? Because it is asking,
"What is the likelihood that $X+Y$ is near 0?" Well, since each time, $Y$ is drawn
from a distribution that is mean $1000$, the likelihood is actually quite low.
On the other hand, one way of thinking about the mixture distribution is that we are first picking
the distribution itself (either $X$ or $Y$), and then getting a value from it.
If that's the case, then the likelihood of getting something near $0$ is pretty high,
if you choose the variable $X$.


Reset drop down and javascript values

Question: To see the problem use the link bellow : example page
Whats happening is if you choose an advert type and choose the amount of issues you want it give you a sub total , vat and total . This is good , but if a user decides they want to select a different advert , the issues box resets to the default message , but the sub total , vat and total boxes dont reset to zero , they hold the amount it would cost to have the new advert with the previous issues . Only after changing the advert again do the sub total ect fileds change to 0.
How would i get them to change straight away?
This is the javascrip statment that is used to get the value of the advert type .
if (document.getElementById('advert').value == "item 2 - half page" && document.getElementById('addissues').value == "1 issue")  {adcharge = 320;}

This variable 'adcharge' is then shown as the sub total.
Code for drop downs :
<select name="advert" id="advert"  onchange="calculate('');"  class="validate[required]">
                          <option value="">Please select the advert required</option>

<option value="Back Cover Display Advert (Full Page)">Back Cover Display Advert (216mm x 154mm)</option>
<option value="Inside Front Cover Display Advert">Inside Front Cover Display Advert (Full Page - 136mm x 190mm)</option>
<option value="Inside Front Cover Display AdvertHalf">Inside Front Cover Display Advert (Half Page - 136mm x 93mm)</option>
<option value="Inside Back Cover Display AdvertFull">Inside Back Cover Display Advert (Full Page - 136mm x 190mm)</option>
<option value="Inside Back Cover Display AdvertHalf">Inside Back Cover Display Advert (Half Page - 136mm x 93mm)</option>
<option value="Full Page Display Advert">Full Page Display Advert (136mm x 190mm)</option>
<option value="Half Page Display Advert">Half Page Display Advert (136mm x 93mm)</option>
<option value="Quarter Page Display Advert">Quarter Page Display Advert (66mm x 93mm</option>
<option value="Eighth Page Display Advert">Eighth Page Display Advert (66mm x 44.5mm)</option>

                        </select>

The second drop down has some java script that changes the amount of issues based on the advert selected , but is basically the same code as the first box.
If you need me to be more specific , just ask for it in comments.
Comment: your explanation is so hard to understand..post your complete code then try to comment in the code what you want to happen
Comment: @CodeSlayer Iv edited the question , it should be straight forward
Answer: did you try this code?
function valueChange()
{
document.getElementById('subtotal').value=0.0;
document.getElementById('vat').value=0.0;
document.getElementById('total').value=0.0;
document.getElementById('cboIssues').value='Please select the number issues required';

}
Comment: It dosent work . If i change the onchange bit in the drop down to valueChange(). only the subtotal changes

Reset drop down and javascript values


If a derivative of a continuous function has a limit, must it agree with that limit?

Question: Suppose we have a continuous function $f : \mathbb{R} \to \mathbb{R}$. Suppose also that for a certain point $c$, $\lim_{x \to c} f'(x)$ exists. Must $f'(c)$ exist as well, and be equal to this limit?
This isn't quite the same as asking if derivatives are always continuous. The well-known function $f(x) = x^2 \sin (1/x)$ is continuous and differentiable everywhere, but its derivative has no limit at $x = 0$. I'm wondering if the derivative of a continuous function can have a discontinuity where its limit does exist.
Answer: For the limit to make sense, we have to assume that $f'$ exists on some interval around $c$.
If $\lim_{x\to c}f'(x)=L$, then $f'(c)$ exists and it is equal to $L$. Indeed, using the Mean Value Theorem we have
$$
\frac{f(c+h)-f(c)}h=f'(\xi(h))
$$
for $\xi(h)$ between $c$ and $c+h$. As $h\to0$, $c+h\to c$ and so $\xi(h)\to c$. So
$$
\lim_{h\to 0}\frac{f(c+h)-f(c)}h=\lim_{h\to0}f'(\xi(h))=L.
$$
Comment: I want to ask for the second equation, why the second equality holds.
Answer: For a quicker proof, use L'Hopital's rule
$$\lim_{x\to a}\frac{f(x)-f(a)}{x-a}=\lim_{x\to a}\frac{f'(x)}{1}=\lim_{x\to a}f'(x)$$


QrCode aparece gerado como imagem incorreta

Question: Comecei a procurar por bibliotecas para gerar qr codes e acabei me deparando com esta: https://github.com/endroid/qr-code, me pareceu tranquila de aplicar e portanto optei por ela (E por ser em php).
O problema é que ao gerar o código a resposta que obtenho é esta:

Alguém que já seja mais familiarizado com a biblioteca ou que tenha alguma ideia do porque de o qr code não estar sendo mostrado corretamente saberia me explicar como concertar?
Será que apliquei algo de forma errada, preciso ativar um plug-in específico, algo assim?
Seguem os códigos abaixo. Agradeço qualquer colaboração
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Teste Qr</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

    É pra ter um QR Code logo abaixo ;)

E o arquivo gerador:
<?php

require_once( 'src/QrCode.php' );

use Endroid\QrCode\QrCode;

$qr = new QrCode();

$qr
    ->setText( "Hello There" );
    ->setSize( 200 );
    ->Render();

?>
Answer: Existem vários erros com o seu código que não está a detectar porque está a usar o getCode.php como src da imagem, se invocar directamente o getCode.php no browser por certo que os va identificar.
Este código funciona apenas estou o autoloader.
getCode.php
<?php
require_once 'vendor/autoload.php';

use Endroid\QrCode\QrCode;
$qr = new QrCode();
$qrCode = new QrCode('Hello There');
header('Content-Type: ' . $qrCode->getContentType());
echo $qrCode->writeString();

?>

Comment: Apliquei o seu código e o output seguiu igual
Comment: Invoque o script getCode.php e indique que erros estão a ser produzidos
Comment: O único problema é que a imagem do qr code segue igual, ele não aparece na página.
Comment: O código que apresentei funciona,  pode não ter o relatório de erros ativo no PHP e portanto não vê nenhum erro
Comment: Perdão pela noobada, mas como eu ativo esse relatório?
Comment: error_reporting(E_ALL & ~E_NOTICE); http://php.net/manual/en/function.error-reporting.php
Comment: Acabei nem precisando ativar para encontrar um erro, na pasta extraída do .ZIP não existe nenhum "vendor/autoload.php"
Comment: Como referi eu estou a usar o composer uma sistema de gestão pacotes e dependências para php
Comment: Utilizei o composer e agora está dando certo, muito obrigado


How to extract Twitter follower number using XLM & spreadsheets

Question: I want to get Twitter follower numbers on a google spreadsheet.
I used below line code and the result was N/A
=importXML("https://twitter.com/elonmusk","//a[@href='/elonmusk/followers']/span[@class='css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0'")
The HTML code is

54.8M

Followers

Answer: Please take a closer look at the span nodes.  The span you are trying to target is actually nested within the prior span, it is not a sibling.  Try changing this:
//a[@href='/elonmusk/followers']/span[@class='css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0']

to something like the following (note /span/span instead of /span to reflect the actual hierarchy (a/span/span):
//a[@href='/elonmusk/followers']/span/span[@class='css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0']

or the following (note //span instead of /span) if you don't care about the hierarchy between the a and target span nodes:
//a[@href='/elonmusk/followers']//span[@class='css-901oao css-16my406 r-poiln3 r-bcqeeo r-qvutc0']


Why does my shopping cart item not have a label?

Question: I'm working on D8 site with Drupal Commerce.
I have to create a dynamic product variation and add it to cart for the user checkout.
The problem I have, is when you land on the cart page, the line item doesn't have a label (title) it replaced with the price of the item. Please refer to the attached image.
Here's my code:
<code>   //create variation
            $variation = ProductVariation::create([
                'type' => 'fk_payment',
                'sku' => 'FK'.$faid,
                'status' => TRUE,
                'price' => new Price($trans->getTotal(), $trans->getCurrency()),
                'title' => "Example item label title",
              ]);

            $variation->save();

            //Load the product
            $product_id = 4;
            $product = Product::load($product_id);
            $product->addVariation($variation);
            $product->save();

            //load store
            $storeId = $product->get('stores')->getValue()[0]['target_id'];
            $store = \Drupal::entityTypeManager()
            ->getStorage('commerce_store')
            ->load($storeId);

            //prepare cart
            $cart = \Drupal::service('commerce_cart.cart_provider');
            $cart = $cart->getCart('default', $store);

            if (!$cart) {
                $cart = \Drupal::service('commerce_cart.cart_provider');
                $cart = $cart->createCart('default', $store);
            }

            // Process to place order programatically.
            $cart_manager = \Drupal::service('commerce_cart.cart_manager');

            //empty the cart
            if (!empty($cart)) {
                $cart_manager->emptyCart($cart);
            }

            $cart_manager->addEntity($cart, $variation);
</code>
Answer: Just found the answer.  I have to edit the cart "Views" and change the field "item" to display label.  That's it.


Linux - quota per directory?

Question: I have following scenarios:
Single partition mounted as /, with lots of disk space.
There is a range of directories (/pg/tbs1, /pg/tbs2, /pg/tbs3 and so on), and I would like to limit total size of these directories.
One option is to make some  big files, and then mkfs them, and mount over loopback, and then set quota, but this makes expansion a bit problematic.
Is there any other way to make the quota work per directory?
Comment: Mounting files via loopback doesn't really present an expansion problem.  You would simply extend the underlying file and then use `resize2fs` to grow the filesystem.  I think using LVM is a better solution, but the one you proposed does not have the limitations you think it does.
Comment: also btrfs and zfs
Answer: If you're forced to use ext3, then using LVM is probably your best solution.  Create a new filesystem per project.  That would look something like this:
<code># Create a 10g filesystem for "project1" in volume group "vg0"
lvcreate -L 10g -n project1 vg0

# Create an ext3 filesystem.
mke2fs -j /dev/vg0/project1

# Mount it (obviously you would want this in /etc/fstab)
mount /dev/vg0/project1 /projects/project1
</code>
Growing the project filesystems is easy:
<code># Add 2GB to the volume.
lvextend -L +2g /dev/vg0/project1

# Grow the filesystem.
resize2fs /dev/vg0/project1
</code>
Answer: If you don't rely on group permissions, you can use a different UNIX group for each "quota directory", then set sgid bit on each directory (so created files and directories will belong to the group of the directory instead of the primary group of the creator user), and use group quotas.
Answer: Yes. Look at XFS filesystem and project quota. Other filesystem do not offer this feature.
Comment: Unfortunately I can't change underlying fs. But it's good to know that XFS has this capability.
Answer: I've actually wanted to do this for a while because I didn't want to have to make system users for all of my virtual mail users. ZFS filesystems with quotas would be great, and zfs-fuse makes progress every day, but what I wanted was a very lightweight solution. Finally I decided to write a FUSE filesystem that I could mount as a layer over another filesystem (any base directory will work actually). It has a utility for managing quotas that can be scripted with easily and since quota values are just stored as xattrs on directories or files, one mountpoint can provide support for an arbitrary number of quotas.
I've been testing it on a mail server for a while and recently decided it had reached adolescence and was ready to release into the wild. If you're curious, you can check it out at http://code.google.com/p/fusequota/. I would greatly appreciate any feedback.
Comment: Git mirror https://github.com/floriandejonckheere/fusequota
Comment: The Git mirror did not work for me. No errors, but I can exceed the quota (on ext4 with mount options rw,relatime,data=ordered)
Answer: New filesystem for each shared folder is IMHO overkill. Just make new group for each shared folder, set owner group of shared folder to this group, set a sticky bit to group (so that every new file and directory has this group as owner )and for permissions on files and folders use acl lists. Then set quotas for these groups.
Answer: I am not aware of any method to set quotes per directory.
But along your idea of creating file-systems with a limited size.  This might be a place where lvm would be a good solution.
You could backup/reinstall and use lvm, only allocating the minimum amount of space needed to your logical volumes.  It is very easy to extend lvm logical volumes.

Linux - quota per directory?


Show Continuous Progress Bar on DataGridView Fill

Question: I have two forms (Main.vb and Schedule.vb).  Main has a toolstripmenu and a panel.  When "View Schedule" is selected from the toolstripmenu, the Schedule form is opened within the Main form's panel.  So it opens as a "sub form".  This works perfectly.
Private Sub tsmiScheduleView_Click(sender As Object, e As EventArgs) Handles tsmiScheduleView.Click

Schedule.TopLevel = False
Schedule.Anchor = AnchorStyles.Top Or AnchorStyles.Bottom Or AnchorStyles.Left Or AnchorStyles.Right
Schedule.Size = New Size(pnlMain.Width, pnlMain.Height) 'anchors will be disrupted if form does not open to fit with main
Me.pnlMain.Controls.Add(Schedule)
Schedule.Show()

End Sub

The problem happens in Schedule.vb, there is a DataGridView there that gets populated via a TableAdapter.  But it takes a long time to load.  So I want to show a Continuous Progress Bar while the DataGridView is loading.
Private Sub Schedule_Load(sender As Object, e As EventArgs) Handles MyBase.Load

' Load main data into the Schedule DataGridView
Me.SchedulViewTable_TableAdapter.Fill(Me.DataSetSchedule.SchedulViewTable)

End Sub

I can get the progress bar to show easy enough, but it freezes when the DataGridView is loading.
I've tried using threads, backgroundworkers, putting the ProgressBar in a seperate form and displaying it from there, and I even nixed my ProgressBar idea for an animated gif using picture boxes. None of these are working for me.  Can anyone help?
As a note, I would love to use this all over my program.  Whenever I run into something that's going to take time I'd like to have an easy way to say: "Okay, display the Continuous Progress Bar on Main.vb until I'm done".
Thanks.
Comment: Is your DataTable already bound to the DataGridView when you execute the Fill command ? What is the size, i.e. number of rows and columns of the DataGridView ?
Comment: Yes the DataTable is already bound. Theres 44,926 rows and 40 columns. Though I am working in our test database, the production database has over 100,000 rows.
Comment: Seems like you need to redesign your app to just pull over/display relevant records. 100Kx40 on the client side seems like a bad idea. Since the code loading the grid is not under your control I doubt you will be able to display its progress. You could fake progress with a timer doing the bar updates.
Answer: Set the DataGridView DataSource to null before executing the Fill command.
Then set the DataSource back to DataTable.
If you do that, how long does it take between the binding and the display (I would bet on 5 to 15 seconds)?
Comment: Thanks.  But I'm not looking to shorten the load time.  I can definitely get that done 101 ways.  But I am looking to get a progress bar to animate during the loading of a DataGridView.  I'm assuming this is impossible =(
Comment: I don't see any DataGridView event triggered when the rows count changes during the binding process. The most appropriate would be the RowsAdded event, but it seems that it doesn't work properly for this purpose.
Answer: It seem like the only thing to do is load less rows into the DataGridView so there is no need for a progress bar.  Not what I wanted to do but there isn't a way to do what I originally wanted.
I was able to show text, "Loading..." but no animation.


Web Audio API Delayed Buffer Playback

Question: this is my first interaction in this portal. I have learnt that this portal is made by developers and for developers.
I have a very peculiar problem which I was trying to solve since last 1 month. But unfortunately, I couldn't find the exact solution.
The problem is,
I have a music streaming website from which users will listen songs online. I don't have a web music player for my website yet, so was developing one.
Recently I implemented Web Audio API into my website for streaming. Which works very well but it does not start playing the stream buffer immediately when it receives from server.
I am handling the requests dynamically at server which does not provide the direct link to the resource, whereas I am reading the file in php and streaming for example readfile() or fopen() and fread() etc.
I am receiving the content very well but problem is the api does not start playing the buffer immediately but it plays the stream when the whole content is received.
If the song is 5mb, audio api buffers all 5mb and later on starts to play. I want it to play immediately after some stream received.
My javascript is as below
if(a.status==true&&b=='success'){
                (processView.audioCtx)?processView.audioCtx.close():'';
                processView.audioCtx = new (window.AudioContext || window.webkitAudioContext)();
                processView.songSrc = processView.audioCtx.createBufferSource();
                var request = new XMLHttpRequest();
                request.open('GET', processView.playSong.mp3, true);
                request.responseType = 'arraybuffer';
                request.onload = function(a) {
                    var audioData = request.response;
                    processView.audioCtx.decodeAudioData(audioData, function(buffer) {
                        processView.songSrc.buffer = buffer;
                        //processView.songbuffer = processView.songSrc.buffer;
                        processView.songSrc.connect(processView.audioCtx.destination);
                        processView.songSrc.loop = true;
                        processView.songSrc.start(0);
                        $('#togglePlayerBtn').attr('state','playing').html('').css('background','transparent');
                        //processView.audioCtx.onstatechange = processView.handlePlayer();
                    },
                    function(e){ console.log("Error with decoding audio data" + e.err); });
                }
                request.send();

My php file at server side is as below
$mime_type = "audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3";
        if(file_exists($path)){
            header('Content-type: {$mime_type}');
            header('Content-length: ' . filesize($path));
            header('Content-Disposition: filename="' . $fileName);
            header('X-Pad: avoid browser bug');
            header('Cache-Control: no-cache');
            readfile($path);
            exit;
        }
        else
        {
            header('Error: Unknown Source',true,401);
            echo 'File not found !';
        }

I am really thankful to this portal where I could get the solutions to my problems.
Thank You,
-- HKSM
Comment: Hello? Anyone here?
Answer: The solution was simple, I split the mp3 file at server level and send one by one to the browser requesting...
I amended javascript as below ..
updateSongBuffer    : function(){
    if(processView.songSrc.length < 1)processView.songSrc = new Array();
    var request = new XMLHttpRequest();
    processView.songLength++;
// here i am requesting file parts one by one...
    request.open('GET', processView.playSong.mp3+'/'+processView.songLength, true);
    request.responseType = 'arraybuffer';
    request.onprogress = function(){
        $('#togglePlayerBtn').css('background','url(/images/mloading.gif) no-repeat center center').css('background-size','cover');
    },
    request.onload = function(a) {
        $('#togglePlayerBtn').css('background','transparent');
        var audioData = request.response;
        processView.songSrc[processView.songLength] = processView.audioCtx.createBufferSource();

            processView.audioCtx.decodeAudioData(audioData).then(function(buffer) {
            //processView.audioCtx.decodeAudioData(audioData, function(buffer) {

            processView.songSrc[processView.songLength].buffer = buffer;

            processView.songSrc[processView.songLength].connect(processView.audioCtx.destination);

            if(processView.songSrc[processView.songLength-1]){
                processView.totalDuration += processView.songSrc[processView.songLength-1].buffer.duration;
            }
            else
            {
                processView.totalDuration += processView.audioCtx.currentTime;
            }

            processView.songSrc[processView.songLength].start(processView.totalDuration);
// here i am calling the same function if audio data decoded and buffer is set successfully . . . By doing this, everything is working fine now.
            processView.timeoutFunc = setTimeout('processView.updateSongBuffer()',10000);
        },
        function(e){ console.log("Error with decoding audio data ...");console.log(e);});
     }
     request.send();
},

Anyways, thank you very much to all.
Comment: hi did u ever manage to be able to change the currenttime while buffer is playing?

Web Audio API Delayed Buffer Playback


Is there a word for sequences that are (proper) subsequences of themselves?

Question: Is there a word for when a sequence $s$ is a proper subsequence of themselves, in the sense the sense that there is a (proper) subsequence of the naturals $a(n)$ such that $s(n)=s(a(n))$.
Examples (I've underlined the way in which the sequence is a subsequence of itself

$1, \underline{1}, \underline{1}, \underline{1}, \underline{1}, \underline{1}, \dots$
Any infinite sequence with finite range
$1, \underline{1}, 2, \underline{1}, 3, \underline{2}, 4, \underline{1}, 5, \underline{3}, 6, \underline{2}, 7, \dots$
$1, \underline{1}, 2, \underline{1}, \underline{2}, 3, \underline{1}, \underline{2}, \underline{3}, 4, \dots$

Nonexamples:

$1, 2, 3, 4, 5, 6, \dots$ (since each number only occurs once, every number would need to be in the subsequence, which would make it improper)
Any other sequence that does not repeat terms
$3, 2, 1, 4, 3, 2, 5, 4, 3, 6, 5, 4, \dots$
Finite sequences
Answer: These are called fractal sequences.
Comment: Actually, fractal sequence seems to be more specific. I'm not sure though.


Como preencher corretamente um ListView com  C#

Question: Tenho um método
public List <Veiculos> selectListVeiculos()
    {
        try
        {
            using (MySqlConnection conn = new MySqlConnection(_conexaoMySQL))
            {
                using (MySqlCommand command = new MySqlCommand("Select placa, marca, modelo, cor from veiculos", conn))
                {
                    conn.Open();
                    List<Veiculos> listaVeiculos = new List<Veiculos>();
                    using (MySqlDataReader dr = command.ExecuteReader())
                    {
                        while (dr.Read())
                        {

                            Veiculos veiculos = new Veiculos();

                            veiculos.Placa = (String)dr["placa"];
                            veiculos.Marca = (String)dr["marca"];
                            veiculos.Modelo = (String)dr["modelo"];
                            veiculos.Cor = (String)dr["cor"];
                            listaVeiculos.Add(veiculos);
                        }
                    }
                    return listaVeiculos;
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Erro ao acessar estoque " + ex.Message);
        }
    }

que me retorna um List com Placa, Marca, Modelo e Cor.
Eu adicionei as colunas já e código está assim:
private void UserControlListVehicle_Load(object sender, EventArgs e)
    {
        DLL dll = new DLL();
        List<Veiculos> list = new List<Veiculos>();
        list = dll.listaVeiculoss();
        foreach(var item in list)
        {
            materialListView1.Items.Add(item.Placa.ToString());
            materialListView1.Items.Add(item.Marca.ToString());
            materialListView1.Items.Add(item.Modelo.ToString());
            materialListView1.Items.Add(item.Cor.ToString());
        }
    }

Porém os itens são adicionados todos na mesma coluna, como no print a seguir

Como eu faço pra que a Marca seja adicionada na coluna marca, o modelo na coluna modelo, etc ??
Answer: Você está usando o overload string text que adiciona uma nova linha só com uma string:
materialListView1.Items.Add(item.Placa.ToString());

O que você quer usar seria o overload ListViewItem value, que por sua vez, tem um overload string[] items, que adiciona uma string por cada coluna.
ex:
foreach(var item in list)
{
    materialListView1.Items.Add(new ListViewItem(new string[] { item.Placa, item.Marca, item.Modelo, item.Cor }));
}

Comment: Entendii, funcionou perfeitamente, muito obg


Assessing int data from pandas.Series

Question: data = pandas.read_csv("weather_data.csv")
print(type(data['temp'][1]))

When I tried to print out the type of the integer data accessed from a panda.Series, it shows <class 'numpy.int64'>, does it mean numpy is primarily embedded in pandas?
Answer: From the dependency, it says

NumPy - Adds support for large, multi-dimensional arrays, matrices and high-level mathematical functions to operate on these arrays

So yes, numpy is internally imported in pandas (so the to_numpy function works).
However, you should still import numpy when you want to directly use numpy's functions.

Assessing int data from pandas.Series


Is there a name for dropping the bass note of a chord an octave?

Question: Take the following example (I'm a guitar player, so I'm going to give a guitar-centric example):
Let's say you start by playing an A major triad using the C-shape. So you're fingering the 9th fret on the G string (E), the 11th fret on the D string (C#), and the 12th fret on the A string (A). You strum it. Mountains move. Angels sing. You know, the usual.
Now let's say you're feeling a little bold and instead you play that triad by playing the A string open, without fretting it. The other fingers stay right where they are. It's not an inversion (says the novice with far too much conviction) because the A continues to be the bass note. But it's a distinct voicing change.
Is there a name for this?
Answer: This is usually referred to as an open or spread voicing, it is a general term to indicate the voicing of the chord spans beyond regular stacking, or close voicing. You are right that it isn't an inversion. The guitar lends itself to many different ways to voice the same chord. Depending on the chord sometimes the guitar will give you options for open strings even when playing high up the neck and those chords usually have an extra nice quality to them.
Answer: Yes, but your question title and body describe two difference cases that bring up different terminology.

...A major triad using the C-shape...playing the A string open

In other words: x 12 11 9 x x becomes x 0 11 9 x x.

When the tones of the chord are arranged without skips - basically within one octave for triads and seventh chords - it is called close voicing. When there are larger spaces between tones it is called open voicing.
As you point out this doesn't necessarily make a new inversion.

...dropping the bass note of a chord an octave...

I jazz there is something called drop voicing where the voices of a close voiced chord are labeled by number descending from the highest voice. SATB would be numbered as soprano=1, alto=2, tenor=3, and bass=4.
When one of those voices is dropped an octave it is called drop voicing. Drop the 2 voice and it is called drop 2 voicing, drop 2 and 4 and it is called drop 2-4 voicing, etc.

I have only seen drop voicing in the context of four tone seventh chords. Calling a root position triad with the bass dropped a "drop 3" chord would seem inappropriate.
I imagine you didn't mean to have a distinction between your title and question body, but you should know about the two cases.
Answer: I guess you're looking for a term like 'drop 2 voicing', where the second note from the top in a close position chord is dropped an octave?   I suppose we could say 'drop 4' (if it's a 4-note chord), but we don't really.   There's the general idea of a 'spread' or 'open' voicing, but that doesn't mean 'keep the top notes close, just drop the lowest one'.  It certainly isn't a different inversion, the lowest note doesn't change.
If you need to describe this, safer to just say it in plain English I think. 'Bottom note down an octave'.


$\int_{-b}^{b} \frac{f(x)}{a^x+1} dx$ where $f:[-b,b]\rightarrow\mathbb{R}$ even function and $a,b>0$

Question: $$\int_{-b}^{b} \frac{f(x)}{a^x+1} dx$$ where $$f:[-b,b]\rightarrow\mathbb{R}$$ f is an even function and $a,b>0$. The answer should be : $$\int_{0}^{b} f(x)dx$$
Solve this without any high math level methods please because I'm only a highschooler, thanks.
Answer: Let
$$I=\int_{-b}^b \dfrac{f(x)}{a^x+1}\,\mathrm dx\tag{1}$$
Using the fact that
$$\int_a^b f(x)\,\mathrm dx=\int_a^b f(a+b-x)\,\mathrm dx$$
we can write the integral as
$$\begin{align}I&=\int_{-b}^b\dfrac{f(-x)}{a^{-x}+1}\,\mathrm dx\\&=\int_{-b}^b\dfrac{a^xf(x)}{a^x+1}\,\mathrm dx\qquad f(x)\text{ is even }\Longleftrightarrow f(-x)=f(x)\end{align}\tag{2}$$
Adding $(1)$ and $(2)$
$$\begin{align}2I&=\int_{-b}^b\dfrac{f(x)}{a^x+1}\,\mathrm dx+\int_{-b}^b\dfrac{a^xf(x)}{a^x+1}\,\mathrm dx\\&=\int_{-b}^b\dfrac{(a^x+1)f(x)}{a^x+1}\,\mathrm dx\\&=\int_{-b}^bf(x)\,\mathrm dx\\&=2\int_0^b f(x)\,\mathrm dx\qquad\text{Because }f(x)\text{ is even about }x=0\\I&=\int_0^b f(x)\,\mathrm dx\end{align}$$
Comment: Impressive work, thank you very much sir :)


Question about the proof for "every field is a euclidean domain."

Question: $\color{black}{Background:}$
$\textbf{Definition:}$  An integral domain $R$ is a Euclidean domain if there is a function $\delta$ from the nonzero elements of $R$ to the nonnegative integers with these properties;
$(i)$  If $a$ and $b$ are nonzero elements of $R,$ then $\delta(a)\leq \delta(ab).$
$(ii)$  If $a,b\in R$ and $b\neq 0_R,$ then there exist $q,r\in R$ such that $a=bq+r$ and either $r=0_R$ or $\delta(r) < \delta(b).$
$\textbf{Exercise 14:}$  Let $R$ be a field.  Prove that $R$ is a Euclidean domain with the function $\delta$ given by $\delta(a)=0$ for each nonzero $a\in R.$
$\textbf{Exercise 29:}$  Let $R$ be a Euclidean domain.  If the function $\delta$ is a constant function, prove that $R$ is a field.
$\color{black}{Questions:}$
I have a question about exercise 14 above.  I have seen in some proof of exercise 14 that the $\delta(a)=1$ instead of $\delta(a)=0$. I am just wondering if it matters.  If $\delta(a)=1$, the proof doesn't require that I need to worry about $r\neq 0.$  Also, in light of exercise 29, it seems that it really doesn't matter.
Thank you in advance
Comment: "*If $\delta(a)=1$, the proof doesn't require that I need to worry about $r\neq 0.$*" Neither does it if $\delta=0$.
Comment: @Arthur, make your comment into an answer, so this question can be resolved.
Comment: For a field $R$, we can always take $r = 0$ in condition (ii), so the exact value of $\delta$ is irrelevant for Exercise 14. Similarly, if $\delta$ is constant, then the condition $\delta(r) < \delta(b)$ always fails, so it doesn't matter in Exercise 29 either whether you require $\delta > 0$ or just $\delta \geq 0$. (Condition (i) is easy to dispense with in both cases.)
Answer: None of the requirements on $δ$ (apart from having a codomain of natural numbers) say anything about what values it actually takes, only whether it's larger or smaller on some points than on others. If $x↦δ(x)$ fulfills all the requirements, then so does $x↦δ(x)+1$. And if $δ(x)$ is never equal to $0$, so does $x↦δ(x)−1$ (and so does any other manipulation you can think of that preserves the order and doesn't take us out of the codomain of natural numbers).


Smartwatch Gear 2

Question: I have developed an application getting data from the Gear2 accelorometer.
The devicemotion events are managed by a window event listener such as:
window.addEventListener('devicemotion', function(e) {
        Ax = e.accelerationIncludingGravity.x / 9.8;
        Ay = e.accelerationIncludingGravity.y / 9.8;
        Az = e.accelerationIncludingGravity.z / 9.8;
});

I need to run the application in background even if the screen is switched off.
I adopted the power setup:
 tizen.power.request("SCREEN", "SCREEN_NORMAL");
 tizen.power.request('CPU', 'CPU_AWAKE');

The problem:
when the screen is switched off (by means of the Home button) the motion  event associated to the window is not fired. I think that if the window is not active then the listener itself is not active.
Somebody has any idea how to get the accelometer data even if the screen is off?
Regards
V
Answer: Yes, you can still get the data when app is running in background on pressing the home key.
Please add this in your config.xml
<tizen:setting background-support="enable"/>

This will enable your app to collect data in background as well. :)
Comment: Hi,
I apologise for the big delay in my reply.
I forgotten to report that in my config.xml file the privilege  was already enclosed.

Of course the issue remains.
When the screen is OFF the data (Ax,Ay,Az) are not collected.

Regards
V

Smartwatch Gear 2


How To Convert an XY-RGB dataframe into a Image [cimg type]

Question: Using imager library, I have a dataframe that has the following information about the image in the columns:

X column: x coordinate of pixel
Y column: y coordinate of pixel
Rvalue: Red component of pixel
Gvalue: Green component of pixel
Bvalue: Blue component of pixel

I'm trying to convert this dataframe into a cimg to store it on disk as image -after I finished my processing on the dataframe-.
I tried using as.cimg to do the conversion as instructed in the docs
https://rdrr.io/cran/imager/man/as.cimg.data.frame.html
But It does not support RGB argument and takes instead a value argument representing all colors, how can I convert RGB into value or how is this value calculated so I could rebuild it with my code from RGB components?
Here is an example to try with
install.packages('imager')
library(imager)
im <- load.image("~/any_image.png")
df_image <- as.data.frame(im, wide="c") # that's the same structure as my dataframe
# need to convert that back to an image

here is a head sample of my df
  x y       c.1       c.2       c.3
1 1 1 0.8588235 0.7058824 0.4039216
2 2 1 0.9019608 0.7254902 0.4549020
3 3 1 0.8862745 0.7294118 0.4313725
4 4 1 0.8745098 0.7254902 0.4117647
5 5 1 0.8823529 0.7019608 0.4039216
6 6 1 0.8941176 0.7333333 0.4509804

Answer: If I'm reading the ?cimg help page corrrectly, you would need a time variable for video, and then can stack the rgb data in a single value column. Then reading the ?as.cimg page, it appears you would also need to specify the number of color dimensions with c=3. I do have a png plot from a previous SO answer in my working directory, so I unlisted the three rgb columns as a single vector and called as.cimg with appropriate parameters for the structure:
im <- load.image( file.choose())
df_image <- as.data.frame(im, wide="c")
head(df_image)
  x y c.1 c.2 c.3
1 1 1   1   1   1
2 2 1   1   1   1
3 3 1   1   1   1
4 4 1   1   1   1
5 5 1   1   1   1
6 6 1   1   1   1
?as.cimg
str(df_image)
#-----------------------
'data.frame':   230400 obs. of  5 variables:
 $ x  : int  1 2 3 4 5 6 7 8 9 10 ...
 $ y  : int  1 1 1 1 1 1 1 1 1 1 ...
 $ c.1: num  1 1 1 1 1 1 1 1 1 1 ...
 $ c.2: num  1 1 1 1 1 1 1 1 1 1 ...
 $ c.3: num  1 1 1 1 1 1 1 1 1 1 ...
#--------------
length(unique(df_image$x))
#[1] 480
length(unique(df_image$y))
#[1] 480
my_cimg <- as.cimg(unlist(df_image[3:5]),x=480,y=480,cc=3) #480x480 RGB
plot(my_cimg)

str(my_cimg)
# 'cimg' num [1:480, 1:480, 1, 1:3] 1 1 1 1 1 1 1 1 1 1 ...

Comment: Thanks that works perfectly for my case, I think the docs needs to be updated since there is no mention of the params ```x, y, cc```. It says that only ```obj, v.name, dim``` are supported and all others are ignored which is not correct considering your working example here.
I submitted an edit request to the page to add such details, thanks again for the help
Comment: There's a couple of tutorials in the package that appear very useful and do further explain the parameters with lots of worked examples. I do see x and y mentioned as named parameters in `?as.cimg` Arguments section and also mentioned in the Description section of `?cimg`.


WAMP 2.2 and Subversion 1.7.5., how does it work?

Question: So i have been working with WAMP for a long time and recently decided to include Subversion and try to connect it with the Apache server installed with WAMP. I have been running over about 6 to 8 guides so far of which almost all of them tell me the same deal.
Copy the mod_dav.so files and such to the module directory of the Apache installation, then copy the intl3_svn.dll and libdb48.dll files to the /bin folder of Apache HTTP Server etc. Change the httpd.conf file for Apache to include the new modules as well as a new directory definition for SVN things.
But every single guide seems to mention different mod_dav.so files and different .dll files. To top it off, when i got the files copied every single time i restart Apache it won't work. It simply refuses to work with the changes to the httpd.conf file even though I literally copied it from the guides.
Is there anyone that has experience with installing subversion 1.7.5. with WAMP server 2.2 that could help me out?
EDIT:
The error log of the Apache Server actually doesn't really say anything at all.
I added the following lines to the list of loaded modules in the httpd.conf file:
LoadModule dav_module modules/mod_dav.so
LoadModule dav_svn_module modules/mod_dav_svn.so
LoadModule authz_svn_module modules/mod_authz_svn.so

The dav_module already existed in the standard httpd.conf file and i only had to enable it by removing the '#' tag.
Comment: Post the apache configuration you have added for SVN.  If it fails to start, look in the error_log to see what went wrong.
Comment: Are you just doing this for some learning / education purpose? If so, it's OK. :)

However if you just need to have a working instance of Apache Subversion on a Windows machine -- install the standard edition VisualSVN Server http://www.visualsvn.com/server/
Comment: It is indeed intended as abit of self education on getting this to work without visualSVN.
Comment: @Björn very strange that nothing gets logged into Apache log. What is the logging level on your instance? Try setting it to 'Debug' error level and see what get's logged then. See http://httpd.apache.org/docs/2.2/mod/core.html#loglevel
Answer: I hope this article will guide you in a proper way of installing subversion on WAMP server.
If it works don't forgot to promote it to correct answer.. So it may help others.


Convert yaml to json using javascript

Question: I got this yaml file:
description:
  is_a: AnnotationProperty
  labelEN: description
  labelPT: descrição

relevance:
  is_a: AnnotationProperty
  domain: Indicator
  labelEN: relevance
  labelPT: relevância

title:
  is_a: AnnotationProperty
  labelPT: título
  labelEN: title
  range: Literal

and I need to convert it to json, so I can get something like this:
{
    "description": {
        "is_a": "AnnotationProperty",
        "labelEN": "description",
        "labelPT": "descrição"
    },
    "relevance": {
        "is_a": "AnnotationProperty",
        "domain": "Indicator",
        "labelEN": "relevance",
        "labelPT": "relevância"
    },
    "title": {
        "is_a": "AnnotationProperty",
        "labelPT": "título",
        "labelEN": "title",
        "range": "Literal"
    }
}

and save it in a js variable...
So, how can I do this?
Hey, please check link below for YAML to JSON converter
https://www.yamlonline.com/
Comment: I've voted to reopen (probably not important, as it's an old question). tl:dr - the linked question is different. My interpretation of this Q is "convert YAML to JSON" without specifying why (although the example does then store it in a variable).
The other question is "parse/load Yaml to an object in javascript" (specifically for use in browser).
Answer: You can solve that with a simple javascript script running on node.

install node.js
install the js-yaml package: npm install js-yaml -g

Then save this script into a file, and run it with node.js:
var inputfile = 'input.yml',
    outputfile = 'output.json',
    yaml = require('js-yaml'),
    fs = require('fs'),
    obj = yaml.load(fs.readFileSync(inputfile, {encoding: 'utf-8'}));
// this code if you want to save
fs.writeFileSync(outputfile, JSON.stringify(obj, null, 2));

Answer: There is—unfortunately—nothing in the standard library in JavaScript that will do this for you.
It's possible to build your own, but it's a lot of work. You would have to build a parser and there are likely a lot of edge cases that you would have to solve for. It might be worth considering using a third-party module.

Convert yaml to json using javascript


Views row style plugin override not saving in Views UI

Question: In my ongoing journey to create a customized RSS feed in my D8 site, I've finally gotten closest to what I need by using a Feed display in Views. The basic feed is working, but I need to add a couple custom elements for each item. So based on the fact that the rss fields are rendered in the RSSFields class (\Drupal\views\Plugin\views\row)
namespace Drupal\video_export\Plugin\views\row;

use Drupal\views\Plugin\views\row;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "mycustom_rss_fields",
 *   title = @Translation("My Custom Fields"),
 *   help = @Translation("Display fields as RSS items."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class MyCustomRssFields extends RssFields {

  public function render($row) {
    parent::render();

  }
}

So when I place this in /modules/custom/video_export/src/Plugin/views/row, if I go to select the style, I see my new plugin, but when I click Apply, nothing happens. Is there anything else I need to add to my override to get it to save?
Answer: The issue was an incomplete namespace in the use statement for the RssFields class. I had
use Drupal\views\Plugin\views\row;

so it was looking for that class in my module. Changing it to
use Drupal\views\Plugin\views\row\RssFields;

made everything work.


Jumping in Pygame

Question: I am trying to make a game like geometry dash in pygame. I have everything done except the jumping part. I need it so that when the character is on a square block he can jump up, but cannot double jump in mid air. Right now I have it so that the character is able to jump on the ground but as soon as the character touches jumps on a set of blocks, he starts to bounce up and down and isn't able to jump while gliding on the blocks. Can anyone help please?
onblock = False
for i in squares_list:
        if player_rect.bottom <= 560 and player_rect.colliderect(i):
            onblock = True
            player_rect.bottom = i.top + 1
        if player_rect.collidepoint((i.topleft[0], i.topleft[1]+1)):
            print ('Game Over')
    if event.type == KEYDOWN:     # if space is pressed the character jumps
            if event.key == K_SPACE:
                print(onblock)
                if onblock or player_rect.bottom == screen.get_rect().bottom  :  # prevents double jumps
                    vel_y = -20   # Makes the character jump up
                    player_rect.y -= 1
    if onblock:
        gravity = 0
        vel_y = 0
        current_angle = 0
    else:
        gravity = 1
        vel_y += gravity

    onblock = False

Comment: upon jumping maybe set onblock to True? as in the line after 'player_rect.y -= 1'
Answer: I don't know if you're indention is wrong just in this post or in your game, but according to this post, onblock will always be False after every loop. This might be the problem.
The other possible problem might be that you are placing your character 1 pixel above the platform when a collision happens. This means that the next time you check for collision the character will not be resting on the block and therefore the onblock will be False.
The first problem is easily fixed by removing the last line onblocks = False. The second problem can be fixed with player_rect.bottom = i.top without the +1.
Watch this talk for more information, especially around this timestamp.

Jumping in Pygame


Função para Log

Question: Pessoal peguei um codigo e ele funciona perfeitamente anota a data e o horário como eu modifiquei assim q abro a pagina! Porem na hora de colocar ele em uma função para ser disparado por um Button ele n funciona! Deve ser algo simples segue código:
    <?php

echo date('H:i:s');

function markLog(){
$fp = fopen('meus_links.txt', 'a');
fwrite($fp, date('H:i:s-'));
fclose($fp);
}

?>

    <button type="submit" onClick="markLog()" >Click</button>

Answer: Cesar, há diferençãs aí.
Você criou uma função em PHP e a está chamando via javascript. Isto não vai funcionar. O ideal seria você trabalhar com ajax para isto. Assim você faz com que a função javascript acesse a página com o php feito.
PHP não sabe JavaScript
O PHP não pode chamar diretamente uma função JavaScript porque o PHP é interpretado no lado do servidor.
O PHP não vê um código ali, ele simplesmente copia o texto caractere a caractere e envia para o navegador do usuário.
O navegador sabe JavaScript
Quando o navegador lê os dados recebidos já em HTML, ele começa a interpretar esse HTML e montar os elementos na tela.
Ao encontrar uma tag  o nevegador pára o que está fazendo e executa o que tiver nesse script.
Note que, neste ponto, o navegador está executando o script no computador do usuário, enquanto o PHP (que possivelmente já terminou de executar) estava rodando no servidor.
Bem, vou te ajudar com ajax.
1) página php: chame-a de log.php
<?php

echo date('H:i:s');

$fp = fopen('meus_links.txt', 'a');
fwrite($fp, date('H:i:s-'));
fclose($fp);

?>

2) No seu index copie este código:
<form id="simples-formulario-ajax" method="post">
    <button type="submit" name="enviar" value="enviar" id="enviar">
        Clique aqui para criar um log :)
    </button>

Prontinho, funcionando que uma beleza :)

Função para Log