text:
Q: How to load LUKS passphrase from USB, falling back to keyboard? I want to set up a headless Linux (Debian Wheezy) PC with whole disk encryption, with the ability to unlock the disk either with a USB drive, or by entering a passphrase by keyboard.  My starting point is a fresh install using the basic whole disk encryption option in the Debian Installer, which manages everything besides /boot as a LUKS-encrypted logical volume group and gives me the keyboard option.  I will describe my current solution in an answer, in hopes that it will be useful and that others can improve on it.
Here are some of the issues I had:

*

*Setting up a passphrase and putting it on the USB drive.

*Loading the USB modules in time.

*Waiting for the USB drive to recognized by Linux before trying to read from it.

*Identifying the correct USB drive (not some other drive that happens to be inserted).

*Writing a "keyscript" to pull a passphrase off the USB drive.

*Ensuring that the fall-back to keyboard kicks in in all USB failure cases.
I will accept an answer with significant improvements and upvote answers that offer contributions.

A: It would be ideal to me if I could simply have a small USB stick containing a passphrase that will
unlock the disk. Not only would that be handy for servers (where you could leave the USB stick in the
server - the goal is to be able to return broken harddisks without having to worry about confidential data), it would also be great for my laptop: Insert the USB stick when booting and remove it after
unlocking the cryptodisk.
I have now written a patch that will search the root dir of all devices for the file 'cryptkey.txt' and try decrypting
with each line as a key. If that fails: Revert to typing in the pass phrase.
It does mean the key cannot contain \n, but that would apply to any typed in key, too. The good part is that you can use the same USB disk to store the key for multiple machines: You do not need a separate USB disk for each. So if you have a USB drive in your physical key ring, you can use the same drive for all the machines you boot when being physically close.
You add the key with:
cryptsetup luksAddKey /dev/sda5

And then put the same key as a line in a file on the USB/MMC disk called 'cryptkey.txt'. The patch is here:
https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=864647
If the USB drivers, MMC drivers or the filesystems are not present in your initramfs, you need to add them by adding to /etc/initramfs-tools/modules:
uhci_hcd
ehci_hcd
usb_storage
nls_utf8
nls_cp437
vfat
fat
sd_mod
mmc_block
tifm_sd
tifm_core
mmc_core
tifm_7xx1
sdhci
sdhci_pci

When all is done, update the initramfs:
update-initramfs -u

It can be found as patch and file at: https://gitlab.com/ole.tange/tangetools/tree/master/decrypt-root-with-usb

A: despite the great answer from @Andrew which works in previous versions. The solution actually is outdated and needs lots of tuning for ubuntu 18.04 and 19.10. So I want to share my research on this.
There are several catches about crypttab. The sepcs actually changed a lot from 14.04 to 18.04 and to 19.10. It starts to support more parameters for cryptsetup. For example keyfile-offset, keyfile-size, etc. Some of the options e.g. nobootwait are gone. Some parameters supported in other distro already but is not supported in ubuntu yet (for example very nice parameter keyfile-timeout. This can eliminate the entire keyscript since it will automatically fallback to keyboard input after the keyfile-timeout.)
The major pit-fall for crypttab on ubuntu is that it actually processed by 2 different processes. One is the traditionally initramfs and another is the modern systemd. Systemd is supposed to be more advanced and flexiable in many aspect. However, systemd has poor support for crypptab, there are many options such as keyscript just silently ignored. so I have no idea what is going on, until I spotted this post. Almost all the posts online about crypttab settings is for initramfs not for systemd. So we need to add initramfs to all the entries in crypttab to avoid problems.
I also discovered a nice way to debug our keyscript and crypttab without VM or repeatedly rebooting. It is cryptdisks_start. Before we actually propagate our changes to initramfs, we should always test it with this nice command. Otherwise, you have to end-up locked out from your system and can only recover it through chroot environment.
@andrew  posted a nice way to use data hide in the raw area of a file system. However, I found it is very annoying when we want to automatically create partitions and dd the raw data to lots of usbkeys, we have to calculate the offset for all different file systems and different partition sizes. Moreover, if a user accidentally write onto the FS, there is some risk that the key got overritten. A raw partition without any FS on it makes more sense in this case. However raw partition does not have UUID which is not very useful for automatic unlocking. Thus, I would like introduce a way just use normal passphrase files on the usbkey filesystem. The major issue of passdev is it does not seek/stop during reading the file. Thus we cannot use the keyfile-offset and keyfile-size option when we want to fallback to keyboard input. Because cryptsetup will actually try to skip in the input content and if the content is shorter than keyfile-size, it raises an error. This also means if there is large offset, passdev can be very slow since it always read from beginning. However, there is no point to implement offset and keyfile size for a actual file on file system. I believe those are created for raw device.
The crypttab
luks-part UUID="<uuid>" /dev/disk/by-uuid/<keyfile FS uuid>:/<keyfile path relative to usbkey root>:<timeout in sec> luks,keyfile-offset=<seek to the key>,keyfile-size=<>,keyscript=/bin/passphrase-from-usbfs.sh,tries=<number of times to try>,initramfs

the keyscript passphrase-from-usbfs.sh utilized the /lib/cryptsetup/scripts/passdev which will wait the usb device and mount the fs then pipe out the file content. It supports the CRYPTTAB_KEY in format of /device-path/<keyfile FS uuid>:/<keyfile path relative to usbkey root>:<timeout in sec>.
#!/bin/sh
#all message need to echo to stderr, the stdout is used for passphrase
# TODO: we may need to do something about the plymouth
echo "CRYPTTAB_KEY=$CRYPTTAB_KEY" >&2
echo "CRYPTTAB_OPTION_keyfile_offset=$CRYPTTAB_OPTION_keyfile_offset" >&2
#set your offset and file size here if your system does not support those paramters
#CRYPTTAB_OPTION_keyfile_offset=
#CRYPTTAB_OPTION_keyfile_size=
echo "timeout=$CRYPTTAB_OPTION_keyfile_timeout" >&2
CRYPTTAB_OPTION_keyfile_timeout=10 # keyfile-timeout is not supported yet
pass=$(/lib/cryptsetup/scripts/passdev $CRYPTTAB_KEY)
rc=$?
if ! [ $rc -eq 0 ]; then
    echo "Can't find $CRYPTTAB_KEY; USB stick not present?" >&2
    /lib/cryptsetup/askpass "Unlocking the disk $CRYPTTAB_SOURCE ($CRYPTTAB_NAME) Enter passphrase: "
else
    echo "successfully load passphrase." >&2
    echo -n $pass
fi

The hook tell update-initramfs to copy our scripts.
#!/bin/sh

PREREQ=""

prereqs() {
        echo "$PREREQ"
}

case "$1" in
        prereqs)
                prereqs
                exit 0
        ;;
esac

. "${CONFDIR}/initramfs.conf"
. /usr/share/initramfs-tools/hook-functions
copy_exec /bin/passphrase-from-usbfs.sh
copy_exec /bin/passphrase-from-usb.sh
#when using passdev we need to hook additionaly FS and binary
copy_exec /lib/cryptsetup/scripts/passdev
manual_add_modules ext4 ext3 ext2 vfat btrfs reiserfs xfs jfs ntfs iso9660 udf

Finally I posted the updated version of passphrase-from-usb.sh which can use the new parameters in crypttab:

A: A lot of my solution is derived from the post, Using A USB Key For The LUKS Passphrase.

*

*Create a random passphrase:
dd if=/dev/urandom bs=1 count=256 > passphrase

*Insert a USB drive.  dmesg output will show the device name; assume /dev/sdd.  Figure out its size:
blockdev --getsize64 /dev/sdd

*I decided to install the passphrase at the end of the raw device, figuring it might survive any accidental use of the USB drive.
dd if=passphrase of=/dev/sdd bs=1 seek=<size-256>

*Add the passphrase to the LUKS volume:
cryptsetup luksAddKey /dev/sda5 passphrase

This does not affect the existing hand-entered passphrase from the installer.  The passphrase file can be deleted:
rm passphrase

*Find a unique name for the USB stick, so we can identify it when present:
ls -l /dev/disk/by-id | grep -w sdd

You should see one symlink.  I will call it /dev/disk/by-id/<ID>.

*Edit /etc/crypttab.  You should see a line like:
sdc5_crypt UUID=b9570e0f-3bd3-40b0-801f-ee20ac460207 none luks

Modify it to:
sdc5_crypt UUID=b9570e0f-3bd3-40b0-801f-ee20ac460207 /dev/disk/by-id/<ID> luks,keyscript=/bin/passphrase-from-usb

*The keyscript referred to above will need to read the passphrase from the USB device.  However, it needs to do more than that.  To understand how it is used, check /usr/share/initramfs-tools/scripts/local-top/cryptroot, the script that runs at boot time to unlock the root device.  Note when a keyscript is set, it is simply run and the output piped to luksOpen with no other checking.  There is no way to signal an error (USB drive not present) or fall back to keyboard input.  If the passphrase fails, the keyscript is run again in a loop, up to some number of times; however we are not told which iteration we are on.  Also, we have no control over when the keyscript is run, so we can't be sure Linux has recognized the USB drive.
I addressed this with some hacks:

*

*Poll on the USB drive and wait 3 seconds for it to appear.  This works for me, but I would love to know a better way.

*Create a dummy file /passphrase-from-usb-tried on first run to indicate that we have been run at least once.

*If we have been run at least once, or the USB drive cannot be found, run the askpass program used by cryptroot for keyboard input.
The final script:
#!/bin/sh

set -e

if ! [ -e /passphrase-from-usb-tried ]; then
    touch /passphrase-from-usb-tried
    if ! [ -e "$CRYPTTAB_KEY" ]; then
        echo "Waiting for USB stick to be recognized..." >&2
        sleep 3
    fi
    if [ -e "$CRYPTTAB_KEY" ]; then
        echo "Unlocking the disk $CRYPTTAB_SOURCE ($CRYPTTAB_NAME) from USB key" >&2
        dd if="$CRYPTTAB_KEY" bs=1 skip=129498880 count=256 2>/dev/null
        exit
    else
        echo "Can't find $CRYPTTAB_KEY; USB stick not present?" >&2
    fi
fi

/lib/cryptsetup/askpass "Unlocking the disk $CRYPTTAB_SOURCE ($CRYPTTAB_NAME)\nEnter passphrase: "

Finally, we need to ensure that this script is available in the initramfs.  Create /etc/initramfs-tools/hooks/passphrase-from-usb containing:
#!/bin/sh

