text:
/* $Id: DrvACPI.cpp $ */
/** @file
 * DrvACPI - ACPI Host Driver.
 */

/*
 * Copyright (C) 2006-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 */

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#define LOG_GROUP LOG_GROUP_DRV_ACPI

#ifdef RT_OS_WINDOWS
# include <windows.h>
#endif

#include <VBox/vmm/pdmdrv.h>
#include <VBox/log.h>
#include <iprt/asm.h>
#include <iprt/assert.h>
#include <iprt/string.h>
#include <iprt/uuid.h>

#ifdef RT_OS_LINUX
# include <iprt/critsect.h>
# include <iprt/dir.h>
# include <iprt/semaphore.h>
# include <iprt/stream.h>
#endif

#ifdef RT_OS_DARWIN
# include <Carbon/Carbon.h>
# include <IOKit/ps/IOPowerSources.h>
# include <IOKit/ps/IOPSKeys.h>
#endif

#ifdef RT_OS_FREEBSD
# include <sys/ioctl.h>
# include <dev/acpica/acpiio.h>
# include <sys/types.h>
# include <sys/sysctl.h>
# include <stdio.h>
# include <errno.h>
# include <fcntl.h>
# include <unistd.h>
#endif

#include "VBoxDD.h"

/*******************************************************************************
*   Structures and Typedefs                                                    *
*******************************************************************************/
/**
 * ACPI driver instance data.
 *
 * @implements  PDMIACPICONNECTOR
 */
typedef struct DRVACPI
{
    /** The ACPI interface. */
    PDMIACPICONNECTOR   IACPIConnector;
    /** The ACPI port interface. */
    PPDMIACPIPORT       pPort;
    /** Pointer to the driver instance. */
    PPDMDRVINS          pDrvIns;

#ifdef RT_OS_LINUX
    /** The current power source. */
    PDMACPIPOWERSOURCE  enmPowerSource;
    /** true = one or more batteries preset, false = no battery present. */
    bool                fBatteryPresent;
    /** No need to RTThreadPoke the poller when set.  */
    bool volatile       fDontPokePoller;
    /** Remaining battery capacity. */
    PDMACPIBATCAPACITY  enmBatteryRemainingCapacity;
    /** Battery state. */
    PDMACPIBATSTATE     enmBatteryState;
    /** Preset battery charging/discharging rate. */
    uint32_t            u32BatteryPresentRate;
    /** The poller thread. */
    PPDMTHREAD          pPollerThread;
    /** Synchronize access to the above fields.
     * XXX A spinlock is probably cheaper ... */
    RTCRITSECT          CritSect;
    /** Event semaphore the poller thread is sleeping on. */
    RTSEMEVENT          hPollerSleepEvent;
#endif

} DRVACPI, *PDRVACPI;

/**
 * @interface_method_impl{PDMIBASE,pfnQueryInterface}
 */
static DECLCALLBACK(void *) drvACPIQueryInterface(PPDMIBASE pInterface, const char *pszIID)
{
    PPDMDRVINS pDrvIns = PDMIBASE_2_PDMDRV(pInterface);
    PDRVACPI   pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);

    PDMIBASE_RETURN_INTERFACE(pszIID, PDMIBASE, &pDrvIns->IBase);
    PDMIBASE_RETURN_INTERFACE(pszIID, PDMIACPICONNECTOR, &pThis->IACPIConnector);
    return NULL;
}

/**
 * Get the current power source of the host system.
 *
 * @returns status code
 * @param   pInterface   Pointer to the interface structure containing the called function pointer.
 * @param   pPowerSource Pointer to the power source result variable.
 */
static DECLCALLBACK(int) drvACPIQueryPowerSource(PPDMIACPICONNECTOR pInterface,
                                                 PDMACPIPOWERSOURCE *pPowerSource)
{
#if defined(RT_OS_WINDOWS)
    SYSTEM_POWER_STATUS powerStatus;
    if (GetSystemPowerStatus(&powerStatus))
    {
        /* running on battery? */
        if (    powerStatus.ACLineStatus == 0   /* Offline */
             || powerStatus.ACLineStatus == 255 /* Unknown */
             && (powerStatus.BatteryFlag & 15)  /* high | low | critical | charging */
           ) /** @todo why is 'charging' included in the flag test?  Add parenthesis around the right bits so the code is clearer. */
        {
            *pPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
        }
        /* running on AC link? */
        else if (powerStatus.ACLineStatus == 1)
        {
            *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
        }
        else
        /* what the hell we're running on? */
        {
            *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
        }
    }
    else
    {
        AssertMsgFailed(("Could not determine system power status, error: 0x%x\n",
                         GetLastError()));
        *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
    }

#elif defined (RT_OS_LINUX)
    PDRVACPI pThis = RT_FROM_MEMBER(pInterface, DRVACPI, IACPIConnector);
    RTCritSectEnter(&pThis->CritSect);
    *pPowerSource = pThis->enmPowerSource;
    RTCritSectLeave(&pThis->CritSect);

#elif defined (RT_OS_DARWIN)
    *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;

    CFTypeRef pBlob = IOPSCopyPowerSourcesInfo();
    CFArrayRef pSources = IOPSCopyPowerSourcesList(pBlob);

    CFDictionaryRef pSource = NULL;
    const void *psValue;
    bool fResult;

    if (CFArrayGetCount(pSources) > 0)
    {
        for (int i = 0; i < CFArrayGetCount(pSources); ++i)
        {
            pSource = IOPSGetPowerSourceDescription(pBlob, CFArrayGetValueAtIndex(pSources, i));
            /* If the source is empty skip over to the next one. */
            if(!pSource)
                continue;
            /* Skip all power sources which are currently not present like a
             * second battery. */
            if (CFDictionaryGetValue(pSource, CFSTR(kIOPSIsPresentKey)) == kCFBooleanFalse)
                continue;
            /* Only internal power types are of interest. */
            fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTransportTypeKey), &psValue);
            if (   fResult
                && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSInternalType), 0) == kCFCompareEqualTo)
            {
                /* Check which power source we are connect on. */
                fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSPowerSourceStateKey), &psValue);
                if (   fResult
                    && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSACPowerValue), 0) == kCFCompareEqualTo)
                    *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
                else if (   fResult
                         && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSBatteryPowerValue), 0) == kCFCompareEqualTo)
                    *pPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
            }
        }
    }
    CFRelease(pBlob);
    CFRelease(pSources);

#elif defined(RT_OS_FREEBSD)
    int fAcLine = 0;
    size_t cbParameter = sizeof(fAcLine);

    int rc = sysctlbyname("hw.acpi.acline", &fAcLine, &cbParameter, NULL, 0);

    if (!rc)
    {
        if (fAcLine == 1)
            *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
        else if (fAcLine == 0)
            *pPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
        else
            *pPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
    }
    else
    {
        AssertMsg(errno == ENOENT, ("rc=%d (%s)\n", rc, strerror(errno)));
        *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
    }
#else /* !RT_OS_FREEBSD either - what could this be? */
    *pPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;

#endif /* !RT_OS_FREEBSD */
    return VINF_SUCCESS;
}

/**
 * @copydoc PDMIACPICONNECTOR::pfnQueryBatteryStatus
 */
static DECLCALLBACK(int) drvACPIQueryBatteryStatus(PPDMIACPICONNECTOR pInterface, bool *pfPresent,
        PPDMACPIBATCAPACITY penmRemainingCapacity,
        PPDMACPIBATSTATE penmBatteryState,
        uint32_t *pu32PresentRate)
{
    /* default return values for all architectures */
    *pfPresent              = false;   /* no battery present */
    *penmBatteryState       = PDM_ACPI_BAT_STATE_CHARGED;
    *penmRemainingCapacity  = PDM_ACPI_BAT_CAPACITY_UNKNOWN;
    *pu32PresentRate        = ~0;      /* present rate is unknown */

#if defined(RT_OS_WINDOWS)
    SYSTEM_POWER_STATUS powerStatus;
    if (GetSystemPowerStatus(&powerStatus))
    {
        /* 128 means no battery present */
        *pfPresent = !(powerStatus.BatteryFlag & 128);
        /* just forward the value directly */
        *penmRemainingCapacity = (PDMACPIBATCAPACITY)powerStatus.BatteryLifePercent;
        /* we assume that we are discharging the battery if we are not on-line and
         * not charge the battery */
        uint32_t uBs = PDM_ACPI_BAT_STATE_CHARGED;
        if (powerStatus.BatteryFlag & 8)
            uBs = PDM_ACPI_BAT_STATE_CHARGING;
        else if (powerStatus.ACLineStatus == 0 || powerStatus.ACLineStatus == 255)
            uBs = PDM_ACPI_BAT_STATE_DISCHARGING;
        if (powerStatus.BatteryFlag & 4)
            uBs |= PDM_ACPI_BAT_STATE_CRITICAL;
        *penmBatteryState = (PDMACPIBATSTATE)uBs;
        /* on Windows it is difficult to request the present charging/discharging rate */
    }
    else
    {
        AssertMsgFailed(("Could not determine system power status, error: 0x%x\n",
                    GetLastError()));
    }

#elif defined(RT_OS_LINUX)
    PDRVACPI pThis = RT_FROM_MEMBER(pInterface, DRVACPI, IACPIConnector);
    RTCritSectEnter(&pThis->CritSect);
    *pfPresent = pThis->fBatteryPresent;
    *penmRemainingCapacity = pThis->enmBatteryRemainingCapacity;
    *penmBatteryState = pThis->enmBatteryState;
    *pu32PresentRate = pThis->u32BatteryPresentRate;
    RTCritSectLeave(&pThis->CritSect);

#elif defined(RT_OS_DARWIN)
    CFTypeRef pBlob = IOPSCopyPowerSourcesInfo();
    CFArrayRef pSources = IOPSCopyPowerSourcesList(pBlob);

    CFDictionaryRef pSource = NULL;
    const void *psValue;
    bool fResult;

    if (CFArrayGetCount(pSources) > 0)
    {
        for (int i = 0; i < CFArrayGetCount(pSources); ++i)
        {
            pSource = IOPSGetPowerSourceDescription(pBlob, CFArrayGetValueAtIndex(pSources, i));
            /* If the source is empty skip over to the next one. */
            if(!pSource)
                continue;
            /* Skip all power sources which are currently not present like a
             * second battery. */
            if (CFDictionaryGetValue(pSource, CFSTR(kIOPSIsPresentKey)) == kCFBooleanFalse)
                continue;
            /* Only internal power types are of interest. */
            fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTransportTypeKey), &psValue);
            if (   fResult
                    && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSInternalType), 0) == kCFCompareEqualTo)
            {
                PDMACPIPOWERSOURCE powerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
                /* First check which power source we are connect on. */
                fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSPowerSourceStateKey), &psValue);
                if (   fResult
                        && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSACPowerValue), 0) == kCFCompareEqualTo)
                    powerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
                else if (   fResult
                        && CFStringCompare((CFStringRef)psValue, CFSTR(kIOPSBatteryPowerValue), 0) == kCFCompareEqualTo)
                    powerSource = PDM_ACPI_POWER_SOURCE_BATTERY;

                /* At this point the power source is present. */
                *pfPresent = true;
                *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGED;

                int curCapacity = 0;
                int maxCapacity = 1;
                float remCapacity = 0.0f;

                /* Fetch the current capacity value of the power source */
                fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSCurrentCapacityKey), &psValue);
                if (fResult)
                    CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &curCapacity);
                /* Fetch the maximum capacity value of the power source */
                fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSMaxCapacityKey), &psValue);
                if (fResult)
                    CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &maxCapacity);

                /* Calculate the remaining capacity in percent */
                remCapacity = ((float)curCapacity/(float)maxCapacity * PDM_ACPI_BAT_CAPACITY_MAX);
                *penmRemainingCapacity = (PDMACPIBATCAPACITY)remCapacity;

                if (powerSource == PDM_ACPI_POWER_SOURCE_BATTERY)
                {
                    /* If we are on battery power we are discharging in every
                     * case */
                    *penmBatteryState = PDM_ACPI_BAT_STATE_DISCHARGING;
                    int timeToEmpty = -1;
                    /* Get the time till the battery source will be empty */
                    fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTimeToEmptyKey), &psValue);
                    if (fResult)
                        CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &timeToEmpty);
                    if (timeToEmpty != -1)
                        /* 0...1000 */
                        *pu32PresentRate = (uint32_t)roundf((remCapacity / ((float)timeToEmpty/60.0)) * 10.0);
                }

                if (   powerSource == PDM_ACPI_POWER_SOURCE_OUTLET
                        && CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSIsChargingKey), &psValue))
                {
                    /* We are running on an AC power source, but we also have a
                     * battery power source present. */
                    if (CFBooleanGetValue((CFBooleanRef)psValue) > 0)
                    {
                        /* This means charging. */
                        *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGING;
                        int timeToFull = -1;
                        /* Get the time till the battery source will be charged */
                        fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSTimeToFullChargeKey), &psValue);
                        if (fResult)
                            CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &timeToFull);
                        if (timeToFull != -1)
                            /* 0...1000 */
                            *pu32PresentRate = (uint32_t)roundf((100.0-(float)remCapacity) / ((float)timeToFull/60.0)) * 10.0;
                    }
                }

                /* Check for critical */
                int criticalValue = 20;
                fResult = CFDictionaryGetValueIfPresent(pSource, CFSTR(kIOPSDeadWarnLevelKey), &psValue);
                if (fResult)
                    CFNumberGetValue((CFNumberRef)psValue, kCFNumberSInt32Type, &criticalValue);
                if (remCapacity < criticalValue)
                    *penmBatteryState = (PDMACPIBATSTATE)(*penmBatteryState | PDM_ACPI_BAT_STATE_CRITICAL);
            }
        }
    }
    CFRelease(pBlob);
    CFRelease(pSources);

