/*
 * Copyright (C) 2011 by Nelson Elhage
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include <sys/ptrace.h>
#include <asm/ptrace.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#include <assert.h>
#include <stddef.h>

#include "ptrace.h"

/*
 * RHEL 5's kernel supports these flags, but their libc doesn't ship a ptrace.h
 * that defines them. Define them here, and if our kernel doesn't support them,
 * we'll find out when PTRACE_SETOPTIONS fails.
 */
#ifndef PTRACE_O_TRACESYSGOOD
#define PTRACE_O_TRACESYSGOOD 0x00000001
#endif

#ifndef PTRACE_O_TRACEFORK
#define PTRACE_O_TRACEFORK 0x00000002
#endif

#ifndef PTRACE_EVENT_FORK
#define PTRACE_EVENT_FORK 1
#endif

#define min(x, y) ({				\
	typeof(x) _min1 = (x);			\
	typeof(y) _min2 = (y);			\
	_min1 < _min2 ? _min1 : _min2; })

static long __ptrace_command(struct ptrace_child *child, enum __ptrace_request req,
                             void *, void*);

#define ptrace_command(cld, req, ...) _ptrace_command(cld, req, ## __VA_ARGS__, NULL, NULL)
#define _ptrace_command(cld, req, addr, data, ...) __ptrace_command((cld), (req), (void*)(addr), (void*)(data))

struct ptrace_personality {
    size_t syscall_rv;
    size_t syscall_arg0;
    size_t syscall_arg1;
    size_t syscall_arg2;
    size_t syscall_arg3;
    size_t syscall_arg4;
    size_t syscall_arg5;
    size_t reg_ip;
};

static struct ptrace_personality *personality(struct ptrace_child *child);

#if defined(__amd64__)
#include "arch/amd64.h"
#elif defined(__i386__)
#include "arch/i386.h"
#elif defined(__arm__)
#include "arch/arm.h"
#else
#error Unsupported architecture.
#endif

#ifndef ARCH_HAVE_MULTIPLE_PERSONALITIES
int arch_get_personality(struct ptrace_child *child) {
    return 0;
}

struct syscall_numbers arch_syscall_numbers[] = {
#include "arch/default-syscalls.h"
};
#endif

static struct ptrace_personality *personality(struct ptrace_child *child) {
    return &arch_personality[child->personality];
}

struct syscall_numbers *ptrace_syscall_numbers(struct ptrace_child *child) {
    return &arch_syscall_numbers[child->personality];
}

int ptrace_attach_child(struct ptrace_child *child, pid_t pid) {
    memset(child, 0, sizeof *child);
    child->pid = pid;
    if (ptrace_command(child, PTRACE_ATTACH) < 0)
        return -1;

    return ptrace_finish_attach(child, pid);
}

int ptrace_finish_attach(struct ptrace_child *child, pid_t pid) {
    memset(child, 0, sizeof *child);
    child->pid = pid;

    kill(pid, SIGCONT);
    if (ptrace_wait(child) < 0)
        goto detach;

    if (arch_get_personality(child))
        goto detach;

    if (ptrace_command(child, PTRACE_SETOPTIONS, 0,
                       PTRACE_O_TRACESYSGOOD|PTRACE_O_TRACEFORK) < 0)
        goto detach;

    return 0;

 detach:
    /* Don't clobber child->error */
    ptrace(PTRACE_DETACH, child->pid, 0, 0);
    return -1;
}

int ptrace_detach_child(struct ptrace_child *child) {
    if (ptrace_command(child, PTRACE_DETACH, 0, 0) < 0)
        return -1;
    child->state = ptrace_detached;
    return 0;
}

int ptrace_wait(struct ptrace_child *child) {
    if (waitpid(child->pid, &child->status, 0) < 0) {
        child->error = errno;
        return -1;
    }
    if (WIFEXITED(child->status) || WIFSIGNALED(child->status)) {
        child->state = ptrace_exited;
    } else if (WIFSTOPPED(child->status)) {
        int sig = WSTOPSIG(child->status);
        if (sig & 0x80) {
            child->state = (child->state == ptrace_at_syscall) ?
                ptrace_after_syscall : ptrace_at_syscall;
        } else {
            if (sig == SIGTRAP && (((child->status >> 8) & PTRACE_EVENT_FORK) == PTRACE_EVENT_FORK))
                ptrace_command(child, PTRACE_GETEVENTMSG, 0, &child->forked_pid);
            if (child->state != ptrace_at_syscall)
                child->state = ptrace_stopped;
        }
    } else {
        child->error = EINVAL;
        return -1;
    }
    return 0;
}

int ptrace_advance_to_state(struct ptrace_child *child,
                            enum child_state desired) {
    int err;
    while (child->state != desired) {
        switch(desired) {
        case ptrace_after_syscall:
        case ptrace_at_syscall:
            if (WIFSTOPPED(child->status) && WSTOPSIG(child->status) == SIGSEGV) {
                child->error = EAGAIN;
                return -1;
            }
            err = ptrace_command(child, PTRACE_SYSCALL, 0, 0);
            break;
        case ptrace_running:
            return ptrace_command(child, PTRACE_CONT, 0, 0);
        case ptrace_stopped:
            err = kill(child->pid, SIGSTOP);
            if (err < 0)
                child->error = errno;
            break;
        default:
            child->error = EINVAL;
            return -1;
        }
        if (err < 0)
            return err;
        if (ptrace_wait(child) < 0)
            return -1;
    }
    return 0;
}

int ptrace_save_regs(struct ptrace_child *child) {
    if (ptrace_advance_to_state(child, ptrace_at_syscall) < 0)
        return -1;
    if (ptrace_command(child, PTRACE_GETREGS, 0, &child->user) < 0)
        return -1;
    arch_fixup_regs(child);
    if (arch_save_syscall(child) < 0)
        return -1;
    return 0;
}

int ptrace_restore_regs(struct ptrace_child *child) {
    int err;
    err = ptrace_command(child, PTRACE_SETREGS, 0, &child->user);
    if (err < 0)
        return err;
    return arch_restore_syscall(child);
}

unsigned long ptrace_remote_syscall(struct ptrace_child *child,
                                    unsigned long sysno,
                                    unsigned long p0, unsigned long p1,
                                    unsigned long p2, unsigned long p3,
                                    unsigned long p4, unsigned long p5) {
    unsigned long rv;
    if (ptrace_advance_to_state(child, ptrace_at_syscall) < 0)
        return -1;

#define setreg(r, v) do {                                               \
        if (ptrace_command(child, PTRACE_POKEUSER,                      \
                           personality(child)->r,                       \
                           (v)) < 0)                                    \
            return -1;                                                  \
    } while (0)

    if (arch_set_syscall(child, sysno) < 0)
        return -1;
    setreg(syscall_arg0, p0);
    setreg(syscall_arg1, p1);
    setreg(syscall_arg2, p2);
    setreg(syscall_arg3, p3);
    setreg(syscall_arg4, p4);
    setreg(syscall_arg5, p5);

    if (ptrace_advance_to_state(child, ptrace_after_syscall) < 0)
        return -1;

    rv = ptrace_command(child, PTRACE_PEEKUSER,
                        personality(child)->syscall_rv);
    if (child->error)
        return -1;

    setreg(reg_ip, *(unsigned long*)((void*)&child->user +
                                     personality(child)->reg_ip));

    #undef setreg

    return rv;
}

int ptrace_memcpy_to_child(struct ptrace_child *child, child_addr_t dst, const void *src, size_t n) {
    unsigned long scratch;

    while (n >= sizeof(unsigned long)) {
        if (ptrace_command(child, PTRACE_POKEDATA, dst, *((unsigned long*)src)) < 0)
            return -1;
        dst += sizeof(unsigned long);
        src += sizeof(unsigned long);
        n -= sizeof(unsigned long);
    }

    if (n) {
        scratch = ptrace_command(child, PTRACE_PEEKDATA, dst);
        if (child->error)
            return -1;
        memcpy(&scratch, src, n);
        if (ptrace_command(child, PTRACE_POKEDATA, dst, scratch) < 0)
            return -1;
    }

    return 0;
}

int ptrace_memcpy_from_child(struct ptrace_child *child, void *dst, child_addr_t src, size_t n) {
    unsigned long scratch;

    while (n) {
         scratch = ptrace_command(child, PTRACE_PEEKDATA, src);
        if (child->error) return -1;
        memcpy(dst, &scratch, min(n, sizeof(unsigned long)));

        dst += sizeof(unsigned long);
        src += sizeof(unsigned long);
        if (n >= sizeof(unsigned long))
            n -= sizeof(unsigned long);
        else
            n = 0;
    }
    return 0;
}

static long __ptrace_command(struct ptrace_child *child, enum __ptrace_request req,
                             void *addr, void *data) {
    long rv;
    errno = 0;
    rv = ptrace(req, child->pid, addr, data);
    child->error = errno;
    return rv;
}

#ifdef BUILD_PTRACE_MAIN
int main(int argc, char **argv) {
    struct ptrace_child child;
    pid_t pid;

    if (argc < 2) {
        printf("Usage: %s pid\n", argv[0]);
        return 1;
    }
    pid = atoi(argv[1]);

    assert(!ptrace_attach_child(&child, pid));
    assert(!ptrace_save_regs(&child));

    printf("mmap = %lx\n", ptrace_remote_syscall(&child, mmap_syscall, 0,
                                                 4096, PROT_READ|PROT_WRITE,
                                                 MAP_ANONYMOUS|MAP_PRIVATE, 0, 0));

    reset_user_struct(&child.user);
    assert(!ptrace_restore_regs(&child));
    assert(!ptrace_detach_child(&child));

    return 0;
}
#endif


/* A test program to study the mpz_t structure.
 *
 * Copyright (C) 2011 Daniele Varrazzo
 */

#include <stdio.h>
#include <gmp.h>

int
main(int argc, char **argv)
{
    mpz_t z1, z2;

    mpz_init_set_ui(z1, ~((unsigned long int)0));
    mpz_init(z2);
    mpz_add_ui(z2, z1, 1);

    mpz_out_str(stdout, 10, z2);
    printf("\n");

    return 0;
}


/* pgmp_utils -- misc utility module
 *
 * Copyright (C) 2011 Daniele Varrazzo
 *
 * This file is part of the PostgreSQL GMP Module
 *
 * The PostgreSQL GMP Module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * The PostgreSQL GMP Module is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the PostgreSQL GMP Module.  If not, see
 * http://www.gnu.org/licenses/.
 */

#include "pgmp_utils.h"

#if PG_VERSION_NUM < 90000

#include "nodes/nodes.h"            /* for IsA */
#include "nodes/execnodes.h"        /* for AggState */