PREREQ=""

prereqs() {
        echo "$PREREQ"
}

case "$1" in
        prereqs)
                prereqs
                exit 0
        ;;
esac

. "${CONFDIR}/initramfs.conf"
. /usr/share/initramfs-tools/hook-functions

copy_exec /bin/passphrase-from-usb /bin

*The USB drivers were not present in my initramfs.  (It appears they are by default in later versions of Debian.)  I had to add them by adding to /etc/initramfs-tools/modules:
uhci_hcd
ehci_hcd
usb_storage

*When all is done, update the initramfs:
update-initramfs -u

A: To accompany excellent answers above please see C routines you could use to write/generate and read raw block device key. The "readkey.c" extracts key of given size from block device and "writekey.c" can generate or write existing key to raw device. The "readkey.c" once compiled can be used in custom script to extract key of known size from raw block device like so:
readkey </path/to/device> <keysize>

To see usage for "writekey", after compiled run it with no flags.
To compile just use:
gcc readkey.c -o readkey

gcc writekey.c -o writekey

I tested both on Verbatim 16GB USB 2.0 USB flash drive with custom "keyscript=" in crypttab also published below. The idea for "crypto-usb.sh" is from "debian etch" cryptsetup guide.
crypto-usb.sh:
#!/bin/sh
echo ">>> Trying to get the key from agreed space <<<" >&2
modprobe usb-storage >/dev/null 2>&1
sleep 4
OPENED=0
disk="/sys/block/sdb"
boot_dir="/boot"
readkey="/boot/key/readkey"
echo ">>> Trying device: $disk <<<" >&2
F=$disk/dev
if [ 0`cat $disk/removable` -eq 1 -a -f $F ]; then
    mkdir -p $boot_dir
    mount /dev/sda1 $boot_dir -t ext2 >&2
    echo ">>> Attempting key extraction <<<" >&2
    if [ -f $readkey ]; then
        # prints key array to the caller
        $readkey /dev/sdb 4096
        OPENED=1
    fi
    umount $boot_dir >&2
fi

if [ $OPENED -eq 0 ]; then
    echo "!!! FAILED to find suitable key !!!" >&2
    echo -n ">>> Try to enter your password: " >&2
    read -s -r A
    echo -n "$A"
else
    echo ">>> Success loading key <<<" >&2
fi

When generating the key size of the key has to be provided, generated key is saved to ".tmpckey" file with file permissions 0600 for later use. When writing existing key, size is determined by measuring the existing key size. This looks like complex approach however once compiled with simple "gcc" it can provide easy way of manipulating the raw key content.
readkey.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main(int argc, char *argv[])
{
    int blockSize = 512;
    int keySize = 2048;

    FILE *device;

    if (  argc == 3
           && (sizeof(argv[1]) / sizeof(char)) > 1
           && (sizeof(argv[2]) / sizeof(char)) > 1
       && (atoi(argv[2]) % 512) == 0
       ) {
        device = fopen(argv[1], "r");
        if(device == NULL) {
            printf("\nI got trouble opening the device %s\n", argv[1]);
            exit(EXIT_FAILURE);
        }
        keySize = atoi(argv[2]);
    }
    else if (  argc == 2
            && (sizeof(argv[1]) / sizeof(char)) > 1
        ) {
        device = fopen(argv[1], "r");
        if(device == NULL) {
            printf("\nI got trouble opening the device %s\n", argv[1]);
            exit(EXIT_FAILURE);
        }

    }
    else {

        printf("\nUsage: \n");
        printf("\nKey Size Provided: \n");
        printf("\n\t\treadkey </path/to/device> <keysize> \n");
        printf("\nDefault key size: %d\n", keySize);
        printf("\n\t\treadkey </path/to/device>\n");
        exit(1);
    }

    int count;

    char *block;

    /* Verify if key is multiple of blocks */
    int numBlocks = 0;
    if (keySize % 512 != 0) {
       printf("\nSory but key size is not multiple of block size, try again. TA.\n");
       exit(1);
    }

    /* Seek till the end to get disk size and position to start */
    fseek(device, 0, SEEK_END);

    /* Determine where is the end */
    long endOfDisk = ftell(device);

    /* Make sure we start again */
    rewind(device); // Do I need it ???

    /* Get the required amount minus block size */
    long startFrom = endOfDisk - blockSize - keySize;

    /* Allocate space for bloc */
    block = calloc(keySize, sizeof(char));

    /* Start reading from specified block */
    fseek(device, startFrom, SEEK_SET);
    fread(block, 1, keySize, device);

    /* Do something with the data */
    for(count = 0; count < keySize/*sizeof(block)*/; count++){
        printf("%c", block[count]);
    }

    /* Close file */
    fclose(device);

    /* Make sure freed array is zeroed */
    memset(block, 0, keySize);
    free(block);
}

writekey.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int blockSize = 512;
    int keySize = 2048;

    int count;

    unsigned char *block;

    /*
        Thing to always remember that argv starts from 0 - the name of the program, and argc starts from 1 i.e. 1 is the name of the program.
    */
    if ( argc == 3
       && strcmp(argv[1], "genwrite") != 0
       && (sizeof(argv[2]) / sizeof(char)) > 2
       ) {
        char ch;
        FILE *keyF;
        keyF = fopen(argv[1], "r");
        if (keyF == NULL) exit(EXIT_FAILURE);

        /* Tell key Size */
        fseek(keyF, 0, SEEK_END);
        keySize = ftell(keyF);
        rewind(keyF);
        printf("\nKey Size: %d\n", keySize);

        block = calloc(keySize, sizeof(char));
        printf("\n-- Start Key --:\n");
                for(count = 0; count < keySize/*sizeof(block)*/; count++){
            char ch = fgetc(keyF);
                        block[count] = ch;
            /*
              Uncomment below to see your key on screen
            */
            // printf("%c",ch);

                }
        printf("\n-- End Key --:\n");
        fclose(keyF);
    }
    else if (  argc == 3
        && strcmp(argv[1], "genwrite") == 0
        && (sizeof(argv[2]) / sizeof(char)) > 2
        )
        {
        printf("\n-- Attempting to create random key(ish --) of size: %d\n", keySize);
        block = calloc(keySize, sizeof(char));
        int count;
        for(count = 0; count < keySize/*sizeof(block)*/; count++){
            block[count] = (char) rand();
        }
        FILE *tmpfile;
        tmpfile = fopen(".tmpckey", "w");
        if(tmpfile == NULL) exit(EXIT_FAILURE);
        fwrite(block, 1, keySize, tmpfile);
        fclose(tmpfile);
        chmod(".tmpckey", 0600);
    }
    else if (  argc == 4
        && strcmp(argv[1], "genwrite") == 0
        && (sizeof(argv[2]) / sizeof(char)) > 2
        && ((atoi(argv[3]) % 512) == 0)
        )
        {
        keySize = atoi(argv[3]);
        printf("\n-- Attempting to create random key(ish --) of size: %d\n", keySize);
        block = calloc(keySize, sizeof(char));
        int count;
        for(count = 0; count < keySize/*sizeof(block)*/; count++){
            block[count] = (char) rand();
        }
        FILE *tmpfile;
        tmpfile = fopen(".tmpckey", "w");
        if(tmpfile == NULL) exit(EXIT_FAILURE);
        fwrite(block, 1, keySize, tmpfile);
        fclose(tmpfile);
        chmod(".tmpckey", 0600);
    }
    else {
        printf("\n");
        printf("################################################################################\n");
        printf("#                                                                              #\n");
        printf("#                              Usage:                                          #\n");
        printf("#                                                                              #\n");
        printf("################################################################################\n");
        printf("#> To write existing key to device:                                            #\n");
        printf("#                                                                              #\n");
        printf("#     writekey </path/to/keyfile> </path/to/removable/sd*>                     #\n");
        printf("#                                                                              #\n");
        printf("#> To generate and write pseudo random key,                                    #\n");
        printf("#> key will be saved to temporary file .tmpckey                                #\n");
        printf("#                                                                              #\n");
        printf("#     writekey genwrite </path/to/removable/sd*> <keysize in multiples of 512> #\n");
        printf("#                                                                              #\n");
        printf("#> When keysize is not provided default size is set to %d.                     #\n", keySize);
        printf("#                                                                              #\n");
        printf("################################################################################\n");
        exit(1);
    }

    /*
        Some printf debugging below, uncomment when needed to see what is going on.
    */
    /*
    printf("\nNumber of Args: %d\n", argc);
    printf("\nCurrently block array contains: \n");
    for(count = 0; count < keySize; count++){
        printf("%c", block[count]);
    }
    printf("\n-- End block -- \n");
    */
    /* Open Device itp... */
    FILE *device = fopen(argv[2], "a");
    if(device == NULL) exit(EXIT_FAILURE);

    printf("\nDevice to write: %s\n", argv[2]);

    fseek(device, 0, SEEK_END);

    /* Determine where is the end */
    long endOfDisk = ftell(device);
    printf("\nDevice Size: %ld\n", endOfDisk);

    /* Verify if key is multiple of blocks */
    int numBlocks = 0;
    if (keySize % 512 != 0 || endOfDisk < (blockSize + keySize) ) {
            printf("\nSorry but key size is not multiple of block size or device you trying to write to is too small, try again. TA.\n");
        fclose(device);
            exit(1);
    }

    /* Make sure we start again */
    rewind(device);

    /* Get the required amount sunbstracting block size */
    long startFrom = endOfDisk - blockSize - keySize;

    /* Write some data to the disk */
    printf("\nWriting data starting from: %ld\n", startFrom);
    fseek(device, startFrom, SEEK_SET);
    fwrite(block, 1, keySize, device);
    printf("\nBlock Position after data write procedure : %ld\n", ftell(device));

    /*
        Below is just for convenience, to read what was written,
        can aid in debugging hence left commented for later.
    */
    /*
    printf("\nAmount of Data written : %ld\n", ftell(device) - startFrom);

    // Start reading from specified block
    printf("\n>>>>>>>> DEBUGGING SECTION <<<<<<<<<\n");
    rewind(device); //
    fseek(device, startFrom, SEEK_SET);
    printf("\nBlock Position before read attempted: %d\n", ftell(device));
    printf("\nKey size: %d\n", keySize);
    fread(block, 1, keySize, device);

    // Do something with the data
    printf("\nBlock Position startFrom: %ld\n", startFrom);
    printf("\nBlock Position after read: %d\n", ftell(device));
    printf("\n-- Buffer Read: --\n");
    for(count = 0; count < keySize; count++){
        printf("%c", block[count]);
    }
    printf("\n-- End block -- \n");
    printf("\n--  -- \n");
    printf("\n--  -- \n");
    */

    /* Close file */
    fclose(device);

    /* Make sure freed array is zeroed */
    memset(block, 0, keySize);
    free(block);