#elif defined(RT_OS_FREEBSD)
    /* We try to use /dev/acpi first and if that fails use the sysctls. */
    bool fSuccess = true;
    int FileAcpi = 0;
    int rc = 0;

    FileAcpi = open("/dev/acpi", O_RDONLY);
    if (FileAcpi != -1)
    {
        bool fMilliWatt;
        union acpi_battery_ioctl_arg BatteryIo;

        memset(&BatteryIo, 0, sizeof(BatteryIo));
        BatteryIo.unit = 0; /* Always use the first battery. */

        /* Determine the power units first. */
        if (ioctl(FileAcpi, ACPIIO_BATT_GET_BIF, &BatteryIo) == -1)
            fSuccess = false;
        else
        {
            if (BatteryIo.bif.units == ACPI_BIF_UNITS_MW)
                fMilliWatt = true;
            else
                fMilliWatt = false; /* mA */

            BatteryIo.unit = 0;
            if (ioctl(FileAcpi, ACPIIO_BATT_GET_BATTINFO, &BatteryIo) == -1)
                fSuccess = false;
            else
            {
                if ((BatteryIo.battinfo.state & ACPI_BATT_STAT_NOT_PRESENT) == ACPI_BATT_STAT_NOT_PRESENT)
                    *pfPresent = false;
                else
                {
                    *pfPresent = true;

                    if (BatteryIo.battinfo.state & ACPI_BATT_STAT_DISCHARG)
                        *penmBatteryState = PDM_ACPI_BAT_STATE_DISCHARGING;
                    else if (BatteryIo.battinfo.state & ACPI_BATT_STAT_CHARGING)
                        *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGING;
                    else
                        *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGED;

                    if (BatteryIo.battinfo.state & ACPI_BATT_STAT_CRITICAL)
                        *penmBatteryState = (PDMACPIBATSTATE)(*penmBatteryState | PDM_ACPI_BAT_STATE_CRITICAL);
                }

                if (BatteryIo.battinfo.cap != -1)
                    *penmRemainingCapacity = (PDMACPIBATCAPACITY)BatteryIo.battinfo.cap;

                BatteryIo.unit = 0;
                if (ioctl(FileAcpi, ACPIIO_BATT_GET_BST, &BatteryIo) == 0)
                {
                    /* The rate can be either mW or mA but the ACPI device wants mW. */
                    if (BatteryIo.bst.rate != 0xffffffff)
                    {
                        if (fMilliWatt)
                            *pu32PresentRate = BatteryIo.bst.rate;
                        else if (BatteryIo.bst.volt != 0xffffffff)
                        {
                            /*
                             * The rate is in mA so we have to convert it.
                             * The current power rate can be calculated with P = U * I
                             */
                            *pu32PresentRate = (uint32_t)(  (  ((float)BatteryIo.bst.volt/1000.0)
                                        * ((float)BatteryIo.bst.rate/1000.0))
                                    * 1000.0);
                        }
                    }
                }
            }
        }

        close(FileAcpi);
    }
    else
        fSuccess = false;

    if (!fSuccess)
    {
        int fBatteryState = 0;
        size_t cbParameter = sizeof(fBatteryState);

        rc = sysctlbyname("hw.acpi.battery.state", &fBatteryState, &cbParameter, NULL, 0);
        if (!rc)
        {
            if ((fBatteryState & ACPI_BATT_STAT_NOT_PRESENT) == ACPI_BATT_STAT_NOT_PRESENT)
                *pfPresent = false;
            else
            {
                *pfPresent = true;

                if (fBatteryState & ACPI_BATT_STAT_DISCHARG)
                    *penmBatteryState = PDM_ACPI_BAT_STATE_DISCHARGING;
                else if (fBatteryState & ACPI_BATT_STAT_CHARGING)
                    *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGING;
                else
                    *penmBatteryState = PDM_ACPI_BAT_STATE_CHARGED;

                if (fBatteryState & ACPI_BATT_STAT_CRITICAL)
                    *penmBatteryState = (PDMACPIBATSTATE)(*penmBatteryState | PDM_ACPI_BAT_STATE_CRITICAL);

                /* Get battery level. */
                int curCapacity = 0;
                cbParameter = sizeof(curCapacity);
                rc = sysctlbyname("hw.acpi.battery.life", &curCapacity, &cbParameter, NULL, 0);
                if (!rc && curCapacity >= 0)
                    *penmRemainingCapacity = (PDMACPIBATCAPACITY)curCapacity;

                /* The rate can't be determined with sysctls. */
            }
        }
    }

#endif /* RT_OS_FREEBSD */

    return VINF_SUCCESS;
}

#ifdef RT_OS_LINUX
/**
 * Poller thread for /proc/acpi status files.
 *
 * Reading these files takes ages (several seconds) on some hosts, therefore
 * start this thread. The termination of this thread may take some seconds
 * on such a hosts!
 *
 * @param   pDrvIns     The driver instance data.
 * @param   pThread     The thread.
 */