/*
 * AggCheckCallContext - test if a SQL function is being called as an aggregate
 *
 * The function is available from PG 9.0. This allows compatibility with
 * previous versions.
 */
int
AggCheckCallContext(FunctionCallInfo fcinfo, MemoryContext *aggcontext)
{
    if (fcinfo->context && IsA(fcinfo->context, AggState))
    {
        if (aggcontext) {
            *aggcontext = ((AggState *) fcinfo->context)->aggcontext;
        }
        return AGG_CONTEXT_AGGREGATE;
    }

#if PG_VERSION_NUM >= 80400

    if (fcinfo->context && IsA(fcinfo->context, WindowAggState))
    {
        if (aggcontext) {
            /* different from PG 9.0: in PG 8.4 there is no aggcontext */
            *aggcontext = ((WindowAggState *) fcinfo->context)->wincontext;
        }
        return AGG_CONTEXT_WINDOW;
    }

#endif

    /* this is just to prevent "uninitialized variable" warnings */
    if (aggcontext) {
        *aggcontext = NULL;
    }

    return 0;
}
#endif


/* pmpz_agg -- mpz aggregation functions
 *
 * Copyright (C) 2011 Daniele Varrazzo
 *
 * This file is part of the PostgreSQL GMP Module
 *
 * The PostgreSQL GMP Module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * The PostgreSQL GMP Module is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the PostgreSQL GMP Module.  If not, see
 * http://www.gnu.org/licenses/.
 */

#include "pmpz.h"
#include "pgmp_utils.h"             /* for AggCheckCallContext on PG < 9.0 */
#include "pgmp-impl.h"

#include "fmgr.h"

/* Convert an inplace accumulator into a pmpz structure.
 *
 * This function is strict, so don't care about NULLs
 */
PGMP_PG_FUNCTION(_pmpz_from_agg)
{
    mpz_t       *a;

    a = (mpz_t *)PG_GETARG_POINTER(0);
    PGMP_RETURN_MPZ(*a);
}

/* Macro to create an accumulation function from a gmp operator.
 *
 * This function can't be strict because the internal state is not compatible
 * with the base type.
 */
#define PMPZ_AGG(op, BLOCK, rel) \
 \