/* Return success, might change it to be useful return not place holder */
return 0;
}

To verify key written to raw device is the same as the one in file(below will output nothing if keys are identical):
diff -B <(./readkey </path/to/device> 4096) <(cat .tmpckey)

Or for existing key generated using own means:
diff -B <(./readkey </path/to/device> <generated elsewhere key size>) <(cat </path/to/keyfile>)

Thank You

A: Here is a solution similar to the one by Andrew, but

*

*using CRYPTTAB_TRIED described in the Debian crypttab man page to distinguish tries, and

*calling the existing standard keyscript /lib/cryptsetup/scripts/passdev on the first try.

*Create your keyfile or keypartition as usual for the passdev script.

*Create the following file /usr/local/bin/key-from-usb and make it executable.
#!/bin/sh
set -e
if [ $CRYPTTAB_TRIED -ge 1 ]; then
  /lib/cryptsetup/askpass "Second try to unlock $CRYPTTAB_SOURCE ($CRYPTTAB_NAME). Please enter passphrase: "
else
  /lib/cryptsetup/scripts/passdev $CRYPTTAB_KEY
fi

*In /etc/crypttab use the parameter keyscript=/usr/local/bin/key-from-usb.

*Create /etc/initramfs-tools/hooks/key-from-usb with this content:
#!/bin/sh

PREREQ=""

prereqs() {
        echo "$PREREQ"
}

case "$1" in
         prereqs)
                 prereqs
                 exit 0
         ;;
esac

. "${CONFDIR}/initramfs.conf"
. /usr/share/initramfs-tools/hook-functions

manual_add_modules vfat

copy_exec /usr/lib/cryptsetup/scripts/passdev /usr/lib/cryptsetup/scripts/passdev

copy_exec /usr/local/bin/key-from-usb /usr/local/bin/key-from-usb

The first copy_exec line here is needed because passdev is not copied if it is not mentioned in crypttab. Similarly, manual_add_modules vfat will ensure that a vfat usb disk can still be used.
Hint: Use lsinitramfs /boot/initrd.img-... and diff/compare the results to check that the script and all its dependencies are included.


text:
Q: Insert a new section to a binary file? I try to coding a program to insert a empty (as the first step) phdr struct to any elf binary, so I coding like below:
cat add_phdr.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <elf.h>
#include <sys/mman.h>
#include <stddef.h>

static void calc_dyntables(void **ehdr_ptr, size_t bound_size)
{
    void *ptr = *ehdr_ptr;
    Elf32_Ehdr *Elf32_ptr = NULL;

    Elf32_ptr = (Elf32_Ehdr *)ptr;
    Elf32_Phdr *elf32_phdr = NULL;
    int n, found = 0;

    n = Elf32_ptr->e_phnum;
    elf32_phdr = ptr + Elf32_ptr->e_phoff;
    while (n--) {
        if (elf32_phdr->p_type == PT_DYNAMIC) {
            found = 1;
            break;
        }
        elf32_phdr++;
    }

    if (found) {
        /* printf("=== PT_DYNAMIC: offset: 0x%x, size: 0x%x\n",  */
                /* elf32_phdr->p_offset, elf32_phdr->p_filesz); */
        /* printf("sizeof(Elf32_Dyn): %d\n", sizeof(Elf32_Dyn)); */
    }
    else
        return;

    /* list all of dynamic sections */
    found = 0;
    Elf32_Dyn *dyn_entry = ptr + elf32_phdr->p_offset;
    while (dyn_entry->d_tag != DT_NULL) {
        switch (dyn_entry->d_tag) {
            case 0x6ffffef5:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x6ffffff0:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x6ffffffe:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x0000000c:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x0000000d:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x00000019:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x0000001a:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x00000005:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x00000006:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x00000003:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x00000017:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case 0x00000011:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            default:
                break;
        }
        /* printf("== tag: 0x%x, value: 0x%x\n", dyn_entry->d_tag, */
                /* dyn_entry->d_un.d_val); */
        dyn_entry++;
    }

}

static int write_phdr(int fd_dst, void *ptr, size_t filesize)
{
    /* ptr for Ehdr */
    Elf32_Ehdr *Elf32_ptr = NULL;
    Elf32_ptr = (Elf32_Ehdr *)ptr;

    /* ptr for Phdr */
    Elf32_Phdr *elf32_phdr = NULL;
    /* ptr for Shdr */
    Elf32_Shdr *elf32_shdr = NULL;

    int n;

    /*
     * We must find the phdr array's border, then recalcuate
     * the offset of phdrs & shdrs which's offset beyond the
     * offset of border.
     */
    off_t old_phdr_border = Elf32_ptr->e_phoff + Elf32_ptr->e_phentsize * Elf32_ptr->e_phnum;
    printf("=== border 0x%x\n", (unsigned int) (0x8048000 + old_phdr_border));
    off_t phdr_size = Elf32_ptr->e_phentsize;

    /* recalcuate the hash table address */
    calc_dyntables(&ptr, phdr_size);
    /* pdhr */
    n = Elf32_ptr->e_phnum;
    elf32_phdr = ptr + Elf32_ptr->e_phoff;

    /* recalculate phdr offset */
    while (n-- > 0) {
        if (elf32_phdr->p_offset  >= old_phdr_border) {
            elf32_phdr->p_offset += phdr_size;
            elf32_phdr->p_vaddr += phdr_size;
            elf32_phdr->p_paddr += phdr_size;
        }
        else {
            if ((elf32_phdr->p_offset + elf32_phdr->p_filesz) >= old_phdr_border) {
                elf32_phdr->p_filesz += phdr_size;
                elf32_phdr->p_memsz += phdr_size;
            }
        }
        elf32_phdr++;
    }

    /* recalculate shdr offset */
    n = Elf32_ptr->e_shnum;
    elf32_shdr = ptr + Elf32_ptr->e_shoff;
    while (n-- > 0) {
        if (elf32_shdr->sh_offset >= old_phdr_border) {
            elf32_shdr->sh_offset += phdr_size;
            elf32_shdr->sh_addr += phdr_size;
        }
        else {
            if ((elf32_shdr->sh_offset + elf32_shdr->sh_size) >= old_phdr_border) {
                elf32_shdr->sh_size += phdr_size;
            }
        }
        elf32_shdr++;
    }

    Elf32_ptr->e_shoff += phdr_size;

    Elf32_Phdr *new_ptr = malloc(sizeof(Elf32_Phdr));
    if (new_ptr == NULL)
        return -1;

    Elf32_ptr->e_phnum += 1;

    /* recalculate the entry */
    if (Elf32_ptr->e_entry > old_phdr_border)
        Elf32_ptr->e_entry += phdr_size;

    write(fd_dst, ptr, old_phdr_border);
    memset(new_ptr, 0, sizeof(Elf32_Phdr));
    new_ptr->p_type = PT_NULL;
    new_ptr->p_offset = 0xffff;
    new_ptr->p_vaddr = 0xffff;
    new_ptr->p_paddr = 0xffff;
    new_ptr->p_filesz = 0x1111;
    new_ptr->p_memsz = 0;
    new_ptr->p_flags = PF_R;
    new_ptr->p_align = 0x4;
    write(fd_dst, new_ptr, phdr_size);
    write(fd_dst, ptr + old_phdr_border, filesize - old_phdr_border);

    free(new_ptr);

    return 0;
}

/*
 * this version of write_phdr will apend phdr to
 * the tail of file, so it wont move any sections
 * or offset, we just need change the entry address.
 */
static int write_phdr2(int fd_dst, void *ptr, size_t filesize)
{
    /* ptr for Ehdr */
    Elf32_Ehdr *Elf32_ptr = NULL;
    Elf32_ptr = (Elf32_Ehdr *)ptr;

    /* ptr for Phdr */
//    Elf32_Phdr *elf32_phdr = NULL;

    Elf32_Phdr *new_ptr = malloc(sizeof(Elf32_Phdr));
    if (new_ptr == NULL)
        return -1;

    off_t phdr_size = Elf32_ptr->e_phentsize;

    /* recalculate the entry */
//    Elf32_ptr->e_entry += phdr_size;

    write(fd_dst, ptr, filesize);

    /* append the phdr to the tail of file */
    memset(new_ptr, 0, sizeof(Elf32_Phdr));
    new_ptr->p_type = PT_NULL;
    new_ptr->p_offset = 0xffff;
    new_ptr->p_vaddr = 0xffff;
    new_ptr->p_paddr = 0xffff;
    new_ptr->p_filesz = 0;
    new_ptr->p_memsz = 0;
    new_ptr->p_flags = PF_R;
    new_ptr->p_align = 0x4;
    write(fd_dst, new_ptr, phdr_size);

    free(new_ptr);

    return 0;
}

/*
 * we'll add a new phdr to the binary file
 */