static DECLCALLBACK(int) drvACPIPoller(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
{
    PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);

    if (pThread->enmState == PDMTHREADSTATE_INITIALIZING)
        return VINF_SUCCESS;

    while (pThread->enmState == PDMTHREADSTATE_RUNNING)
    {
        ASMAtomicWriteBool(&pThis->fDontPokePoller, false);

        PDMACPIPOWERSOURCE enmPowerSource = PDM_ACPI_POWER_SOURCE_UNKNOWN;
        PRTSTREAM  pStrmStatus;
        PRTSTREAM  pStrmType;
        PRTDIR     pDir = NULL;
        RTDIRENTRY DirEntry;
        char       szLine[1024];
        bool       fBatteryPresent = false;     /* one or more batteries present */
        bool       fCharging = false;           /* one or more batteries charging */
        bool       fDischarging = false;        /* one or more batteries discharging */
        bool       fCritical = false;           /* one or more batteries in critical state */
        int32_t    maxCapacityTotal = 0;        /* total capacity of all batteries */
        int32_t    currentCapacityTotal = 0;    /* total current capacity of all batteries */
        int32_t    presentRateTotal = 0;        /* total present (dis)charging rate of all batts */

        int rc = RTDirOpen(&pDir, "/sys/class/power_supply/");
        if (RT_SUCCESS(rc))
        {
            /*
             * The new /sys interface introduced with Linux 2.6.25.
             */
            while (pThread->enmState == PDMTHREADSTATE_RUNNING)
            {
                rc = RTDirRead(pDir, &DirEntry, NULL);
                if (RT_FAILURE(rc))
                    break;
                if (   strcmp(DirEntry.szName, ".") == 0
                    || strcmp(DirEntry.szName, "..") == 0)
                    continue;
#define POWER_OPEN(s, n) RTStrmOpenF("r", s, "/sys/class/power_supply/%s/" n, DirEntry.szName)
                rc = POWER_OPEN(&pStrmType, "type");
                if (RT_FAILURE(rc))
                    continue;
                rc = RTStrmGetLine(pStrmType, szLine, sizeof(szLine));
                if (RT_SUCCESS(rc))
                {
                    if (strcmp(szLine, "Mains") == 0)
                    {
                        /* AC adapter */
                        rc = POWER_OPEN(&pStrmStatus, "online");
                        if (RT_SUCCESS(rc))
                        {
                            rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                            if (   RT_SUCCESS(rc)
                                && strcmp(szLine, "1") == 0)
                                enmPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
                            else
                                enmPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
                            RTStrmClose(pStrmStatus);
                        }
                    }
                    else if (strcmp(szLine, "Battery") == 0)
                    {
                        /* Battery */
                        rc = POWER_OPEN(&pStrmStatus, "present");
                        if (RT_SUCCESS(rc))
                        {
                            rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                            RTStrmClose(pStrmStatus);
                            if (   RT_SUCCESS(rc)
                                && strcmp(szLine, "1") == 0)
                            {
                                fBatteryPresent = true;
                                rc = RTStrmOpenF("r", &pStrmStatus,
                                                 "/sys/class/power_supply/%s/status", DirEntry.szName);
                                if (RT_SUCCESS(rc))
                                {
                                    rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                                    if (RT_SUCCESS(rc))
                                    {
                                        if (strcmp(szLine, "Discharging") == 0)
                                            fDischarging = true;
                                        else if (strcmp(szLine, "Charging") == 0)
                                            fCharging = true;
                                    }
                                    RTStrmClose(pStrmStatus);
                                }
                                rc = POWER_OPEN(&pStrmStatus, "capacity_level");
                                if (RT_SUCCESS(rc))
                                {
                                    rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                                    if (   RT_SUCCESS(rc)
                                        && strcmp(szLine, "Critical") == 0)
                                        fCritical = true;
                                    RTStrmClose(pStrmStatus);
                                }
                                rc = POWER_OPEN(&pStrmStatus, "energy_full");
                                if (RT_FAILURE(rc))
                                    rc = POWER_OPEN(&pStrmStatus, "charge_full");
                                if (RT_SUCCESS(rc))
                                {
                                    rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                                    if (RT_SUCCESS(rc))
                                    {
                                        int32_t maxCapacity = 0;
                                        rc = RTStrToInt32Full(szLine, 0, &maxCapacity);
                                        if (   RT_SUCCESS(rc)
                                            && maxCapacity > 0)
                                            maxCapacityTotal += maxCapacity;
                                    }
                                    RTStrmClose(pStrmStatus);
                                }
                                rc = POWER_OPEN(&pStrmStatus, "energy_now");
                                if (RT_FAILURE(rc))
                                    rc = POWER_OPEN(&pStrmStatus, "charge_now");
                                if (RT_SUCCESS(rc))
                                {
                                    rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                                    if (RT_SUCCESS(rc))
                                    {
                                        int32_t currentCapacity = 0;
                                        rc = RTStrToInt32Full(szLine, 0, &currentCapacity);
                                        if (   RT_SUCCESS(rc)
                                            && currentCapacity > 0)
                                            currentCapacityTotal += currentCapacity;
                                    }
                                    RTStrmClose(pStrmStatus);
                                }
                                rc = POWER_OPEN(&pStrmStatus, "current_now");
                                if (RT_SUCCESS(rc))
                                {
                                    rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                                    if (RT_SUCCESS(rc))
                                    {
                                        int32_t presentRate = 0;
                                        rc = RTStrToInt32Full(szLine, 0, &presentRate);
                                        if (   RT_SUCCESS(rc)
                                            && presentRate > 0)
                                        {
                                            if (fDischarging)
                                                presentRateTotal -= presentRate;
                                            else
                                                presentRateTotal += presentRate;
                                        }
                                    }
                                    RTStrmClose(pStrmStatus);
                                }
                            }
                        }
                    }
                }
                RTStrmClose(pStrmType);
#undef POWER_OPEN
            }
            RTDirClose(pDir);
        }
        else /* !/sys */
        {
            /*
             * The old /proc/acpi interface
             */
            /*
             * Read the status of the powerline-adapter.
             */
            rc = RTDirOpen(&pDir, "/proc/acpi/ac_adapter/");
            if (RT_SUCCESS(rc))
            {
#define POWER_OPEN(s, n) RTStrmOpenF("r", s, "/proc/acpi/ac_adapter/%s/" n, DirEntry.szName)
                while (pThread->enmState == PDMTHREADSTATE_RUNNING)
                {
                    rc = RTDirRead(pDir, &DirEntry, NULL);
                    if (RT_FAILURE(rc))
                        break;
                    if (   strcmp(DirEntry.szName, ".") == 0
                        || strcmp(DirEntry.szName, "..") == 0)
                        continue;
                    rc = POWER_OPEN(&pStrmStatus, "status");
                    if (RT_FAILURE(rc))
                        rc = POWER_OPEN(&pStrmStatus, "state");
                    if (RT_SUCCESS(rc))
                    {
                        while (pThread->enmState == PDMTHREADSTATE_RUNNING)
                        {
                            rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                            if (RT_FAILURE(rc))
                                break;
                            if (   strstr(szLine, "Status:") != NULL
                                || strstr(szLine, "state:") != NULL)
                            {
                                if (strstr(szLine, "on-line") != NULL)
                                    enmPowerSource = PDM_ACPI_POWER_SOURCE_OUTLET;
                                else
                                    enmPowerSource = PDM_ACPI_POWER_SOURCE_BATTERY;
                                break;
                            }
                        }
                        RTStrmClose(pStrmStatus);
                        break;
                    }
                }
                RTDirClose(pDir);
#undef POWER_OPEN
            }

            /*
             * Read the status of all batteries and collect it into one.
             */
            rc = RTDirOpen(&pDir, "/proc/acpi/battery/");
            if (RT_SUCCESS(rc))
            {
#define POWER_OPEN(s, n) RTStrmOpenF("r", s, "/proc/acpi/battery/%s/" n, DirEntry.szName)
                bool fThisBatteryPresent = false;
                bool fThisDischarging = false;

                while (pThread->enmState == PDMTHREADSTATE_RUNNING)
                {
                    rc = RTDirRead(pDir, &DirEntry, NULL);
                    if (RT_FAILURE(rc))
                        break;
                    if (   strcmp(DirEntry.szName, ".") == 0
                        || strcmp(DirEntry.szName, "..") == 0)
                        continue;

                    rc = POWER_OPEN(&pStrmStatus, "status");
                    /* there is a 2nd variant of that file */
                    if (RT_FAILURE(rc))
                        rc = POWER_OPEN(&pStrmStatus, "state");
                    if (RT_FAILURE(rc))
                        continue;

                    PRTSTREAM pStrmInfo;
                    rc = POWER_OPEN(&pStrmInfo, "info");
                    if (RT_FAILURE(rc))
                    {
                        RTStrmClose(pStrmStatus);
                        continue;
                    }

                    /* get 'present' status from the info file */
                    while (pThread->enmState == PDMTHREADSTATE_RUNNING)
                    {
                        rc = RTStrmGetLine(pStrmInfo, szLine, sizeof(szLine));
                        if (RT_FAILURE(rc))
                            break;
                        if (strstr(szLine, "present:") != NULL)
                        {
                            if (strstr(szLine, "yes") != NULL)
                            {
                                fThisBatteryPresent = true;
                                break;
                            }
                        }
                    }

                    if (fThisBatteryPresent)
                    {
                        fBatteryPresent = true;
                        RTStrmRewind(pStrmInfo);

                        /* get the maximum capacity from the info file */
                        while (pThread->enmState == PDMTHREADSTATE_RUNNING)
                        {
                            rc = RTStrmGetLine(pStrmInfo, szLine, sizeof(szLine));
                            if (RT_FAILURE(rc))
                                break;
                            if (strstr(szLine, "last full capacity:") != NULL)
                            {
                                char *psz;
                                int32_t maxCapacity = 0;
                                rc = RTStrToInt32Ex(RTStrStripL(&szLine[19]), &psz, 0, &maxCapacity);
                                if (RT_FAILURE(rc))
                                    maxCapacity = 0;
                                maxCapacityTotal += maxCapacity;
                                break;
                            }
                        }

                        /* get the current capacity/state from the status file */
                        int32_t presentRate = 0;
                        bool fGotRemainingCapacity = false;
                        bool fGotBatteryState = false;
                        bool fGotCapacityState = false;
                        bool fGotPresentRate = false;
                        while (  (   !fGotRemainingCapacity
                                  || !fGotBatteryState
                                  || !fGotCapacityState
                                  || !fGotPresentRate)
                               && pThread->enmState == PDMTHREADSTATE_RUNNING)
                        {
                            rc = RTStrmGetLine(pStrmStatus, szLine, sizeof(szLine));
                            if (RT_FAILURE(rc))
                                break;
                            if (strstr(szLine, "remaining capacity:") != NULL)
                            {
                                char *psz;
                                int32_t currentCapacity = 0;
                                rc = RTStrToInt32Ex(RTStrStripL(&szLine[19]), &psz, 0, &currentCapacity);
                                if (   RT_SUCCESS(rc)
                                    && currentCapacity > 0)
                                    currentCapacityTotal += currentCapacity;
                                fGotRemainingCapacity = true;
                            }
                            else if (strstr(szLine, "charging state:") != NULL)
                            {
                                if (strstr(szLine + 15, "discharging") != NULL)
                                {
                                    fDischarging = true;
                                    fThisDischarging = true;
                                }
                                else if (strstr(szLine + 15, "charging") != NULL)
                                    fCharging = true;
                                fGotBatteryState = true;
                            }
                            else if (strstr(szLine, "capacity state:") != NULL)
                            {
                                if (strstr(szLine + 15, "critical") != NULL)
                                    fCritical = true;
                                fGotCapacityState = true;
                            }
                            if (strstr(szLine, "present rate:") != NULL)
                            {
                                char *psz;
                                rc = RTStrToInt32Ex(RTStrStripL(&szLine[13]), &psz, 0, &presentRate);
                                if (RT_FAILURE(rc))
                                    presentRate = 0;
                                fGotPresentRate = true;
                            }
                        }
                        if (fThisDischarging)
                            presentRateTotal -= presentRate;
                        else
                            presentRateTotal += presentRate;
                    }
                    RTStrmClose(pStrmStatus);
                    RTStrmClose(pStrmInfo);
                }
                RTDirClose(pDir);
#undef POWER_OPEN
            }
        } /* /proc/acpi */

        /* atomic update of the state */
        RTCritSectEnter(&pThis->CritSect);
        pThis->enmPowerSource = enmPowerSource;
        pThis->fBatteryPresent = fBatteryPresent;

        /* charging/discharging bits are mutual exclusive */
        uint32_t uBs = PDM_ACPI_BAT_STATE_CHARGED;
        if (fDischarging)
            uBs = PDM_ACPI_BAT_STATE_DISCHARGING;
        else if (fCharging)
            uBs = PDM_ACPI_BAT_STATE_CHARGING;
        if (fCritical)
            uBs |= PDM_ACPI_BAT_STATE_CRITICAL;
        pThis->enmBatteryState = (PDMACPIBATSTATE)uBs;

        if (maxCapacityTotal > 0 && currentCapacityTotal > 0)
        {
            if (presentRateTotal < 0)
                presentRateTotal = -presentRateTotal;

            /* calculate the percentage */
            pThis->enmBatteryRemainingCapacity =
                                 (PDMACPIBATCAPACITY)( (  (float)currentCapacityTotal
                                                        / (float)maxCapacityTotal)
                                                      * PDM_ACPI_BAT_CAPACITY_MAX);
            pThis->u32BatteryPresentRate =
                                 (uint32_t)((  (float)presentRateTotal
                                             / (float)maxCapacityTotal) * 1000);
        }
        else
        {
            /* unknown capacity / state */
            pThis->enmBatteryRemainingCapacity = PDM_ACPI_BAT_CAPACITY_UNKNOWN;
            pThis->u32BatteryPresentRate = ~0;
        }
        RTCritSectLeave(&pThis->CritSect);

        /* wait a bit (e.g. Ubuntu/GNOME polls every 30 seconds) */
        ASMAtomicWriteBool(&pThis->fDontPokePoller, true);
        rc = RTSemEventWait(pThis->hPollerSleepEvent, 20000);
    }

    return VINF_SUCCESS;
}

static DECLCALLBACK(int) drvACPIPollerWakeup(PPDMDRVINS pDrvIns, PPDMTHREAD pThread)
{
    PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);

    RTSemEventSignal(pThis->hPollerSleepEvent);
    if (!ASMAtomicReadBool(&pThis->fDontPokePoller))
        RTThreadPoke(pThread->Thread);
    return VINF_SUCCESS;
}
#endif /* RT_OS_LINUX */

/**
 * Destruct a driver instance.
 *
 * Most VM resources are freed by the VM. This callback is provided so that any non-VM
 * resources can be freed correctly.
 *
 * @param   pDrvIns     The driver instance data.
 */
static DECLCALLBACK(void) drvACPIDestruct(PPDMDRVINS pDrvIns)
{
    PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);

    LogFlow(("drvACPIDestruct\n"));
    PDMDRV_CHECK_VERSIONS_RETURN_VOID(pDrvIns);

#ifdef RT_OS_LINUX
    if (pThis->hPollerSleepEvent != NIL_RTSEMEVENT)
    {
        RTSemEventDestroy(pThis->hPollerSleepEvent);
        pThis->hPollerSleepEvent = NIL_RTSEMEVENT;
    }
    RTCritSectDelete(&pThis->CritSect);
#endif
}

/**
 * Construct an ACPI driver instance.
 *
 * @copydoc FNPDMDRVCONSTRUCT
 */