PGMP_PG_FUNCTION(_pmpz_agg_ ## op) \
{ \
    mpz_t           *a; \
    const mpz_t     z; \
    MemoryContext   oldctx; \
    MemoryContext   aggctx; \
 \
    if (UNLIKELY(!AggCheckCallContext(fcinfo, &aggctx))) \
    { \
        ereport(ERROR, \
            (errcode(ERRCODE_DATA_EXCEPTION), \
            errmsg("_mpz_agg_" #op " can only be called in accumulation"))); \
    } \
 \
    if (PG_ARGISNULL(1)) { \
        if (PG_ARGISNULL(0)) { \
            PG_RETURN_NULL(); \
        } \
        else { \
            PG_RETURN_POINTER(PG_GETARG_POINTER(0)); \
        } \
    } \
 \
    PGMP_GETARG_MPZ(z, 1); \
 \
    oldctx = MemoryContextSwitchTo(aggctx); \
 \
    if (LIKELY(!PG_ARGISNULL(0))) { \
        a = (mpz_t *)PG_GETARG_POINTER(0); \
        BLOCK(op, rel); \
    } \
    else {                      /* uninitialized */ \
        a = (mpz_t *)palloc(sizeof(mpz_t)); \
        mpz_init_set(*a, z); \
    } \
 \
    MemoryContextSwitchTo(oldctx); \
 \
    PG_RETURN_POINTER(a); \
}

#define PMPZ_AGG_OP(op, rel) \
    mpz_ ## op (*a, *a, z)

PMPZ_AGG(add, PMPZ_AGG_OP, 0)
PMPZ_AGG(mul, PMPZ_AGG_OP, 0)
PMPZ_AGG(and, PMPZ_AGG_OP, 0)
PMPZ_AGG(ior, PMPZ_AGG_OP, 0)
PMPZ_AGG(xor, PMPZ_AGG_OP, 0)

#define PMPZ_AGG_REL(op, rel) \
do { \
    if (mpz_cmp(*a, z) rel 0) { \
        mpz_set(*a, z); \
    } \
} while (0)

PMPZ_AGG(min, PMPZ_AGG_REL, >)
PMPZ_AGG(max, PMPZ_AGG_REL, <)


/* pmpq_io -- mpq Input/Output functions
 *
 * Copyright (C) 2011 Daniele Varrazzo
 *
 * This file is part of the PostgreSQL GMP Module
 *
 * The PostgreSQL GMP Module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * The PostgreSQL GMP Module is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the PostgreSQL GMP Module.  If not, see
 * http://www.gnu.org/licenses/.
 */

#include "pmpq.h"
#include "pmpz.h"
#include "pgmp-impl.h"

#include "fmgr.h"
#include "utils/builtins.h"     /* for numeric_out */

#include <string.h>

/*
 * Input/Output functions
 */

PGMP_PG_FUNCTION(pmpq_in)
{
    char    *str;
    mpq_t   q;

    str = PG_GETARG_CSTRING(0);

    mpq_init(q);
    if (0 != mpq_set_str(q, str, 0))
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("invalid input syntax for mpq: \"%s\"",
                        str)));
    }

    ERROR_IF_DENOM_ZERO(mpq_denref(q));

    mpq_canonicalize(q);
    PGMP_RETURN_MPQ(q);
}

PGMP_PG_FUNCTION(pmpq_in_base)
{
    int     base;
    char    *str;
    mpq_t   q;

    base = PG_GETARG_INT32(1);

    if (!(base == 0 || (2 <= base && base <= PGMP_MAXBASE_IO)))
    {
        ereport(ERROR, (
            errcode(ERRCODE_INVALID_PARAMETER_VALUE),
            errmsg("invalid base for mpq input: %d", base),
            errhint("base should be between 2 and %d", PGMP_MAXBASE_IO)));
    }

    str = TextDatumGetCString(PG_GETARG_POINTER(0));

    mpq_init(q);
    if (0 != mpq_set_str(q, str, base))
    {
        const char *ell;
        const int maxchars = 50;
        ell = (strlen(str) > maxchars) ? "..." : "";

        ereport(ERROR, (
            errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
            errmsg("invalid input for mpq base %d: \"%.*s%s\"",
                base, 50, str, ell)));
    }

    ERROR_IF_DENOM_ZERO(mpq_denref(q));

    mpq_canonicalize(q);
    PGMP_RETURN_MPQ(q);
}

PGMP_PG_FUNCTION(pmpq_out)
{
    const mpq_t     q;
    char            *buf;

    PGMP_GETARG_MPQ(q, 0);

    /* Allocate the output buffer manually - see mpmz_out to know why */
    buf = palloc(3             /* add sign, slash and null */
        + mpz_sizeinbase(mpq_numref(q), 10)
        + mpz_sizeinbase(mpq_denref(q), 10));

    PG_RETURN_CSTRING(mpq_get_str(buf, 10, q));
}

PGMP_PG_FUNCTION(pmpq_out_base)
{
    const mpq_t     q;
    int             base;
    char            *buf;

    PGMP_GETARG_MPQ(q, 0);
    base = PG_GETARG_INT32(1);

    if (!((-36 <= base && base <= -2) ||
        (2 <= base && base <= PGMP_MAXBASE_IO)))
    {
        ereport(ERROR, (
            errcode(ERRCODE_INVALID_PARAMETER_VALUE),
            errmsg("invalid base for mpq output: %d", base),
            errhint("base should be between -36 and -2 or between 2 and %d",
                PGMP_MAXBASE_IO)));
    }

    /* Allocate the output buffer manually - see mpmz_out to know why */
    buf = palloc(3             /* add sign, slash and null */
        + mpz_sizeinbase(mpq_numref(q), ABS(base))
        + mpz_sizeinbase(mpq_denref(q), ABS(base)));
    PG_RETURN_CSTRING(mpq_get_str(buf, base, q));
}

/*
 * Cast functions
 */

static Datum _pmpq_from_long(long in);

PGMP_PG_FUNCTION(pmpq_from_int2)
{
    int16 in = PG_GETARG_INT16(0);
    return _pmpq_from_long(in);
}

PGMP_PG_FUNCTION(pmpq_from_int4)
{
    int32 in = PG_GETARG_INT32(0);
    return _pmpq_from_long(in);
}

static Datum
_pmpq_from_long(long in)
{
    mpq_t   q;

    mpz_init_set_si(mpq_numref(q), in);
    mpz_init_set_si(mpq_denref(q), 1L);

    PGMP_RETURN_MPQ(q);
}

static Datum _pmpq_from_double(double in);

PGMP_PG_FUNCTION(pmpq_from_float4)
{
    double in = (double)PG_GETARG_FLOAT4(0);
    return _pmpq_from_double(in);
}

PGMP_PG_FUNCTION(pmpq_from_float8)
{
    double in = PG_GETARG_FLOAT8(0);
    return _pmpq_from_double(in);
}

static Datum
_pmpq_from_double(double in)
{
    mpq_t   q;

    mpq_init(q);
    mpq_set_d(q, in);

    PGMP_RETURN_MPQ(q);
}

/* to convert from int8 we piggyback all the mess we've made for mpz */

Datum pmpz_from_int8(PG_FUNCTION_ARGS);

PGMP_PG_FUNCTION(pmpq_from_int8)
{
    mpq_t           q;
    mpz_t           tmp;

    mpz_from_pmpz(tmp,
        (pmpz *)DirectFunctionCall1(pmpz_from_int8,
            PG_GETARG_DATUM(0)));

    /* Make a copy of the num as MPQ will try to realloc on it */
    mpz_init_set(mpq_numref(q), tmp);
    mpz_init_set_si(mpq_denref(q), 1L);

    PGMP_RETURN_MPQ(q);
}

/* To convert from numeric we convert the numeric in str, then work on that */

PGMP_PG_FUNCTION(pmpq_from_numeric)
{
    mpq_t       q;
    char        *sn, *pn;

    sn = DatumGetCString(DirectFunctionCall1(numeric_out,
            PG_GETARG_DATUM(0)));

    if ((pn = strchr(sn, '.')))
    {
        char    *sd, *pd;

        /* Convert "123.45" into "12345" and produce "100" in the process. */
        pd = sd = (char *)palloc(strlen(sn));
        *pd++ = '1';
        while (pn[1])
        {
            pn[0] = pn[1];
            ++pn;
            *pd++ = '0';
        }
        *pd = *pn = '\0';

        if (0 != mpz_init_set_str(mpq_numref(q), sn, 10)) {
            goto error;
        }

        mpz_init_set_str(mpq_denref(q), sd, 10);
        mpq_canonicalize(q);
    }
    else {
        /* just an integer */
        if (0 != mpz_init_set_str(mpq_numref(q), sn, 10)) {
            goto error;
        }
        mpz_init_set_si(mpq_denref(q), 1L);
    }

    PGMP_RETURN_MPQ(q);

error:
    ereport(ERROR, (
        errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
        errmsg("can't convert numeric value to mpq: \"%s\"", sn)));

    PG_RETURN_NULL();
}

PGMP_PG_FUNCTION(pmpq_from_mpz)
{
    mpq_t           q;
    mpz_t           tmp;

    /* Make a copy of the num as MPQ will try to realloc on it */
    PGMP_GETARG_MPZ(tmp, 0);
    mpz_init_set(mpq_numref(q), tmp);
    mpz_init_set_si(mpq_denref(q), 1L);

    PGMP_RETURN_MPQ(q);
}

PGMP_PG_FUNCTION(pmpq_to_mpz)
{
    const mpq_t     q;
    mpz_t           z;

    PGMP_GETARG_MPQ(q, 0);

    mpz_init(z);
    mpz_set_q(z, q);

    PGMP_RETURN_MPZ(z);
}

#define PMPQ_TO_INT(type) \
 \
Datum pmpz_to_ ## type (PG_FUNCTION_ARGS); \
 \
PGMP_PG_FUNCTION(pmpq_to_ ## type) \
{ \
    const mpq_t     q; \
    mpz_t           z; \
 \
    PGMP_GETARG_MPQ(q, 0); \
 \
    mpz_init(z); \
    mpz_set_q(z, q); \
 \
    return DirectFunctionCall1(pmpz_to_ ## type, (Datum)pmpz_from_mpz(z)); \
}

PMPQ_TO_INT(int2)
PMPQ_TO_INT(int4)
PMPQ_TO_INT(int8)

PGMP_PG_FUNCTION(pmpq_to_float4)
{
    const mpq_t     q;
    PGMP_GETARG_MPQ(q, 0);

    PG_RETURN_FLOAT4((float4)mpq_get_d(q));
}

PGMP_PG_FUNCTION(pmpq_to_float8)
{
    const mpq_t     q;
    PGMP_GETARG_MPQ(q, 0);

    PG_RETURN_FLOAT8((float8)mpq_get_d(q));
}

PGMP_PG_FUNCTION(pmpq_to_numeric)
{
    const mpq_t     q;
    int32           typmod;
    unsigned long   scale;
    mpz_t           z;
    char            *buf;
    int             sbuf, snum;

    PGMP_GETARG_MPQ(q, 0);
    typmod = PG_GETARG_INT32(1);

    /* Parse precision and scale from the type modifier */
    if (typmod >= VARHDRSZ) {
        scale = (typmod - VARHDRSZ) & 0xffff;
    }
    else {
        scale = 15;
    }

    if (scale) {
        /* Convert q into a scaled z */
        char *cmult;
        mpz_t mult;

        /* create 10000... with as many 0s as the scale */
        cmult = (char *)palloc(scale + 2);
        memset(cmult + 1, '0', scale);
        cmult[0] = '1';
        cmult[scale + 1] = '\0';
        mpz_init_set_str(mult, cmult, 10);
        pfree(cmult);

        mpz_init(z);
        mpz_mul(z, mpq_numref(q), mult);
        sbuf = mpz_sizeinbase(z, 10);       /* size of the output buffer */
        mpz_tdiv_q(z, z, mpq_denref(q));
        snum = mpz_sizeinbase(z, 10);       /* size of the number */
    }
    else {
        /* Just truncate q into an integer */
        mpz_init(z);
        mpz_set_q(z, q);
        sbuf = snum = mpz_sizeinbase(z, 10);
    }

    /* If the numer is 0, everything is a special case: bail out */
    if (mpz_cmp_si(z, 0) == 0) {
        return DirectFunctionCall3(numeric_in,
            CStringGetDatum("0"),
            ObjectIdGetDatum(0),            /* unused 2nd value */
            Int32GetDatum(typmod));
    }

    /* convert z into a string */
    buf = palloc(sbuf + 3);                 /* add sign, point and null */
    mpz_get_str(buf, 10, z);
    if (scale) {
        char *end, *p;

        /* Left pad with 0s the number if smaller than the buffer */
        if (snum < sbuf) {
            char *num0 = buf + (buf[0] == '-'); /* start of the num w/o sign */
            memmove(num0 + (sbuf - snum), num0, snum + 1);
            memset(num0, '0', sbuf - snum);
        }

        end = buf + strlen(buf);

        /* Add the decimal point in the right place */
        memmove(end - scale + 1, end - scale, scale + 1);
        end[-scale] = '.';

        /* delete trailing 0s or they will be used to add extra precision */
        if (typmod < VARHDRSZ) {        /* scale was not specified */
            for (p = end; p > (end - scale) && *p == '0'; --p) {
                *p = '\0';
            }
            /* Don't leave a traliling point */
            if (*p == '.') {
                *p = '\0';
            }
        }
    }

    /* use numeric_in to build the value from the string and to apply the
     * typemod (which may result in overflow) */
    return DirectFunctionCall3(numeric_in,
        CStringGetDatum(buf),
        ObjectIdGetDatum(0),    /* unused 2nd value */
        Int32GetDatum(typmod));
}

/*
 * Constructor and accessors to num and den
 */

PGMP_PG_FUNCTION(pmpq_mpz_mpz)
{
    const mpz_t     num;
    const mpz_t     den;
    mpq_t           q;

    /* We must take a copy of num and den because they may be modified by
     * canonicalize */
    PGMP_GETARG_MPZ(num, 0);
    PGMP_GETARG_MPZ(den, 1);
    ERROR_IF_DENOM_ZERO(den);

    /* Put together the input and canonicalize */
    mpz_init_set(mpq_numref(q), num);
    mpz_init_set(mpq_denref(q), den);
    mpq_canonicalize(q);

    PGMP_RETURN_MPQ(q);
}

PGMP_PG_FUNCTION(pmpq_int4_int4)
{
    int32 num = PG_GETARG_INT32(0);
    int32 den = PG_GETARG_INT32(1);
    mpq_t           q;

    /* Put together the input and canonicalize */
    mpz_init_set_si(mpq_numref(q), (long)num);
    mpz_init_set_si(mpq_denref(q), (long)den);
    ERROR_IF_DENOM_ZERO(mpq_denref(q));
    mpq_canonicalize(q);

    PGMP_RETURN_MPQ(q);
}

PGMP_PG_FUNCTION(pmpq_numeric_numeric)
{
    char        *sn;
    char        *sd;
    mpq_t       q;

    sn = DatumGetCString(DirectFunctionCall1(numeric_out, PG_GETARG_DATUM(0)));
    if (0 != mpz_init_set_str(mpq_numref(q), sn, 10))
    {
        ereport(ERROR, (
            errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
            errmsg("can't handle numeric value at numerator: %s", sn),
            errhint("the mpq components should be integers")));
    }

    sd = DatumGetCString(DirectFunctionCall1(numeric_out, PG_GETARG_DATUM(1)));
    if (0 != mpz_init_set_str(mpq_denref(q), sd, 10))
    {
        ereport(ERROR, (
            errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
            errmsg("can't handle numeric value at denominator: %s", sd),
            errhint("the mpq components should be integers")));
    }

    ERROR_IF_DENOM_ZERO(mpq_denref(q));
    mpq_canonicalize(q);

    PGMP_RETURN_MPQ(q);
}

PGMP_PG_FUNCTION(pmpq_num)
{
    const mpq_t     q;
    mpz_t           z;

    PGMP_GETARG_MPQ(q, 0);

    mpz_init_set(z, mpq_numref(q));

    PGMP_RETURN_MPZ(z);
}

PGMP_PG_FUNCTION(pmpq_den)
{
    const mpq_t     q;
    mpz_t           z;

    PGMP_GETARG_MPQ(q, 0);

    mpz_init_set(z, mpq_denref(q));

    PGMP_RETURN_MPZ(z);
}


/* pmpz_roots -- root extraction functions
 *
 * Copyright (C) 2011 Daniele Varrazzo
 *
 * This file is part of the PostgreSQL GMP Module
 *
 * The PostgreSQL GMP Module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * The PostgreSQL GMP Module is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the PostgreSQL GMP Module.  If not, see
 * http://www.gnu.org/licenses/.
 */

#include "pmpz.h"
#include "pgmp-impl.h"

#include "fmgr.h"
#include "funcapi.h"
#if PG_VERSION_NUM >= 90300
#include <access/htup_details.h>    /* for heap_form_tuple */
#endif

/* Functions with a more generic signature are defined in pmpz.arith.c */

#if __GMP_MP_RELEASE >= 40200

PGMP_PG_FUNCTION(pmpz_rootrem)
{
    const mpz_t     z1;
    mpz_t           zroot;
    mpz_t           zrem;
    unsigned long   n;

    PGMP_GETARG_MPZ(z1, 0);
    PMPZ_CHECK_NONEG(z1);

    PGMP_GETARG_ULONG(n, 1);
    PMPZ_CHECK_LONG_POS(n);

    mpz_init(zroot);
    mpz_init(zrem);
    mpz_rootrem (zroot, zrem, z1, n);

    PGMP_RETURN_MPZ_MPZ(zroot, zrem);
}

#endif

PGMP_PG_FUNCTION(pmpz_sqrtrem)
{
    const mpz_t     z1;
    mpz_t           zroot;
    mpz_t           zrem;

    PGMP_GETARG_MPZ(z1, 0);

    mpz_init(zroot);
    mpz_init(zrem);
    mpz_sqrtrem(zroot, zrem, z1);

    PGMP_RETURN_MPZ_MPZ(zroot, zrem);
}


/* pgmp -- PostgreSQL GMP module
 *
 * Copyright (C) 2011 Daniele Varrazzo
 *
 * This file is part of the PostgreSQL GMP Module
 *
 * The PostgreSQL GMP Module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * The PostgreSQL GMP Module is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the PostgreSQL GMP Module.  If not, see
 * http://www.gnu.org/licenses/.
 */

#include <gmp.h>
#include "postgres.h"
#include "fmgr.h"

#include "pgmp-impl.h"

PG_MODULE_MAGIC;

void    _PG_init(void);
void    _PG_fini(void);

static void     *_pgmp_alloc(size_t alloc_size);
static void     *_pgmp_realloc(void *ptr, size_t old_size, size_t new_size);
static void     _pgmp_free(void *ptr, size_t size);

/* A couple of constant limbs used to create constant mp? data
 * from the content of varlena data */
const mp_limb_t _pgmp_limb_0 = 0;
const mp_limb_t _pgmp_limb_1 = 1;

/*
 * Module initialization and cleanup
 */

void
_PG_init(void)
{
    /* A vow to the gods of the memory allocation */
    mp_set_memory_functions(
        _pgmp_alloc, _pgmp_realloc, _pgmp_free);
}

void
_PG_fini(void)
{
}

/*
 * GMP custom allocation functions using PostgreSQL memory management.
 *
 * In order to store data into the database, the structure must be contiguous
 * in memory. GMP instead allocated the limbs dynamically. This means that to
 * convert from mpz_p to the varlena a memcpy would be required.
 *
 * But we don't like memcpy... So we allocate enough space to add the varlena
 * header and we return an offsetted pointer to GMP, so that we can always
 * scrubble a varlena header in front of the limbs and just ask the database
 * to store the result.
 */

static void *
_pgmp_alloc(size_t size)
{
    return PGMP_MAX_HDRSIZE + (char *)palloc(size + PGMP_MAX_HDRSIZE);
}

static void *
_pgmp_realloc(void *ptr, size_t old_size, size_t new_size)
{
    return PGMP_MAX_HDRSIZE + (char *)repalloc(
        (char *)ptr - PGMP_MAX_HDRSIZE,
        new_size + PGMP_MAX_HDRSIZE);
}

static void
_pgmp_free(void *ptr, size_t size)
{
    pfree((char *)ptr - PGMP_MAX_HDRSIZE);
}

/* Return the version of the library as an integer
 *
 * Parse the format from the variable gmp_version instead of using the macro
 * __GNU_PG_VERSION* in order to detect the runtime version instead of the
 * version pgmp was compiled against (although if I'm not entirely sure it is
 * working as expected).
 */
PGMP_PG_FUNCTION(pgmp_gmp_version)
{
    int maj = 0, min = 0, patch = 0;
    const char *p;

    /* Parse both A.B.C and A.B formats. */

    maj = atoi(gmp_version);

    if (NULL == (p = strchr(gmp_version, '.'))) {
        goto end;
    }
    min = atoi(p + 1);

    if (NULL == (p = strchr(p + 1, '.'))) {
        goto end;
    }
    patch = atoi(p + 1);

end:
    PG_RETURN_INT32(maj * 10000 + min * 100 + patch);
}


/* pmpq_arith -- mpq arithmetic functions
 *
 * Copyright (C) 2011 Daniele Varrazzo
 *
 * This file is part of the PostgreSQL GMP Module
 *
 * The PostgreSQL GMP Module is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 3 of the License,
 * or (at your option) any later version.
 *
 * The PostgreSQL GMP Module is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
 * General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the PostgreSQL GMP Module.  If not, see
 * http://www.gnu.org/licenses/.
 */

#include "pmpq.h"
#include "pmpz.h"
#include "pgmp-impl.h"

#include "fmgr.h"
#include "access/hash.h"            /* for hash_any */

/*
 * Unary operators
 */

PGMP_PG_FUNCTION(pmpq_uplus)
{
    const pmpq      *pq1;
    pmpq            *res;

    pq1 = PGMP_GETARG_PMPQ(0);

    res = (pmpq *)palloc(VARSIZE(pq1));
    memcpy(res, pq1, VARSIZE(pq1));

    PG_RETURN_POINTER(res);
}

#define PMPQ_UN(op, CHECK) \
 \
PGMP_PG_FUNCTION(pmpq_ ## op) \
{ \
    const mpq_t     q; \
    mpq_t           qf; \
 \
    PGMP_GETARG_MPQ(q, 0); \
    CHECK(q); \
 \
    mpq_init(qf); \
    mpq_ ## op (qf, q); \
 \
    PGMP_RETURN_MPQ(qf); \
}

PMPQ_UN(neg, PMPQ_NO_CHECK)
PMPQ_UN(abs, PMPQ_NO_CHECK)
PMPQ_UN(inv, PMPQ_CHECK_DIV0)

/*
 * Binary operators
 */

/* Template to generate binary operators */

#define PMPQ_OP(op, CHECK2) \
 \
PGMP_PG_FUNCTION(pmpq_ ## op) \
{ \
    const mpq_t     q1; \
    const mpq_t     q2; \
    mpq_t           qf; \
 \
    PGMP_GETARG_MPQ(q1, 0); \
    PGMP_GETARG_MPQ(q2, 1); \
    CHECK2(q2); \
 \
    mpq_init(qf); \
    mpq_ ## op (qf, q1, q2); \
 \
    PGMP_RETURN_MPQ(qf); \
}

PMPQ_OP(add, PMPQ_NO_CHECK)
PMPQ_OP(sub, PMPQ_NO_CHECK)
PMPQ_OP(mul, PMPQ_NO_CHECK)
PMPQ_OP(div, PMPQ_CHECK_DIV0)

/* Functions defined on bit count */

#define PMPQ_BIT(op) \
 \
PGMP_PG_FUNCTION(pmpq_ ## op) \
{ \
    const mpq_t     q; \
    unsigned long   b; \
    mpq_t           qf; \
 \
    PGMP_GETARG_MPQ(q, 0); \
    PGMP_GETARG_ULONG(b, 1); \
 \
    mpq_init(qf); \
    mpq_ ## op (qf, q, b); \
 \
    PGMP_RETURN_MPQ(qf); \
}

PMPQ_BIT(mul_2exp)
PMPQ_BIT(div_2exp)

/*
 * Comparison operators
 */

PGMP_PG_FUNCTION(pmpq_cmp)
{
    const mpq_t     q1;
    const mpq_t     q2;

    PGMP_GETARG_MPQ(q1, 0);
    PGMP_GETARG_MPQ(q2, 1);

    PG_RETURN_INT32(mpq_cmp(q1, q2));
}

#define PMPQ_CMP_EQ(op, rel) \
 \
PGMP_PG_FUNCTION(pmpq_ ## op) \
{ \
    const mpq_t     q1; \
    const mpq_t     q2; \
 \
    PGMP_GETARG_MPQ(q1, 0); \
    PGMP_GETARG_MPQ(q2, 1); \
 \
    PG_RETURN_BOOL(mpq_equal(q1, q2) rel 0); \
}

PMPQ_CMP_EQ(eq, !=)     /* note that the operators are reversed */
PMPQ_CMP_EQ(ne, ==)

#define PMPQ_CMP(op, rel) \
 \
PGMP_PG_FUNCTION(pmpq_ ## op) \
{ \
    const mpq_t     q1; \
    const mpq_t     q2; \
 \
    PGMP_GETARG_MPQ(q1, 0); \
    PGMP_GETARG_MPQ(q2, 1); \
 \
    PG_RETURN_BOOL(mpq_cmp(q1, q2) rel 0); \
}

PMPQ_CMP(gt, >)
PMPQ_CMP(ge, >=)
PMPQ_CMP(lt, <)
PMPQ_CMP(le, <=)

/* The hash of an integer mpq is the same of the same number as mpz.
 * This allows cross-type hash joins with mpz and builtins.
 */
PGMP_PG_FUNCTION(pmpq_hash)
{
    const mpq_t     q;
    Datum           nhash;

    PGMP_GETARG_MPQ(q, 0);

    nhash = pmpz_get_hash(mpq_numref(q));

    if (mpz_cmp_si(mpq_denref(q), 1L) == 0) {
        return nhash;
    }

    PG_RETURN_INT32(
        DatumGetInt32(nhash) ^ hash_any(
            (unsigned char *)LIMBS(mpq_denref(q)),
            NLIMBS(mpq_denref(q)) * sizeof(mp_limb_t)));
}

/* limit_den */

static void limit_den(mpq_ptr q_out, mpq_srcptr q_in, mpz_srcptr max_den);

PGMP_PG_FUNCTION(pmpq_limit_den)
{
    const mpq_t     q_in;
    const mpz_t     max_den;
    mpq_t           q_out;

    PGMP_GETARG_MPQ(q_in, 0);
    if (PG_NARGS() >= 2) {
        PGMP_GETARG_MPZ(max_den, 1);
    }
    else {
        mpz_init_set_si((mpz_ptr)max_den, 1000000);
    }

    if (mpz_cmp_si(max_den, 1) < 0)
    {
        ereport(ERROR, ( \
            errcode(ERRCODE_INVALID_PARAMETER_VALUE), \
            errmsg("max_den should be at least 1"))); \
    }

    mpq_init(q_out);
    limit_den(q_out, q_in, max_den);

    PGMP_RETURN_MPQ(q_out);
}

/*
 * Set q_out to the closest fraction to q_in with denominator at most max_den
 *
 * Ported from Python library: see
 * http://hg.python.org/cpython/file/v2.7/Lib/fractions.py#l206
 * for implementation notes.
 */
static void
limit_den(mpq_ptr q_out, mpq_srcptr q_in, mpz_srcptr max_den)
{
    mpz_t p0, q0, p1, q1;
    mpz_t n, d;
    mpz_t a, q2;
    mpz_t k;
    mpq_t b1, b2;
    mpq_t ab1, ab2;

    if (mpz_cmp(mpq_denref(q_in), max_den) <= 0) {
        mpq_set(q_out, q_in);
        return;
    }

    /* p0, q0, p1, q1 = 0, 1, 1, 0 */
    mpz_init_set_si(p0, 0);
    mpz_init_set_si(q0, 1);
    mpz_init_set_si(p1, 1);
    mpz_init_set_si(q1, 0);

    /* n, d = self._numerator, self._denominator */
    mpz_init_set(n, mpq_numref(q_in));
    mpz_init_set(d, mpq_denref(q_in));

    mpz_init(a);
    mpz_init(q2);

    for (;;) {
        /* a = n // d */
        mpz_tdiv_q(a, n, d);

        /* q2 = q0+a*q1 */
        mpz_set(q2, q0);
        mpz_addmul(q2, a, q1);

        if (mpz_cmp(q2, max_den) > 0) { break; }

        /* p0, q0, p1, q1 = p1, q1, p0+a*p1, q2 */
        mpz_swap(p0, p1);
        mpz_addmul(p1, a, p0);
        mpz_swap(q0, q1);
        mpz_swap(q1, q2);

        /* n, d = d, n-a*d */
        mpz_swap(n, d);
        mpz_submul(d, a, n);
    }

    /* k = (max_denominator - q0) // q1 */
    mpz_init(k);
    mpz_sub(k, max_den, q0);
    mpz_tdiv_q(k, k, q1);

    /* bound1 = Fraction(p0+k*p1, q0+k*q1) */
    mpq_init(b1);
    mpz_addmul(p0, k, p1);
    mpz_set(mpq_numref(b1), p0);
    mpz_addmul(q0, k, q1);
    mpz_set(mpq_denref(b1), q0);
    mpq_canonicalize(b1);

    /* bound2 = Fraction(p1, q1) */
    mpq_init(b2);
    mpz_set(mpq_numref(b2), p1);
    mpz_set(mpq_denref(b2), q1);
    mpq_canonicalize(b2);

    /* if abs(bound2 - self) <= abs(bound1 - self): */
    mpq_init(ab1);
    mpq_sub(ab1, b1, q_in);
    mpq_abs(ab1, ab1);

    mpq_init(ab2);
    mpq_sub(ab2, b2, q_in);
    mpq_abs(ab2, ab2);

    if (mpq_cmp(ab2, ab1) <= 0) {
        /* return bound2 */
        mpq_set(q_out, b2);
    }
    else {
        /* return bound1 */
        mpq_set(q_out, b1);
    }
}


@marwilliamson @andrealane1 There should also be a group Of Life Coaches comprised of 80% Women of Color who crushed COVID19 100% in 2O20 who are both COVID19 and CANCER Survivors.
This book by Dr. David Spangler MD. PHD. wil provecthat we offer a clear scientifically viable option to vaccines. https://t.co/RGMrHJvYqQ


@unitysf_240page 1480 Church St. Noe Valley for years. Loved it. We have crushed COVID19 in all of 2020. This book will inform you why 60 countries choose our PDR aporoved  immune boosters above any vaccines. https://t.co/rwUpt4Rgl2


Geek medical post of the month: yes, Trump is lying about how much vaccine he had made. What an a$$hole. https://t.co/0nJ9eRGEEK


@ElonMuskNewsOrg
@elonmusk
This book will prove to you that we have something  20 years ahead of vaccines. https://t.co/qDT6yi9yAC


I will believe it when I see it.
Just goes to show what an utter failure the #Trump administration is...
Good riddance to bad rubbish.
Now let's get the vaccines out sooner then later please. There have been to many lives lost. https://t.co/wKraZK93oG


Our Hidden Figures if COVID19 are 80% Women Of Color. With this book, ye shall know the truth about the immune system and vaccines.
@womenofcolor @WOCNetwork @WOCNetwork @womenofcolorfdn @WLGH2020 @RockWOC @womenofcolorusa @TruDescendent @Womanofcolor7 https://t.co/57AxYZlk8W https://t.co/1m1pGaYdIt


Context: Provided is a universal Ku band LNB (9.75/10.600 GHz) which is fitted at the end of the dish and pointed at the correct satellite constellation; most digital receivers will receive the free to air channels. Some broadcasts are free-to-air and unencrypted, some are encrypted but do not require a monthly subscription (known as free-to-view), some are encrypted and require a monthly subscription, and some are pay-per-view services. To view the encrypted content a VideoGuard UK equipped receiver (all of which are dedicated to the Sky service, and cannot be used to decrypt other services) needs to be used. Unofficial CAMs are now available to view the service, although use of them breaks the user's contract with Sky and invalidates the user's rights to use the card.

Question: What is the universal band that digital recievers will receive free to air channels on?

9.75/10.600 GHz
universal Ku band
Ku band


Context: At the beginning of the 20th century, important advancement in geological science was facilitated by the ability to obtain accurate absolute dates to geologic events using radioactive isotopes and other methods. This changed the understanding of geologic time. Previously, geologists could only use fossils and stratigraphic correlation to date sections of rock relative to one another. With isotopic dates it became possible to assign absolute ages to rock units, and these absolute dates could be applied to fossil sequences in which there was datable material, converting the old relative ages into new absolute ages.

Question: What did using fossils help change for scientists?


Context: Packet mode communication may be implemented with or without intermediate forwarding nodes (packet switches or routers). Packets are normally forwarded by intermediate network nodes asynchronously using first-in, first-out buffering, but may be forwarded according to some scheduling discipline for fair queuing, traffic shaping, or for differentiated or guaranteed quality of service, such as weighted fair queuing or leaky bucket. In case of a shared physical medium (such as radio or 10BASE5), the packets may be delivered according to a multiple access scheme.

Question: If there is no radio or 10BASE5, how are the packets delivered?


Context: Many complexity classes are defined using the concept of a reduction. A reduction is a transformation of one problem into another problem. It captures the informal notion of a problem being at least as difficult as another problem. For instance, if a problem X can be solved using an algorithm for Y, X is no more difficult than Y, and we say that X reduces to Y. There are many different types of reductions, based on the method of reduction, such as Cook reductions, Karp reductions and Levin reductions, and the bound on the complexity of reductions, such as polynomial-time reductions or log-space reductions.

Question: What are two examples of different types of reduction?

Karp reductions and Levin reductions
Cook reductions, Karp reductions


Context: In 1096, Crusaders passing by the siege of Amalfi were joined by Bohemond of Taranto and his nephew Tancred with an army of Italo-Normans. Bohemond was the de facto leader of the Crusade during its passage through Asia Minor. After the successful Siege of Antioch in 1097, Bohemond began carving out an independent principality around that city. Tancred was instrumental in the conquest of Jerusalem and he worked for the expansion of the Crusader kingdom in Transjordan and the region of Galilee.[citation needed]

Question: When did Tancred lay siege to Antioch?


Context: In October 2010, the open-access scientific journal PLoS Pathogens published a paper by a multinational team who undertook a new investigation into the role of Yersinia pestis in the Black Death following the disputed identification by Drancourt and Raoult in 1998. They assessed the presence of DNA/RNA with Polymerase Chain Reaction (PCR) techniques for Y. pestis from the tooth sockets in human skeletons from mass graves in northern, central and southern Europe that were associated archaeologically with the Black Death and subsequent resurgences. The authors concluded that this new research, together with prior analyses from the south of France and Germany, ". . . ends the debate about the etiology of the Black Death, and unambiguously demonstrates that Y. pestis was the causative agent of the epidemic plague that devastated Europe during the Middle Ages".

Question: What scientific journal in France published a prior analysis of the Black Death?


An atherosclerosis risk factor assessment program for patients with peripheral arterial occlusive disease.

From a group of 251 high-risk patients less than 65 years of age, 84 with angiographic or vascular laboratory proven peripheral arterial occlusive disease were evaluated in detail.

The following risk factors were identified: smoking in 91% with an average of 35 +/- 18 pack/years; treated or untreated hypertension in 40%; hyperlipidemia in 49%; obesity with a body weight greater than 120% of ideal in 18%; diabetes in 9%; family history of premature vascular disease in 70%; and hyperuricemia in 13%.

Based on these results, we have introduced a practical approach for investigating and managing risk factors that can be administered by paramedical personnel, utilizing a questionnaire given to patients and standard blood tests to identify important risk factors.

The results of the completed questionnaires and blood test are entered on a microcomputer.

A program written using d-Base III stores the data, identifies the risk factors and grades their severity.

We have designed an information booklet that highlights the individual patient's risk factors and suggests alternatives for management based on the sources of medical and community help available in our area.


WINNER: Sean T. Kean (R)

Attorney

Howard Kleinhendler (D)

Attorney

Shaun O'Rourke (D)

Retired

WINNER: David P. Rible (R)

Legislator

David Schneck (I)

In brief, what will be your top three priorities if elected (one sentence each, please).

Should the state provide more school choice for children, including the expansion of charter schools, vouchers for private schools and enabling children to attend public schools outside of their home districts?

Would you make any changes to how schools are funded by the state, including so-called Abbott districts and wealthier suburban localities?

Should the state continue to adopt regional planning initiatives to prevent sprawl, and if so, how should preservation be funded?

Do you support Gov. Christie's energy master plan or would you seek more lofty goals for conservation and renewable energy?

Experts say New Jersey's transportation infrastructure is crumbling.

How should the state fund upgrades: continued bonding or borrowing, a gas tax, toll hikes or some other specified method?

What would you do to provide relief for property taxpayers -- for example, further program cuts, additional state aid and rebates -- and should municipalities and schools be forced to do more to regionalize or share services?

What can be done to improve the public discourse here in New Jersey?

WINNER: Sean T. Kean:
The candidate has not responded to repeated requests to answer questions.

Shaun O'Rourke:
Fix the State of New Jersey.

The tax system needs to be altered to tax wealth, not income.

Mandated Education needs to be entirely funded by the State without the use of property taxes.

Regional services, that save costs, need to aggressively pursued.

Shaun O'Rourke:
The State of New Jersey, not local municipal taxes, should pay every penny our constitution mandates for a thorough and efficient education.

How the State accomplishes that is subject to recognizing tried and true educational services while allowing experimentation on new methods for encouraging success in our students.

Every means should be explored in this goal.

If a given jurisdiction wants "extra" educational activities beyond the scope of "thorough and efficient", they should have nothing placed in their way which would prevent their raising funds from their own citizens for something their own citizens feel is important for their children. "

Abbott" district funding would need not exist if the State funds its mandate without the use of local property taxes.

Shaun O'Rourke:
Regional planning has been an exercise in power brokering between pro-development and pro-preservation lobbies.

Success has been in the eye of the beholder.

I feel Pinelands was too protective, CAFRA was too lenient, and Highlands a miserable compromise.

The State development strategies have been largely ignored by local municipalities as either pie in the sky or too onerous.

Underfunded regulatory/planning offices have been used as pawns to demonstrate political agendas.

Fund preservation and total mitigation of regional effects from development through a developers' fee.

Shaun O'Rourke:
The Governor's farce, I mean plan, is an insult to twenty-first century New Jerseyans.

Our State could be a net energy producer using clean and renewable technologies that exist today.

We need politicians willing to make the necessary choices that will bring the financial, environmental, and societal benefits clean energy production would bring with it.

We could cut taxes on our citizens by using the funds generated through our clean energy generation facilities.

And we don't need to choose between farms and energy.

Shaun O'Rourke:
Stop using funds for highways to build sound walls for wealthy communities.

The State doesn't fund upgrades, its people do through taxes and fees, occasionally, with the matching grant help of our federal taxes and fees.

Require State taxes to fund Through and efficient education.

NO free rides for police services in the 99 towns now receiving it.

Make more effective and fiscally prudent use of our public places to generate more revenue.

Shaun O'Rourke:
Rewrite the NJ Constitution to eliminate legislative power brokering, eliminate political influences on our courts, and free the executive to get his legislative mandates accomplished.

Require every legislative action to include specifically how it is to be paid for.

Governor's position and make it an elected Comptroller who audits bills to verify their fiscal responsibility and has absolute veto power if they have not paid for themselves.

The comptroller can be next in succession to the governor.

Public Service:38 months as Point Pleasant Borough Council member.

With short breaks in service, Point Pleasant Borough Planning Board member 1979-present (Chair, Vice chair on occasion) PP Boro Environmental Commission member and chair 1979-1985+.

WINNER: David P. Rible :
The candidate has not responded to repeated requests to answer questions.


504 F.2d 453
CHICAGO AND NORTH WESTERN TRANSPORTATION COMPANY, acorporation, Plaintiff-Appellant,v.CHICAGO, ROCK ISLAND AND PACIFIC RAILROAD COMPANY, acorporation, Defendant-Appellee.

CHICAGO AND NORTH WESTERN TRANSPORTATION COMPANY, acorporation, Plaintiff-Appellant,v.BURLINGTON NORTHERN INC.,

United States Court of Appeals, Seventh Circuit.

Argued Sept. 20, 1974.Decided Oct. 23, 1974.

Christopher A. Mills, Chicago, Ill., for plaintiff-appellant.

O. L. Houts, Richard J. Schreiber, Chicago, Ill., for defendants-appellees.

Before CASTLE, Senior Circuit Judge, and FAIRCHILD and SPRECHER, Circuit Judges.

1
Plaintiff Chicago and North Western Transportation Company ('North Western') appeals the dismissal of its complaints seeking enforcement of its protective services contract with the defendants Chicago, Rock Island and Pacific Railroad Company ('Rock Island'), and Burlington Northern Inc.  ('Burlington').

North Western argues on appeal that the district court erroneously concluded that the contract was unenforceable because it had not been submitted to the Interstate Commerce Commission as required by Section 1(14)(b) of the Interstate Commerce Act, 49 U.S.C. 1(14)(b) (1970).

2
North Western, Rock Island, and Burlington are common carriers by rail.

North Western owns and operates a railroad terminal facility known as the Wood Street Terminal, which is used chiefly as a receiving and distribution center for carload shipments of perishable produce.

Pursuant to Sections 1(3)(a) and 1(4) of the Act and applicable tariffs, North Western is obligated to provide protective service against heat and cold to refrigerator car shipments of perishables while they are under its control.

Protection is accomplished by refilling the ice bunkers of the refrigerator cars while at the Wood Street Terminal with ice supplied to North Western under a contract with City Products Corporation, an independent contractor.

City Products loads the ice into the bunkers at the direction of North Western.

3
North Western, Rock Island, and Burlington are parties to an agreement known as National Perishable Freight Committee Division Sheet 7 ('Division Sheet 7'), under which North Western is entitled to recover its actual cost of performing the protective services.

Both Rock Island and Burlington, however, have not fully reimbursed North Western for the actual cost of the protective services rendered, and North Western filed the instant complaints to recover the amounts owed.

Division Sheet 7 apparently has never been submitted to the ICC for approval, and the district court found that this fact precluded liability based on that agreement.

Section 1(14)(b) provides in part:

4
It shall be unlawful for any common carrier by railroad . . .

to make or enter into any contract, agreement, or arrangement with any person for the furnishing to or on behalf of such carrier . . .

of protective service against heat or cold . . .

unless and until such contract, agreement, or arrangement has been submitted to and approved by the Commission as just, reasonable, and consistent with the public interest . . ..

801, 807-808 (N.D.Ill.1973), Judge Bauer concluded that Division Sheet 7 need not be submitted to the ICC for approval because Section 1(14)(b) does not apply to protective service contracts between common carriers themselves.1  We agree.

In Section 1(3)(a) of the Act, Congress has defined 'person' to include 'an individual, firm, copartnership, corporation, company, association, or joint-stock association . . ..'

In that same section, however, Congress has separately defined 'common carrier' as inter alia, 'all persons, natural or artificial, engaged in . . .

Thus, the definition of 'person' is not sufficient to encompass 'common carrier.'

Since Section 1(14) (b), which carefully differentiates between the two terms, applies only to agreements between a 'common carrier' and any 'person,' Commission approval of protective service agreements between common carriers is not required.

6
The purpose behind the enactment of Section 1(14)(b) confirms our conclusion.

Although the Act provides that it is the duty of every common carrier to provide protective services, these services were often supplied to or on behalf of the railroads by railroad-owned subsidiaries (car-line companies) which were not carriers and therefore not subject to Commission regulation.

See Ellis v. ICC, 237 U.S. 434, 35 S.Ct.

This prevented the Commission from determining the actual cost of providing protective services so that it would have a proper basis for prescribing cost-related tariff charges to be paid for by shippers.

See, e.g., Refrigeration Charges on Fruits, Vegetables, Berries, and Melons From the South, 151 I.C.C. 649, 693 (1929).

To remedy this situation, Section 1(14)(b) was included as part of the Transportation Act of 1940 to enable the Commission to exercise supervision over the cost of furnishing protective services by those who were not common carriers.

Accordingly, Congress employed the term 'person' in Section 1(14)(b) to achieve that end.

7
The court below relied on the Commission's report in Ex Parte No.

137, Contracts for Protective Services, 318 I.C.C. 111, 125 (1962), directly carriers to submit for its approval 'contracts covering protective services which shall replace all prior contracts, including division sheet 7,' to support its ruling that Section 1(14)(b) requires Commission approval of agreements between common carriers.

First, all of the agreements before the Commission in that report were between various carriers and specified protective service companies, and none was solely between rail carriers.

Second, the question whether Section 1(14)(b) requires Commission approval of Division Sheet 7 was never raised in that proceeding.

Similarly, that question was not raised before the Commission in Ex Parte No.

137, Contracts for Protective Services, 278 I.C.C. 531 (1950), where agreements for protective services between carriers were submitted by the carriers to the Commission for approval.

We are satisfied that these decisions do not indicate any belief by the Commission that Section 1(14)(b) requires approval of protective service contracts between common carriers.

8
The district court also determined that Division Sheet 7 was unenforceable because City Products' contract to supply ice to North Western had not been approved by the ICC Section 1(14)(b), however, only requires Commission approval of contracts between a common carrier and the person who furnishes the protective services.

City Products did not contract to provide protection against heat and cold to North Western, and therefore the contract itself does not constitute a protective service agreement as contemplated by Section 1(14) (b).

9
Moreover, it cannot be found that City Products actually contracted to provide protective services to Rock Island and Burlington.

Division Sheet 7 is not converted into a protective service agreement between City Products and the carriers by the fact that the cost of protective services to Rock Island and Burlington depends on the cost of ice to North Western, or by the fact that City Products loads the ice into the bunkers of the refrigerator cars.

City Products does not receive any of the tariff revenues paid to North Western under Division Sheet 7, but is compensated for the ice under a separate contract at a stated annual price per ton, and the loading is done only at North Western's direction and in order to avoid needless duplication of effort.

Thus, the arrangement here is readily distinguishable from that in Pacific Fruit Express Co. v. Akron, Canton & Youngstown, R.R., 355 F.Supp.

700 (N.D.Cal.1973) because in that case the mechanical protective service arrangement was directly between the car-line company and the carriers.

We conclude, therefore, that the contract with City Products does not defeat the enforcement of Division Sheet 7 by North Western.

10
Finally, Burlington argues for the first time on appeal that North Western's actions to recover its uncompensated cost of providing protective services are in reality an attempt to obtain a retroactive division of freight revenues, and that as a result the actions are precluded by Section 15(6) of the Interstate Commerce Act and by Supreme Court decisions interpreting that section.

North Western is not seeking any retroactive readjustment of revenues, but only brings these actions to recover amounts owed as provided for by the terms of Division Sheet 7 in effect since its existence.

11
The judgments of the district court are reversed.

1
 Two other district courts have reached the same conclusion.


Ultrashort pulse characterization by ultra-thin ZnO, GaN, and AlN crystals.

Ultra-thin semiconductor crystals were investigated as nonlinear materials for second-harmonic generation.

Nonlinear susceptibilities of sub-micrometer- thick ZnO, GaN, and AlN crystals were measured, and these crystals were used for sub-10-fs pulse measurement by a fringe-resolved autocorrelation method.

We found that a one-cycle pulse could be characterized by using these ultra-thin-film crystals.


n, m = map(int, input().split())

mat_A = []
vec_b = []

for j in range(n):
    mat_A.append(list(map(int, input().split())))
for i in range(m):
    vec_b.append(int(input()))

for j in range(n):
    tmp = 0
    for i in range(m):
        tmp += mat_A[j][i] * vec_b[i]
    print(tmp)

while True:
    H, W = map(int, input().split())
    if not(H or W):
        break
    print('#' * W)
    for i in range(H-2):
        print('#' + '.' * (W - 2) + '#')
    print('#' * W, end='\n\n')


n,q = map(int,raw_input().split())
task = []
lst = []
a = 0
for i in range(n):
    name,time = raw_input().split()
    task.append(int(time))
    lst.append(name)
while True:
	if task[0] > q:
		task[0] = task[0] - q
		task.append(task.pop(0))
		lst.append(lst.pop(0))
		a += q
	else:
		a += task[0]
		print lst[0],a
		task.pop(0)
		lst.pop(0)
		if len(lst) == 0:
			break

n,m = map(int,input().split())
a = [0]*n
ac =0
wa = 0

for i in range(m):
    p,s =  map(str,input().split())
    p = int(p)
    if s == "AC" and a[p-1] !=-1:
        ac +=1
        wa += a[p-1]
        a[p-1] = -1
    elif s =="WA" and a[p-1] != -1:
        a[p-1] += 1
print(ac,wa)


N = int(input())
A = list(map(int,input().split()))

minm = A[0]
ans = 0
for i in range(1,N):
    if A[i] < minm:
        ans += minm - A[i]
    if A[i] > minm:
        minm = A[i]

print(ans)

N = int(input())
A = list(map(int, input().split()))

ans = 0

for i in range(N - 1):
    if A[i] > A[i + 1]:
        ans += A[i] - A[i + 1]
    A[i + 1] = max(A[i], A[i + 1])

print(ans)


K = int(input())
ans = -1
keep = 0
check = 7
for i in range(K):
    keep = (keep + check) % K
    if keep == 0:
        ans = i + 1
        break
    check = (check * 10) % K
print(ans)

import sys
K=input()
if int(K)%2==0:
    print(-1)
    sys.exit()

S=int('7'*(len(K)))
ans=len(K)
K=int(K)
for i in range(10**6):
    if S%K==0:
        print(ans)
        break
    else:
        S=(S*10)%K+7
        ans+=1
else:
    print(-1)


N,X,Y = (int(x) for x in input().split())
A = [0]*(N)

for i in range(1,N):
    for j in range(i+1,N+1):
        if j <= X or i >= Y:
            A[j-i] += 1
        else:
            A[min((j-i),(abs(i-X)+abs(j-Y)+1))] += 1

for i in range(1,N):
    print(A[i])

from collections import defaultdict

N, X, Y = map(int, input().split())
cnt_dict = defaultdict(int)

for i in range(1,N):
    for j in range(i+1, N+1):
        if j<=X or i>=Y:
            path = j-i
        else:
            path = min(j-i, abs(X-i)+abs(j-Y)+1)
        cnt_dict[path] += 1

for i in range(1,N):
    print(cnt_dict[i])


#importing libraries


from sklearn.cluster import KMeans


import pandas as pd


from sklearn.preprocessing import MinMaxScaler


import matplotlib.pyplot as plt


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: As the barometer reading goes lower there is not a greater chance of
A. sunshine
B. getting wet
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: If a cat has a body temp that is below average, it isn't in
A. danger
B. safe ranges
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: Coral is not a type of living organism which can be identified in
A. saltwater locations that are open
B. any where with liquid
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: an inherited characteristic found on all mammals isn't
A. fur
B. shoes
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: The type of climate change known as anthropogenic isn't caused by this:
A. volcanic activity
B. humanity
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: If a thing is going between liquid and solid, it is not likely to
A. measure consistently
B. be a door
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: Which was not happens most near canyons
A. riverflow
B. fear
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: which isn't most likely to be eaten by a rabbit
A. dandelions
B. spiders
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: This isn't likely to be an insulator
A. a flip flop
B. a can
Answer:


Prompt:
The following are multiple choice questions (with answers) about common sense.

Question: A ferret darting around a space in the wild in a panic is not likely
A. eluding foe
B. laying eggs
Answer:


Diesel model Winnie Harlow, who suffers from vitiligo, the same rare skin condition that singer Michael Jackson was diagnosed with, has been pictured enjoying a cozy night on the town with albino fashion star Shaun Ross. The pair attended a launch event for Popular magazine at Siren Studios in Hollywood, California, on Tuesday night, and were snapped holding hands while making their way into the venue. Winnie, 19, who was unveiled as one of the newest faces of fashion label Diesel earlier this year, was wearing a short and simple black and gold mini dress, which she accessorized with a pair of gold strappy heels. Scroll down for video . Looking cozy: Winnie Harlow, 19, who suffers from the same rare skin condition as Michael Jackson, was pictured hand-in-hand with albino model Shaun Ross on Tuesday night . Out on the town: The duo were attending the launch for Popular magazine at Hollywood venue Siren Studios . Skingraft black and gold dress . Get it from Pasar here . Visit site . This look is all types of yes. Winnie Harlow looks incredible in her leather tunic dress which features striking gold trims on the sleeves and hemline. The loose fit creates a flattering silhouette too. Winnie's dress is from LA-based fashion house Skingraft, and you can still buy it by clicking right to Paser's website now. It'll be your go-to party piece! It is however, slightly pricey coming in at $750, so if you want to add a golden standard to your style for less, why not check out these various finds below? We are particularly dazzled by this Mynt 1792 number at Nordstrom. A pair of strappy metallic heels will finish off your look to perfection! Choice's black and gold stamping dress . Visit site . Mynt 1792 color block dress at Nordstrom . Visit site . Maykool black and gold dress . Visit site . Dailylook fit and flare dress . Visit site . Meanwhile Shaun, 23, opted for a more low-key look, wearing an all-black ensemble, which he topped off with a unique tall baseball hat and a pair of leather sneaker-style boots. And while it appears to be the first time that the duo have been spotted enjoying an evening out together, it is likely not the first occasion that they have met. Both stars have made regular appearances on the catwalks at various Fashion Weeks, while Shaun has also starred in campaigns for the likes of Alexander McQueen and Givenchy. Coincidentally, the models also each had a helping hand from fellow fashion star Tyra Banks. Fashion stars: While Evan opted for an all-black ensemble, topped off with a bizarre baseball cap, Winnie wore a black and gold mini dress and strappy sandals . Rising stars: Both Shaun and Winnie have each achieved global recognition in the fashion indsutry, appearing in numerous high-profile fashion campaigns . Strut your stuff: Both Winnie (L), pictured at the Desigual fall/winter 2015 show, and Shaun (R), pictured on the catwalk in February, boast impressive runway credentials . Winnie, whose real name is Chantelle Brown-Young, was one of the contestants on Tyra's hit reality series America's Next Top Model, while Shaun made an appearance on the former model's eponymous talk show in 2009. Despite their cozy appearance, it's not thought that the two are dating - however Shaun did take the time to post a heartwarming message to the model on his Instagram account, just hours after the pair attended the Popular magazine event. Alongside an image of the two of them, Shaun wrote: 'So much fun last night @winnieharlow keep up the good work. From an original believer in you.' And it seems his sweet sentiments were reciprocated by Winnie, who posted a similar image on her own account, saying: 'Sweet nothings with my fly friend @shaundross'

Winnie, 19, was diagnosed with the rare condition when she was four-years-old .
Condition causes a lack of melanin which forms white patches on the skin .


(CNN)When Melissa Atkins Wardy, author of "Redefining Girly" and a passionate advocate for fighting gender stereotypes, heard from a frustrated mom on Facebook, she knew she needed to do something. So she shared the mom's story. In a blog post, Wardy told how the mom, Veronica of Richland, Washington, wanted to buy "Big Hero 6" fabric to make pillows for her two children. The problem? The fabric didn't include two of the heroes from the movie: the female characters, Honey Lemon and GoGo. So Veronica decided to send an email to Springs Creative, the company that makes the fabric, saying that as a woman and an engineer, she was offended. She got an answer from the company but it didn't help. Girl empowerment ads like GoldieBlox: Do they work? A licensing manager for Springs Creative responded that the company has found that boys don't want girl characters on their things. "Eeeww girls! Yuck! Haha," the licensing manager wrote. It will come as no surprise that Veronica was none too pleased to receive that response. "I was frustrated and disgusted that a manager, and a female manager too, would laugh off my initial contact with the company. It was unprofessional. So I responded," Veronica told CNN. She asked that we not use her last name, in order to maintain her privacy. In an email back to the company, Veronica wrote, "By eliminating the women in your fabric design, you are telling boys that it's OK to think girls are yucky, unworthy and less than a boy. "You are also telling girls they are unworthy, unwanted and that it's un-cool to be smart and confident." What happened next shows that parents, aided by social media outrage, may have more leverage to combat gender stereotyping in our culture than they realize. And the "Big Hero 6" example -- along with a similar recent one involving TOMS, the shoes retailer -- suggests that manufacturers may be finally getting it, too. First, the rest of the story about Springs Creative and the "Big Hero" fabric: After sharing Veronica's story with her readers and her 6,700 Twitter followers, Wardy encouraged people to give Springs Creative a piece of their mind. She also invited them to tweet their own stories with the hashtag #IncludeTheGirls. Women responded in droves, pointing out how Black Widow, the female character in the popular "Avengers" superhero movie franchise, is often excluded from merchandise and how cereal boxes rarely include female characters. "This sends the direct message to both boys and girls that females are forgettable, unimportant, undesirable. What a horrible thing to teach our children!" said Wardy, who is also the founder and chief executive officer of Pigtail Pals & Ballcap Buddies, a company that makes empowering clothing for boys and girls. "The prevailing theory is, 1. boys are the default audience, and 2. boys won't want an item with a girl on it," Wardy said. "Yet, I talk with thousands of parents every week who say otherwise." Why trying to make our kids happy can backfire . Those parents are clearly making their voices heard. Because not too long after Veronica received her initial response from Springs Creative, Wardy said she got a call from the company, asking her to post a statement from Springs Creative on her site. "It is sometimes difficult to hear negative feedback but the message was clear and we intend to act upon your message," the statement read. "Most importantly, Springs Creative does not condone sexism in any shape or form and does not design products to shine a negative light on females OR males." The company said it would be talking with Disney "immediately" about additional designs for "Big Hero 6" that would incorporate all the characters. "We would never intentionally offend any segment of the population. We are a strong company with positive morals and values and we respect and see both genders equally," said the statement. Springs Creative told CNN it would have no further comment. Veronica said she was surprised the company responded so quickly. "I do not believe this would have happened without the Pigtail Pals and Ballcap Buddies community also raising their voices." The real March Madness: When will women's teams get equal buzz? Around the same time, Wardy heard from another follower about an issue with TOMS and wrote about it on her site. On the normally progressive retailer's Web landing page for kids were photos that some parents felt played into gender stereotypes. One photo suggested "Playtime Approved" shoes for boys, and the other, this one on a pink background, included the caption "Little Ladies: adorn their feet for spring." "Really, TOMS? Girls are not ornaments we adorn. Girls play, too!" Wardy wrote on her Facebook page. Two hours later, Wardy received a comment from TOMS on her Facebook page, saying that the company completely agrees and that the wording has been changed to now say "new arrivals for kids." "We're really grateful whenever our community brings something like this to our attention," said Doug Piwinski, senior vice president, global marketing and communications for TOMS. "Perhaps as much or more than any other brand, I mean we really listen to our customers in our community." So, here's my question: Are the two speedy responses from companies after women spoke out on social media more a sign that companies are truly getting it about gender stereotypes and girl and boy empowerment, or more a sign of the power of parents? Or are they a mixture of both? How to Super Bowl #LikeAGirl . Wardy said there's no doubt that companies are in business to protect their bottom line, and that will always be a motivator. But she said these back-to-back incidents show what can happen when parents make it clear they won't buy products from companies that sell gender stereotypes. " 'Be not silent' is my mantra. Speak up!" Wardy said. "The success with Springs Creative and TOMS and other wins we've had in the past is an example of the power of parents (moms and dads) and children's advocates aggregating their voices to say, 'Enough is enough.' " Veronica said it's a sign of the power of parents becoming "more aware, reactive and using social media to make their voices heard by companies that market to children." She added, "One voice can be dismissed; the hailstorm of voices collectively cannot be ignored so easily." It is clear, from these two examples, that parents using their voices online and with their wallets can encourage companies to change. There's no question that raising awareness about stereotypes helps, said Wardy. "If companies aren't paying attention by now, they most certainly should be." Pink, princess-y and sexy too soon . Do you think more companies are getting the message to include girl characters on merchandise? Share your thoughts with Kelly Wallace on Twitter or CNN Living on Facebook.

A mom of two got upset when "Big Hero 6" fabric didn't include the two female characters .
Another mom called attention to gender stereotypes on a TOMS Web page .
In both cases, the companies responded quickly to answer parents' concerns .


(CNN)Blinky and Pinky on the Champs Elysees? Inky and Clyde running down Broadway? Power pellets on the Embarcadero? Leave it to Google to make April Fools' Day into throwback fun by combining Google Maps with Pac-Man. The massive tech company is known for its impish April Fools' Day pranks, and Google Maps has been at the center of a few, including a Pokemon Challenge and a treasure map. This year the company was a day early to the party, rolling out the Pac-Man game Tuesday. It's easy to play: Simply pull up Google Maps on your desktop browser, click on the Pac-Man icon on the lower left, and your map suddenly becomes a Pac-Man course. Twitterers have been tickled by the possibilities, playing Pac-Man in Manhattan, on the University of Illinois quad, in central London and down crooked Lombard Street in San Francisco, among many locations: .

Google Maps has a temporary Pac-Man function .
Google has long been fond of April Fools' Day pranks and games .
Many people are turning their cities into Pac-Man courses .


(CNN)Would you want a TV program about your family history to include details of a distant, long-deceased relative who had owned slaves? Seriously, who in their right mind would want to be tarnished by the sins of an ancestor you had no connection to other than a remote bloodline? I wouldn't, and neither did Ben Affleck, who lobbied producers of a PBS show, "Finding Your Roots," to remove any reference to his great-great-great grandfather Benjamin Cole, a Georgia slave owner in the mid-1800's, in an episode that looked at Affleck's family history. (Affleck revealed Cole's name Wednesday night.) Here's the thing that might surprise many, given the tendency of the media to exploit any potentially scandalous material: The show's producer, Harvard professor Henry Louis Gates Jr., apparently acquiesced to Affleck's request, because when the episode aired in October 2014, there was no mention of the star's slave-owning ancestor. Affleck's attempt to alter the content of the program only publicly became known a few days ago after WikiLeaks released hacked emails revealing an exchange between Gates and Sony Pictures chief Michael Lynton. When Gates asked how he should respond to Affleck's request to delete the material, Lynton responded, "all things being equal, I would definitely take it out." And on Tuesday, Affleck, via Facebook, admitted that he had urged Gates to excise any reference to his slave-owning relative. Affleck explained, "I didn't want any television show about my family to include a guy who owned slaves. I was embarrassed. The very thought left a bad taste in my mouth." Now Gates has publicly denied that he made his decision about the content of the program based on Affleck's request, but it seems likely that he did. After all, Affleck noted as much in his Facebook post, writing that Gates "agreed with me on the slave owner but made other choices I disagreed with." And three other celebrities profiled on the series last season were shown to have been related to slave owners. So it's unlikely that it was simply happenstance that it left out any reference to Affleck's familial slave ownership connection. In any event, PBS has launched an internal review to determine if the show violated its own editorial standards. Whatever the results of the review, Affleck and Gates did the right thing. Let's be clear: "Finding Your Roots" is not an investigative news show; it's an entertainment program. In fact, as Affleck noted, much of the material is provided directly by the celebrity being profiled. It's not "60 Minutes" but more in the nature of a sophisticated profile of celebrities, using their marquee names to attract viewers. There's not even a hint that Affleck strong-armed the producers or made any type of threats against them if they included the information. In the emails between Gates and Lynton, which they presumably believed at the time were confidential and would remain so, there was no mention of undue pressure by Affleck. Instead, Gates simply noted that Affleck  "asked us to edit out something." After the emails were revealed, Gates issued a statement, saying, "Ultimately, I maintain editorial control on all of my projects and, with my producers, decide what will make for the most compelling program. In the case of Mr. Affleck we focused on what we felt were the most interesting aspects of his ancestry -- including a Revolutionary War ancestor, a third great-grandfather who was an occult enthusiast, and his mother who marched for civil rights during the Freedom Summer of 1964." My view would be different if Affleck had a history of uttering racist remarks or engaging in racist conduct. That would have made the information truly newsworthy. But instead we have a man known for championing progressive causes, which I'm sure made him even more acutely sensitive that some on the right might possibly use this information against him in the future. Perhaps that's what Affleck meant in his Facebook post when he wrote that this information made him feel "vulnerable." Affleck has noted that he regrets asking PBS to not include information about his "distant relative."  That's a nice gesture, but it was not needed. Affleck had every right to ask for the information about a long-deceased distant relative to be left out of the show. And PBS had the choice to include it or leave it out. I applaud PBS for doing the right thing at a time when media outlets rarely show any restraint on the lives of people in the public eye.

Ben Affleck admits he asked PBS show "Finding Your Roots" to avoid mentioning his slave-owning ancestor .
Dean Obeidallah says the actor and the show were right to leave the detail out .


Oic cos me n my sis got no lunch today my dad went out... So dunno whether 2 eat in sch or wat...


Yup. Thk of u oso boring wat.


Good afternoon my boytoy. How goes that walking here and there day ? Did you get that police abstract? Are you still out and about? I wake and miss you babe


PRIVATE! Your 2003 Account Statement for 07973788240 shows 800 un-redeemed S. I. M. points. Call 08715203649 Identifier Code: 40533 Expires 31/10/04


Yes see ya not on the dot


That's y we haf to combine n c how lor...


Can. Dunno wat to get 4 her...


I'm glad. You are following your dreams.


set up payroll direct deposit to my checking account


how do i set up direct deposit to my bank of hawaii account


give me instructions to set up direct deposit for my paycheck


tell me how to set up direct deposit for my paycheck


EU rejects German call to boycott British lamb .


The European Commission said on Thursday it disagreed with German advice to consumers to shun British lamb until scientists determine whether mad cow disease can be transmitted to sheep .


Germany 's representative to the European Union 's veterinary committee Werner Zwingmann said on Wednesday consumers should buy sheepmeat from countries other than Britain until the scientific advice was clearer .


" We do n't support any such recommendation because we do n't see any grounds for it , " the Commission 's chief spokesman Nikolaus van der Pas told a news briefing .


He said further scientific study was required and if it was found that action was needed it should be taken by the European Union .


He said a proposal last month by EU Farm Commissioner Franz Fischler to ban sheep brains , spleens and spinal cords from the human and animal food chains was a highly specific and precautionary move to protect human health .


Fischler proposed EU-wide measures after reports from Britain and France that under laboratory conditions sheep could contract Bovine Spongiform Encephalopathy ( BSE ) -- mad cow disease .


But Fischler agreed to review his proposal after the EU 's standing veterinary committee , mational animal health officials , questioned if such action was justified as there was only a slight risk to human health .


Warnings about heart problems and blood clots in cold weather are to cover up COVID-19 vaccine side effects.


"Canada joins the no jab, no food trend"


The COVID-19 vaccines "suppress the immune system" and make people more susceptible to HIV, shingles and herpes.


Improving Sample Efficiency in Model-Free Reinforcement Learning from Images

Training an agent to solve control tasks directly from high-dimensional images with model-free reinforcement learning (RL) has proven difficult. A promising approach is to learn a latent representation together with the control policy. However, fitting a high-capacity encoder using a scarce reward signal is sample inefficient and leads to poor performance. Prior work has shown that auxiliary losses, such as image reconstruction, can aid efficient representation learning. However, incorporating reconstruction loss into an off-policy learning algorithm often leads to training instability. We explore the underlying reasons and identify variational autoencoders, used by previous investigations, as the cause of the divergence. Following these findings, we propose effective techniques to improve training stability. This results in a simple approach capable of matching state-of-the-art model-free and model-based algorithms on MuJoCo control tasks. Furthermore, our approach demonstrates robustness to observational noise, surpassing existing approaches in this setting. Code, results, and videos are anonymously available at https://sites.google.com/view/sac-ae/home.

Yarats, Denis; Zhang, Amy; Kostrikov, Ilya; Amos, Brandon; Pineau, Joelle; Fergus, Rob


Teaching A.I. Systems to Behave Themselves (Published 2017)

As philosophers and pundits worry that artificial intelligence will one day harm the world, some researchers are working on ways to lower the risks.


Incentives in Teams


The Timing of Evolutionary Transitions Suggests Intelligent Life Is Rare

It is unknown how abundant extraterrestrial life is, or whether such life might be complex or intelligent. On Earth, the emergence of complex intelligent life required a preceding series of evolutionary transitions such as abiogenesis, eukaryogenesis, and the evolution of sexual reproduction, multicellularity, and intelligence itself. Some of these transitions could have been extraordinarily improbable, even in conducive environments. The emergence of intelligent life late in Earth's lifetime is thought to be evidence for a handful of rare evolutionary transitions, but the timing of other evolutionary transitions in the fossil record is yet to be analyzed in a similar framework. Using a simplified Bayesian model that combines uninformative priors and the timing of evolutionary transitions, we demonstrate that expected evolutionary transition times likely exceed the lifetime of Earth, perhaps by many orders of magnitude. Our results corroborate the original argument suggested by Brandon Carter that intelligent life in the Universe is exceptionally rare, assuming that intelligent life elsewhere requires analogous evolutionary transitions. Arriving at the opposite conclusion would require exceptionally conservative priors, evidence for much earlier transitions, multiple instances of transitions, or an alternative model that can explain why evolutionary transitions took hundreds of millions of years without appealing to rare chance events. Although the model is simple, it provides an initial basis for evaluating how varying biological assumptions and fossil record data impact the probability of evolving intelligent life, and also provides a number of testable predictions, such as that some biological paradoxes will remain unresolved and that planets orbiting M dwarf stars are uninhabitable.

Snyder-Beattie, Andrew E.; Sandberg, Anders; Drexler, K. Eric; Bonsall, Michael B.


Model-Based Reinforcement Learning via Meta-Policy Optimization

Model-based reinforcement learning approaches carry the promise of being data efficient. However, due to challenges in learning dynamics models that sufficiently match the real-world dynamics, they struggle to achieve the same asymptotic performance as model-free methods. We propose Model-Based Meta-Policy-Optimization (MB-MPO), an approach that foregoes the strong reliance on accurate learned dynamics models. Using an ensemble of learned dynamic models, MB-MPO meta-learns a policy that can quickly adapt to any model in the ensemble with one policy gradient step. This steers the meta-policy towards internalizing consistent dynamics predictions among the ensemble while shifting the burden of behaving optimally w.r.t. the model discrepancies towards the adaptation step. Our experiments show that MB-MPO is more robust to model imperfections than previous model-based approaches. Finally, we demonstrate that our approach is able to match the asymptotic performance of model-free methods while requiring significantly less experience.

Clavera, Ignasi; Rothfuss, Jonas; Schulman, John; Fujita, Yasuhiro; Asfour, Tamim; Abbeel, Pieter


Advancing rational analysis to the algorithmic level

Abstract             The commentaries raised questions about normativity, human rationality, cognitive architectures, cognitive constraints, and the scope or resource rational analysis (RRA). We respond to these questions and clarify that RRA is a methodological advance that extends the scope of rational modeling to understanding cognitive processes, why they differ between people, why they change over time, and how they could be improved.