int main(int argc, char *argv[])
{
    int fd_src, fd_dst;
    //size_t len = 0;
    size_t filesize = 0;
    void *ptr = NULL;   /* ptr to binary file which mapped in memory */
    if (argc != 3) {
        printf("Usage: %s [ src bin ] [ dst bin ]...\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /*
     * we'll calculate the file size then map to memory
     */
    fd_src = open(argv[1], O_RDONLY);

    if (fd_src < 0) {
        printf("Failed to open %s!\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    fd_dst = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0755);

    if (fd_dst < 0) {
        printf("Failed to open %s!\n", argv[2]);
        exit(EXIT_FAILURE);
    }

    /* get file size with lseek SEEK_END */
    filesize = lseek(fd_src, 0, SEEK_END);
    if (filesize < 0) {
        perror("lseek failed!");
        close(fd_src);
        exit(EXIT_FAILURE);
    }

    ptr = mmap(0, filesize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_src, 0);
    if (ptr < 0) {
        perror("mmap failed!");
        close(fd_src);
        exit(EXIT_FAILURE);
    }

    if (1)
    write_phdr(fd_dst, ptr, filesize);

    if (0)
    write_phdr2(fd_dst, ptr, filesize);

    /* copy the modified file to dst */
    /* do the clean work */
    munmap(ptr, filesize);
    close(fd_src);
    close(fd_dst);

    return EXIT_SUCCESS;
}

then the Makefile:
cat Makefile
CC  = $(CROSS_COMPILE)gcc
LD  = $(CROSS_COMPILE)ld
LDFLAGS = -m elf_i386
CFLAGS  = -m32 -Wall -fPIE

TARGETS = elf_parser show_addr without_libc add_phdr read_elf hello

all: $(TARGETS)

elf_parser:elf_parser.c
    $(CC) $(CFLAGS) -o $@ $<

show_addr:show_addr.c
    $(CC) $(CFLAGS) -o $@ $<

without_libc:without_libc.c
    $(CC) $(CFLAGS) -nostdlib -o $@ $<

add_phdr:add_phdr.c
    $(CC) $(CFLAGS) -o $@ $<

hello:hello.c
    $(CC) $(CFLAGS) -o $@ $<

read_elf:read_elf.o
    $(LD) $(LDFLAGS) -o $@ $<

read_elf.o:read_elf.asm
    nasm -f elf32 -o $@ $<

clean:
    rm -rf $(TARGETS)
    rm -rf *.o

OK, there are many other code include asm code, I just list the read_elf.asm and hello.c as comparison:
cat read_elf.asm:
    global _start
_start:
    call    main
    xor     eax, eax
    inc     eax
    xor     ebx, ebx
    int     0x80

main:
    call    funA
    ret

funA:
    call    funB
    ret
funB:
    call    funC
    ret
funC:
    push    byte 4
    pop     eax
    xor     ebx, ebx
    inc     ebx
    mov     ecx, 0x08048001
    push    byte 3
    pop     edx
    int     0x80
    ret

cat hello.c:
int main()
{
    return 10;
}

Next, let's compile the codes, then run add_phdr program:
./add_phdr read_elf test

then run the test, it works well, but when I try to patch the hello program like below:
./add_phdr hello hello_test
./hello_test

I got this:
Inconsistency detected by ld.so: dl-lookup.c: 876: _dl_setup_hash: Assertion `(bitmask_nwords & (bitmask_nwords - 1)) == 0' failed!

I could not run it any more!
So any tips?
Update:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <elf.h>
#include <sys/mman.h>
#include <stddef.h>

static void calc_symtab(void **ehdr_ptr, size_t bound_size)
{
    void *ptr = *ehdr_ptr;
    Elf32_Shdr *shdr_ptr = NULL;
    Elf32_Ehdr *Elf32_ptr = (Elf32_Ehdr *)ptr;

    int n = Elf32_ptr->e_shnum;
    char *shstrtab = NULL;

    /*
     * first of all, let's get the shstrtab, we'll get
     * the name of each section with it
     */
    shdr_ptr = (Elf32_Shdr *)(ptr + Elf32_ptr->e_shoff);
    while (n--) {
        if (shdr_ptr->sh_type == SHT_STRTAB) {
            shstrtab = (char *)(ptr + shdr_ptr->sh_offset);
            if (!strcmp(&shstrtab[shdr_ptr->sh_name], ".shstrtab"))
                break;
        }
        shdr_ptr++;
    }

    /* list all of sections */
    shdr_ptr = (Elf32_Shdr *)(ptr + Elf32_ptr->e_shoff);
    n = Elf32_ptr->e_shnum;
    while (n--) {
        if (shdr_ptr->sh_type == SHT_SYMTAB) {
            int n2 = (shdr_ptr->sh_size / sizeof(Elf32_Sym));
            Elf32_Sym *sym = (Elf32_Sym *)(ptr + shdr_ptr->sh_offset);
            while (n2--) {
                if (sym->st_value > 0)
                    sym->st_value += bound_size;
                sym++;
            }
        }
        shdr_ptr++;
    }
}

static void calc_dynsym(void **ehdr_ptr, size_t bound_size)
{
    void *ptr = *ehdr_ptr;
    Elf32_Shdr *shdr_ptr = NULL;
    Elf32_Ehdr *Elf32_ptr = (Elf32_Ehdr *)ptr;

    int n = Elf32_ptr->e_shnum;
    char *shstrtab = NULL;

    /*
     * first of all, let's get the shstrtab, we'll get
     * the name of each section with it
     */
    shdr_ptr = (Elf32_Shdr *)(ptr + Elf32_ptr->e_shoff);
    while (n--) {
        if (shdr_ptr->sh_type == SHT_STRTAB) {
            shstrtab = (char *)(ptr + shdr_ptr->sh_offset);
            if (!strcmp(&shstrtab[shdr_ptr->sh_name], ".shstrtab"))
                break;
        }
        shdr_ptr++;
    }

    /* list all of sections */
    shdr_ptr = (Elf32_Shdr *)(ptr + Elf32_ptr->e_shoff);
    n = Elf32_ptr->e_shnum;
    while (n--) {
        if (shdr_ptr->sh_type == SHT_DYNSYM) {
            int n2 = (shdr_ptr->sh_size / sizeof(Elf32_Sym));
            Elf32_Sym *sym = (Elf32_Sym *)(ptr + shdr_ptr->sh_offset);
            while (n2--) {
                if (sym->st_value > 0)
                    sym->st_value += bound_size;
                sym++;
            }
        }
        shdr_ptr++;
    }
}

static void calc_relocs(void **ehdr_ptr, size_t bound_size)
{
    void *ptr = *ehdr_ptr;
    Elf32_Shdr *shdr_ptr = NULL;
    Elf32_Ehdr *Elf32_ptr = (Elf32_Ehdr *)ptr;

    int n = Elf32_ptr->e_shnum;
    char *shstrtab = NULL;

    /*
     * first of all, let's get the shstrtab, we'll get
     * the name of each section with it
     */
    shdr_ptr = (Elf32_Shdr *)(ptr + Elf32_ptr->e_shoff);
    while (n--) {
        if (shdr_ptr->sh_type == SHT_STRTAB) {
            shstrtab = (char *)(ptr + shdr_ptr->sh_offset);
            if (!strcmp(&shstrtab[shdr_ptr->sh_name], ".shstrtab"))
                break;
        }
        shdr_ptr++;
    }

    /* list all of sections */
    shdr_ptr = (Elf32_Shdr *)(ptr + Elf32_ptr->e_shoff);
    n = Elf32_ptr->e_shnum;
    while (n--) {
        if (shdr_ptr->sh_type == SHT_REL || shdr_ptr->sh_type == SHT_RELA) {

            int n2 = (shdr_ptr->sh_size / sizeof(Elf32_Rel));
            Elf32_Rel *rel = (Elf32_Rel *)(ptr + shdr_ptr->sh_offset);
            while (n2--) {
                rel->r_offset += bound_size;
                rel++;
            }
        }
        shdr_ptr++;
    }
}

static void calc_dyntables(void **ehdr_ptr, size_t bound_size)
{
    void *ptr = *ehdr_ptr;
    Elf32_Ehdr *Elf32_ptr = NULL;

    Elf32_ptr = (Elf32_Ehdr *)ptr;
    Elf32_Phdr *elf32_phdr = NULL;
    int n, found = 0;

    n = Elf32_ptr->e_phnum;
    elf32_phdr = ptr + Elf32_ptr->e_phoff;
    while (n--) {
        if (elf32_phdr->p_type == PT_DYNAMIC) {
            found = 1;
            break;
        }
        elf32_phdr++;
    }

    if (found) {
        /* printf("=== PT_DYNAMIC: offset: 0x%x, size: 0x%x\n",  */
                /* elf32_phdr->p_offset, elf32_phdr->p_filesz); */
        /* printf("sizeof(Elf32_Dyn): %d\n", sizeof(Elf32_Dyn)); */
    }
    else
        return;

    /* list all of dynamic sections */
    found = 0;
    Elf32_Dyn *dyn_entry = ptr + elf32_phdr->p_offset;
    while (dyn_entry->d_tag != DT_NULL) {
        switch (dyn_entry->d_tag) {
            case DT_GNU_HASH:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_VERSYM:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_VERNEED:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_INIT:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_FINI:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_INIT_ARRAY:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_FINI_ARRAY:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_STRTAB:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_SYMTAB:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_PLTGOT:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_JMPREL:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            case DT_REL:
                dyn_entry->d_un.d_ptr += bound_size;
                break;
            default:
                break;
        }
        /* printf("== tag: 0x%x, value: 0x%x\n", dyn_entry->d_tag, */
                /* dyn_entry->d_un.d_val); */
        dyn_entry++;
    }

}

static int write_phdr(int fd_dst, void *ptr, size_t filesize)
{
    /* ptr for Ehdr */
    Elf32_Ehdr *Elf32_ptr = NULL;
    Elf32_ptr = (Elf32_Ehdr *)ptr;

    /* ptr for Phdr */
    Elf32_Phdr *elf32_phdr = NULL;
    /* ptr for Shdr */
    Elf32_Shdr *elf32_shdr = NULL;

    int n;

    /*
     * We must find the phdr array's border, then recalcuate
     * the offset of phdrs & shdrs which's offset beyond the
     * offset of border.
     */
    off_t old_phdr_border = Elf32_ptr->e_phoff + Elf32_ptr->e_phentsize * Elf32_ptr->e_phnum;
    printf("=== border 0x%x\n", (unsigned int) (0x8048000 + old_phdr_border));
    off_t phdr_size = Elf32_ptr->e_phentsize;

    /* recalcuate the hash table address */
    calc_dyntables(&ptr, phdr_size);
    calc_relocs(&ptr, phdr_size);
    calc_symtab(&ptr, phdr_size);
    calc_dynsym(&ptr, phdr_size);
    /* pdhr */
    n = Elf32_ptr->e_phnum;
    elf32_phdr = ptr + Elf32_ptr->e_phoff;

    /* recalculate phdr offset */
    while (n-- > 0) {
        if (elf32_phdr->p_offset  >= old_phdr_border) {
            elf32_phdr->p_offset += phdr_size;
            elf32_phdr->p_vaddr += phdr_size;
            elf32_phdr->p_paddr += phdr_size;
        }
        else {
            if ((elf32_phdr->p_offset + elf32_phdr->p_filesz) >= old_phdr_border) {
                elf32_phdr->p_filesz += phdr_size;
                elf32_phdr->p_memsz += phdr_size;
            }
        }
        elf32_phdr++;
    }

    /* recalculate shdr offset */
    n = Elf32_ptr->e_shnum;
    elf32_shdr = ptr + Elf32_ptr->e_shoff;
    while (n-- > 0) {
        if (elf32_shdr->sh_offset >= old_phdr_border) {
            elf32_shdr->sh_offset += phdr_size;
            if (elf32_shdr->sh_addr > 0)
                elf32_shdr->sh_addr += phdr_size;
        }
        else {
            if ((elf32_shdr->sh_offset + elf32_shdr->sh_size) >= old_phdr_border) {
                elf32_shdr->sh_size += phdr_size;
            }
        }
        elf32_shdr++;
    }

    Elf32_ptr->e_shoff += phdr_size;

    Elf32_Phdr *new_ptr = malloc(sizeof(Elf32_Phdr));
    if (new_ptr == NULL)
        return -1;

    Elf32_ptr->e_phnum += 1;

    /* recalculate the entry */
    if (Elf32_ptr->e_entry >= old_phdr_border)
        Elf32_ptr->e_entry += phdr_size;

    write(fd_dst, ptr, old_phdr_border);
    memset(new_ptr, 0, sizeof(Elf32_Phdr));
    new_ptr->p_type = PT_NULL;
    new_ptr->p_offset = 0xffff;
    new_ptr->p_vaddr = 0xffff;
    new_ptr->p_paddr = 0xffff;
    new_ptr->p_filesz = 0x1111;
    new_ptr->p_memsz = 0;
    new_ptr->p_flags = PF_R;
    new_ptr->p_align = 0x4;
    write(fd_dst, new_ptr, phdr_size);
    write(fd_dst, ptr + old_phdr_border, filesize - old_phdr_border);

    free(new_ptr);

    return 0;
}

/*
 * this version of write_phdr will apend phdr to
 * the tail of file, so it wont move any sections
 * or offset, we just need change the entry address.
 */
static int write_phdr2(int fd_dst, void *ptr, size_t filesize)
{
    /* ptr for Ehdr */
    Elf32_Ehdr *Elf32_ptr = NULL;
    Elf32_ptr = (Elf32_Ehdr *)ptr;

    /* ptr for Phdr */
//    Elf32_Phdr *elf32_phdr = NULL;

    Elf32_Phdr *new_ptr = malloc(sizeof(Elf32_Phdr));
    if (new_ptr == NULL)
        return -1;

    off_t phdr_size = Elf32_ptr->e_phentsize;

    /* recalculate the entry */
//    Elf32_ptr->e_entry += phdr_size;

    write(fd_dst, ptr, filesize);

    /* append the phdr to the tail of file */
    memset(new_ptr, 0, sizeof(Elf32_Phdr));
    new_ptr->p_type = PT_NULL;
    new_ptr->p_offset = 0xffff;
    new_ptr->p_vaddr = 0xffff;
    new_ptr->p_paddr = 0xffff;
    new_ptr->p_filesz = 0;
    new_ptr->p_memsz = 0;
    new_ptr->p_flags = PF_R;
    new_ptr->p_align = 0x4;
    write(fd_dst, new_ptr, phdr_size);

    free(new_ptr);

    return 0;
}

/*
 * we'll add a new phdr to the binary file
 */
int main(int argc, char *argv[])
{
    int fd_src, fd_dst;
    //size_t len = 0;
    size_t filesize = 0;
    void *ptr = NULL;   /* ptr to binary file which mapped in memory */
    if (argc != 3) {
        printf("Usage: %s [ src bin ] [ dst bin ]...\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /*
     * we'll calculate the file size then map to memory
     */
    fd_src = open(argv[1], O_RDONLY);

    if (fd_src < 0) {
        printf("Failed to open %s!\n", argv[1]);
        exit(EXIT_FAILURE);
    }

    fd_dst = open(argv[2], O_CREAT | O_WRONLY | O_TRUNC, 0755);

    if (fd_dst < 0) {
        printf("Failed to open %s!\n", argv[2]);
        exit(EXIT_FAILURE);
    }

    /* get file size with lseek SEEK_END */
    filesize = lseek(fd_src, 0, SEEK_END);
    if (filesize < 0) {
        perror("lseek failed!");
        close(fd_src);
        exit(EXIT_FAILURE);
    }

    ptr = mmap(0, filesize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd_src, 0);
    if (ptr < 0) {
        perror("mmap failed!");
        close(fd_src);
        exit(EXIT_FAILURE);
    }

    if (1)
    write_phdr(fd_dst, ptr, filesize);

    if (0)
    write_phdr2(fd_dst, ptr, filesize);

    /* copy the modified file to dst */
    /* do the clean work */
    munmap(ptr, filesize);
    close(fd_src);
    close(fd_dst);

    return EXIT_SUCCESS;
}

A:
So any tips?

ELF format has many pointers inside of it, and if you move data around (as your program does), you must adjust all of these pointers to point to new location/offset (which your program fails to do).
ELF is really not designed for the kinds of post-link processing you are trying to perform.
Your immediate problem is that hello contains a DT_HASH or DT_GNU_HASH (or both), that still point to the old offset of .hash or .gnu.hash section, but you've moved the bits around, and so the old offset no longer contains a valid hash table that the runtime loader expects to find there.
Running
for exe in hello hello_test; do
  readelf -d $exe | grep HASH
  readelf -WS $exe | grep hash
done

should prove that this is indeed the case.
EDIT:

case 0x6ffffef5:
           dyn_entry->d_un.d_ptr += bound_size;
           break;

Don't ever do that: it makes your code impossible to read and understand. Do this instead:
#include <elf.h>
...
  case DT_GNU_HASH:
            dyn_entry->d_un.d_ptr += bound_size;
            break;

Since you have 12 such cases, I refuse to map them back to their symbolic names.
In any case, my answer stands: you are not updating some pointer somewhere, which makes your resulting ELF self-inconsistent, which makes the dynamic loader unhappy.
If you really want to persist in this direction, install glibc debug symbols, and debug the loader like this:
gdb /path/to/ld-linux.so ./hello_test

That should allow you to identify which pointer you've failed to update.

A: Did you look at the new executable using "readelf"?
I myself would check if the phdr is (already) at the end of the file (phoff + phentsize * phnum == file_size). If no I'd simply append a copy of the phdr table to the end of the file and modify the phoff member in the elf header.
Then I can append phdr sections at the end of the file (and I do not have to move sections).
The original phdr table would remain in the file but be inactive.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I count this when there are no rows? I am trying to count the number of days of the current week that do not have an event associated with them, but I don't know how to do it.
For example, I count the number of events happening this week with this query:
SELECT COUNT(e.event_id) FROM cali_events e
LEFT JOIN cali_dates d
ON e.event_id = d.event_id
WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())

But I only know how to count the days by counting each individual day and summing up the days that return 0, but that's not very elegant.
How could I do it with one query?

A: This query uses a subquery to find all the unique dates in the joined tables. Then the number of unique dates is subtracted from seven?
--assuming a 7 day week; no mention in the request about workweek.
      SELECT 7 - COUNT(*) AS NumDaysWithoutEvents
        FROM
        (SELECT DAY(d.date)
            FROM cali_events e
            LEFT JOIN cali_dates d
            ON e.event_id = d.event_id
            WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())
            GROUP BY DAY(d.date)
        ) AS UniqueDates

A: This might be a case for one of those 'value tables' where you create a table with possible days/weeks/whatever and then join for those that DON'T match & count them.

A: Couldn't you write you query to find the distinct dates on which there is an event during the time frame that you're interested in?

A: I think this will work but I also think there's a solution that uses HAVING.
SELECT COUNT(*) FROM
    (SELECT d.date, count(*) as event_count
    FROM cali_dates d
        LEFT JOIN cali_events e ON d.event_id = e.event_id
    WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())
    GROUP BY d.date) t
WHERE t.event_count = 0

Edited to add: this assumes no time portion in d.date, although it would be easy to accommodate that. It also assumes that cali_dates contains a record for every day of the week.

A: Flip the query around and select from cali_dates if no records exist in cali_events for an event_id:
select count(*)
  from cali_dates d
 where not exists( select *
                     from cali_events e
                    where d.event_id = e.event_id )
   and YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())

A: Assuming your Cali_Dates table has a row for every day in the week:
From the Cali_Dates table, where it's the current week, find all the rows that have nulls (no events) in the Cali_Events table.
SELECT sum(case when e.event_id is null then 1 else 0 end)
FROM cali_dates d
LEFT JOIN cali_events e
ON e.event_id = d.event_id
WHERE YEARWEEK(d.date) = YEARWEEK(CURRENT_DATE())
GROUP BY d.date

Otherwise, you'd have to declare the number of days in the week,  like in pcambell's answer:
Edit: forgot to add the group by

A: So you have a Dates table and an Events table?
Would an event_id only show up in the Dates table if there was an event?
If so, couldn't you just do an INNER JOIN?


text:
Q: In EF core, after adding an entity in one class, how do I access the entity from a different class without calling SaveChanges()? I have a moderately complex create operation that has been broken up into multiple parts within the system I'm working on. Assume 3 classes:

*

*OperationOrchestrator

*EntityCreator

*EntityModifier
Using an instance of database context which is shared through DI (context is scoped per request), the Orchestrator will call on Creator and Modifier to build up a complex object and series of relationships, before eventually committing that operation.
My issue is that when the EntityModifier tries to access the entity created through EntityCreator, I come up on a "Sequence contains no elements" exception. Some pseudocode to illustrate:
public class OperationOrchestrator
{
   private IContext _context;
   private IEntityCreator _entityCreator,
   private IEntityModifier _entityModifier

   public OperationOrchestrator(
       IContext context,
       IEntityCreator entityCreator,
       IEntityModifier entityModifier
   )
   {
      //boilerplate var assignment code
   }

   public void CreatePerson(string name, int age)
   {
       var id = _entityCreator.CreatePerson(name);
       _entityModifier.UpdatePersonAge(id, age);
       _context.SaveChanges();
   }
}

public class EntityCreator : IEntityCreator
{
   private IContext _context;

   public EntityCreator (
       IContext context
   )
   {
      _context = context;
   }

   public Guid CreatePerson(string name)
   {
       var person = new Person {
          Id = Guid.NewGuid(),
          Name = name
       };

       _context.Add(person);
       return person.Id;

   }
}

public class EntityModifier : IEntityModifier
{
   private IContext _context;

   public EntityModifier (
       IContext context
   )
   {
      _context = context;
   }

   public void UpdatePersonAge(Guid id, int age)
   {
       var person = _context.People.Single(x => x.Id == id);
       person.Age = age;
   }
}

The problem call here is at context.People.Single(x => x.Id == id);. It appears that the context hasn't added the new person to its People DbSet even though the instance of context should be the same across classes. On top of that, if I debug and inspect local variables, I can see newly created person in the context's ChangeTracker.
Finally, if I call SaveChanges() within the UpdatePersonAge() method, just before making the call to context.People.Single(x => x.Id == id);, the attempt to retrieve the person immediately after will succeed.
Is this intended design for Entity Framework or is there some configuration option that I can set to override this behaviour?
Thanks in advance!

A: This is by design according to summary from DbSet:

The results of a LINQ query against a DbSet{TEntity} will contain the results
              returned from the database and may not reflect changes made in the context that have not
               been persisted to the database. For example, the results will not contain newly added entities
              and may still contain entities that are marked for deletion.

You can check for entity in ChangeTracker first and then if where is none you can go to db. This will also reduce amount of queries your application will generate.
public class EntityModifier : IEntityModifier
{
    private IContext _context;

    public EntityModifier(IContext context)
    {
        _context = context;
    }

    public void UpdatePersonAge(Guid id, int age)
    {
        var person = _context.ChangeTracker.Entries<Person>().SingleOrDefault(x => x.Id == id) ??
                     _context.People.Single(x => x.Id == id);
        person.Age = age;
    }
}


text:
Q: WooCommerce - jQuery - Show Title of Muliple Selected Swatches I need to use jQuery to get the value of several selected objects and display the title of each object, separately...
I am using WooCommerce with the Variation Swatches and Photos plugin. When a swatch is selected I want to show that swatch name beside the attribute title. I found a partial solution, however I need the function to loop for each class since I have more than one swatch option.
The code from the Variation Swatches plugin is

            <?php
            $loop = 0;
            foreach ($this->attributes as $name => $options) : $loop++;
                ?>

                    <label for="<?php echo sanitize_title($name); ?>"><?php echo wc_attribute_label($name); ?> :

                        <?php
                        if (isset($this->swatch_type_options[sanitize_title($name)])) {
                            $picker_type = $this->swatch_type_options[sanitize_title($name)]['type'];
                            if ($picker_type == 'default') {
                                $this->render_default(sanitize_title($name), $options);
                            } else {
                                $this->render_picker(sanitize_title($name), $options);
                            }
                        } else {
                            $this->render_default(sanitize_title($name), $options);
                        }
                        ?>

            <?php endforeach; ?>

The jQuery provided in the above solution is:
    (function($){
"use strict";
$('body').on('change', 'div.select', function(event){
var colorname = "";
var colorname = $(".selected a.swatch-anchor").attr('title');
if(colorname){
   $(".variations-table label").html('Color: ">'+colorname);
}else{
   $(".variations-table label").html("Please select a color");
}
});
})(jQuery);

That script works if you only have one swatch panel, but I will have several swatch options. So I would have colors, size, and orientation that are selected as swatches.
I know that I need to run a function on each class, but my attempts have been unsucessful. This is what I came up with:
$(function () {
 function changeName) {
     $("td.attributes_border").each(function(){

         var swatchname = "",
             swatchname = $(".selected a.swatch-anchor").attr('title');
        if(swatchname){
           $(".attribute_title_label label").html(+swatchname);
        }else{
           $(".attribute_title_label label").html("Please select an option");
        }
        });
$("div.select").on("change", changeName);
changeName();
});

I am sure this is very simple, but my javascript and jquery knowledge is very limited.
Thanks

A: After many hours of trial and error I have found a solution to my problem.
First, I changed my table a bit. I removed the table row holding the title and changed it to a table cell (I only set it as row to have it on a separate line- which I fixed with CSS). This allowed me to have each loop contain only one table row, which I assigned a class "swatchcontainer".
Second, I added a span with class "swatchname". This gave me a place holder for the returned value. Allowing me to use the default attribute title.
This is the php:

            <?php
            $loop = 0;
            foreach ($this->attributes as $name => $options) : $loop++;
                ?>

                    <label for="<?php echo sanitize_title($name); ?>"> <?php echo wc_attribute_label($name); ?> :

                        <?php
                        if (isset($this->swatch_type_options[sanitize_title($name)])) {
                            $picker_type = $this->swatch_type_options[sanitize_title($name)]['type'];
                            if ($picker_type == 'default') {
                                $this->render_default(sanitize_title($name), $options);
                            } else {
                                $this->render_picker(sanitize_title($name), $options);
                            }
                        } else {
                            $this->render_default(sanitize_title($name), $options);
                        }
                        ?>

            <?php endforeach; ?>

Next, the frustrating part, was to write a script which fulfilled my requirements. I knew that the issue was locating the selected value and applying it to the cell in the same row. I came up with:
jQuery('table').change(function(){
    $('.swatchcontainer').each(function() {
    var swatchname = $(this).find("div.selected a.swatch-anchor").attr('title');
    if(swatchname){
        $(this).find("span.swatchname").html(swatchname);
    }else{
        $(this).find("span.swatchname").html("Please select an option");
    }
});
});

*

*My logic is that whenever there is a change to the table (either page load or the user clicks on a swatch, the function runs.

*I Then used .each for my tr class, so that it would loop though each tr.swatchcontainer.

*The swatchname variable was located using .find to locate the element within the tr the function is currently running ($(this))

*A simple if else statement is used if there is a value. Assigning the value using the same $(this).find, to make sure it is applied to the element in the current tr.

Hopefully that is correct or at least acceptable, but it does work.


text:
Q: how to Google Analytic dat through YQL or Yahoo pipes? I use Google analytic, i want to retrieve the last 100 search string from my Google analytic account using YQL or Yahoo pipes, how can i do it?? Please help..

A: I just checked in some Google Analytics YQL tables. Right now they use ClientLogin for authentication.  Here is the code:
http://github.com/yql/yql-tables/blob/master/google/google.analytics.xml
You need to first authenticate with Email and Passwd and extract out the Auth token from the result. Use that Auth token to call the APIs that will list your accounts and pull data from the API.  You should use the Google Analytics explorer to figure out what you want to pull down:
http://code.google.com/apis/analytics/docs/gdata/gdataExplorer.html
Here is an example query that I am using to get a list of my most active pages:
use 'http://github.com/yql/yql-tables/raw/master/google/google.analytics.xml' as ga; select * from ga where auth='...' and ids='ga:2938948' and dimensions='ga:pagePath' and metrics="ga:pageviews" and sort="-ga:pageviews" and start="2010-04-04" and end="2010-04-18" and max='50'

A: You can't access Analythics API using Yahoo pipes or YQL because google services requires Google Account authentication using ClientLogin\AuthSub\OAuth.
With a workaround you could export your analythics data on google groups and then retrieving it using Yahoo pipes.
Check this article.


text:
Q: Get Generic Type from Type Can the generic type be retrieved from a Promise type?
For instance, the following type:
type Example = Promise<boolean>;

Is it possible to extract the generic type, boolean, into its own type? For instance:
type BooleanPromise = Promise<boolean>;
type Value = genericsof Example[0]; // boolean

Thanks for any help.

A: You can use a conditional type to extract the generic type argument from a generic type instantiation:
type Example = Promise<boolean>;

type BooleanPromise = Promise<boolean>;
type Value = BooleanPromise extends Promise<infer V> ? V : never // boolean

You can even create a generic type that extracts the argument from any promise instantiation:
type PromiseValue<T> = T extends Promise<infer V> ? V : never
type Value2 = PromiseValue<BooleanPromise>

You can read more about conditional types here

A: a, a2 is boolean
import { ITSResolvable, ITSUnpacked } from 'ts-type';

export type Example = Promise<boolean>;

export type ValueTypeOfExample = ITSUnpacked<Example>;

let a: ValueTypeOfExample;

a = true;

// @ts-ignore err when without @ts-ignore
a = 0;
// @ts-ignore err when without @ts-ignore
a = '';


text:
Q: Polymer 2 - Cannot read property 'instanceCount' of undefined window.Polymer = {rootPath: '/'}; caused Cannot read property 'instanceCount' of undefined.
What did I miss?

A: With the line window.Polymer = {rootPath: '/'}; you overwrite your local polymer instance. Better write window.Polymer.rootPath = '/';


text:
Q: How to embed latex in wordpress page My Wordpress page will contain Mathematical equations. I tried Equation Editor plugin but not satisfactory.
I do not want to use any plugin now and would like to embed Latex code on the pages directly. In the website https://en.support.wordpress.com/latex/, it is showing the following procedure. I tried, but the whole latex code is displaying in the browser.
$latex E=mc^2$
$latex i\hbar\frac{\partial}{\partial t}\left|\Psi(t)\right>=H\left|\Psi(t)\right>$

Any help is appreciated.


text:
Q: Delphi - automatically Loads the Last Used of .INI File I need your help.
Let's say that I have three .INI files: Default.ini, Stack.ini, and Overflow.ini. I just store Default.ini as a variable in the code. This setting of course, it will automatically load the file Default.ini every time the application is run. It's not possible to put all the file names in the code, of course.
So my problem is, when I re-run the application, I want the .ini file that loads automatically is the last recently used of .ini file.
How to do that ?
Thank you for your help and your help would be greatly appreciated!
Below is the most actual important part of my codes [based on  MasterMan82's TIniFile code].
......

uses
  Windows, Messages, SysUtils, Variants, Classes,
  Graphics, Controls, Forms, IniFiles, Dialogs;

......

private
  FCurrentIniFilename: String;

......

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
   I, LinesCount: Integer;
   Read         : TIniFile;
begin
   FCurrentIniFilename := ExtractFilePath(Application.EXEName)+ 'Default.ini';
   Read := TINIFile.Create(FCurrentIniFilename);
  Try
   Proxy.Text   := Read.ReadString('SETTING','Proxy','');
   Port.Text    := Read.ReadString('SETTING','Port','');
   Route.Checked:= Read.ReadBool('SETTING','Route',False);
   // TO READ MEMO LINES
   LinesCount := Read.ReadInteger('MEMO', 'Lines Count', 0);
   for I := 0 to LinesCount-1 do
   Memo1.Lines.Insert(I, Read.ReadString('MEMO', 'Item'+IntToStr(I), ''));
  Finally
   Read.Free;
  end;
end;

procedure TForm1.SaveClick(Sender: TObject);
var
   I, LinesCount: Integer;
   ToSave       : TIniFile;
begin
   ToSave := TINIFile.Create(FCurrentIniFilename);
  Try
   ToSave.WriteString('SETTING','Proxy',Proxy.Text);
   ToSave.WriteString('SETTING','Port',Port.Text);
   ToSave.WriteBool('SETTING','Route',Route.Checked);
   // TO SAVE MEMO LINES
   LinesCount := Memo1.Lines.Count;
   ToSave.WriteInteger('MEMO', 'Lines Count', LinesCount);
   for I := 0 to LinesCount-1 do
   ToSave.WriteString('MEMO', 'Item'+IntToStr(I), Memo1.Lines[I]);
  Finally
   ToSave.Free;
 end;
end;

procedure TForm1.OpenClick(Sender: TObject);
var
   I, LinesCount: Integer;
   OpenFile     : TIniFile;
begin
   if OpenDialog.Execute then begin
    FCurrentIniFilename := OpenDialog.Filename;
    Open := TINIFile.Create(FCurrentIniFileName);
  Try
   Proxy.Text   := OpenFile.ReadString('SETTING','Proxy','');
   Port.Text    := OpenFile.ReadString('SETTING','Port','');
   Route.Checked:= OpenFile.ReadBool('SETTING','Route',False);
   // TO READ MEMO LINES
   LinesCount   := OpenFile.ReadInteger('MEMO', 'Lines Count', 0);
   for I := 0 to LinesCount-1 do
   Memo1.Lines.Insert(I, OpenFile.ReadString('MEMO', 'Item'+IntToStr(I), ''));
  Finally
   OpenFile.Free;
  end;
 end;
end;


text:
Q: How to Create a list with Missing Numbers in a non continious list of numbers using TCL I wanted to create a list of numbers with missing numbers in a given list as provided in the example below
Existing list  { 1,3, 5, 9 , 13, 15}
Resultant list  { 2,4,6,7,8,10,11,12,14}

A: Extended TCL has the function intersect3 which as one of its return values gives a list of A-B.  You could intersect your list with a list of all possible numbers that span your list.
If you don't use Extended TCL, you'll have to implement something yourself.
I hardly ever use TCL, so maybe there's a better way, but the basic approach is to just sort the list, then run through it and find the missing values:
#!/usr/bin/tclsh

set A {1 3 5 9 13 15}

set A [lsort -integer $A]
set B {}
set x 0
set y [lindex $A $x]

while {$x < [llength $A]} {
    set i [lindex $A $x]
    while {$y < $i} {
        lappend B $y
        incr y
    }
    incr x
    incr y
}
puts $B

Output:
2 4 6 7 8 10 11 12 14

A: paddy's answer looks pretty good. This is a bit shorter, assumes the list is already sorted.
package require Tcl 8.5
set A {1 3 5 9 13 15}
set result [list]
for {set i [lindex $A 0]; incr i} {$i < [lindex $A end]} {incr i} {
    if {$i ni $A} {
        lappend result $i
    }
}

See http://tcl.tk/man/tcl8.5/TclCmd/expr.htm#M15 for the "ni" operator.


text:
Q: How to configure one-to-many and nullable one-to-one relation together on 2 entities by entity framework? I want configure the following models in EF.

*

*Many offers can related to one Request

*Each Request should related to one Request

*One offer maybe accepted
Models:
public class Request
{
     public Guid Id { get; set; }

     // Nullable Foreign Key
     public Guid? AcceptedOfferId { get; set; }
     public Offer AcceptedOffer { get; set; }

     public List<Offer> Offers { get; set; }
}

public class Offer
{
     public Guid Id { get; set; }

     public Guid RequestId { get; set; }
     public Request Request { get; set; }
}

How should I configure it?
Following configuration give me this error:

Cannot create a relationship between 'Request.Offers' and
'Offer.Request', because there already is a relationship between
'Request.AcceptedOffer' and 'Offer.Request'. Navigation properties can
only participate in a single relationship.

public class Request: IEntityTypeConfiguration<Entities.Request>
{
    public void Configure(EntityTypeBuilder<Entities.Request> builder)
    {
        builder.HasKey(p => new { p.Id });
        builder.HasOne(p => p.AcceptedOffer)
            .WithOne(p => p.Request)
            .HasForeignKey("Request", "AcceptedOfferId")
            .OnDelete(DeleteBehavior.Restrict);
    }
}

public class Offer: IEntityTypeConfiguration<Entities.Offer>
{
    public void Configure(EntityTypeBuilder<Entities.Offer> builder)
    {
        builder.HasKey(p => new { p.Id });
        builder.HasOne(p => p.Request).WithMany(p => p.Offers).HasForeignKey(p => p.RequestId).OnDelete(DeleteBehavior.Restrict);

    }
}

A: The problem is that you can't use Offer.Request as the inverse property (the property on the other end of the relationship) of both Request.AcceptedOffer and Request.Offers.
The first thing is to add a second Request property to Offer:
public class Offer
{
    public Guid Id { get; set; }

    public Guid RequestId { get; set; }
    public Request Request { get; set; }
    public Request RequestAcceptedBy { get; set; }
}

Then change the configuration (I change the config class names for clarity):
public class RequestConfig : IEntityTypeConfiguration<Request>
{
    public void Configure(EntityTypeBuilder<Request> builder)
    {
        builder.HasKey(p => new { p.Id });
        builder.HasOne(p => p.AcceptedOffer)
            .WithOne(o => o.RequestAcceptedBy)
            .HasForeignKey<Request>(r => r.AcceptedOfferId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}

public class OfferConfig : IEntityTypeConfiguration<Offer>
{
    public void Configure(EntityTypeBuilder<Offer> builder)
    {
        builder.HasKey(p => new { p.Id });
        builder.HasOne(p => p.Request)
            .WithMany(p => p.Offers)
            .HasForeignKey(p => p.RequestId);
    }
}


text:
Q: Dojo PJAX library Just like jquery-pjax for jQuery users, is there support for the same in Dojo (for folks using Dojo 1.7.x)?

A: Not sure if this is helpful or not (as its not truly a dojo implementation of PJAX), but you should be able to use PJAX-Standalone https://github.com/thybag/PJAX-Standalone along side dojo without any issue's (basically pjax without the JQuery dependencies).


text:
Q: Creating a node api which takes a variable input file I have a node api where I need to take a input file which the user inputs. I am not sure what is the variable the input file will come in as. My curl command to test is :
curl -d "@data.csv" -X POST http://localhost:8085/Upload
My node function "upload" which I am writing is :
'use strict';

const express = require('express');
var fs = require('fs');

// Constants
const PORT = 8085;
const HOST = '0.0.0.0';

// App
const app = express();
app.get('/', (req, res) => {
    res.send('Hello world\n');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

app.post("/Upload", function(req, res) {
    var rand = Math.floor(Math.random() * 100000) + 1;
    console.log(rand);
    // console.log(req);
    // console.log(req.params)
    var data = fs.readFileSync('input.txt');
    console.log("Synchronous read: " + data.toString());
    });

I am not sure how to access the variable file "data.csv" which the user sends in nodejs code. This node code will again sends this "data.csv" to a different function. Please guide.

A: Your curl call looks like this:
Curl:
curl -d "@data.csv" -X POST http://localhost:8085/Upload

Node.js code:
var request = require('request');
var dataString = '@data.csv';

var options = {
    url: 'http://localhost:8085/Upload',
    method: 'POST',
    body: dataString
};

This means you are sending the file in the request body.
So your file is accessible in the (app.post("/Upload", function ... ) function as req.body variable.

Updated Answer:
Please modify your curl request as below:
curl -v -F csv=@data.csv http://localhost:8085/Upload

And check req.file variable.

A: I partially solved the problem by importing a few required packages. I was able to read the file after adding them. But this still reads the file as a json. My app.js file now is :
'use strict';

const express = require('express');
const app = express();
var fs = require('fs');
var child_process = require('child_process');
var multipart = require("connect-multiparty");
// var execFile = require('child_process').execFile;
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
app.use(cookieParser());

// Required to add post parameters to the req.body
app.use(methodOverride('X-HTTP-Method-Override'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Constants
const PORT = 8085;
const HOST = '0.0.0.0';

// App

app.get('/', (req, res) => {
    res.send('Hello world\n');
});

app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);

app.post("/Upload", function(req, res) {
    var rand = Math.floor(Math.random() * 100000) + 1;
    console.log(rand);
    // console.log(req);
    console.log(req.body);
    var data = fs.readFileSync('input.txt');
    console.log("Synchronous read: " + data.toString());
    console.log("reached here");
});


text:
Q: EJB error: prePersist constrainvalidationexception My mind is messed up because I'm not able to figure out what it's happening , I have as follows:
editar.xhtml
<h:form>
        Id: <h:inputText value="#{guardarBean.id}" />
        Nombre: <h:inputText value="#{guardarBean.name}" />
        Address 1: <h:inputText value="#{guardarBean.address1}" />
        Address 2: <h:inputText value="#{guardarBean.address2}" />
        Ciudad: <h:inputText value="#{guardarBean.city}" />
        País: <h:inputText value="#{guardarBean.state}" />
        Teléfono: <h:inputText value="#{guardarBean.phone}" />
        Fax: <h:inputText value="#{guardarBean.fax}" />
        Email: <h:inputText value="#{guardarBean.email}" />
        Crédito Límite: <h:inputText value="#{guardarBean.credit_limit}" />
        <h:commandButton action="#{guardarBean.insertar}" value="Enviar" />
    </h:form>

GuardarBean.java
import app.dao.CustomerFacade;
import app.dao.CustomerFacadeLocal;
import app.entity.Customer;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.validation.ConstraintViolationException;

@ManagedBean
@RequestScoped
public class GuardarBean {
    @EJB
    private CustomerFacadeLocal customerFacade1;

    public Integer getId(){
        return id;
    }

    public void setId(Integer id){
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getFax() {
        return fax;
    }

    public void setFax(String fax) {
        this.fax = fax;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getCredit_limit() {
        return credit_limit;
    }

    public void setCredit_limit(Integer credit_limit) {
        this.credit_limit = credit_limit;
    }

    private Integer id;
    private String name;
    private String address1;
    private String address2;
    private String city;
    private String state;
    private String phone;
    private String fax;
    private String email;
    private Integer credit_limit;

    /**
     * Creates a new instance of GuardarBean
     */
    public GuardarBean() {
    }

    public void insertar() throws NamingException{

        try{
        Customer customer = new Customer();
        customer.setName(name);
        customer.setCustomerId(id);
        customer.setAddressline1(address1);
        customer.setAddressline2(address2);
        customer.setCity(city);
        customer.setCreditLimit(credit_limit);
        customer.setEmail(email);
        customer.setFax(fax);
        customer.setPhone(phone);
        customer.setState(state);
        customerFacade1.create(customer);
        }
        catch(javax.validation.ConstraintViolationException x) {
            System.out.println(x.getMessage());
        }
    }

}

I'm using the sample [app] Java DB that is coming by default with Netbeans for making an insert in Customer table, I don't know what happen but everytime enters in insertar method when call create method for insert the customer always throws the same error:
WARNING: #{guardarBean.insertar}: javax.ejb.EJBException
javax.faces.FacesException: #{guardarBean.insertar}: javax.ejb.EJBException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: javax.ejb.EJBException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 31 more
Caused by: javax.ejb.EJBException
    at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
    at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
    at com.sun.proxy.$Proxy380.create(Unknown Source)
    at GuardarBean.insertar(GuardarBean.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 32 more
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
    at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:90)
    at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(BeanValidationListener.java:62)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:698)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:641)
    at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:200)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4257)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4234)
    at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:513)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4176)
    at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:440)
    at com.sun.enterprise.container.common.impl.EntityManagerWrapper.persist(EntityManagerWrapper.java:269)
    at app.dao.AbstractFacade.create(AbstractFacade.java:24)
    at app.dao.CustomerFacade.create(CustomerFacade.java:16)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
    ... 43 more

So I don't know what it means by 'prePersist' error, at the beginning, I didn't define customerID so I define the @GeneratedValue(strategy = GenerationType.IDENTITY) in Customer entity but threw the same error, now I define the id in my form but always the same, what I'm doing wrong?
Regards!

A: Dunno if it helps but we have the same error once, it was because we created data with a sequence in SQL, and that sequence was marking a number that we have data already, like this
Table data_created has 150 data, and the sequence pointed to 122, so we updated it to 151 and was fixed,  hope it helps


text:
Q: does not support Arabic Content in webpage Hi All I am creating Arabic website. But problem is that it does not support the Arabic content. it comes ???????????? . Even I put charset="utf-8" in .htaccess. I also put meta tag in every page. I saved the files as utf-8 support file format. Even I put there header('Content-Type: text/html; charset=utf-8');
 MySQL Stored data shown in Arabic language but if I put some Arabic language in tag it wont support
Somebody have some idea regarding this because this is my firs Arabic website.

A: You will likely want to add extra designations to your HTML. For example, if you are using HTML 5, it will look like:
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
:
your content here
:

A: Change the structure of the field Collation to: UTF8 general CI

A: Try with adding meta charset for arabic at the begning
<META HTTP-EQUIV="Content-Type"  CONTENT="text/html; CHARSET=iso-8859-6">

Or you may try it out with following steps :-
Displaying Arabic text using PHP

1. Don't use the short tags <? ?>. Use the full tags <?php ?>

2. Remove the quotes and semicolon from the first line and others that are outside the php tags
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">";

3. Close the span tag <span lang='ar-kw'

4. Make sure save the file with utf-8 encoding. You might be saving it with another coding.


text:
Q: Is there any R function that I can use to calculate e^π and π^e? I am trying to compare the values e^π and π^e using R. However I keep getting the message object 'e' not found.

A: e isn't automatically defined in R, but it can be obtained with exp(1), so you can do exp(1) ^ pi and pi ^ exp(1)


text:
Q: OpenPojo IncompatibleClassChangeError Exception I'm using OpenPojo for validating getter and setter methods of a class.
But while trying to validate my getter and setter methods I'm having following exception:

java.lang.IncompatibleClassChangeError: class com.openpojo.reflection.java.bytecode.asm.SubClassCreator has
  interface org.objectweb.asm.ClassVisitor as super class

Here is my code:
public final class ClientToken implements RememberMeAuthenticationToken {

private static final long serialVersionUID = 3141878022445836151L;

private final String clientName;

private final Credentials credentials;

private String userId;

private boolean isRememberMe;

public ClientToken(final String clientName, final Credentials credentials) {
    this.clientName = clientName;
    this.credentials = credentials;
}

public void setUserId(final String userId) {
    this.userId = userId;
}

public void setRememberMe(boolean isRememberMe) {
    this.isRememberMe = isRememberMe;
}

public String getClientName() {
    return this.clientName;
}

public Object getCredentials() {
    return this.credentials;
}

public Object getPrincipal() {
    return this.userId;
}

@Override
public String toString() {
    return CommonHelper.toString(ClientToken.class, "clientName", this.clientName, "credentials", this.credentials,
            "userId", this.userId);
}

public boolean isRememberMe() {
    return isRememberMe;
}
}

Does anybody help me why this problem occurs.

A: Have you tried to add the ASM 5.0.3 or higher as a dependency?
It seems an older version for ASM is getting pulled in.


text:
Q: Find a sequence whose generating function is given.
Chap4 q2) Of which sequence is $U(s)=(1-4pqs^2)^{\frac{-1}{2}}$ the
  generating function(where $0<p=1-q<1$)?

Solution: So we need to find out a sequence $u_0,u_1,...$ such that $u_0+u_1s+u_2s^2+...=(1-4pqs^2)^{\frac{-1}{2}}$. Given that $\sum_i ar^i=\frac{a}{1-r}$, I feel like I need to make the exponent of $(1-4pqs^2)$ be $-1$

A: By the binomial series:
$\begin{align*}
(1 + x)^{-1/2}
  &= \sum_{n \ge 0} \binom{-1/2}{n} x^n \\
  &= \sum_{n \ge 0} \frac{(-1)^k}{2^{2 n}} \binom{2 n}{n} x^n
\end{align*}$


text:
Q: Angular setup with nginx cannot hit the api I'm new on Angular development. So I have serious problem is I cannot deploy angular on server
If I try on local, the code is running well and can hit the api using proxy
for the Api build with spring and deploy on heroku
and for the Angular I using Aws Lightsail with nginx configuration

*

*I'm run ng build for get the dist folder

*and then I move all file inside dist/my-folder-generate/ to /var/ww/html

*when I open via browser, the Angular running well but I cannot hit the api

this is my nginx configurations
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
       try_files $uri $uri/ /index.html;
       error_page 405 =200 $uri;
    }
}

this is my angular.json
"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "my-app:build:production",
              "proxyConfig": "src/proxy.conf.json"
            },
            "development": {
              "browserTarget": "my-app:build:development",
              "proxyConfig": "src/proxy.conf.json"
            }
          },
          "defaultConfiguration": "development",
          "options": {
            "browserTarget": "my-app:build",
            "proxyConfig": "src/proxy.conf.json"
          }
 },

for the proxy.conf.json
{
  "/api": {
      "target": "https://my-api.herokuapp.com",
      "secure": false,
      "logLevel": "debug",
      "changeOrigin": true
  }
}

and this how I consume the api
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
const AUTH_API = '/api/';
const httpOptions = {
  headers: new HttpHeaders({
    accept: ' application/json',
    'Content-Type': ' application/json',
  }),
};
@Injectable({
  providedIn: 'root',
})
export class AuthService {
  constructor(private http: HttpClient) {}
  login(username: string, password: string): Observable<any> {
    return this.http.post(
      AUTH_API + 'auth/login',
      {
        username,
        password,
      },
      httpOptions
    );
  }
}

for sure this config running well on local but not on server, can anyone help me? may I have a mistake about server configurations?

A: Based on @mojtaba suggestions for add /api. So I add nginx configuration like this
location /api {
  proxy_method POST;
  proxy_http_version 1.1;
  proxy_pass https://my-api.herokuapp.com;

}

so for who have trouble and same case like me you can use this block
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
       try_files $uri $uri/ /index.html;
       error_page 405 =200 $uri;
    }
}

location /api {
  proxy_method POST;
  proxy_http_version 1.1;
  proxy_pass https://my-api.herokuapp.com;
}


text:
Q: What is the correct type for inserting OLE object? I'm trying to insert data from a MS Access form in to a table so I've knocked up a short function to see whether it is possible.
The function I have is this:
Function Module2() As Boolean

On Error GoTo Err_Insert

  Dim adoCMD As Object
  Dim adoRS As Object
  Dim strSQL As String

  'Define a query to INSERT a new record into the FE temp table
  strSQL = "INSERT INTO [Table1] ([A1],[A2],[A3],[img] VALUES (p1,p2,p3,img);"

  'Define attachment to database table specifics
  Set adoCMD = CreateObject("ADODB.Command")
  With adoCMD
    .ActiveConnection = CurrentProject.Connection
    .CommandType = adCmdText
    .Parameters.Append .CreateParameter("p1", adVarChar, adParamInput, Len(Forms("Form1").Controls("text0").value), Forms("Form1").Controls("Text0").value)
    .Parameters.Append .CreateParameter("p2", adBoolean, adParamInput, Len(Forms("Form1").Controls("Check2").value), Forms("Form1").Controls("Check2").value)
    '.Parameters.Append .CreateParameter("p3", adVarChar, adParamInput, Len(Forms("Form1").Controls("Combo4").value), Forms("Form1").Controls("Combo4").value)
    .Parameters.Append .CreateParameter("img", adLongVarBinary, adParamInput, Len(Forms("Form1").OLEBound6), Forms("Form1").Controls("OLEBound6"))
    .CommandText = strSQL
    Set adoRS = .Execute
  End With

  'Return a good return code
  Module2 = True

Exit_Insert:
  'Clean up the connection to the database
  Set adoRS = Nothing
  Set adoCMD = Nothing

  Exit Function

Err_Insert:
  Call MsgBox("Class: Module2, Function: Insert()")
  Module2 = False
  Resume Exit_Insert

End Function

when run, I get the following error:
Run-time error 3421
Application uses a value of the wrong type for the current operation
and breaks at this point:
.Parameters.Append .CreateParameter("img", adLongVarBinary, adParamInput, Len(Forms("Form1").OLEBound6), Forms("Form1").Controls("OLEBound6"))
What is the correct type for an OLEObject?  I've tried several all with the same result.  I cannot find which DataTypeEnum looks to be the correct type.
Thanks

A: When you skip parameter P3, the query will try to insert img (now the third parameter) to A3, thus the error.