static DECLCALLBACK(int) drvACPIConstruct(PPDMDRVINS pDrvIns, PCFGMNODE pCfg, uint32_t fFlags)
{
    PDRVACPI pThis = PDMINS_2_DATA(pDrvIns, PDRVACPI);
    PDMDRV_CHECK_VERSIONS_RETURN(pDrvIns);
    int rc = VINF_SUCCESS;

    /*
     * Init the static parts.
     */
    pThis->pDrvIns                              = pDrvIns;
#ifdef RT_OS_LINUX
    pThis->hPollerSleepEvent                    = NIL_RTSEMEVENT;
#endif
    /* IBase */
    pDrvIns->IBase.pfnQueryInterface            = drvACPIQueryInterface;
    /* IACPIConnector */
    pThis->IACPIConnector.pfnQueryPowerSource   = drvACPIQueryPowerSource;
    pThis->IACPIConnector.pfnQueryBatteryStatus = drvACPIQueryBatteryStatus;

    /*
     * Validate the config.
     */
    if (!CFGMR3AreValuesValid(pCfg, "\0"))
        return VERR_PDM_DRVINS_UNKNOWN_CFG_VALUES;

    /*
     * Check that no-one is attached to us.
     */
    AssertMsgReturn(PDMDrvHlpNoAttach(pDrvIns) == VERR_PDM_NO_ATTACHED_DRIVER,
                    ("Configuration error: Not possible to attach anything to this driver!\n"),
                    VERR_PDM_DRVINS_NO_ATTACH);

    /*
     * Query the ACPI port interface.
     */
    pThis->pPort = PDMIBASE_QUERY_INTERFACE(pDrvIns->pUpBase, PDMIACPIPORT);
    if (!pThis->pPort)
    {
        AssertMsgFailed(("Configuration error: the above device/driver didn't export the ACPI port interface!\n"));
        return VERR_PDM_MISSING_INTERFACE_ABOVE;
    }

#ifdef RT_OS_LINUX
    /*
     * Start the poller thread.
     */
    rc = PDMDrvHlpThreadCreate(pDrvIns, &pThis->pPollerThread, pThis, drvACPIPoller,
                               drvACPIPollerWakeup, 0, RTTHREADTYPE_INFREQUENT_POLLER, "ACPI Poller");
    if (RT_FAILURE(rc))
        return rc;

    rc = RTCritSectInit(&pThis->CritSect);
    if (RT_FAILURE(rc))
        return rc;

    rc = RTSemEventCreate(&pThis->hPollerSleepEvent);
#endif

    return rc;
}

/**
 * ACPI driver registration record.
 */
const PDMDRVREG g_DrvACPI =
{
    /* u32Version */
    PDM_DRVREG_VERSION,
    /* szName */
    "ACPIHost",
    /* szRCMod */
    "",
    /* szR0Mod */
    "",
    /* pszDescription */
    "ACPI Host Driver",
    /* fFlags */
    PDM_DRVREG_FLAGS_HOST_BITS_DEFAULT,
    /* fClass. */
    PDM_DRVREG_CLASS_ACPI,
    /* cMaxInstances */
    ~0U,
    /* cbInstance */
    sizeof(DRVACPI),
    /* pfnConstruct */
    drvACPIConstruct,
    /* pfnDestruct */
    drvACPIDestruct,
    /* pfnRelocate */
    NULL,
    /* pfnIOCtl */
    NULL,
    /* pfnPowerOn */
    NULL,
    /* pfnReset */
    NULL,
    /* pfnSuspend */
    NULL,
    /* pfnResume */
    NULL,
    /* pfnAttach */
    NULL,
    /* pfnDetach */
    NULL,
    /* pfnPowerOff */
    NULL,
    /* pfnSoftReset */
    NULL,
    /* u32EndVersion */
    PDM_DRVREG_VERSION
};


text:
namespace {

const char* kOrigin1 = "https://google.com";
const char* kOrigin2 = "https://maps.google.com";
const char* kOrigin3 = "https://example.com";

}  // namespace

class FlashTemporaryPermissionTrackerTest
    : public ChromeRenderViewHostTestHarness {
 public:
  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();
    tracker_ = new FlashTemporaryPermissionTracker(profile());
  }

 protected:
  FlashTemporaryPermissionTracker* tracker() { return tracker_.get(); }

  content::RenderFrameHost* GetMainRFH(const char* origin) {
    content::RenderFrameHost* result = web_contents()->GetMainFrame();
    content::RenderFrameHostTester::For(result)
        ->InitializeRenderFrameIfNeeded();
    content::RenderFrameHostTester::For(result)->SimulateNavigationCommit(
        GURL(origin));
    return result;
  }

  content::RenderFrameHost* AddChildRFH(content::RenderFrameHost* parent,
                                        const char* origin) {
    content::RenderFrameHost* result =
        content::RenderFrameHostTester::For(parent)->AppendChild("");
    content::RenderFrameHostTester::For(result)
        ->InitializeRenderFrameIfNeeded();
    content::RenderFrameHostTester::For(result)->SimulateNavigationCommit(
        GURL(origin));
    return result;
  }

 private:
  scoped_refptr<FlashTemporaryPermissionTracker> tracker_;
};

TEST_F(FlashTemporaryPermissionTrackerTest, Basic) {
  GetMainRFH(kOrigin1);

  // Flash shouldn't be enabled initially.
  EXPECT_FALSE(tracker()->IsFlashEnabled(GURL(kOrigin1)));
  tracker()->FlashEnabledForWebContents(web_contents());

  // Flash should be enabled now.
  EXPECT_TRUE(tracker()->IsFlashEnabled(GURL(kOrigin1)));

  // Refresh the page.
  Reload();
  // Flash should still be enabled after a single refresh.
  EXPECT_TRUE(tracker()->IsFlashEnabled(GURL(kOrigin1)));

  // Refresh again.
  Reload();
  // Flash shouldn't be enabled anymore.
  EXPECT_FALSE(tracker()->IsFlashEnabled(GURL(kOrigin1)));
}

TEST_F(FlashTemporaryPermissionTrackerTest, NavigateAway) {
  content::RenderFrameHost* rfh = GetMainRFH(kOrigin1);

  tracker()->FlashEnabledForWebContents(web_contents());
  Reload();
  EXPECT_TRUE(tracker()->IsFlashEnabled(GURL(kOrigin1)));

  // Navigate to another origin. Flash shouldn't be enabled anymore.
  content::RenderFrameHostTester::For(rfh)->SimulateNavigationCommit(
      GURL(kOrigin2));
  EXPECT_FALSE(tracker()->IsFlashEnabled(GURL(kOrigin1)));
}

TEST_F(FlashTemporaryPermissionTrackerTest, NavigateChildFrame) {
  content::RenderFrameHost* rfh = GetMainRFH(kOrigin1);
  content::RenderFrameHost* child = AddChildRFH(rfh, kOrigin2);

  tracker()->FlashEnabledForWebContents(web_contents());
  Reload();
  EXPECT_TRUE(tracker()->IsFlashEnabled(GURL(kOrigin1)));

  // Navigate the child frame. Flash should still be enabled after this.
  content::RenderFrameHostTester::For(child)->SimulateNavigationCommit(
      GURL(kOrigin3));
  EXPECT_TRUE(tracker()->IsFlashEnabled(GURL(kOrigin1)));
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<chargeback-amount-notification xmlns="http://checkout.google.com/schema/2"
    serial-number="bea6bc1b-e1e2-44fe-80ff-0180e33a2614">
    <google-order-number>841171949013218</google-order-number>
    <latest-chargeback-amount currency="USD">226.06</latest-chargeback-amount>
    <total-chargeback-amount currency="USD">226.06</total-chargeback-amount>
    <timestamp>2006-03-18T20:25:31</timestamp>
</chargeback-amount-notification>


text:
if [[ $# -ne 1 ]]; then
	echo "ERROR; missing SNAP_TEST_TYPE (Usage: $0 SNAP_TEST_TYPE)"
	exit -2
elif [[ "$1" != "legacy" && "$1" != "small" && "$1" != "medium" && "$1" != "large" ]]; then
	echo "Error; invalid SNAP_TEST_TYPE (value must be one of 'legacy', 'small', 'medium', or 'large'; received $1)"
	exit -1
fi
SNAP_TEST_TYPE=$1

# If the following plugins don't exist, exit
[ -f $SNAP_PATH/plugin/snap-collector-mock1 ] || { echo 'Error: $SNAP_PATH/plugin/snap-collector-mock1 does not exist. Run make to build it.' ; exit 1; }
[ -f $SNAP_PATH/plugin/snap-collector-mock2 ] || { echo 'Error: $SNAP_PATH/plugin/snap-collector-mock2 does not exist. Run make to build it.' ; exit 1; }
[ -f $SNAP_PATH/plugin/snap-processor-passthru ] || { echo 'Error: $SNAP_PATH/plugin/snap-processor-passthru does not exist. Run make to build it.' ; exit 1; }
[ -f $SNAP_PATH/plugin/snap-publisher-file ] || { echo 'Error: $SNAP_PATH/plugin/snap-publisher-file does not exist. Run make to build it.' ; exit 1; }

TEST_DIRS="cmd/ control/ core/ mgmt/ pkg/ snapd.go scheduler/"
# VET_DIRS="./cmd/... ./control/... ./core/... ./mgmt/... ./pkg/... ./scheduler/... ."

set -e

# If the following tools don't exist, get them
echo "Getting GoConvey if not found"
go get github.com/smartystreets/goconvey
echo "Getting goimports if not found"
go get golang.org/x/tools/cmd/goimports
echo "Getting cover if not found"
go get golang.org/x/tools/cmd/cover

# Automatic checks
echo "gofmt"
test -z "$(gofmt -s -l -d $TEST_DIRS | tee /dev/stderr)"

echo "goimports"
test -z "$(goimports -l -d $TEST_DIRS | tee /dev/stderr)"

# Useful but should not fail on link per: https://github.com/golang/lint
# "The suggestions made by golint are exactly that: suggestions. Golint is not perfect,
# and has both false positives and false negatives. Do not treat its output as a gold standard.
# We will not be adding pragmas or other knobs to suppress specific warnings, so do not expect
# or require code to be completely "lint-free". In short, this tool is not, and will never be,
# trustworthy enough for its suggestions to be enforced automatically, for example as part of
# a build process"
# echo "golint"
# golint ./...

# Disabling running go vet currently due to the inconsistency in it's reported
# outputs depending on whether the project was pulled down via 'go get' or 'git clone'.
# We will look to re-enable go vet checking when we can provide consistency in outputs
# no matter how a developer gets the project.
#echo "go vet"
#go vet $VET_DIRS

# go test -race ./... - Lets disable for now

# Run test coverage on each subdirectories and merge the coverage profile.
echo "mode: count ($SNAP_TEST_TYPE)" > profile-$SNAP_TEST_TYPE.cov
echo ""
echo "====================   $SNAP_TEST_TYPE    ===================="

# Standard go tooling behavior is to ignore dirs with leading underscors
for dir in $(find . -maxdepth 10 -not -path './.git*' -not -path '*/_*' -not -path './examples/*' -not -path './scripts/*' -type d);
do
	if ls $dir/*.go &> /dev/null; then
	    go test -tags=$SNAP_TEST_TYPE -covermode=count -coverprofile=$dir/profile.tmp $dir
	    if [ -f $dir/profile.tmp ]
	    then
	        cat $dir/profile.tmp | tail -n +2 >> profile-$SNAP_TEST_TYPE.cov
	        rm $dir/profile.tmp
	    fi
	fi
done

go tool cover -func profile-$SNAP_TEST_TYPE.cov
echo "==================== end $SNAP_TEST_TYPE  ===================="


text:
var vows = require('vows');
var assert = require('assert');
var path = require('path');
var AssetsInclude = require('../index');

exports.suite = vows.describe('module tests').addBatch({
  'without options': {
    topic: function() {
      return new AssetsInclude(path.join('test', 'data', 'config.yml'));
    },
    'should default root to ./public under config ': function(includer) {
      assert.equal(includer.options.root, path.join(process.cwd(), 'test', 'data', 'public'));
    },
    'should not resolve stylesheets correctly': function(includer) {
      assert.equal(includer.group('stylesheets/all.css').match(/<link/g).length, 3);
    }
  }
});


text:
namespace ppapi {

class HostResource;

namespace proxy {

class PPB_Broker_Proxy : public InterfaceProxy {
 public:
  explicit PPB_Broker_Proxy(Dispatcher* dispatcher);
  virtual ~PPB_Broker_Proxy();

  static PP_Resource CreateProxyResource(PP_Instance instance);

  // InterfaceProxy implementation.
  virtual bool OnMessageReceived(const IPC::Message& msg);

  static const ApiID kApiID = API_ID_PPB_BROKER;

 private:
  // Message handlers.
  void OnMsgCreate(PP_Instance instance, ppapi::HostResource* result_resource);
  void OnMsgConnect(const ppapi::HostResource& broker);
  void OnMsgConnectComplete(const ppapi::HostResource& broker,
                            IPC::PlatformFileForTransit foreign_socket_handle,
                            int32_t result);

  void ConnectCompleteInHost(int32_t result,
                             const ppapi::HostResource& host_resource);

  ProxyCompletionCallbackFactory<PPB_Broker_Proxy> callback_factory_;
};

}  // namespace proxy
}  // namespace ppapi

#endif  // PPAPI_PROXY_PPB_BROKER_PROXY_H_


text:
layout: page
title: Theresa Page's 95th Birthday
date: 2016-05-24
author: Randy Cobb
tags: weekly links, java
status: published
summary: Cras porttitor, eros ut mollis ullamcorper, diam turpis.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 11/24/2016
  endDate: 11/27/2016
  ctyhocn: LRLJFHX
  groupCode: TP9B
published: true
---
Praesent sapien enim, porttitor fringilla felis vel, hendrerit dapibus ipsum. Proin est turpis, interdum id dictum sit amet, imperdiet eu enim. Mauris dapibus arcu sed neque dictum, in ornare ligula hendrerit. Nulla in diam varius, fringilla orci et, luctus dui. Sed vestibulum elit sit amet massa ultrices tempor. Mauris gravida sem justo, sed cursus tellus cursus sed. Etiam iaculis convallis leo non ullamcorper. Vivamus sed mauris pellentesque, tincidunt leo vitae, accumsan ante. Donec et maximus dui. Mauris sit amet metus lobortis, ornare felis quis, ultricies justo. Cras in fringilla nibh, sit amet rutrum est. Aenean nec varius nunc. Praesent dapibus tincidunt sapien, nec sollicitudin mi posuere ut. Donec maximus, est sed venenatis tincidunt, est tortor scelerisque sem, et malesuada augue leo eget magna. Donec fermentum pulvinar lorem sed imperdiet.

1 Fusce at purus in tortor rutrum tristique
1 In quis risus blandit tortor tristique lobortis ut dapibus mi
1 Sed quis tortor vel orci semper ultrices.

Aliquam gravida eros sed auctor placerat. Etiam pharetra, sem a molestie aliquet, sem eros aliquet tellus, lacinia dictum nisl ligula vel nisi. Morbi non magna nec est vehicula sollicitudin. Suspendisse convallis scelerisque risus sed tempor. Vestibulum lobortis erat vel metus convallis venenatis. Praesent pretium condimentum sodales. Curabitur pharetra, purus eu commodo placerat, nunc risus blandit purus, ac consectetur libero odio ut neque.


text:
/**********************************************************\

  This file is distributed under the MIT License.
  See https://github.com/morzhovets/momo/blob/master/LICENSE
  for details.

  momo/details/ArrayBucket.h

\**********************************************************/

#ifndef MOMO_INCLUDE_GUARD_DETAILS_ARRAY_BUCKET
#define MOMO_INCLUDE_GUARD_DETAILS_ARRAY_BUCKET

#include "BucketUtility.h"
#include "../MemPool.h"

namespace momo
{

namespace internal
{
	template<typename TArrayBucketItemTraits>
	class ArrayBucketNestedArrayItemTraits
	{
	protected:
		typedef TArrayBucketItemTraits ArrayBucketItemTraits;
		typedef typename ArrayBucketItemTraits::MemManager ArrayBucketMemManager;

	public:
		typedef typename ArrayBucketItemTraits::Item Item;

		typedef MemManagerPtr<ArrayBucketMemManager> MemManager;

		static const size_t alignment = ArrayBucketItemTraits::alignment;

		static const bool isTriviallyRelocatable = ArrayBucketItemTraits::isTriviallyRelocatable;

		template<typename ItemArg>
		class Creator
		{
			MOMO_STATIC_ASSERT((std::is_same<ItemArg, const Item&>::value));

		public:
			explicit Creator(MemManager& memManager, const Item& item) noexcept
				: mMemManager(memManager),
				mItem(item)
			{
			}

			void operator()(Item* newItem) const
			{
				ArrayBucketItemTraits::Copy(mMemManager.GetBaseMemManager(), mItem, newItem);
			}

		private:
			MemManager& mMemManager;
			const Item& mItem;
		};

	public:
		static void Destroy(MemManager& memManager, Item* items, size_t count) noexcept
		{
			ArrayBucketItemTraits::Destroy(memManager.GetBaseMemManager(), items, count);
		}

		static void Relocate(MemManager& memManager, Item* srcItems, Item* dstItems, size_t count)
		{
			ArrayBucketItemTraits::RelocateCreate(memManager.GetBaseMemManager(), srcItems,
				dstItems, count, [] (Item*) {}, nullptr);
		}

		template<typename ItemCreator>
		static void RelocateCreate(MemManager& memManager, Item* srcItems, Item* dstItems,
			size_t count, ItemCreator&& itemCreator, Item* newItem)
		{
			ArrayBucketItemTraits::RelocateCreate(memManager.GetBaseMemManager(), srcItems,
				dstItems, count, std::forward<ItemCreator>(itemCreator), newItem);
		}
	};

	template<typename TItemTraits, size_t tMaxFastCount, typename TMemPoolParams,
		typename TArraySettings>
	class ArrayBucket
	{
	protected:
		typedef TItemTraits ItemTraits;
		typedef TMemPoolParams MemPoolParams;
		typedef TArraySettings ArraySettings;

		static const size_t maxFastCount = tMaxFastCount;
		MOMO_STATIC_ASSERT(0 < maxFastCount && maxFastCount < 16);

	public:
		typedef typename ItemTraits::Item Item;
		typedef typename ItemTraits::MemManager MemManager;

		typedef ArrayBounds<Item*> Bounds;
		typedef typename Bounds::ConstBounds ConstBounds;

	private:
		typedef internal::MemManagerPtr<MemManager> MemManagerPtr;

		typedef ArrayBucketNestedArrayItemTraits<ItemTraits> ArrayItemTraits;

		typedef momo::Array<Item, MemManagerPtr, ArrayItemTraits,
			NestedArraySettings<ArraySettings>> Array;

		static const size_t arrayAlignment = ObjectAlignmenter<Array>::alignment;
		typedef MemPoolParamsStatic<sizeof(Array) + arrayAlignment, arrayAlignment,
			MemPoolParams::blockCount, MemPoolParams::cachedFreeBlockCount> ArrayMemPoolParams;

		typedef MemPool<MemPoolParams, MemManagerPtr, NestedMemPoolSettings> FastMemPool;
		typedef MemPool<ArrayMemPoolParams, MemManagerPtr,
			NestedMemPoolSettings> ArrayMemPool;

		typedef BucketMemory<FastMemPool, uint8_t*> FastMemory;
		typedef BucketMemory<ArrayMemPool, uint8_t*> ArrayMemory;

	public:
		class Params
		{
		private:
			typedef NestedArrayIntCap<maxFastCount, FastMemPool, MemManagerDummy> FastMemPools;

		public:
			explicit Params(MemManager& memManager)
				: mArrayMemPool(MemManagerPtr(memManager))
			{
				for (size_t i = 1; i <= maxFastCount; ++i)
				{
					size_t blockSize = i * sizeof(Item) + ItemTraits::alignment;
					mFastMemPools.AddBackNogrow(
						FastMemPool(MemPoolParams(blockSize, ItemTraits::alignment),
						MemManagerPtr(memManager)));
				}
			}

			Params(const Params&) = delete;

			~Params() = default;

			Params& operator=(const Params&) = delete;

			void Clear() noexcept
			{
				if (mArrayMemPool.CanDeallocateAll())
					mArrayMemPool.DeallocateAll();
				for (FastMemPool& memPool : mFastMemPools)
				{
					if (memPool.CanDeallocateAll())
						memPool.DeallocateAll();
				}
			}

			MemManager& GetMemManager() noexcept
			{
				return mArrayMemPool.GetMemManager().GetBaseMemManager();
			}

			FastMemPool& GetFastMemPool(size_t memPoolIndex) noexcept
			{
				MOMO_ASSERT(memPoolIndex > 0);
				return mFastMemPools[memPoolIndex - 1];
			}

			ArrayMemPool& GetArrayMemPool() noexcept
			{
				return mArrayMemPool;
			}

		private:
			FastMemPools mFastMemPools;
			ArrayMemPool mArrayMemPool;
		};

	public:
		explicit ArrayBucket() noexcept
			: mPtr(nullptr)
		{
		}

		ArrayBucket(ArrayBucket&& bucket) noexcept
			: mPtr(nullptr)
		{
			Swap(bucket);
		}

		ArrayBucket(const ArrayBucket& bucket) = delete;

		explicit ArrayBucket(Params& params, const ArrayBucket& bucket)
		{
			MemManager& memManager = params.GetMemManager();
			ConstBounds bounds = bucket.GetBounds();
			size_t count = bounds.GetCount();
			if (count == 0)
			{
				mPtr = nullptr;
			}
			else if (count <= maxFastCount)
			{
				size_t memPoolIndex = pvGetFastMemPoolIndex(count);
				FastMemory memory(params.GetFastMemPool(memPoolIndex));
				Item* items = pvGetFastItems(memory.GetPointer());
				size_t index = 0;
				try
				{
					for (; index < count; ++index)
						ItemTraits::Copy(memManager, bounds[index], items + index);
				}
				catch (...)
				{
					ItemTraits::Destroy(memManager, items, index);
					throw;
				}
				pvSet(memory.Extract(), pvMakeState(memPoolIndex, count));
			}
			else
			{
				ArrayMemory memory(params.GetArrayMemPool());
				::new(static_cast<void*>(&pvGetArray(memory.GetPointer())))
					Array(bounds.GetBegin(), bounds.GetEnd(), MemManagerPtr(memManager));
				pvSet(memory.Extract(), uint8_t{0});
			}
		}

		~ArrayBucket() noexcept
		{
			MOMO_ASSERT(mPtr == nullptr);
		}

		ArrayBucket& operator=(ArrayBucket&& bucket) noexcept
		{
			ArrayBucket(std::move(bucket)).Swap(*this);
			return *this;
		}

		ArrayBucket& operator=(const ArrayBucket&) = delete;

		void Swap(ArrayBucket& bucket) noexcept
		{
			std::swap(mPtr, bucket.mPtr);
		}

		ConstBounds GetBounds() const noexcept
		{
			return pvGetBounds();
		}

		Bounds GetBounds() noexcept
		{
			return pvGetBounds();
		}

		void Clear(Params& params) noexcept
		{
			pvRemoveAll<true>(params);
		}

		template<typename ItemCreator>
		void AddBackCrt(Params& params, ItemCreator&& itemCreator)
		{
			if (mPtr == nullptr)
			{
				size_t newCount = 1;
				size_t newMemPoolIndex = pvGetFastMemPoolIndex(newCount);
				FastMemory memory(params.GetFastMemPool(newMemPoolIndex));
				std::forward<ItemCreator>(itemCreator)(pvGetFastItems(memory.GetPointer()));
				pvSet(memory.Extract(), pvMakeState(newMemPoolIndex, newCount));
			}
			else
			{
				size_t memPoolIndex = pvGetMemPoolIndex();
				if (memPoolIndex > 0)
				{
					size_t count = pvGetFastCount();
					MOMO_ASSERT(count <= memPoolIndex);
					if (count == memPoolIndex)
					{
						size_t newCount = count + 1;
						Item* items = pvGetFastItems();
						if (newCount <= maxFastCount)
						{
							size_t newMemPoolIndex = pvGetFastMemPoolIndex(newCount);
							FastMemory memory(params.GetFastMemPool(newMemPoolIndex));
							Item* newItems = pvGetFastItems(memory.GetPointer());
							ItemTraits::RelocateCreate(params.GetMemManager(), items, newItems,
								count, std::forward<ItemCreator>(itemCreator), newItems + count);
							params.GetFastMemPool(memPoolIndex).Deallocate(mPtr);
							pvSet(memory.Extract(), pvMakeState(newMemPoolIndex, newCount));
						}
						else
						{
							ArrayMemPool& arrayMemPool = params.GetArrayMemPool();
							ArrayMemory memory(arrayMemPool);
							Array array = Array::CreateCap(maxFastCount * 2,
								MemManagerPtr(arrayMemPool.GetMemManager()));
							Item* newItems = array.GetItems();
							ItemTraits::RelocateCreate(params.GetMemManager(), items, newItems,
								count, std::forward<ItemCreator>(itemCreator), newItems + count);
							array.SetCountCrt(newCount, [] (Item* /*newItem*/) {});
							::new(static_cast<void*>(&pvGetArray(memory.GetPointer())))
								Array(std::move(array));
							params.GetFastMemPool(memPoolIndex).Deallocate(mPtr);
							pvSet(memory.Extract(), uint8_t{0});
						}
					}
					else
					{
						std::forward<ItemCreator>(itemCreator)(pvGetFastItems() + count);
						++*mPtr;
					}
				}
				else
				{
					pvGetArray().AddBackCrt(std::forward<ItemCreator>(itemCreator));
				}
			}
		}

		void RemoveBack(Params& params) noexcept
		{
			size_t count = GetBounds().GetCount();
			MOMO_ASSERT(count > 0);
			if (count == 1)
				return pvRemoveAll<false>(params);
			if (pvGetMemPoolIndex() > 0)
			{
				ItemTraits::Destroy(params.GetMemManager(), pvGetFastItems() + count - 1, 1);
				--*mPtr;
			}
			else
			{
				Array& array = pvGetArray();
				array.RemoveBack();
				if (2 < count && count <= array.GetCapacity() / 4)
				{
					try
					{
						array.Shrink(count * 2);
					}
					catch (...)
					{
						// no throw!
					}
				}
			}
		}

		void RemoveAll(Params& params) noexcept
		{
			pvRemoveAll<false>(params);
		}

	private:
		void pvSet(uint8_t* ptr, uint8_t state) noexcept
		{
			MOMO_ASSERT(ptr != nullptr);
			mPtr = ptr;
			*mPtr = state;
		}

		static uint8_t pvMakeState(size_t memPoolIndex, size_t count) noexcept
		{
			return static_cast<uint8_t>((memPoolIndex << 4) | count);
		}

		static size_t pvGetFastMemPoolIndex(size_t count) noexcept
		{
			MOMO_ASSERT(0 < count && count <= maxFastCount);
			return count;
		}

		size_t pvGetMemPoolIndex() const noexcept
		{
			MOMO_ASSERT(mPtr != nullptr);
			return size_t{*mPtr} >> 4;
		}

		size_t pvGetFastCount() const noexcept
		{
			MOMO_ASSERT(pvGetMemPoolIndex() > 0);
			return size_t{*mPtr} & 15;
		}

		Item* pvGetFastItems() const noexcept
		{
			MOMO_ASSERT(pvGetMemPoolIndex() > 0);
			return pvGetFastItems(mPtr);
		}

		static Item* pvGetFastItems(uint8_t* ptr) noexcept
		{
			return PtrCaster::Shift<Item>(ptr, ItemTraits::alignment);
		}

		Array& pvGetArray() const noexcept
		{
			MOMO_ASSERT(pvGetMemPoolIndex() == 0);
			return pvGetArray(mPtr);
		}

		static Array& pvGetArray(uint8_t* ptr) noexcept
		{
			return *PtrCaster::Shift<Array>(ptr, arrayAlignment);
		}

		Bounds pvGetBounds() const noexcept
		{
			if (mPtr == nullptr)
			{
				return Bounds();
			}
			else if (pvGetMemPoolIndex() > 0)
			{
				return Bounds(pvGetFastItems(), pvGetFastCount());
			}
			else
			{
				Array& array = pvGetArray();
				return Bounds(array.GetItems(), array.GetCount());
			}
		}

		template<bool onClear>
		void pvRemoveAll(Params& params) noexcept
		{
			if (mPtr == nullptr)
				return;
			size_t memPoolIndex = pvGetMemPoolIndex();
			if (memPoolIndex > 0)
			{
				ItemTraits::Destroy(params.GetMemManager(), pvGetFastItems(), pvGetFastCount());
				FastMemPool& memPool = params.GetFastMemPool(memPoolIndex);
				if (!onClear || !memPool.CanDeallocateAll())
					memPool.Deallocate(mPtr);
			}
			else
			{
				pvGetArray().~Array();
				ArrayMemPool& memPool = params.GetArrayMemPool();
				if (!onClear || !memPool.CanDeallocateAll())
					memPool.Deallocate(mPtr);
			}
			mPtr = nullptr;
		}

	private:
		uint8_t* mPtr;
	};
}

} // namespace momo

#endif // MOMO_INCLUDE_GUARD_DETAILS_ARRAY_BUCKET


text:
GoogleLocationSettingsHelper* GoogleLocationSettingsHelper::Create() {
  return new ChromeShellGoogleLocationSettingsHelper();
}

ChromeShellGoogleLocationSettingsHelper::
    ChromeShellGoogleLocationSettingsHelper()
    : GoogleLocationSettingsHelper() {
}

ChromeShellGoogleLocationSettingsHelper::
    ~ChromeShellGoogleLocationSettingsHelper() {
}

bool ChromeShellGoogleLocationSettingsHelper::IsSystemLocationEnabled() {
  return true;
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.hive;

import io.prestosql.Session;
import io.prestosql.execution.DynamicFilterConfig;
import io.prestosql.operator.OperatorStats;
import io.prestosql.sql.analyzer.FeaturesConfig;
import io.prestosql.testing.AbstractTestJoinQueries;
import io.prestosql.testing.MaterializedResult;
import io.prestosql.testing.QueryRunner;
import io.prestosql.testing.ResultWithQueryId;
import org.testng.annotations.Test;

import static com.google.common.base.Verify.verify;
import static io.prestosql.SystemSessionProperties.JOIN_DISTRIBUTION_TYPE;
import static io.prestosql.tpch.TpchTable.getTables;
import static org.testng.Assert.assertEquals;

/**
 * @see TestHiveDistributedJoinQueriesWithoutDynamicFiltering for tests with dynamic filtering enabled
 */
public class TestHiveDistributedJoinQueries
        extends AbstractTestJoinQueries
{
    @Override
    protected QueryRunner createQueryRunner()
            throws Exception
    {
        verify(new DynamicFilterConfig().isEnableDynamicFiltering(), "this class assumes dynamic filtering is enabled by default");
        return HiveQueryRunner.builder()
                .setInitialTables(getTables())
                .build();
    }

    @Test
    public void verifyDynamicFilteringEnabled()
    {
        assertQuery(
                "SHOW SESSION LIKE 'enable_dynamic_filtering'",
                "VALUES ('enable_dynamic_filtering', 'true', 'true', 'boolean', 'Enable dynamic filtering')");
    }

    @Test
    public void testJoinWithEmptyBuildSide()
    {
        Session session = Session.builder(getSession())
                .setSystemProperty(JOIN_DISTRIBUTION_TYPE, FeaturesConfig.JoinDistributionType.BROADCAST.name())
                .build();
        ResultWithQueryId<MaterializedResult> result = getDistributedQueryRunner().executeWithQueryId(
                session,
                "SELECT * FROM lineitem JOIN orders ON lineitem.orderkey = orders.orderkey AND orders.totalprice = 123.4567");
        assertEquals(result.getResult().getRowCount(), 0);

        OperatorStats probeStats = searchScanFilterAndProjectOperatorStats(result.getQueryId(), "tpch:lineitem");
        // Probe-side is not scanned at all, due to dynamic filtering:
        assertEquals(probeStats.getInputPositions(), 0L);
        assertEquals(probeStats.getDynamicFilterSplitsProcessed(), probeStats.getTotalDrivers());
    }
}


text:
package backend;

import drat.proteus.services.general.DratServiceStatus;

/**
 * This interface abstracts the main communication methods between Apache DRAT
 * and Proteus
 */
public interface AbstractDratWrapper {
  public void crawl() throws Exception;

  public void index() throws Exception;

  public void map() throws Exception;

  public void reduce() throws Exception;

  public void go() throws Exception;

  public void reset() throws Exception;

  public void setIndexablePath(String path);

  public String getIndexablePath();

  public DratServiceStatus getDratStatus();
}


text:
package com.google.cloud.recommendationengine.v1beta1.samples;

// [START recommendationengine_v1beta1_generated_catalogserviceclient_deletecatalogitem_sync]
import com.google.cloud.recommendationengine.v1beta1.CatalogItemPathName;
import com.google.cloud.recommendationengine.v1beta1.CatalogServiceClient;
import com.google.cloud.recommendationengine.v1beta1.DeleteCatalogItemRequest;
import com.google.protobuf.Empty;

public class SyncDeleteCatalogItem {

  public static void main(String[] args) throws Exception {
    syncDeleteCatalogItem();
  }

  public static void syncDeleteCatalogItem() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CatalogServiceClient catalogServiceClient = CatalogServiceClient.create()) {
      DeleteCatalogItemRequest request =
          DeleteCatalogItemRequest.newBuilder()
              .setName(
                  CatalogItemPathName.of(
                          "[PROJECT]", "[LOCATION]", "[CATALOG]", "[CATALOG_ITEM_PATH]")
                      .toString())
              .build();
      catalogServiceClient.deleteCatalogItem(request);
    }
  }
}
// [END recommendationengine_v1beta1_generated_catalogserviceclient_deletecatalogitem_sync]


text:
package com.box.l10n.mojito.rest.resttemplate;

import com.google.common.annotations.VisibleForTesting;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.InterceptingClientHttpRequestFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.DefaultCsrfToken;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;

/**
 * An interceptor that will check to see if there's a valid request csrf.
 *
 * @author wyau
 */
@Component
public class FormLoginAuthenticationCsrfTokenInterceptor implements ClientHttpRequestInterceptor {

  /** logger */
  Logger logger = LoggerFactory.getLogger(FormLoginAuthenticationCsrfTokenInterceptor.class);

  public static final String CSRF_PARAM_NAME = "_csrf";
  public static final String CSRF_HEADER_NAME = "X-CSRF-TOKEN";
  public static final String COOKIE_SESSION_NAME = "JSESSIONID";

  @Autowired FormLoginConfig formLoginConfig;

  /** The {@link AuthenticatedRestTemplate} to which this interceptor is being used. */
  @Autowired AuthenticatedRestTemplate authRestTemplate;

  @Autowired ResttemplateConfig resttemplateConfig;

  /**
   * This is used for the authentication flow to keep things separate from the restTemplate that
   * this interceptor is intercepting
   */
  CookieStoreRestTemplate restTemplateForAuthenticationFlow;

  /**
   * This is so that we obtain access to the cookie store used inside HttpClient to check to see if
   * we have a session
   */
  CookieStore cookieStore;

  /** This is the latest session id that was used to obtain the {@link this#latestCsrfToken} */
  String latestSessionIdForLatestCsrfToken;

  /**
   * This is the lastest CSRF token that was obtained from the {@link
   * this#latestSessionIdForLatestCsrfToken}
   */
  CsrfToken latestCsrfToken = null;

  @Autowired CredentialProvider credentialProvider;

  /** Init */
  @PostConstruct
  protected void init() {

    restTemplateForAuthenticationFlow = new CookieStoreRestTemplate();
    cookieStore = restTemplateForAuthenticationFlow.getCookieStore();

    logger.debug(
        "Inject cookie store used in the rest template for authentication flow into the authRestTemplate so that they will match");
    authRestTemplate.restTemplate.setCookieStoreAndUpdateRequestFactory(cookieStore);

    List<ClientHttpRequestInterceptor> interceptors =
        Collections.<ClientHttpRequestInterceptor>singletonList(
            new ClientHttpRequestInterceptor() {
              @Override
              public ClientHttpResponse intercept(
                  HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
                  throws IOException {
                if (latestCsrfToken != null) {
                  // At the beginning of auth flow, there's no token yet
                  injectCsrfTokenIntoHeader(request, latestCsrfToken);
                }
                return execution.execute(request, body);
              }
            });

    restTemplateForAuthenticationFlow.setRequestFactory(
        new InterceptingClientHttpRequestFactory(
            restTemplateForAuthenticationFlow.getRequestFactory(), interceptors));
  }

  /**
   * This intercepts a request then will either use the existing session, or will authenticate to
   * obtain a proper session, or will inject the request with the correct CSRF token.
   *
   * <p>Flow example: 1. GET /login - because it has not been prepped, it starts auth flow 2. POST
   * /login 3. GET /session-timeout-endpoint - response 302/login 4. GET /login 5. POST /login 6.
   * GET /session-timeout-endpoint
   *
   * @param request
   * @param body
   * @param execution
   * @return
   * @throws IOException
   */
  @Override
  public ClientHttpResponse intercept(
      HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    if (doesSessionIdInCookieStoreExistAndMatchLatestSessionId()) {
      injectCsrfTokenIntoHeader(request, latestCsrfToken);
    } else {
      startAuthenticationAndInjectCsrfToken(request);
    }

    ClientHttpResponse clientHttpResponse = execution.execute(request, body);

    clientHttpResponse = handleResponse(request, body, execution, clientHttpResponse);

    return clientHttpResponse;
  }

  /**
   * Handle http response from the intercept. It will check to see if the initial response was
   * successful (ie. error status such as 301, 403). If so, it'll try the authentication flow again.
   * If it further encounters an unsuccessful response, then it'll throw a {@link
   * RestClientException}
   *
   * @param request
   * @param body
   * @param execution
   * @param clientHttpResponse
   * @return
   * @throws IOException
   */
  protected ClientHttpResponse handleResponse(
      HttpRequest request,
      byte[] body,
      ClientHttpRequestExecution execution,
      ClientHttpResponse clientHttpResponse)
      throws IOException {
    if (isForbiddened(clientHttpResponse) || isUnauthenticated(clientHttpResponse)) {
      reauthenticate(request);

      clientHttpResponse = execution.execute(request, body);

      if (isForbiddened(clientHttpResponse) || isUnauthenticated(clientHttpResponse)) {
        throw new RestClientException(
            "Tried to re-authenticate but the response remains to be unauthenticated");
      }
    }
    return clientHttpResponse;
  }

  /**
   * Checks to see if response was {@link HttpStatus#FORBIDDEN}
   *
   * @param clientHttpResponse
   * @return
   * @throws IOException
   */
  private Boolean isForbiddened(ClientHttpResponse clientHttpResponse) throws IOException {
    return clientHttpResponse.getStatusCode().equals(HttpStatus.FORBIDDEN);
  }

  /**
   * Reauthenticate the {@link AuthenticatedRestTemplate}
   *
   * @param request
   */
  private void reauthenticate(HttpRequest request) {
    logger.debug("Reseting authentication");
    resetAuthentication();

    logger.debug("Authenticate again");
    startAuthenticationAndInjectCsrfToken(request);
  }

  /**
   * Starts authentication flow and inject csrf token
   *
   * @param request
   */
  protected void startAuthenticationAndInjectCsrfToken(HttpRequest request) {
    logger.debug(
        "Authenticate because no session is found in cookie store or it doesn't match with the one used to get the CSRF token we have.");
    startAuthenticationFlow();

    logger.debug("Injecting CSRF token");
    injectCsrfTokenIntoHeader(request, latestCsrfToken);
  }

  /**
   * Gets the authenticated session id. If it is not found, an authentication flow will be started
   * so that a proper session id is available
   *
   * @return
   */
  protected boolean doesSessionIdInCookieStoreExistAndMatchLatestSessionId() {
    logger.debug(
        "Check to see if session id in cookie store matches the session id used to get the latest CSRF token");
    String sessionId = getAuthenticationSessionIdFromCookieStore();

    return sessionId != null && sessionId.equals(latestSessionIdForLatestCsrfToken);
  }

  /** @return null if no sesson id cookie is found */
  protected String getAuthenticationSessionIdFromCookieStore() {
    List<Cookie> cookies = cookieStore.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(COOKIE_SESSION_NAME)) {
        String cookieValue = cookie.getValue();
        logger.debug("Found session cookie: {}", cookieValue);
        return cookieValue;
      }
    }

    return null;
  }

  /**
   * @param request the request, containing method, URI, and headers
   * @param csrfToken the CSRF token to be injected into the request header
   */
  protected void injectCsrfTokenIntoHeader(HttpRequest request, CsrfToken csrfToken) {
    if (csrfToken == null) {
      throw new SessionAuthenticationException("There is no CSRF token to inject");
    }

    logger.debug(
        "Injecting CSRF token into request {} header: {}", request.getURI(), csrfToken.getToken());
    request.getHeaders().add(csrfToken.getHeaderName(), csrfToken.getToken());
  }

  /**
   * Starts the traditioanl form login authentication flow handshake. Consequencially, the cookie
   * store (which contains the session id) and the CSRF token will be updated.
   *
   * @throws AuthenticationException
   */
  protected synchronized void startAuthenticationFlow() throws AuthenticationException {
    logger.debug("Getting authenticated session");

    logger.debug(
        "Start by loading up the login form to get a valid unauthenticated session and CSRF token");
    ResponseEntity<String> loginResponseEntity =
        restTemplateForAuthenticationFlow.getForEntity(
            authRestTemplate.getURIForResource(formLoginConfig.getLoginFormPath()), String.class);

    latestCsrfToken = getCsrfTokenFromLoginHtml(loginResponseEntity.getBody());
    latestSessionIdForLatestCsrfToken = getAuthenticationSessionIdFromCookieStore();
    logger.debug(
        "Update CSRF token for interceptor ({}) from login form", latestCsrfToken.getToken());

    MultiValueMap<String, Object> loginPostParams = new LinkedMultiValueMap<>();
    loginPostParams.add("username", credentialProvider.getUsername());
    loginPostParams.add("password", credentialProvider.getPassword());

    logger.debug(
        "Post to login url to startAuthenticationFlow with user={}, pwd={}",
        credentialProvider.getUsername(),
        credentialProvider.getPassword());
    ResponseEntity<String> postLoginResponseEntity =
        restTemplateForAuthenticationFlow.postForEntity(
            authRestTemplate.getURIForResource(formLoginConfig.getLoginFormPath()),
            loginPostParams,
            String.class);

    // TODO(P1) This current way of checking if authentication is successful is somewhat
    // hacky. Bascailly it says that authentication is successful if a 302 is returned
    // and the redirect (from location header) maps to the login redirect path from the config.
    URI locationURI = URI.create(postLoginResponseEntity.getHeaders().get("Location").get(0));
    String expectedLocation =
        resttemplateConfig.getContextPath() + "/" + formLoginConfig.getLoginRedirectPath();

    if (postLoginResponseEntity.getStatusCode().equals(HttpStatus.FOUND)
        && expectedLocation.equals(locationURI.getPath())) {

      latestCsrfToken =
          getCsrfTokenFromEndpoint(
              authRestTemplate.getURIForResource(formLoginConfig.getCsrfTokenPath()));
      latestSessionIdForLatestCsrfToken = getAuthenticationSessionIdFromCookieStore();

      logger.debug(
          "Update CSRF token interceptor in AuthRestTempplate ({})", latestCsrfToken.getToken());

    } else {
      throw new SessionAuthenticationException(
          "Authentication failed.  Post login status code = "
              + postLoginResponseEntity.getStatusCode()
              + ", location = ["
              + locationURI.getPath()
              + "], expected location = ["
              + expectedLocation
              + "]");
    }
  }

  /**
   * Gets the CSRF token from login html because the CSRF token endpoint needs to be authenticated
   * first.
   *
   * @param loginHtml The login page HTML which contains the csrf token. It is assumed that the CSRF
   *     token is embedded on the page inside an input field with name matching {@link
   *     com.box.l10n.mojito.rest.resttemplate.FormLoginAuthenticationCsrfTokenInterceptor#CSRF_PARAM_NAME}
   * @return
   * @throws AuthenticationException
   */
  protected CsrfToken getCsrfTokenFromLoginHtml(String loginHtml) throws AuthenticationException {
    Pattern pattern = Pattern.compile("CSRF_TOKEN = '(.*?)';");
    Matcher matcher = pattern.matcher(loginHtml);

    if (matcher.find()) {
      String csrfTokenString = matcher.group(1);

      logger.debug("CSRF token from login html: {}", csrfTokenString);
      return new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAM_NAME, csrfTokenString);
    } else {
      throw new SessionAuthenticationException("Could not find CSRF_TOKEN variable on login page");
    }
  }

  /**
   * Use the CSRF token endpoint to get the CSRF token corresponding to this session
   *
   * @param csrfTokenUrl The full URL to which the CSRF token can be obtained
   * @return
   */
  protected CsrfToken getCsrfTokenFromEndpoint(String csrfTokenUrl) {
    ResponseEntity<String> csrfTokenEntity =
        restTemplateForAuthenticationFlow.getForEntity(csrfTokenUrl, String.class, "");
    logger.debug("CSRF token from {} is {}", csrfTokenUrl, csrfTokenEntity.getBody());
    return new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAM_NAME, csrfTokenEntity.getBody());
  }

  @VisibleForTesting
  public void resetAuthentication() {
    cookieStore.clear();
    latestCsrfToken = null;
  }

  @VisibleForTesting
  public void setCredentialProvider(CredentialProvider credentialProvider) {
    this.credentialProvider = credentialProvider;
  }

  /**
   * Checks if the response status is unauthenticated
   *
   * @param clientHttpResponse
   * @return
   * @throws IOException
   */
  protected boolean isUnauthenticated(ClientHttpResponse clientHttpResponse) throws IOException {
    return (clientHttpResponse.getStatusCode().equals(HttpStatus.FOUND)
            && clientHttpResponse.getHeaders().getLocation().getPath().equals("/login"))
        || (clientHttpResponse.getStatusCode().equals(HttpStatus.UNAUTHORIZED));
  }
}


text:
"""
    setup script for pyGpufit

    TODO get version, get meaningful email
"""

from setuptools import setup, find_packages
import os
from io import open # to have encoding as parameter of open on Python >=2.6
import pygpufit.version as vs

if os.name == 'nt':
	lib_ext = '.dll' # library name extension on Windows
elif os.name == 'posix':
	lib_ext = '.so'  # library name extensions on Unix
else:
	raise RuntimeError('OS {} not supported'.format(os.name))

HERE = os.path.abspath(os.path.dirname(__file__))

CLASSIFIERS = ['Development Status :: 5 - Production/Stable',
               'Intended Audience :: End Users/Desktop',
               'Operating System :: Microsoft :: Windows',
               'Topic :: Scientific/Engineering',
               'Topic :: Software Development :: Libraries']

def get_long_description():
    """
    Get the long description from the README file.
    """
    with open(os.path.join(HERE, 'README.txt'), encoding='utf-8') as f:
        return f.read()

if __name__ == "__main__":
    setup(name='pyGpufit',
        version=vs.__version__,
        description='Levenberg Marquardt curve fitting in CUDA',
        long_description=get_long_description(),
        url='https://github.com/gpufit/Gpufit',
        author='M. Bates, A. Przybylski, B. Thiel, and J. Keller-Findeisen',
        author_email='a@b.c',
        license='MIT license',
        classifiers=[],
        keywords='Levenberg Marquardt, curve fitting, CUDA',
        packages=find_packages(where=HERE),
        package_data={'pygpufit': ['*{}'.format(lib_ext)]},
        install_requires=['NumPy>=1.0'],
        zip_safe=False)


text:
package org.hibernate.validator;

import java.lang.annotation.Documented;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;

/**
 * Link between an constraint annotation and it's validator implementation
 *
 * @author Gavin King
 */
@Documented
@Target({ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface ValidatorClass {
	Class<? extends Validator> value();
}


text:
"""Compare a directory of abc and midi files.

Assumes a directory of abc files converted with something like:
# First, remove 'hornpipe' rhythm marker because abc2midi changes note durations
# when that is present.
ls *.abc | xargs -l1 sed -i '/R: hornpipe/d'
ls *.abc | xargs -l1 abc2midi
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import pdb
import re

from magenta.music import abc_parser
from magenta.music import midi_io
from magenta.music import sequences_lib
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

tf.app.flags.DEFINE_string('input_dir', None,
                           'Directory containing files to convert.')

class CompareDirectory(tf.test.TestCase):
  """Fake test used to compare directories of abc and midi files."""

  def runTest(self):
    pass

  def compare_directory(self, directory):
    self.maxDiff = None  # pylint: disable=invalid-name

    files_in_dir = tf.gfile.ListDirectory(directory)
    files_parsed = 0
    for file_in_dir in files_in_dir:
      if not file_in_dir.endswith('.abc'):
        continue
      abc = os.path.join(directory, file_in_dir)
      midis = {}
      ref_num = 1
      while True:
        midi = re.sub(r'\.abc$', str(ref_num) + '.mid',
                      os.path.join(directory, file_in_dir))
        if not tf.gfile.Exists(midi):
          break
        midis[ref_num] = midi
        ref_num += 1

      print('parsing {}: {}'.format(files_parsed, abc))
      tunes, exceptions = abc_parser.parse_abc_tunebook_file(abc)
      files_parsed += 1
      self.assertEqual(len(tunes), len(midis) - len(exceptions))

      for tune in tunes.values():
        expanded_tune = sequences_lib.expand_section_groups(tune)
        midi_ns = midi_io.midi_file_to_sequence_proto(
            midis[tune.reference_number])
        # abc2midi adds a 1-tick delay to the start of every note, but we don't.
        tick_length = ((1 / (midi_ns.tempos[0].qpm / 60)) /
                       midi_ns.ticks_per_quarter)
        for note in midi_ns.notes:
          note.start_time -= tick_length
          # For now, don't compare velocities.
          note.velocity = 90
        if len(midi_ns.notes) != len(expanded_tune.notes):
          pdb.set_trace()
          self.assertProtoEquals(midi_ns, expanded_tune)
        for midi_note, test_note in zip(midi_ns.notes, expanded_tune.notes):
          try:
            self.assertProtoEquals(midi_note, test_note)
          except Exception as e:  # pylint: disable=broad-except
            print(e)
            pdb.set_trace()
        self.assertEqual(midi_ns.total_time, expanded_tune.total_time)

def main(unused_argv):
  if not FLAGS.input_dir:
    tf.logging.fatal('--input_dir required')
    return

  input_dir = os.path.expanduser(FLAGS.input_dir)

  CompareDirectory().compare_directory(input_dir)

def console_entry_point():
  tf.app.run(main)

if __name__ == '__main__':
  console_entry_point()


text:
@interface AreaModel : NSObject

@property (nonatomic, assign) NSInteger idField;
@property (nonatomic, strong) NSString * name;

-(instancetype)initWithDictionary:(NSDictionary *)dictionary;

@end


text:
package no.kjelli.generic;

public interface Game {

	public void init();

	public void loadSounds();

	public void render();

	public void update();

	public void destroy();

	public double getWidth();

	public double getHeight();

	public String getTitle();

}


text:
exports = module.exports = function (request, response, done) {
    done();
};


text:
package sun.net.www.content.notes;

import java.io.IOException;
import java.net.ContentHandler;
import java.net.URLConnection;
import java.util.Map;

import lotus.domino.NotesException;

import com.route246.vimnotes.service.NotesDocumentService;
import com.route246.vimnotes.util.NotesUrl;

/**
 * Notes Document content handler implementation.
 *
 * @author Gen Nishimura
 */
public class document extends ContentHandler {

    /**
     *
     */
    private enum KnownDocumentAttributes {
        NotesUrl, Subject, Body, From, To, Cc, SentBy, Attachments
    }

    /**
     * @see java.net.ContentHandler#getContent(java.net.URLConnection)
     */
    @Override
    public Object getContent(URLConnection urlConnection) throws IOException {
        return getContent(urlConnection, new Class[] { String.class });
    }

    /**
     * @see java.net.ContentHandler#getContent(java.net.URLConnection, java.lang.Class[])
     */
    @Override
    public Object getContent(URLConnection urlConnection, @SuppressWarnings("rawtypes") Class[] classes)
            throws IOException {
        for (Class<?> clazz : classes) {
            if (clazz.isAssignableFrom(Map.class)) {
                return getDocumentAsMap(urlConnection);
            }
            if (clazz.isAssignableFrom(String.class)) {
                return getDocumentAsString(urlConnection);
            }
        }
        return null;
    }

    /**
     * @param urlConnection
     * @return
     * @throws IOException
     */
    public Map<String, String> getDocumentAsMap(URLConnection urlConnection) throws IOException {
        NotesUrl notesUrl = new NotesUrl(urlConnection.getURL());
        try {
            return new NotesDocumentService().getDocument(notesUrl);
        } catch (NotesException e) {
            throw new IOException(e);
        }
    }

    /**
     * @param urlConnection
     * @return
     * @throws IOException
     */
    public String getDocumentAsString(URLConnection urlConnection) throws IOException {
        Map<String, String> map = getDocumentAsMap(urlConnection);
        StringBuilder sb = new StringBuilder();
        String notesUrl, subject, body, from, sentby, to, cc, attachments;
        notesUrl = subject = body = from = sentby = to = cc = attachments = "";
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            KnownDocumentAttributes keyEnum;
            try {
                keyEnum = KnownDocumentAttributes.valueOf(key);
            } catch (IllegalArgumentException e) {
                sb.append(key).append(": ").append(entry.getValue()).append("\n");
                continue;
            }
            switch (keyEnum) {
            case Body:
                body = entry.getValue();
                break;
            case Cc:
                cc = formatMultipleNames(entry.getValue());
                break;
            case From:
                from = entry.getValue();
                break;
            case NotesUrl:
                notesUrl = entry.getValue();
                break;
            case SentBy:
                sentby = entry.getValue();
                break;
            case Subject:
                subject = entry.getValue();
                break;
            case To:
                to = formatMultipleNames(entry.getValue());
                break;
            case Attachments:
                attachments = entry.getValue().replaceAll("\t", "\n             ");
                break;
            default:
                sb.append(key).append(": ").append(entry.getValue()).append("\n");
            }
        }
        if (0 < to.length()) {
            sb.append("To: ").append(to).append("\n");
        }
        if (0 < cc.length()) {
            sb.append("Cc: ").append(cc).append("\n");
        }
        if (0 < from.length()) {
            sb.append("From: ").append(from).append("\n");
        }
        if (0 < sentby.length()) {
            sb.append("SentBy: ").append(sentby).append("\n");
        }
        if (0 < attachments.length()) {
            sb.append("Attachments: ").append(attachments).append("\n");
        }
        sb.append("Subject: ").append(subject);
        sb.append("\nBody: \n").append(body);
        sb.insert(0, "\n");
        sb.insert(0, notesUrl);
        sb.insert(0, "NotesUrl: ");
        return sb.toString();
    }

    /**
     * @param names
     * @return
     */
    private String formatMultipleNames(final String names) {
        return names.replaceAll("\t", ", ");
    }
}


text:
<?xml version="1.0" encoding='UTF-8'?>
<!DOCTYPE [
<!ELEMENT animal EMPTY>
] animal>
<!-- Wrong ordering [ ] Name in doctypedecl -->
<animal/>


text:
<TITLE>Review for Guinevere (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Guinevere (1999)

reviewed by
Chuck Schwartz

CrankyCritic® movie reviews: Guinevere
Starring Sarah Polley, Stephen Rea, Jean Smart, Gina Gershon, Paul
Dooley, Carrie Preston, Jasmine Guy
Written and Directed by Audrey Wells
website: www.miramax.com

IN SHORT: For the arthouse.

Didn't we see enough magazine articles about Hollywood's predilection
for teaming older actors and way too young for them actresses ad nauseam
in the past year? At least in the case of Guinevere the perpetrator is a
female, the writer of the most excellent The Truth About Cats and Dogs,
Audrey Wells. Wells makes her directorial debut with Guinevere, which is
a straight romance without any of the gentle humor found in Cats and
Dogs.

To call Harper Sloane (Sarah Polley) anything other than wallflower
would be an exaggeration. She hides behind closed doors, bottle in hand,
at her sister's wedding; Asks the wedding photographer to leave her out
of the photographs; Doesn't understand why the shutterbug, Cornelius
"Connie" Fitzpatrick (Stephen Rea) calls her "Guinevere". As we will
discover, it's an opening line that Connie has used many times before.

Connie's sole claim to fame is his one published book, "Street Glory,"
which connected him with his own patron (Paul Dooley), who bought
Connie's photographs as art. In between, he shoots weddings to pay the
end of the month rent on his industrial loft. Which brings us full
circle.

Like the mentor/student story of artists Alfred Steiglitz and Georgia
O'Keefe, referenced in the flick, Connie takes unfocussed young chicks
under his wing and puts them to work, discovering their creative sides
in photography, art, painting, or other creative processes. It's a good
thing to be a mentor, to guide the young on a path towards some
manifestation of enlightenment and, if you get a little on the side, or
in the darkroom, or on the roof, so much the better . . .

Stephen Rea brings his droopy dog-eyed look to the screen and Sarah
Polley is occasionally flitty, but why the pair connect on an emotional
level is quite beyond me. There's no sense that Connie is the proverbial
"dirty old man" though, as we meet earlier Guineveres (including Jasmine
Guy and the more prominent Gina Gershon) a pattern emerges. Harper's
family, believing that she is away at college, is initially deceived.
When Mom (Jean Smart) discovers the relationship, she reacts with a cold
fury and a savage verbal deconstruction as to Connie's motives. This
scene alone is worth the price of a ticket and earns Smart a place on my
end of year "best" list.

On average, a first run movie ticket will run you Eight Bucks. Were
Cranky able to set his own price to Guinevere, he would have paid...

$4.00

Pay per view level. Guinevere is just an OK flick for the indie arthouse
circuit.

The Cranky Critic® is a Registered Trademark of, and Copyright © 1999
by, Chuck Schwartz. All Rights Reserved. Cranky on the web at
www.crankycritic.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews