text:
/* $Id: VBoxUsbRt.cpp $ */
/** @file
 * VBox USB R0 runtime
 */
/*
 * Copyright (C) 2011-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.
 */

#include "VBoxUsbCmn.h"
#include "../cmn/VBoxUsbIdc.h"
#include "../cmn/VBoxUsbTool.h"

#include <VBox/usblib-win.h>
#include <iprt/assert.h>
#include <VBox/log.h>
#define _USBD_

#define USBD_DEFAULT_PIPE_TRANSFER 0x00000008

#define VBOXUSB_MAGIC  0xABCF1423

typedef struct VBOXUSB_URB_CONTEXT
{
    PURB pUrb;
    PMDL pMdlBuf;
    PVBOXUSBDEV_EXT pDevExt;
    PVOID pOut;
    ULONG ulTransferType;
    ULONG ulMagic;
} VBOXUSB_URB_CONTEXT, * PVBOXUSB_URB_CONTEXT;

typedef struct VBOXUSB_SETUP
{
    uint8_t  bmRequestType;
    uint8_t  bRequest;
    uint16_t wValue;
    uint16_t wIndex;
    uint16_t wLength;
} VBOXUSB_SETUP, *PVBOXUSB_SETUP;

static bool vboxUsbRtCtxSetOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj)
{
    bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, pFObj, NULL);
    if (bRc)
    {
        Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) acquired\n", pFObj));
    }
    else
    {
        Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) FAILED!!\n", pFObj));
    }
    return bRc;
}

static bool vboxUsbRtCtxReleaseOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj)
{
    bool bRc = ASMAtomicCmpXchgPtr(&pDevExt->Rt.pOwner, NULL, pFObj);
    if (bRc)
    {
        Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) released\n", pFObj));
    }
    else
    {
        Log((__FUNCTION__": pDevExt (0x%x) Owner(0x%x) release: is NOT an owner\n", pFObj));
    }
    return bRc;
}

static bool vboxUsbRtCtxIsOwner(PVBOXUSBDEV_EXT pDevExt, PFILE_OBJECT pFObj)
{
    PFILE_OBJECT pOwner = (PFILE_OBJECT)ASMAtomicReadPtr((void *volatile *)(&pDevExt->Rt.pOwner));
    return pOwner == pFObj;
}

static NTSTATUS vboxUsbRtIdcSubmit(ULONG uCtl, void *pvBuffer)
{
    /* we just reuse the standard usb tooling for simplicity here */
    NTSTATUS Status = VBoxUsbToolIoInternalCtlSendSync(g_VBoxUsbGlobals.RtIdc.pDevice, uCtl, pvBuffer, NULL);
    Assert(Status == STATUS_SUCCESS);
    return Status;
}

static NTSTATUS vboxUsbRtIdcInit()
{
    UNICODE_STRING UniName;
    RtlInitUnicodeString(&UniName, USBMON_DEVICE_NAME_NT);
    NTSTATUS Status = IoGetDeviceObjectPointer(&UniName, FILE_ALL_ACCESS, &g_VBoxUsbGlobals.RtIdc.pFile, &g_VBoxUsbGlobals.RtIdc.pDevice);
    if (NT_SUCCESS(Status))
    {
        VBOXUSBIDC_VERSION Version;
        vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_GET_VERSION, &Version);
        if (NT_SUCCESS(Status))
        {
            if (Version.u32Major == VBOXUSBIDC_VERSION_MAJOR
                    && Version.u32Minor >= VBOXUSBIDC_VERSION_MINOR)
                return STATUS_SUCCESS;
            AssertFailed();
        }
        else
        {
            AssertFailed();
        }

        /* this will as well dereference the dev obj */
        ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile);
    }
    else
    {
        AssertFailed();
    }

    memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc));
    return Status;
}

static VOID vboxUsbRtIdcTerm()
{
    Assert(g_VBoxUsbGlobals.RtIdc.pFile);
    Assert(g_VBoxUsbGlobals.RtIdc.pDevice);
    ObDereferenceObject(g_VBoxUsbGlobals.RtIdc.pFile);
    memset(&g_VBoxUsbGlobals.RtIdc, 0, sizeof (g_VBoxUsbGlobals.RtIdc));
}

static NTSTATUS vboxUsbRtIdcReportDevStart(PDEVICE_OBJECT pPDO, HVBOXUSBIDCDEV *phDev)
{
    VBOXUSBIDC_PROXY_STARTUP Start;
    Start.u.pPDO = pPDO;

    *phDev = NULL;

    NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_STARTUP, &Start);
    Assert(Status == STATUS_SUCCESS);
    if (!NT_SUCCESS(Status))
        return Status;

    *phDev = Start.u.hDev;
    return STATUS_SUCCESS;
}

static NTSTATUS vboxUsbRtIdcReportDevStop(HVBOXUSBIDCDEV hDev)
{
    VBOXUSBIDC_PROXY_TEARDOWN Stop;
    Stop.hDev = hDev;

    NTSTATUS Status = vboxUsbRtIdcSubmit(VBOXUSBIDC_INTERNAL_IOCTL_PROXY_TEARDOWN, &Stop);
    Assert(Status == STATUS_SUCCESS);
    return Status;
}

DECLHIDDEN(NTSTATUS) vboxUsbRtGlobalsInit()
{
    return vboxUsbRtIdcInit();
}

DECLHIDDEN(VOID) vboxUsbRtGlobalsTerm()
{
    vboxUsbRtIdcTerm();
}

DECLHIDDEN(NTSTATUS) vboxUsbRtInit(PVBOXUSBDEV_EXT pDevExt)
{
    RtlZeroMemory(&pDevExt->Rt, sizeof (pDevExt->Rt));
    NTSTATUS Status = IoRegisterDeviceInterface(pDevExt->pPDO, &GUID_CLASS_VBOXUSB,
                                NULL, /* IN PUNICODE_STRING ReferenceString OPTIONAL */
                                &pDevExt->Rt.IfName);
    Assert(Status == STATUS_SUCCESS);
    if (NT_SUCCESS(Status))
    {
        Status = vboxUsbRtIdcReportDevStart(pDevExt->pPDO, &pDevExt->Rt.hMonDev);
        Assert(Status == STATUS_SUCCESS);
        if (NT_SUCCESS(Status))
        {
            Assert(pDevExt->Rt.hMonDev);
            return STATUS_SUCCESS;
        }

        NTSTATUS tmpStatus = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE);
        Assert(tmpStatus == STATUS_SUCCESS);
        if (NT_SUCCESS(tmpStatus))
        {
            RtlFreeUnicodeString(&pDevExt->Rt.IfName);
        }
    }
    return Status;
}

/**
 * Free cached USB device/configuration descriptors
 *
 * @param   pDevExt             USB DevExt pointer
 */
static void vboxUsbRtFreeCachedDescriptors(PVBOXUSBDEV_EXT pDevExt)
{
    if (pDevExt->Rt.devdescr)
    {
        vboxUsbMemFree(pDevExt->Rt.devdescr);
        pDevExt->Rt.devdescr = NULL;
    }
    for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i)
    {
        if (pDevExt->Rt.cfgdescr[i])
        {
            vboxUsbMemFree(pDevExt->Rt.cfgdescr[i]);
            pDevExt->Rt.cfgdescr[i] = NULL;
        }
    }
}

/**
 * Free per-device interface info
 *
 * @param   pDevExt             USB DevExt pointer
 * @param   fAbortPipes         If true, also abort any open pipes
 */
static void vboxUsbRtFreeInterfaces(PVBOXUSBDEV_EXT pDevExt, BOOLEAN fAbortPipes)
{
    unsigned i;
    unsigned j;

    /*
     * Free old interface info
     */
    if (pDevExt->Rt.pVBIfaceInfo)
    {
        for (i=0;i<pDevExt->Rt.uNumInterfaces;i++)
        {
            if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo)
            {
                if (fAbortPipes)
                {
                    for(j=0; j<pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++)
                    {
                        Log(("Aborting Pipe %d handle %x address %x\n", j,
                                 pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle,
                                 pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress));
                        VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle, FALSE);
                    }
                }
                vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo);
            }
            pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = NULL;
            if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo)
                vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo);
            pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL;
        }
        vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo);
        pDevExt->Rt.pVBIfaceInfo = NULL;
    }
}

DECLHIDDEN(VOID) vboxUsbRtClear(PVBOXUSBDEV_EXT pDevExt)
{
    vboxUsbRtFreeCachedDescriptors(pDevExt);
    vboxUsbRtFreeInterfaces(pDevExt, FALSE);
}

DECLHIDDEN(NTSTATUS) vboxUsbRtRm(PVBOXUSBDEV_EXT pDevExt)
{
    if (!pDevExt->Rt.IfName.Buffer)
        return STATUS_SUCCESS;

    NTSTATUS Status = vboxUsbRtIdcReportDevStop(pDevExt->Rt.hMonDev);
    Assert(Status == STATUS_SUCCESS);
    Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, FALSE);
    Assert(Status == STATUS_SUCCESS);
    if (NT_SUCCESS(Status))
    {
        RtlFreeUnicodeString(&pDevExt->Rt.IfName);
        pDevExt->Rt.IfName.Buffer = NULL;
    }
    return Status;
}

DECLHIDDEN(NTSTATUS) vboxUsbRtStart(PVBOXUSBDEV_EXT pDevExt)
{
    NTSTATUS Status = IoSetDeviceInterfaceState(&pDevExt->Rt.IfName, TRUE);
    Assert(Status == STATUS_SUCCESS);
    return Status;
}

static NTSTATUS vboxUsbRtCacheDescriptors(PVBOXUSBDEV_EXT pDevExt)
{
    NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES;
//    uint32_t uTotalLength;
//    unsigned                        i;

    /* Read device descriptor */
    Assert(!pDevExt->Rt.devdescr);
    pDevExt->Rt.devdescr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_DEVICE_DESCRIPTOR));
    if (pDevExt->Rt.devdescr)
    {
        memset(pDevExt->Rt.devdescr, 0, sizeof (USB_DEVICE_DESCRIPTOR));
        Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.devdescr, sizeof (USB_DEVICE_DESCRIPTOR), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT);
        if (NT_SUCCESS(Status))
        {
            Assert(pDevExt->Rt.devdescr->bNumConfigurations > 0);
            PUSB_CONFIGURATION_DESCRIPTOR pDr = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(sizeof (USB_CONFIGURATION_DESCRIPTOR));
            Assert(pDr);
            if (pDr)
            {
                UCHAR i = 0;
                for (; i < pDevExt->Rt.devdescr->bNumConfigurations; ++i)
                {
                    Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof (USB_CONFIGURATION_DESCRIPTOR), USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT);
                    if (!NT_SUCCESS(Status))
                    {
                        break;
                    }

                    USHORT uTotalLength = pDr->wTotalLength;
                    pDevExt->Rt.cfgdescr[i] = (PUSB_CONFIGURATION_DESCRIPTOR)vboxUsbMemAlloc(uTotalLength);
                    if (!pDevExt->Rt.cfgdescr[i])
                    {
                        Status = STATUS_INSUFFICIENT_RESOURCES;
                        break;
                    }

                    Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDevExt->Rt.cfgdescr[i], uTotalLength, USB_CONFIGURATION_DESCRIPTOR_TYPE, i, 0, RT_INDEFINITE_WAIT);
                    if (!NT_SUCCESS(Status))
                    {
                        break;
                    }
                }

                vboxUsbMemFree(pDr);

                if (NT_SUCCESS(Status))
                    return Status;

                /* recources will be freed in vboxUsbRtFreeCachedDescriptors below */
            }
        }

        vboxUsbRtFreeCachedDescriptors(pDevExt);
    }

    /* shoud be only on fail here */
    Assert(!NT_SUCCESS(Status));
    return Status;
}

static NTSTATUS vboxUsbRtDispatchClaimDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    PUSBSUP_CLAIMDEV pDev  = (PUSBSUP_CLAIMDEV)pIrp->AssociatedIrp.SystemBuffer;
    ULONG cbOut = 0;
    NTSTATUS Status = STATUS_SUCCESS;

    do
    {
        if (!pFObj)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (  !pDev
            || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pDev)
            || pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pDev))
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (!vboxUsbRtCtxSetOwner(pDevExt, pFObj))
        {
            AssertFailed();
            pDev->fClaimed = false;
            cbOut = sizeof (*pDev);
            break;
        }

        vboxUsbRtFreeCachedDescriptors(pDevExt);
        Status = vboxUsbRtCacheDescriptors(pDevExt);
        if (NT_SUCCESS(Status))
        {
            pDev->fClaimed = true;
            cbOut = sizeof (*pDev);
        }
    } while (0);

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, cbOut);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtDispatchReleaseDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    NTSTATUS Status= STATUS_SUCCESS;

    if (vboxUsbRtCtxIsOwner(pDevExt, pFObj))
    {
        vboxUsbRtFreeCachedDescriptors(pDevExt);
        bool bRc = vboxUsbRtCtxReleaseOwner(pDevExt, pFObj);
        Assert(bRc);
    }
    else
    {
        AssertFailed();
        Status = STATUS_ACCESS_DENIED;
    }

    VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return STATUS_SUCCESS;
}

static NTSTATUS vboxUsbRtGetDeviceDescription(PVBOXUSBDEV_EXT pDevExt)
{
    NTSTATUS Status = STATUS_INSUFFICIENT_RESOURCES;
    PUSB_DEVICE_DESCRIPTOR pDr = (PUSB_DEVICE_DESCRIPTOR)vboxUsbMemAllocZ(sizeof (USB_DEVICE_DESCRIPTOR));
    if (pDr)
    {
        Status = VBoxUsbToolGetDescriptor(pDevExt->pLowerDO, pDr, sizeof(*pDr), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, RT_INDEFINITE_WAIT);
        if (NT_SUCCESS(Status))
        {
            pDevExt->Rt.idVendor    = pDr->idVendor;
            pDevExt->Rt.idProduct   = pDr->idProduct;
            pDevExt->Rt.bcdDevice   = pDr->bcdDevice;
            pDevExt->Rt.szSerial[0] = 0;

            if (pDr->iSerialNumber
#ifdef DEBUG
                    || pDr->iProduct || pDr->iManufacturer
#endif
               )
            {
                int langId;
                Status = VBoxUsbToolGetLangID(pDevExt->pLowerDO, &langId, RT_INDEFINITE_WAIT);
                if (NT_SUCCESS(Status))
                {
                    Status = VBoxUsbToolGetStringDescriptorA(pDevExt->pLowerDO, pDevExt->Rt.szSerial, sizeof (pDevExt->Rt.szSerial), pDr->iSerialNumber, langId, RT_INDEFINITE_WAIT);
                }
                else
                {
                    Status = STATUS_SUCCESS;
                }
            }
        }
        vboxUsbMemFree(pDr);
    }

    return Status;
}

static NTSTATUS vboxUsbRtDispatchGetDevice(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PUSBSUP_GETDEV pDev  = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status = STATUS_SUCCESS;
    ULONG cbOut = 0;

    /* don't check for owner since this request is allowed for non-owners as well */

    if (pDev && pSl->Parameters.DeviceIoControl.InputBufferLength == sizeof (*pDev)
             && pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pDev))
    {
        Status = VBoxUsbToolGetDeviceSpeed(pDevExt->pLowerDO, &pDevExt->Rt.fIsHighSpeed);
        if (NT_SUCCESS(Status))
        {
            pDev->hDevice = pDevExt->Rt.hMonDev;
            pDev->fAttached = true;
            pDev->fHiSpeed = pDevExt->Rt.fIsHighSpeed;
            cbOut = sizeof (*pDev);
        }
    }
    else
    {
        Status = STATUS_INVALID_PARAMETER;
    }

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, cbOut);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtDispatchUsbReset(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    PUSBSUP_GETDEV pDev  = (PUSBSUP_GETDEV)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status = STATUS_SUCCESS;

    do
    {
        if (!pFObj)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
        {
            AssertFailed();
            Status = STATUS_ACCESS_DENIED;
            break;
        }

        if (pIrp->AssociatedIrp.SystemBuffer
                || pSl->Parameters.DeviceIoControl.InputBufferLength
                || pSl->Parameters.DeviceIoControl.OutputBufferLength)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        Status = VBoxUsbToolIoInternalCtlSendSync(pDevExt->pLowerDO, IOCTL_INTERNAL_USB_RESET_PORT, NULL, NULL);
        Assert(NT_SUCCESS(Status));
    } while (0);

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static PUSB_CONFIGURATION_DESCRIPTOR vboxUsbRtFindConfigDesc(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration)
{
    PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = NULL;

    for (ULONG i = 0; i < VBOXUSBRT_MAX_CFGS; ++i)
    {
        if (pDevExt->Rt.cfgdescr[i])
        {
            if (pDevExt->Rt.cfgdescr[i]->bConfigurationValue == uConfiguration)
            {
                pCfgDr = pDevExt->Rt.cfgdescr[i];
                break;
            }
        }
    }

    return pCfgDr;
}

static NTSTATUS vboxUsbRtSetConfig(PVBOXUSBDEV_EXT pDevExt, uint8_t uConfiguration)
{
    PURB pUrb = NULL;
    NTSTATUS Status = STATUS_SUCCESS;
    uint32_t i;

    if (!uConfiguration)
    {
        pUrb = VBoxUsbToolUrbAllocZ(URB_FUNCTION_SELECT_CONFIGURATION, sizeof (struct _URB_SELECT_CONFIGURATION));
        if(!pUrb)
        {
            AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n"));
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        vboxUsbRtFreeInterfaces(pDevExt, TRUE);

        pUrb->UrbSelectConfiguration.ConfigurationDescriptor = NULL;

        Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT);
        if(NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status))
        {
            pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle;
            pDevExt->Rt.uConfigValue = uConfiguration;
        }
        else
        {
            AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
        }

        VBoxUsbToolUrbFree(pUrb);

        return Status;
    }

    PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, uConfiguration);
    if (!pCfgDr)
    {
        AssertMsgFailed((__FUNCTION__": VBoxUSBFindConfigDesc did not find cfg (%d)\n", uConfiguration));
        return STATUS_INVALID_PARAMETER;
    }

    PUSBD_INTERFACE_LIST_ENTRY pIfLe = (PUSBD_INTERFACE_LIST_ENTRY)vboxUsbMemAllocZ((pCfgDr->bNumInterfaces + 1) * sizeof(USBD_INTERFACE_LIST_ENTRY));
    if (!pIfLe)
    {
        AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ for pIfLe failed\n"));
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    for (i = 0; i < pCfgDr->bNumInterfaces; i++)
    {
        pIfLe[i].InterfaceDescriptor = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, i, 0, -1, -1, -1);
        if (!pIfLe[i].InterfaceDescriptor)
        {
            AssertMsgFailed((__FUNCTION__": interface %d not found\n", i));
            Status = STATUS_INVALID_PARAMETER;
            break;
        }
    }
    pIfLe[pCfgDr->bNumInterfaces].InterfaceDescriptor = NULL;

    if (NT_SUCCESS(Status))
    {
        pUrb = USBD_CreateConfigurationRequestEx(pCfgDr, pIfLe);
        if (pUrb)
        {
            Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT);
            if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status))
            {
                vboxUsbRtFreeInterfaces(pDevExt, FALSE);

                pDevExt->Rt.hConfiguration = pUrb->UrbSelectConfiguration.ConfigurationHandle;
                pDevExt->Rt.uConfigValue = uConfiguration;
                pDevExt->Rt.uNumInterfaces = pCfgDr->bNumInterfaces;

                pDevExt->Rt.pVBIfaceInfo = (VBOXUSB_IFACE_INFO*)vboxUsbMemAllocZ(pDevExt->Rt.uNumInterfaces * sizeof (VBOXUSB_IFACE_INFO));
                if (pDevExt->Rt.pVBIfaceInfo)
                {
                    Assert(NT_SUCCESS(Status));
                    for (i = 0; i < pDevExt->Rt.uNumInterfaces; i++)
                    {
                        size_t uTotalIfaceInfoLength = GET_USBD_INTERFACE_SIZE(pIfLe[i].Interface->NumberOfPipes);
                        pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength);
                        if (!pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo)
                        {
                            AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n"));
                            Status = STATUS_INSUFFICIENT_RESOURCES;
                            break;
                        }

                        if (pIfLe[i].Interface->NumberOfPipes > 0)
                        {
                            pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = (VBOXUSB_PIPE_INFO *)vboxUsbMemAlloc(pIfLe[i].Interface->NumberOfPipes * sizeof(VBOXUSB_PIPE_INFO));
                            if (!pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo)
                            {
                                AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n"));
                                Status = STATUS_NO_MEMORY;
                                break;
                            }
                        }
                        else
                        {
                            pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo = NULL;
                        }

                        RtlCopyMemory(pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo, pIfLe[i].Interface, uTotalIfaceInfoLength);

                        for (ULONG j = 0; j < pIfLe[i].Interface->NumberOfPipes; j++)
                        {
                            pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress = pIfLe[i].Interface->Pipes[j].EndpointAddress;
                            pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].NextScheduledFrame = 0;
                        }
                    }

//                    if (NT_SUCCESS(Status))
//                    {
//
//                    }
                }
                else
                {
                    AssertMsgFailed((__FUNCTION__": vboxUsbMemAllocZ failed\n"));
                    Status = STATUS_NO_MEMORY;
                }
            }
            else
            {
                AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x), usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
            }
            ExFreePool(pUrb);
        }
        else
        {
            AssertMsgFailed((__FUNCTION__": USBD_CreateConfigurationRequestEx failed\n"));
            Status = STATUS_INSUFFICIENT_RESOURCES;
        }
    }

    vboxUsbMemFree(pIfLe);

    return Status;
}

static NTSTATUS vboxUsbRtDispatchUsbSetConfig(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    PUSBSUP_SET_CONFIG pCfg  = (PUSBSUP_SET_CONFIG)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status = STATUS_SUCCESS;

    do
    {
        if (!pFObj)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
        {
            AssertFailed();
            Status = STATUS_ACCESS_DENIED;
            break;
        }

        if (      !pCfg
                || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCfg)
                || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
        {
            AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        Status = vboxUsbRtSetConfig(pDevExt, pCfg->bConfigurationValue);
    } while (0);

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtSetInterface(PVBOXUSBDEV_EXT pDevExt, uint32_t InterfaceNumber, int AlternateSetting)
{
    if (!pDevExt->Rt.uConfigValue)
    {
        AssertMsgFailed((__FUNCTION__": Can't select an interface without an active configuration\n"));
        return STATUS_INVALID_PARAMETER;
    }

    if (InterfaceNumber >= pDevExt->Rt.uNumInterfaces)
    {
        AssertMsgFailed((__FUNCTION__": InterfaceNumber %d too high!!\n", InterfaceNumber));
        return STATUS_INVALID_PARAMETER;
    }

    PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = vboxUsbRtFindConfigDesc(pDevExt, pDevExt->Rt.uConfigValue);
    if (!pCfgDr)
    {
        AssertMsgFailed((__FUNCTION__": configuration %d not found!!\n", pDevExt->Rt.uConfigValue));
        return STATUS_INVALID_PARAMETER;
    }

    PUSB_INTERFACE_DESCRIPTOR pIfDr = USBD_ParseConfigurationDescriptorEx(pCfgDr, pCfgDr, InterfaceNumber, AlternateSetting, -1, -1, -1);
    if (!pIfDr)
    {
        AssertMsgFailed((__FUNCTION__": invalid interface %d or alternate setting %d\n", InterfaceNumber, AlternateSetting));
        return STATUS_UNSUCCESSFUL;
    }

    USHORT uUrbSize = GET_SELECT_INTERFACE_REQUEST_SIZE(pIfDr->bNumEndpoints);
    ULONG uTotalIfaceInfoLength = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints);
    NTSTATUS Status = STATUS_SUCCESS;
    PURB pUrb = VBoxUsbToolUrbAllocZ(0, uUrbSize);
    if (!pUrb)
    {
        AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbAlloc failed\n"));
        return STATUS_NO_MEMORY;
    }

    /*
     * Free old interface and pipe info, allocate new again
     */
    if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo)
    {
        /* Clear pipes associated with the interface, else Windows may hang. */
        for(ULONG i = 0; i < pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->NumberOfPipes; i++)
        {
            VBoxUsbToolPipeClear(pDevExt->pLowerDO, pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo->Pipes[i].PipeHandle, FALSE);
        }
        vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo);
    }

    if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo)
    {
        vboxUsbMemFree(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo);
    }

    pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo = (PUSBD_INTERFACE_INFORMATION)vboxUsbMemAlloc(uTotalIfaceInfoLength);
    if (pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo)
    {
        if (pIfDr->bNumEndpoints > 0)
        {
            pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = (VBOXUSB_PIPE_INFO*)vboxUsbMemAlloc(pIfDr->bNumEndpoints * sizeof(VBOXUSB_PIPE_INFO));
            if (!pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo)
            {
                AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n"));
                Status = STATUS_NO_MEMORY;
            }
        }
        else
        {
            pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo = NULL;
        }

        if (NT_SUCCESS(Status))
        {
            UsbBuildSelectInterfaceRequest(pUrb, uUrbSize, pDevExt->Rt.hConfiguration, InterfaceNumber, AlternateSetting);
            pUrb->UrbSelectInterface.Interface.Length = GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints);

            Status = VBoxUsbToolUrbPost(pDevExt->pLowerDO, pUrb, RT_INDEFINITE_WAIT);
            if (NT_SUCCESS(Status) && USBD_SUCCESS(pUrb->UrbHeader.Status))
            {
                USBD_INTERFACE_INFORMATION *pIfInfo = &pUrb->UrbSelectInterface.Interface;
                memcpy(pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pInterfaceInfo, pIfInfo, GET_USBD_INTERFACE_SIZE(pIfDr->bNumEndpoints));

                Assert(pIfInfo->NumberOfPipes == pIfDr->bNumEndpoints);
                for(ULONG i = 0; i < pIfInfo->NumberOfPipes; i++)
                {
                    pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].EndpointAddress = pIfInfo->Pipes[i].EndpointAddress;
                    pDevExt->Rt.pVBIfaceInfo[InterfaceNumber].pPipeInfo[i].NextScheduledFrame = 0;
                }
            }
            else
            {
                AssertMsgFailed((__FUNCTION__": VBoxUsbToolUrbPost failed Status (0x%x) usb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
            }
        }

    }
    else
    {
        AssertMsgFailed(("VBoxUSBSetInterface: ExAllocatePool failed!\n"));
        Status = STATUS_NO_MEMORY;
    }

    VBoxUsbToolUrbFree(pUrb);

    return Status;
}

static NTSTATUS vboxUsbRtDispatchUsbSelectInterface(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    PUSBSUP_SELECT_INTERFACE pIf = (PUSBSUP_SELECT_INTERFACE)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status;

    do
    {
        if (!pFObj)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
        {
            AssertFailed();
            Status = STATUS_ACCESS_DENIED;
            break;
        }

        if (  !pIf
            || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pIf)
            || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
        {
            AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        Status = vboxUsbRtSetInterface(pDevExt, pIf->bInterfaceNumber, pIf->bAlternateSetting);
    } while (0);

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static HANDLE vboxUsbRtGetPipeHandle(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress)
{
    for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++)
    {
        for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++)
        {
            /* Note that bit 7 determines pipe direction, but is still significant
             * because endpoints may be numbered like 0x01, 0x81, 0x02, 0x82 etc.
             */
            if (pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].EndpointAddress == EndPointAddress)
                return pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->Pipes[j].PipeHandle;
        }
    }
    return 0;
}

static VBOXUSB_PIPE_INFO* vboxUsbRtGetPipeInfo(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress)
{
    for (ULONG i = 0; i < pDevExt->Rt.uNumInterfaces; i++)
    {
        for (ULONG j = 0; j < pDevExt->Rt.pVBIfaceInfo[i].pInterfaceInfo->NumberOfPipes; j++)
        {
            if (pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j].EndpointAddress == EndPointAddress)
                return &pDevExt->Rt.pVBIfaceInfo[i].pPipeInfo[j];
        }
    }
    return NULL;
}

static NTSTATUS vboxUsbRtClearEndpoint(PVBOXUSBDEV_EXT pDevExt, uint32_t EndPointAddress, bool fReset)
{
    NTSTATUS Status = VBoxUsbToolPipeClear(pDevExt->pLowerDO, vboxUsbRtGetPipeHandle(pDevExt, EndPointAddress), fReset);
    if (!NT_SUCCESS(Status))
    {
        AssertMsgFailed((__FUNCTION__": VBoxUsbToolPipeClear failed Status (0x%x)\n", Status));
    }

    return Status;
}

static NTSTATUS vboxUsbRtDispatchUsbClearEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status;

    do
    {
        if (!pFObj)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
        {
            AssertFailed();
            Status = STATUS_ACCESS_DENIED;
            break;
        }

        if (   !pCe
             || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe)
             || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
        {
            AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, TRUE);
    } while (0);

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtDispatchUsbAbortEndpoint(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    PUSBSUP_CLEAR_ENDPOINT pCe = (PUSBSUP_CLEAR_ENDPOINT)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status;

    do
    {
        if (!pFObj)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
        {
            AssertFailed();
            Status = STATUS_ACCESS_DENIED;
            break;
        }

        if (  !pCe
            || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pCe)
            || pSl->Parameters.DeviceIoControl.OutputBufferLength != 0)
        {
            AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        Status = vboxUsbRtClearEndpoint(pDevExt, pCe->bEndpoint, FALSE);
    } while (0);

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtUrbSendCompletion(PDEVICE_OBJECT pDevObj, IRP *pIrp, void *pvContext)
{
    if (!pvContext)
    {
        AssertMsgFailed((__FUNCTION__":  context is NULL\n"));
        pIrp->IoStatus.Information = 0;
        return STATUS_CONTINUE_COMPLETION;
    }

    PVBOXUSB_URB_CONTEXT pContext = (PVBOXUSB_URB_CONTEXT)pvContext;

    if (pContext->ulMagic != VBOXUSB_MAGIC)
    {
        AssertMsgFailed((__FUNCTION__": Invalid context magic\n"));
        pIrp->IoStatus.Information = 0;
        return STATUS_CONTINUE_COMPLETION;
    }

    PURB pUrb = pContext->pUrb;
    PMDL pMdlBuf = pContext->pMdlBuf;
    PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pContext->pOut;
    PVBOXUSBDEV_EXT pDevExt = pContext->pDevExt;

    if (!pUrb || !pMdlBuf || !pUrbInfo | !pDevExt)
    {
        AssertMsgFailed((__FUNCTION__": Invalid args\n"));
        if (pDevExt)
            vboxUsbDdiStateRelease(pDevExt);
        pIrp->IoStatus.Information = 0;
        return STATUS_CONTINUE_COMPLETION;
    }

    NTSTATUS Status = pIrp->IoStatus.Status;
    if (Status == STATUS_SUCCESS)
    {
        switch(pUrb->UrbHeader.Status)
        {
            case USBD_STATUS_CRC:
                pUrbInfo->error = USBSUP_XFER_CRC;
                break;
            case USBD_STATUS_SUCCESS:
                pUrbInfo->error = USBSUP_XFER_OK;
                break;
            case USBD_STATUS_STALL_PID:
                pUrbInfo->error = USBSUP_XFER_STALL;
                break;
            case USBD_STATUS_INVALID_URB_FUNCTION:
            case USBD_STATUS_INVALID_PARAMETER:
                AssertMsgFailed((__FUNCTION__": sw error, urb Status (0x%x)\n", pUrb->UrbHeader.Status));
            case USBD_STATUS_DEV_NOT_RESPONDING:
            default:
                pUrbInfo->error = USBSUP_XFER_DNR;
            break;
        }

        switch(pContext->ulTransferType)
        {
            case USBSUP_TRANSFER_TYPE_CTRL:
            case USBSUP_TRANSFER_TYPE_MSG:
                pUrbInfo->len = pUrb->UrbControlTransfer.TransferBufferLength;
                if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_MSG)
                {
                    /* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special
                     * the first 8 bytes of the buffer is the setup packet so the real
                     * data length is therefore urb->len - 8
                     */
                    pUrbInfo->len += sizeof (pUrb->UrbControlTransfer.SetupPacket);
                }
                break;
            case USBSUP_TRANSFER_TYPE_ISOC:
                pUrbInfo->len = pUrb->UrbIsochronousTransfer.TransferBufferLength;
                break;
            case USBSUP_TRANSFER_TYPE_BULK:
            case USBSUP_TRANSFER_TYPE_INTR:
                if (pUrbInfo->dir == USBSUP_DIRECTION_IN && pUrbInfo->error == USBSUP_XFER_OK
                        && !(pUrbInfo->flags & USBSUP_FLAG_SHORT_OK)
                        && pUrbInfo->len > pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength
                        )
                {
                    /* If we don't use the USBD_SHORT_TRANSFER_OK flag, the returned buffer lengths are
                     * wrong for short transfers (always a multiple of max packet size?). So we just figure
                     * out if this was a data underrun on our own.
                     */
                    pUrbInfo->error = USBSUP_XFER_UNDERRUN;
                }
                pUrbInfo->len = pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength;
                break;
            default:
                break;
        }
    }
    else
    {
        pUrbInfo->len = 0;

        Log((__FUNCTION__": URB failed Status (0x%x) urb Status (0x%x)\n", Status, pUrb->UrbHeader.Status));
#ifdef DEBUG
        switch(pContext->ulTransferType)
        {
            case USBSUP_TRANSFER_TYPE_CTRL:
            case USBSUP_TRANSFER_TYPE_MSG:
                LogRel(("Ctrl/Msg length=%d\n", pUrb->UrbControlTransfer.TransferBufferLength));
                break;
            case USBSUP_TRANSFER_TYPE_ISOC:
                LogRel(("ISOC length=%d\n", pUrb->UrbIsochronousTransfer.TransferBufferLength));
                break;
            case USBSUP_TRANSFER_TYPE_BULK:
            case USBSUP_TRANSFER_TYPE_INTR:
                LogRel(("BULK/INTR length=%d\n", pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength));
                break;
        }
#endif
        switch(pUrb->UrbHeader.Status)
        {
            case USBD_STATUS_CRC:
                pUrbInfo->error = USBSUP_XFER_CRC;
                Status = STATUS_SUCCESS;
                break;
            case USBD_STATUS_STALL_PID:
                pUrbInfo->error = USBSUP_XFER_STALL;
                Status = STATUS_SUCCESS;
                break;
            case USBD_STATUS_DEV_NOT_RESPONDING:
            case USBD_STATUS_DEVICE_GONE:
                pUrbInfo->error = USBSUP_XFER_DNR;
                Status = STATUS_SUCCESS;
                break;
            case ((USBD_STATUS)0xC0010000L): // USBD_STATUS_CANCELED - too bad usbdi.h and usb.h aren't consistent!
                // TODO: What the heck are we really supposed to do here?
                pUrbInfo->error = USBSUP_XFER_STALL;
                Status = STATUS_SUCCESS;
                break;
            case USBD_STATUS_BAD_START_FRAME:   // This one really shouldn't happen
            case USBD_STATUS_ISOCH_REQUEST_FAILED:
                pUrbInfo->error = USBSUP_XFER_NAC;
                Status = STATUS_SUCCESS;
                break;
            default:
                AssertMsgFailed((__FUNCTION__": err Status (0x%x) (0x%x)\n", Status, pUrb->UrbHeader.Status));
                pUrbInfo->error = USBSUP_XFER_DNR;
                Status = STATUS_SUCCESS;
                break;
        }
    }
    // For isochronous transfers, always update the individual packets
    if (pContext->ulTransferType == USBSUP_TRANSFER_TYPE_ISOC)
    {
        Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets);
        for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i)
        {
            Assert(pUrbInfo->aIsoPkts[i].off == pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset);
            pUrbInfo->aIsoPkts[i].cb = (uint16_t)pUrb->UrbIsochronousTransfer.IsoPacket[i].Length;
            switch (pUrb->UrbIsochronousTransfer.IsoPacket[i].Status)
            {
                case USBD_STATUS_SUCCESS:
                    pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_OK;
                    break;
                case USBD_STATUS_NOT_ACCESSED:
                    pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_NAC;
                    break;
                default:
                    pUrbInfo->aIsoPkts[i].stat = USBSUP_XFER_STALL;
                    break;
            }
        }
    }

    MmUnlockPages(pMdlBuf);
    IoFreeMdl(pMdlBuf);

    vboxUsbMemFree(pContext);

    vboxUsbDdiStateRelease(pDevExt);

    Assert(pIrp->IoStatus.Status != STATUS_IO_TIMEOUT);
    pIrp->IoStatus.Information = sizeof(*pUrbInfo);
    pIrp->IoStatus.Status = Status;
    return STATUS_CONTINUE_COMPLETION;
}

static NTSTATUS vboxUsbRtUrbSend(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp, PUSBSUP_URB pUrbInfo)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PVBOXUSB_URB_CONTEXT pContext = NULL;
    PMDL pMdlBuf = NULL;
    ULONG cbUrb;

    Assert(pUrbInfo);
    if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_ISOC)
    {
        Assert(pUrbInfo->numIsoPkts <= 8);
        cbUrb = GET_ISO_URB_SIZE(pUrbInfo->numIsoPkts);
    }
    else
        cbUrb = sizeof (URB);

    do
    {
        pContext = (PVBOXUSB_URB_CONTEXT)vboxUsbMemAllocZ(cbUrb + sizeof (VBOXUSB_URB_CONTEXT));
        if (!pContext)
        {
            AssertMsgFailed((__FUNCTION__": vboxUsbMemAlloc failed\n"));
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        PURB pUrb = (PURB)(pContext + 1);
        HANDLE hPipe = NULL;
        if (pUrbInfo->ep)
        {
            hPipe = vboxUsbRtGetPipeHandle(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00));
            if (!hPipe)
            {
                AssertMsgFailed((__FUNCTION__": vboxUsbRtGetPipeHandle failed for endpoint (0x%x)\n", pUrbInfo->ep));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }
        }

        pMdlBuf = IoAllocateMdl(pUrbInfo->buf, (ULONG)pUrbInfo->len, FALSE, FALSE, NULL);
        if (!pMdlBuf)
        {
            AssertMsgFailed((__FUNCTION__": IoAllocateMdl failed for buffer (0x%p) length (%d)\n", pUrbInfo->buf, pUrbInfo->len));
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        __try
        {
            MmProbeAndLockPages(pMdlBuf, KernelMode, IoModifyAccess);
        }
        __except(EXCEPTION_EXECUTE_HANDLER)
        {
            Status = GetExceptionCode();
            IoFreeMdl(pMdlBuf);
            pMdlBuf = NULL;
            AssertMsgFailed((__FUNCTION__": Exception Code (0x%x)\n", Status));
            break;
        }

        /* For some reason, passing a MDL in the URB does not work reliably. Notably
         * the iPhone when used with iTunes fails.
         */
        PVOID pBuffer = MmGetSystemAddressForMdlSafe(pMdlBuf, NormalPagePriority);
        if (!pBuffer)
        {
            AssertMsgFailed((__FUNCTION__": MmGetSystemAddressForMdlSafe failed\n"));
            Status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        switch (pUrbInfo->type)
        {
            case USBSUP_TRANSFER_TYPE_CTRL:
            case USBSUP_TRANSFER_TYPE_MSG:
            {
                pUrb->UrbHeader.Function = URB_FUNCTION_CONTROL_TRANSFER;
                pUrb->UrbHeader.Length = sizeof (struct _URB_CONTROL_TRANSFER);
                pUrb->UrbControlTransfer.PipeHandle = hPipe;
                pUrb->UrbControlTransfer.TransferBufferLength = (ULONG)pUrbInfo->len;
                pUrb->UrbControlTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT);
                pUrb->UrbControlTransfer.UrbLink = 0;

                if (!hPipe)
                    pUrb->UrbControlTransfer.TransferFlags |= USBD_DEFAULT_PIPE_TRANSFER;

                if (pUrbInfo->type == USBSUP_TRANSFER_TYPE_MSG)
                {
                   /* QUSB_TRANSFER_TYPE_MSG is a control transfer, but it is special
                    * the first 8 bytes of the buffer is the setup packet so the real
                    * data length is therefore pUrb->len - 8
                    */
                    PVBOXUSB_SETUP pSetup = (PVBOXUSB_SETUP)pUrb->UrbControlTransfer.SetupPacket;
                    memcpy(pUrb->UrbControlTransfer.SetupPacket, pBuffer, min(sizeof (pUrb->UrbControlTransfer.SetupPacket), pUrbInfo->len));

                    if (pUrb->UrbControlTransfer.TransferBufferLength <= sizeof (pUrb->UrbControlTransfer.SetupPacket))
                        pUrb->UrbControlTransfer.TransferBufferLength = 0;
                    else
                        pUrb->UrbControlTransfer.TransferBufferLength -= sizeof (pUrb->UrbControlTransfer.SetupPacket);

                    pUrb->UrbControlTransfer.TransferBuffer = (uint8_t *)pBuffer + sizeof(pUrb->UrbControlTransfer.SetupPacket);
                    pUrb->UrbControlTransfer.TransferBufferMDL = 0;
                    pUrb->UrbControlTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK;
                }
                else
                {
                    pUrb->UrbControlTransfer.TransferBuffer = 0;
                    pUrb->UrbControlTransfer.TransferBufferMDL = pMdlBuf;
                }
                break;
            }
            case USBSUP_TRANSFER_TYPE_ISOC:
            {
                Assert(hPipe);
                VBOXUSB_PIPE_INFO *pPipeInfo = vboxUsbRtGetPipeInfo(pDevExt, pUrbInfo->ep | ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? 0x80 : 0x00));
                if (pPipeInfo == NULL)
                {
                    /* Can happen if the isoc request comes in too early or late. */
                    AssertMsgFailed((__FUNCTION__": pPipeInfo not found\n"));
                    Status = STATUS_INVALID_PARAMETER;
                    break;
                }

                pUrb->UrbHeader.Function = URB_FUNCTION_ISOCH_TRANSFER;
                pUrb->UrbHeader.Length = (USHORT)cbUrb;
                pUrb->UrbIsochronousTransfer.PipeHandle = hPipe;
                pUrb->UrbIsochronousTransfer.TransferBufferLength = (ULONG)pUrbInfo->len;
                pUrb->UrbIsochronousTransfer.TransferBufferMDL = 0;
                pUrb->UrbIsochronousTransfer.TransferBuffer = pBuffer;
                pUrb->UrbIsochronousTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT);
                pUrb->UrbIsochronousTransfer.TransferFlags |= USBD_SHORT_TRANSFER_OK;  // May be implied already
                pUrb->UrbIsochronousTransfer.NumberOfPackets = pUrbInfo->numIsoPkts;
                pUrb->UrbIsochronousTransfer.ErrorCount = 0;
                pUrb->UrbIsochronousTransfer.UrbLink = 0;

                Assert(pUrbInfo->numIsoPkts == pUrb->UrbIsochronousTransfer.NumberOfPackets);
                for (ULONG i = 0; i < pUrbInfo->numIsoPkts; ++i)
                {
                    pUrb->UrbIsochronousTransfer.IsoPacket[i].Offset = pUrbInfo->aIsoPkts[i].off;
                    pUrb->UrbIsochronousTransfer.IsoPacket[i].Length = pUrbInfo->aIsoPkts[i].cb;
                }

                /* We have to schedule the URBs ourselves. There is an ASAP flag but
                 * that can only be reliably used after pipe creation/reset, ie. it's
                 * almost completely useless.
                 */
                ULONG iFrame, iStartFrame;
                VBoxUsbToolCurrentFrame(pDevExt->pLowerDO, pIrp, &iFrame);
                iFrame += 2;
                iStartFrame = pPipeInfo->NextScheduledFrame;
                if ((iFrame < iStartFrame) || (iStartFrame > iFrame + 512))
                    iFrame = iStartFrame;
                pPipeInfo->NextScheduledFrame = iFrame + pUrbInfo->numIsoPkts;
                pUrb->UrbIsochronousTransfer.StartFrame = iFrame;
                break;
            }
            case USBSUP_TRANSFER_TYPE_BULK:
            case USBSUP_TRANSFER_TYPE_INTR:
            {
                Assert(pUrbInfo->dir != USBSUP_DIRECTION_SETUP);
                Assert(pUrbInfo->dir == USBSUP_DIRECTION_IN || pUrbInfo->type == USBSUP_TRANSFER_TYPE_BULK);
                Assert(hPipe);

                pUrb->UrbHeader.Function = URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER;
                pUrb->UrbHeader.Length = sizeof (struct _URB_BULK_OR_INTERRUPT_TRANSFER);
                pUrb->UrbBulkOrInterruptTransfer.PipeHandle = hPipe;
                pUrb->UrbBulkOrInterruptTransfer.TransferBufferLength = (ULONG)pUrbInfo->len;
                pUrb->UrbBulkOrInterruptTransfer.TransferBufferMDL = 0;
                pUrb->UrbBulkOrInterruptTransfer.TransferBuffer = pBuffer;
                pUrb->UrbBulkOrInterruptTransfer.TransferFlags = ((pUrbInfo->dir == USBSUP_DIRECTION_IN) ? USBD_TRANSFER_DIRECTION_IN : USBD_TRANSFER_DIRECTION_OUT);

                if (pUrb->UrbBulkOrInterruptTransfer.TransferFlags & USBD_TRANSFER_DIRECTION_IN)
                    pUrb->UrbBulkOrInterruptTransfer.TransferFlags |= (USBD_SHORT_TRANSFER_OK);

                pUrb->UrbBulkOrInterruptTransfer.UrbLink = 0;
                break;
            }
            default:
            {
                AssertFailed();
                Status = STATUS_INVALID_PARAMETER;
                break;
            }
        }

        if (!NT_SUCCESS(Status))
        {
            break;
        }

        pContext->pDevExt = pDevExt;
        pContext->pMdlBuf = pMdlBuf;
        pContext->pUrb = pUrb;
        pContext->pOut = pUrbInfo;
        pContext->ulTransferType = pUrbInfo->type;
        pContext->ulMagic = VBOXUSB_MAGIC;

        PIO_STACK_LOCATION pSl = IoGetNextIrpStackLocation(pIrp);
        pSl->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
        pSl->Parameters.DeviceIoControl.IoControlCode = IOCTL_INTERNAL_USB_SUBMIT_URB;
        pSl->Parameters.Others.Argument1 = pUrb;
        pSl->Parameters.Others.Argument2 = NULL;

        IoSetCompletionRoutine(pIrp, vboxUsbRtUrbSendCompletion, pContext, TRUE, TRUE, TRUE);
        IoMarkIrpPending(pIrp);
        Status = IoCallDriver(pDevExt->pLowerDO, pIrp);
        AssertMsg(NT_SUCCESS(Status), (__FUNCTION__": IoCallDriver failed Status (0x%x)\n", Status));
        return STATUS_PENDING;
    } while (0);

    Assert(!NT_SUCCESS(Status));

    if (pMdlBuf)
    {
        MmUnlockPages(pMdlBuf);
        IoFreeMdl(pMdlBuf);
    }

    if (pContext)
        vboxUsbMemFree(pContext);

    VBoxDrvToolIoComplete(pIrp, Status, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtDispatchSendUrb(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    PUSBSUP_URB pUrbInfo = (PUSBSUP_URB)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status;

    do
    {
        if (!pFObj)
        {
            AssertFailed();
            Status = STATUS_INVALID_PARAMETER;
            break;
        }

        if (!vboxUsbRtCtxIsOwner(pDevExt, pFObj))
        {
            AssertFailed();
            Status = STATUS_ACCESS_DENIED;
            break;
        }

        if (  !pUrbInfo
            || pSl->Parameters.DeviceIoControl.InputBufferLength != sizeof (*pUrbInfo)
            || pSl->Parameters.DeviceIoControl.OutputBufferLength != sizeof (*pUrbInfo))
        {
            AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
            Status = STATUS_INVALID_PARAMETER;
            break;
        }
        return vboxUsbRtUrbSend(pDevExt, pIrp, pUrbInfo);
    } while (0);

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtDispatchIsOperational(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    VBoxDrvToolIoComplete(pIrp, STATUS_SUCCESS, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return STATUS_SUCCESS;
}

static NTSTATUS vboxUsbRtDispatchGetVersion(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PUSBSUP_VERSION pVer= (PUSBSUP_VERSION)pIrp->AssociatedIrp.SystemBuffer;
    NTSTATUS Status = STATUS_SUCCESS;

    if (pVer && pSl->Parameters.DeviceIoControl.InputBufferLength == 0
             && pSl->Parameters.DeviceIoControl.OutputBufferLength == sizeof (*pVer))
    {
        pVer->u32Major = USBDRV_MAJOR_VERSION;
        pVer->u32Minor = USBDRV_MINOR_VERSION;
    }
    else
    {
        AssertMsgFailed((__FUNCTION__": STATUS_INVALID_PARAMETER\n"));
        Status = STATUS_INVALID_PARAMETER;
    }

    Assert(Status != STATUS_PENDING);
    VBoxDrvToolIoComplete(pIrp, Status, sizeof (*pVer));
    vboxUsbDdiStateRelease(pDevExt);
    return Status;
}

static NTSTATUS vboxUsbRtDispatchDefault(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    VBoxDrvToolIoComplete(pIrp, STATUS_INVALID_DEVICE_REQUEST, 0);
    vboxUsbDdiStateRelease(pDevExt);
    return STATUS_INVALID_DEVICE_REQUEST;
}

DECLHIDDEN(NTSTATUS) vboxUsbRtCreate(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    if (!pFObj)
    {
        AssertFailed();
        return STATUS_INVALID_PARAMETER;
    }

    return STATUS_SUCCESS;
}

DECLHIDDEN(NTSTATUS) vboxUsbRtClose(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFObj = pSl->FileObject;
    Assert(pFObj);

    vboxUsbRtCtxReleaseOwner(pDevExt, pFObj);

    return STATUS_SUCCESS;
}

DECLHIDDEN(NTSTATUS) vboxUsbRtDispatch(PVBOXUSBDEV_EXT pDevExt, PIRP pIrp)
{
    PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
    switch (pSl->Parameters.DeviceIoControl.IoControlCode)
    {
        case SUPUSB_IOCTL_USB_CLAIM_DEVICE:
        {
            return vboxUsbRtDispatchClaimDevice(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_USB_RELEASE_DEVICE:
        {
            return vboxUsbRtDispatchReleaseDevice(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_GET_DEVICE:
        {
            return vboxUsbRtDispatchGetDevice(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_USB_RESET:
        {
            return vboxUsbRtDispatchUsbReset(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_USB_SET_CONFIG:
        {
            return vboxUsbRtDispatchUsbSetConfig(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_USB_SELECT_INTERFACE:
        {
            return vboxUsbRtDispatchUsbSelectInterface(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_USB_CLEAR_ENDPOINT:
        {
            return vboxUsbRtDispatchUsbClearEndpoint(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_USB_ABORT_ENDPOINT:
        {
            return vboxUsbRtDispatchUsbAbortEndpoint(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_SEND_URB:
        {
            return vboxUsbRtDispatchSendUrb(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_IS_OPERATIONAL:
        {
            return vboxUsbRtDispatchIsOperational(pDevExt, pIrp);
        }
        case SUPUSB_IOCTL_GET_VERSION:
        {
            return vboxUsbRtDispatchGetVersion(pDevExt, pIrp);
        }
        default:
        {
            return vboxUsbRtDispatchDefault(pDevExt, pIrp);
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<parent>
		<groupId>org.kaleidofoundry</groupId>
		<artifactId>kaleido-parent</artifactId>
		<version>0.10.1</version>
	</parent>

	<artifactId>kaleido-distrib</artifactId>
	<name>KaleidoFoundry assembly and distribution bundle</name>
	<description>Distribution assembly bundles</description>
	<packaging>jar</packaging>

	<build>
		<finalName>kaleidofoundry-${project.version}-Rev${buildNumber}-bundle.zip</finalName>
		<plugins>
			<!-- assemble artifact -->
			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<finalName>kaleidofoundry-${project.version}</finalName>
					<descriptors>
						<descriptor>src/assemble/distribution.xml</descriptor>
					</descriptors>
<!-- 					<siteDirectory>../target/site</siteDirectory> -->
				</configuration>
				<executions>
					<execution>
						<id>bundle</id>
						<phase>deploy</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>

	</build>

</project>

redpajama_set_name: RedPajamaGithub


text:
Ghost is a free, open, simple blogging platform. Visit the project's website at <http://ghost.org>, or read the docs on <http://support.ghost.org>.

## Deploying on Heroku

Ghost Version 0.11.0

To get your own Ghost blog running on Heroku, click the button below:

[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy?template=https://github.com/nakamuraagatha/ghost-on-heroku)


text:
package alluxio.client.metrics;

import alluxio.AbstractMasterClient;
import alluxio.Constants;
import alluxio.exception.status.UnavailableException;
import alluxio.grpc.ClientMetrics;
import alluxio.grpc.MetricsHeartbeatPOptions;
import alluxio.grpc.MetricsHeartbeatPRequest;
import alluxio.grpc.MetricsMasterClientServiceGrpc;
import alluxio.grpc.ServiceType;
import alluxio.master.MasterClientContext;
import alluxio.retry.RetryUtils;

import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.util.List;

/**
 * A client to use for interacting with a metrics master.
 */
@ThreadSafe
public class MetricsMasterClient extends AbstractMasterClient {
  private MetricsMasterClientServiceGrpc.MetricsMasterClientServiceBlockingStub mClient = null;

  /**
   * Creates a new metrics master client.
   *
   * @param conf master client configuration
   */
  public MetricsMasterClient(MasterClientContext conf) {
    super(conf, null, RetryUtils::defaultMetricsClientRetry);
  }

  @Override
  protected ServiceType getRemoteServiceType() {
    return ServiceType.METRICS_MASTER_CLIENT_SERVICE;
  }

  @Override
  protected String getServiceName() {
    return Constants.METRICS_MASTER_CLIENT_SERVICE_NAME;
  }

  @Override
  protected long getServiceVersion() {
    return Constants.METRICS_MASTER_CLIENT_SERVICE_VERSION;
  }

  @Override
  protected void afterConnect() {
    mClient = MetricsMasterClientServiceGrpc.newBlockingStub(mChannel);
  }

  /**
   * The method the worker should periodically execute to heartbeat back to the master.
   *
   * @param metrics a list of client metrics
   */
  public void heartbeat(final List<ClientMetrics> metrics) throws IOException {
    connect();
    try {
      MetricsHeartbeatPRequest.Builder request = MetricsHeartbeatPRequest.newBuilder();
      request.setOptions(MetricsHeartbeatPOptions.newBuilder()
          .addAllClientMetrics(metrics).build());
      mClient.metricsHeartbeat(request.build());
    } catch (io.grpc.StatusRuntimeException e) {
      disconnect();
      throw new UnavailableException(e);
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using BookStoreAdmin.Models;
using BookStoreAdmin.ViewModels;

namespace BookStoreAdmin.BAL
{
    public class Category
    {
        public static List<BookStoreAdmin.ViewModels.Category> GetCategories()
        {
            using(BookStoreAdmin.Models.BookStoreAdminEntities1 context = new BookStoreAdminEntities1())
            {
                return context.categories.Select(category => new BookStoreAdmin.ViewModels.Category() { id = category.id, description = category.description, name = category.name }).ToList();
            }
        }

        public static BookStoreAdmin.ViewModels.Category AddCategory(BookStoreAdmin.ViewModels.Category category)
        {
            BookStoreAdmin.Models.category objCategory = new BookStoreAdmin.Models.category();

            using (BookStoreAdmin.Models.BookStoreAdminEntities1 context = new BookStoreAdminEntities1())
            {
                objCategory.name = category.description;
                objCategory.description = category.description;
                objCategory = context.categories.Add(objCategory);
                context.SaveChanges();
                category.id = objCategory.id;
            }

            return category;
        }

        public static BookStoreAdmin.ViewModels.Category EditCategory(BookStoreAdmin.ViewModels.Category category)
        {
            BookStoreAdmin.Models.category objCategory = new Models.category();

            using (BookStoreAdmin.Models.BookStoreAdminEntities1 context = new BookStoreAdminEntities1())
            {
                objCategory = context.categories.Find(category.id);
                objCategory.name = category.name;
                objCategory.description = category.description;
                context.SaveChanges();
            }
            return category;
        }
    }
}


text:
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/clockchips.h>
#include <linux/clocksource.h>
#include <linux/of_address.h>
#include <linux/of_irq.h>
#include <linux/of_platform.h>
#include <linux/clk.h>
#include <linux/jiffies.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/sched_clock.h>
#include <asm/mach/time.h>

/*
 * The MTU device hosts four different counters, with 4 set of
 * registers. These are register names.
 */

#define MTU_IMSC	0x00	/* Interrupt mask set/clear */
#define MTU_RIS		0x04	/* Raw interrupt status */
#define MTU_MIS		0x08	/* Masked interrupt status */
#define MTU_ICR		0x0C	/* Interrupt clear register */

/* per-timer registers take 0..3 as argument */
#define MTU_LR(x)	(0x10 + 0x10 * (x) + 0x00)	/* Load value */
#define MTU_VAL(x)	(0x10 + 0x10 * (x) + 0x04)	/* Current value */
#define MTU_CR(x)	(0x10 + 0x10 * (x) + 0x08)	/* Control reg */
#define MTU_BGLR(x)	(0x10 + 0x10 * (x) + 0x0c)	/* At next overflow */

/* bits for the control register */
#define MTU_CRn_ENA		0x80
#define MTU_CRn_PERIODIC	0x40	/* if 0 = free-running */
#define MTU_CRn_PRESCALE_MASK	0x0c
#define MTU_CRn_PRESCALE_1		0x00
#define MTU_CRn_PRESCALE_16		0x04
#define MTU_CRn_PRESCALE_256		0x08
#define MTU_CRn_32BITS		0x02
#define MTU_CRn_ONESHOT		0x01	/* if 0 = wraps reloading from BGLR*/

/* Other registers are usual amba/primecell registers, currently not used */
#define MTU_ITCR	0xff0
#define MTU_ITOP	0xff4

#define MTU_PERIPH_ID0	0xfe0
#define MTU_PERIPH_ID1	0xfe4
#define MTU_PERIPH_ID2	0xfe8
#define MTU_PERIPH_ID3	0xfeC

#define MTU_PCELL0	0xff0
#define MTU_PCELL1	0xff4
#define MTU_PCELL2	0xff8
#define MTU_PCELL3	0xffC

static void __iomem *mtu_base;
static bool clkevt_periodic;
static u32 clk_prescale;
static u32 nmdk_cycle;		/* write-once */
static struct delay_timer mtu_delay_timer;

#ifdef CONFIG_CLKSRC_NOMADIK_MTU_SCHED_CLOCK
/*
 * Override the global weak sched_clock symbol with this
 * local implementation which uses the clocksource to get some
 * better resolution when scheduling the kernel.
 */
static u64 notrace nomadik_read_sched_clock(void)
{
	if (unlikely(!mtu_base))
		return 0;

	return -readl(mtu_base + MTU_VAL(0));
}
#endif

static unsigned long nmdk_timer_read_current_timer(void)
{
	return ~readl_relaxed(mtu_base + MTU_VAL(0));
}

/* Clockevent device: use one-shot mode */
static int nmdk_clkevt_next(unsigned long evt, struct clock_event_device *ev)
{
	writel(1 << 1, mtu_base + MTU_IMSC);
	writel(evt, mtu_base + MTU_LR(1));
	/* Load highest value, enable device, enable interrupts */
	writel(MTU_CRn_ONESHOT | clk_prescale |
	       MTU_CRn_32BITS | MTU_CRn_ENA,
	       mtu_base + MTU_CR(1));

	return 0;
}

static void nmdk_clkevt_reset(void)
{
	if (clkevt_periodic) {
		/* Timer: configure load and background-load, and fire it up */
		writel(nmdk_cycle, mtu_base + MTU_LR(1));
		writel(nmdk_cycle, mtu_base + MTU_BGLR(1));

		writel(MTU_CRn_PERIODIC | clk_prescale |
		       MTU_CRn_32BITS | MTU_CRn_ENA,
		       mtu_base + MTU_CR(1));
		writel(1 << 1, mtu_base + MTU_IMSC);
	} else {
		/* Generate an interrupt to start the clockevent again */
		(void) nmdk_clkevt_next(nmdk_cycle, NULL);
	}
}

static int nmdk_clkevt_shutdown(struct clock_event_device *evt)
{
	writel(0, mtu_base + MTU_IMSC);
	/* disable timer */
	writel(0, mtu_base + MTU_CR(1));
	/* load some high default value */
	writel(0xffffffff, mtu_base + MTU_LR(1));
	return 0;
}

static int nmdk_clkevt_set_oneshot(struct clock_event_device *evt)
{
	clkevt_periodic = false;
	return 0;
}

static int nmdk_clkevt_set_periodic(struct clock_event_device *evt)
{
	clkevt_periodic = true;
	nmdk_clkevt_reset();
	return 0;
}

static void nmdk_clksrc_reset(void)
{
	/* Disable */
	writel(0, mtu_base + MTU_CR(0));

	/* ClockSource: configure load and background-load, and fire it up */
	writel(nmdk_cycle, mtu_base + MTU_LR(0));
	writel(nmdk_cycle, mtu_base + MTU_BGLR(0));

	writel(clk_prescale | MTU_CRn_32BITS | MTU_CRn_ENA,
	       mtu_base + MTU_CR(0));
}

static void nmdk_clkevt_resume(struct clock_event_device *cedev)
{
	nmdk_clkevt_reset();
	nmdk_clksrc_reset();
}

static struct clock_event_device nmdk_clkevt = {
	.name			= "mtu_1",
	.features		= CLOCK_EVT_FEAT_ONESHOT |
				  CLOCK_EVT_FEAT_PERIODIC |
				  CLOCK_EVT_FEAT_DYNIRQ,
	.rating			= 200,
	.set_state_shutdown	= nmdk_clkevt_shutdown,
	.set_state_periodic	= nmdk_clkevt_set_periodic,
	.set_state_oneshot	= nmdk_clkevt_set_oneshot,
	.set_next_event		= nmdk_clkevt_next,
	.resume			= nmdk_clkevt_resume,
};

/*
 * IRQ Handler for timer 1 of the MTU block.
 */
static irqreturn_t nmdk_timer_interrupt(int irq, void *dev_id)
{
	struct clock_event_device *evdev = dev_id;

	writel(1 << 1, mtu_base + MTU_ICR); /* Interrupt clear reg */
	evdev->event_handler(evdev);
	return IRQ_HANDLED;
}

static struct irqaction nmdk_timer_irq = {
	.name		= "Nomadik Timer Tick",
	.flags		= IRQF_TIMER,
	.handler	= nmdk_timer_interrupt,
	.dev_id		= &nmdk_clkevt,
};

static void __init nmdk_timer_init(void __iomem *base, int irq,
				   struct clk *pclk, struct clk *clk)
{
	unsigned long rate;

	mtu_base = base;

	BUG_ON(clk_prepare_enable(pclk));
	BUG_ON(clk_prepare_enable(clk));

	/*
	 * Tick rate is 2.4MHz for Nomadik and 2.4Mhz, 100MHz or 133 MHz
	 * for ux500.
	 * Use a divide-by-16 counter if the tick rate is more than 32MHz.
	 * At 32 MHz, the timer (with 32 bit counter) can be programmed
	 * to wake-up at a max 127s a head in time. Dividing a 2.4 MHz timer
	 * with 16 gives too low timer resolution.
	 */
	rate = clk_get_rate(clk);
	if (rate > 32000000) {
		rate /= 16;
		clk_prescale = MTU_CRn_PRESCALE_16;
	} else {
		clk_prescale = MTU_CRn_PRESCALE_1;
	}

	/* Cycles for periodic mode */
	nmdk_cycle = DIV_ROUND_CLOSEST(rate, HZ);

	/* Timer 0 is the free running clocksource */
	nmdk_clksrc_reset();

	if (clocksource_mmio_init(mtu_base + MTU_VAL(0), "mtu_0",
			rate, 200, 32, clocksource_mmio_readl_down))
		pr_err("timer: failed to initialize clock source %s\n",
		       "mtu_0");

#ifdef CONFIG_CLKSRC_NOMADIK_MTU_SCHED_CLOCK
	sched_clock_register(nomadik_read_sched_clock, 32, rate);
#endif

	/* Timer 1 is used for events, register irq and clockevents */
	setup_irq(irq, &nmdk_timer_irq);
	nmdk_clkevt.cpumask = cpumask_of(0);
	nmdk_clkevt.irq = irq;
	clockevents_config_and_register(&nmdk_clkevt, rate, 2, 0xffffffffU);

	mtu_delay_timer.read_current_timer = &nmdk_timer_read_current_timer;
	mtu_delay_timer.freq = rate;
	register_current_timer_delay(&mtu_delay_timer);
}

static void __init nmdk_timer_of_init(struct device_node *node)
{
	struct clk *pclk;
	struct clk *clk;
	void __iomem *base;
	int irq;

	base = of_iomap(node, 0);
	if (!base)
		panic("Can't remap registers");

	pclk = of_clk_get_by_name(node, "apb_pclk");
	if (IS_ERR(pclk))
		panic("could not get apb_pclk");

	clk = of_clk_get_by_name(node, "timclk");
	if (IS_ERR(clk))
		panic("could not get timclk");

	irq = irq_of_parse_and_map(node, 0);
	if (irq <= 0)
		panic("Can't parse IRQ");

	nmdk_timer_init(base, irq, pclk, clk);
}
CLOCKSOURCE_OF_DECLARE(nomadik_mtu, "st,nomadik-mtu",
		       nmdk_timer_of_init);


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Positive tests for the use of the invariant qualifier and pragma</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>
<link rel="stylesheet" href="../../resources/glsl-feature-tests.css"/>


text:
<?xml version="1.0"?>
<window id="2007">
    <dynamiccontents>true</dynamiccontents>
	<controls>
		<control type="group">
			<visible>Slideshow.ShowInfo</visible>
			<posx>36</posx>
			<posy>36</posy>
			<control type="image">
				<visible>!IsEmpty(slideshow.label)</visible>
				<visible>IsEmpty(slideshow.description)</visible>
				<posx>0</posx>
				<posy>0</posy>
				<width>1208</width>
				<height>64</height>
				<texture border="20">browse_menu_dialog_background.png</texture>
				<colordiffuse>C0212121</colordiffuse>
			</control>
			<control type="image">
				<visible>!IsEmpty(slideshow.label)</visible>
				<visible>!IsEmpty(slideshow.description)</visible>
				<posx>0</posx>
				<posy>0</posy>
				<width>1208</width>
				<height>192</height>
				<texture border="20">browse_menu_dialog_background.png</texture>
				<colordiffuse>C0212121</colordiffuse>
			</control>
			<control type="label">
				<posx>14</posx>
				<posy>16</posy>
				<width>1180</width>
				<height>32</height>
				font32b
				<textcolor>offwhite</textcolor>
				$INFO[slideshow.label]
				<aligny>center</aligny>
				<align>left</align>
				<scroll>false</scroll>
			</control>
			<control type="label">
				<posx>14</posx>
				<posy>56</posy>
				<width>1180</width>
				<height>120</height>
				font24
				<textcolor>offwhite</textcolor>
				$INFO[slideshow.description]
				<aligny>top</aligny>
				<align>left</align>
				<scroll>false</scroll>
				$INFO[slideshow.description]
				<wrapmultiline>true</wrapmultiline>
			</control>
		</control>
	</controls>
</window>


text:
import os
import unittest
from mock import Mock

from robotide.robotapi import TestCaseFile, ResourceFile
from robotide.controller import Project
from robotide.controller.commands import RenameResourceFile
from robotide.controller.filecontrollers import TestCaseFileController
from robotide.namespace.namespace import Namespace
from nose.tools import (
    assert_is_not_none, assert_true, assert_false, assert_equals,
    assert_is_none)

from resources import (
    MINIMAL_SUITE_PATH, SUITEPATH, MessageRecordingLoadObserver, FakeSettings)
from robotide.spec.librarymanager import LibraryManager

class TestFormatChange(unittest.TestCase):

    def setUp(self):
        ns = Namespace(FakeSettings())
        self.project = ProjectChecker(ns, settings=ns._settings)

    def test_format_change_to_tsv(self):
        self._test_format_change('tsv')

    def test_format_change_to_robot(self):
        self._test_format_change('robot')

    def _test_format_change(self, to_format):
        controller = self._get_file_controller(MINIMAL_SUITE_PATH)
        assert_is_not_none(controller)
        controller.save_with_new_format(to_format)
        self._assert_removed(MINIMAL_SUITE_PATH)
        path_with_tsv = os.path.splitext(MINIMAL_SUITE_PATH)[0] + '.'+to_format
        self._assert_serialized(path_with_tsv)

    def test_recursive_format_change(self):
        controller = self._get_file_controller(SUITEPATH)
        controller.save_with_new_format_recursive('txt')
        init_file = os.path.join(SUITEPATH,'__init__.txt')
        self._assert_serialized(init_file)
        path_to_sub_init_file = os.path.join(SUITEPATH,'subsuite','__init__.txt')
        self._assert_serialized(path_to_sub_init_file)
        path_to_old_sub_init_file = os.path.join(SUITEPATH,'subsuite','__init__.tsv')
        self._assert_removed(path_to_old_sub_init_file)
        path_to_txt_file = os.path.join(SUITEPATH,'subsuite','test.txt')
        self._assert_not_serialized(path_to_txt_file)
        self._assert_not_removed(path_to_txt_file)

    def _get_file_controller(self, path):
        self.project.load_datafile(path, MessageRecordingLoadObserver())
        return self.project._controller

    def _assert_serialized(self, path):
        assert_true(path in self.project.serialized_files)

    def _assert_not_serialized(self, path):
        assert_false(path in self.project.serialized_files)

    def _assert_removed(self, path):
        assert_true(path in self.project.removed_files)

    def _assert_not_removed(self, path):
        assert_false(path in self.project.removed_files)

class ProjectChecker(Project):

    def __init__(self, namespace, settings=None, library_manager=None):
        self.removed_files = []
        self.serialized_files = []
        library_manager = library_manager or LibraryManager(':memory:')
        if not library_manager:
            library_manager.create_database()
        Project.__init__(self, namespace, settings, library_manager)

    def save(self, controller):
        self.serialized_files.append(controller.source)

    def _remove_file(self, path):
        self.removed_files.append(path)

class _UnitTestsWithWorkingResourceImports(unittest.TestCase):

    def _create_data(self, resource_name, resource_import):
        res_path = os.path.abspath(resource_name)
        tcf = TestCaseFile(source=os.path.abspath('test.txt'))
        tcf.setting_table.add_resource(resource_import)
        tcf.variable_table.add('${dirname}', os.path.abspath('.').replace('\\', '\\\\'))
        tcf.variable_table.add('${path}', os.path.abspath(resource_name).replace('\\', '\\\\'))
        library_manager = LibraryManager(':memory:')
        library_manager.create_database()
        self.project = Project(Namespace(FakeSettings()), FakeSettings(), library_manager)
        self.project._controller = TestCaseFileController(tcf, self.project)
        res = ResourceFile(source=res_path)
        self.res_controller = \
            self.project._resource_file_controller_factory.create(res)
        self.project._namespace._resource_factory.cache[os.path.normcase(res_path)] = res

    @property
    def import_setting(self):
        return self.project._controller.imports[0]

    def _verify_import_reference(self, imp_is_resolved):
        if imp_is_resolved:
            self._verify_import_reference_exists()
        else:
            self._verify_import_reference_is_not_resolved()

    def _verify_import_reference_exists(self):
        assert_equals(self.import_setting.get_imported_controller(),
                          self.res_controller)

    def _verify_import_reference_is_not_resolved(self):
        imported_controller = self.import_setting.get_imported_controller()
        if imported_controller:
            msg = 'Resolved to source %s' % imported_controller.source
        else:
            msg = None
        assert_is_none(imported_controller, msg)

class TestResourceFileRename(_UnitTestsWithWorkingResourceImports):

    def test_import_is_invalidated_when_resource_file_name_changes(self):
        self._create_data('resource.txt', '${path}')
        self._verify_import_reference_exists()
        self._rename_resource('resu', False)
        self._verify_import_reference_is_not_resolved()
        assert_equals(self.import_setting.name, '${path}')

    def test_import_is_modified_when_resource_file_name_changes_and_habaa(self):
        self._create_data('fooo.txt', 'fooo.txt')
        self._verify_import_reference_exists()
        self._rename_resource('gooo', True)
        self._verify_import_reference_exists()
        assert_equals(self.import_setting.name, 'gooo.txt')

    def test_cancel_execute_when_modify_imports_is_canceled(self):
        self._create_data('fooo.txt', 'fooo.txt')
        self._verify_import_reference_exists()
        self._execute_rename_resource('gooo', None)
        assert_false(self.res_controller.remove_from_filesystem.called)
        assert_false(self.res_controller.save.called)

    def test_import_is_invalidated_when_resource_file_name_changes_and_hubaa(self):
        self._create_data('resource.txt', '${path}')
        self._verify_import_reference_exists()
        self._rename_resource('resu', True)
        self._verify_import_reference_is_not_resolved()
        assert_equals(self.import_setting.name, '${path}')

    def _execute_rename_resource(self, new_basename, boolean_variable):
        self.res_controller.remove_from_filesystem = Mock()
        self.res_controller.save = Mock()
        self.res_controller.execute(RenameResourceFile(new_basename, lambda : boolean_variable))

    def _rename_resource(self, new_basename, boolean_variable):
        self._execute_rename_resource(new_basename, boolean_variable)
        assert_true(self.res_controller.remove_from_filesystem.called)
        assert_true(self.res_controller.save.called)

class TestResourceFormatChange(_UnitTestsWithWorkingResourceImports):

    def test_imports_are_updated(self):
        self._create_data('name.txt', 'name.txt')
        self._change_format('BAR')
        self._assert_format_change('name.bar', 'name.bar')

    def test_imports_with_variables_and_path_are_updated(self):
        self._create_data('name.txt', '${dirname}${/}name.txt')
        self._change_format('cock')
        self._assert_format_change('${dirname}${/}name.cock', 'name.cock')

    def test_imports_with_only_variables(self):
        self._create_data('res.txt', '${path}')
        self._change_format('zap')
        self._assert_format_change('${path}', 'res.zap', imp_is_resolved=False)

    def _change_format(self, format):
        self.res_controller.set_format(format)

    def _assert_format_change(self, import_name, resource_path,
                              imp_is_resolved=True):
        imp = self.import_setting
        assert_equals(imp.name, import_name)
        assert_equals(self.res_controller.filename, os.path.abspath(resource_path))
        self._verify_import_reference(imp_is_resolved)


text:
class AddCoordsToEvent < ActiveRecord::Migration
  def change
    add_column :events, :address, :text
    add_column :events, :lat, :decimal, :precision => 9, :scale => 6
    add_column :events, :lng, :decimal, :precision => 9, :scale => 6
    add_index :events, [:lat, :lng]
   end
end


text:
'use strict';
var path = require('path');
var babel = require('babel-core');

module.exports = function (grunt) {
	grunt.registerMultiTask('babel', 'Use next generation JavaScript, today', function () {
		var options = this.options();

		this.files.forEach(function (el) {
			delete options.filename;
			delete options.filenameRelative;

			options.sourceFileName = path.relative(path.dirname(el.dest), el.src[0]);

			if (process.platform === 'win32') {
				options.sourceFileName = options.sourceFileName.replace(/\\/g, '/');
			}

			options.sourceMapTarget = path.basename(el.dest);

			var res = babel.transformFileSync(el.src[0], options);
			var sourceMappingURL = '';

			if (res.map) {
				sourceMappingURL = '\n//# sourceMappingURL=' + path.basename(el.dest) + '.map';
			}

			grunt.file.write(el.dest, res.code + sourceMappingURL + '\n');

			if (res.map) {
				grunt.file.write(el.dest + '.map', JSON.stringify(res.map));
			}
		});
	});
};


text: from . import sly


text:
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <sstream>
#include <math.h>
#include <signal.h>
#include <sys/stat.h>
#include "SuMo.h"

/* associated source code: */
#include "calibration/makePedandLin.cpp"
#include "calibration/loadPedandLin.cpp"
#include "GetAcdcPackets.cpp"
#include "GetSysPackets.cpp"
#include "DAQinstruction.cpp"
#include "form_meta_data.cpp"

using namespace std;

SuMo::SuMo() //Double Colons indicate that the thing coming before the colons is a class.
{
  check_readout_mode();
  for(int i=0; i<numFrontBoards; i++){
    DC_ACTIVE[i] = false;
    EVENT_FLAG[i] = false;
    adcDat[i] = new packet_t();
  }
}

SuMo::~SuMo()
{
  dump_data();
  for(int i=0; i<numFrontBoards; i++) delete [] adcDat[i];

}
void SuMo::cleanup(){
  for(int jj=0; jj<2; jj++){
    if(mode==USB2x) system_slave_card_trig_valid(false);
    system_card_trig_valid(false);
    if(mode==USB2x) manage_cc_fifo_slaveDevice(1);
    manage_cc_fifo(1);
    //
    dump_data();
    if(mode==USB2x) set_usb_read_mode_slaveDevice(16), set_usb_read_mode_slaveDevice(0);
    set_usb_read_mode(16), set_usb_read_mode(0);
    //
    dump_data();
  }
  //for(int i=0; i<numFrontBoards; i++) delete [] adcDat[i];
}
//this function does something, change this
//comment later
void SuMo::dump_data(void){
  bool all[numFrontBoards];
  for(int i=0; i<numFrontBoards; i++) all[i] = true;
  manage_cc_fifo(1);
  if(mode == USB2x) manage_cc_fifo_slaveDevice(1);
  read_AC(1, all,false);
  manage_cc_fifo(1);
  if(mode == USB2x) manage_cc_fifo_slaveDevice(1);
}

int SuMo::check_readout_mode(void){
  if(usb2.createHandles() == stdUSB::SUCCEED && usb.createHandles() == stdUSB::SUCCEED){
    mode = USB2x;
    usb.freeHandles();
    usb2.freeHandles();
    cout << "mode is " << mode << endl;
  }
  if(usb.createHandles() == stdUSB::SUCCEED){
    mode = USB;
    //    cout << "worked on else if" << "\n" << endl;
    usb.freeHandles();
  }
  else
    mode = UNK;

  return mode;
}

int SuMo::check_active_boards(bool print){

  int num_boards_active = 0;
  for(int targetAC = 0; targetAC < numFrontBoards; targetAC++){
    if(DC_ACTIVE[targetAC]){
      num_boards_active ++;
      if(print) cout << "Board at address " << targetAC << " of " << numFrontBoards-1 << " found" << endl;
    }
  }
  return num_boards_active;
}
/* slave USB device checks */
int SuMo::check_active_boards_slaveDevice(void){

  int num_boards_active = 0;
  for(int targetAC = 4; targetAC < numFrontBoards; targetAC++){
    if(DC_ACTIVE[targetAC]){
      num_boards_active ++;
    }
  }
  return num_boards_active;
}

int SuMo::check_active_boards(int NUM){

  for(int i=0; i<NUM; i++){
    int device = 0;
    read_CC(false, false, device);
    if(mode==USB2x){
      device=1;
      read_CC(false, false, device);
    }
  }

  if(check_active_boards(false) == 0){
      cout << "failed to find connected ADC boards" << endl;
      return 1;
  }
  //cout << "readout mode is " << mode << endl;
  return 0;
}
bool SuMo::fileExists(const string& filename)
{
    struct stat buf;
    if (stat(filename.c_str(), &buf) != -1)
    {
        return true;
    }
    return false;
}
int SuMo::unwrap(int ASIC){
  int last_sampling_bin = adcDat[ASIC]->bin_count_rise;
  //int last_sampling_bin = 0;
  unsigned int BIN_40[16];

  //note BIN_40 assuming 160MHz triggering clock

  for(int k=0; k<4; k++){
    BIN_40[k] = (int)256/16*k;
  }
  return BIN_40[last_sampling_bin];
}

void SuMo::unwrap_baseline(int *baseline, int ASIC){
  int start_baseline[256];
  for(int i = 0; i < 256; i++){
    start_baseline[i] = i;
  }

  int wraparound = unwrap(ASIC);

  if((wraparound+WRAP_CONSTANT) < 257)
    wraparound = wraparound+WRAP_CONSTANT;
  else
    wraparound = wraparound+WRAP_CONSTANT-256;

  //printf("%d", wraparound);
  for(int i = 0; i < 256; i++){
    baseline[i] = start_baseline[ (wraparound + i) % 256];
  }
}

int SuMo::measure_rate(bool* AC_read_mask){
  set_usb_read_mode(0); //Allow messages to be passed to ACDC, allow for triggers.
  manage_cc_fifo(1); //Reset some stuff in the tranceivers.
  usleep(100); //sleep for 100usec.

  prep_sync(); //Get ready to start triggering.
  system_card_trig_valid(true); //send in trig valid signal (allow psec4 to send self trig signals).
  make_sync(); //commence.

  usleep(3e6); //sleep for 3 seconds.

  prep_sync(); //get ready to send trigger.
  software_trigger((unsigned int) 15); //send over a software trigger.
  make_sync(); //

  usleep(100); //sleep and let the data roll on in.
  read_CC(false,false,0); //read the ACC to update the list of active boards ACDC boards.
  int num_boards = read_AC(1,AC_read_mask,false); //trig mode 1, read all the boards, don't save to a file.
  usleep(4000); //wait 4000usec.
  system_card_trig_valid(false); //don't allow triggers while we work with the data.
  return(num_boards);
}

void SuMo::adjust_thresh(int threshold, unsigned int board_number){
  unsigned int chipAddress;
  unsigned int boardAddress;
  boardAddress = pow(2,board_number);
  for (int k =0;k<5;k++){ //Adjust the thresholds on each chip to the one we want to use.
    chipAddress = pow(2,k); //generate chip adress
    set_trig_threshold(threshold,boardAddress,0,chipAddress); //set threshold to new value.
    usleep(100); //sleep 100usec.
  }
}


text:
package net.pubnative.api.core.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import net.pubnative.sdk.R;

public class PNAPILoadingView extends FrameLayout {
    public PNAPILoadingView(Context context) {
        super(context);
        init(context);
    }

    public PNAPILoadingView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PNAPILoadingView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    protected void init(Context context) {
        setBackgroundColor(context.getResources().getColor(R.color.pubnative_loading_background_color));
        ProgressBar progressBar = new ProgressBar(context);
        FrameLayout.LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        addView(progressBar, params);
    }
}


text:
{% load i18n %}

<form id="editable-toolbar" method="POST"
    action="{% url admin:logout %}?{{ REDIRECT_FIELD_NAME }}={{ request.path }}">
    {% csrf_token %}
    >>
    {% if page %}
        {% trans "Admin" %}
    {% else %}
        {% trans "Admin" %}
    {% endif %}
    {% trans "Log out" %}
</form>


text:
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week

@implementation  ZC_SDImageCacheConfig

- (instancetype)init {
    if (self = [super init]) {
        _shouldDecompressImages = YES;
        _shouldDisableiCloud = YES;
        _shouldCacheImagesInMemory = YES;
        _maxCacheAge = kDefaultCacheMaxCacheAge;
        _maxCacheSize = 0;
    }
    return self;
}

@end


text:
<?php

namespace CfdiUtils\Elements\Pagos20;

use CfdiUtils\Elements\Common\AbstractElement;

class RetencionesP extends AbstractElement
{
    public function getElementName(): string
    {
        return 'pago20:RetencionesP';
    }

    public function addRetencionP(array $attributes = []): RetencionP
    {
        $subject = new RetencionP($attributes);
        $this->addChild($subject);
        return $subject;
    }

    public function multiRetencionP(array ...$elementAttributes): self
    {
        foreach ($elementAttributes as $attributes) {
            $this->addRetencionP($attributes);
        }
        return $this;
    }
}


text:
CKEDITOR.plugins.setLang('lineheight','en', {
    title: 'Line Height'
} );


text:
package org.apache.datasketches;

/**
 * Useful methods for byte arrays.
 * @author Lee Rhodes
 */
public final class ByteArrayUtil {

  /**
   * Get a short from the given byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the short
   */
  public static short getShortLE(final byte[] array, final int offset) {
    return (short) ((array[offset    ] & 0XFF       )
                 | ((array[offset + 1] & 0XFF) <<  8));
  }

  /**
   * Put the source short into the destination byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source short
   */
  public static void putShortLE(final byte[] array, final int offset, final short value) {
    array[offset    ] = (byte) (value       );
    array[offset + 1] = (byte) (value >>>  8);
  }

  /**
   * Get a short from the given byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the short
   */
  public static short getShortBE(final byte[] array, final int offset) {
    return (short) ((array[offset + 1] & 0XFF       )
                 | ((array[offset    ] & 0XFF) <<  8));
  }

  /**
   * Put the source short into the destination byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source short
   */
  public static void putShortBE(final byte[] array, final int offset, final short value) {
    array[offset + 1] = (byte) (value       );
    array[offset    ] = (byte) (value >>>  8);
  }

  /**
   * Get a int from the given byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the int
   */
  public static int getIntLE(final byte[] array, final int offset) {
    return  ( array[offset    ] & 0XFF       )
          | ((array[offset + 1] & 0XFF) <<  8)
          | ((array[offset + 2] & 0XFF) << 16)
          | ((array[offset + 3] & 0XFF) << 24);
  }

  /**
   * Put the source int into the destination byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source int
   */
  public static void putIntLE(final byte[] array, final int offset, final int value) {
    array[offset    ] = (byte) (value       );
    array[offset + 1] = (byte) (value >>>  8);
    array[offset + 2] = (byte) (value >>> 16);
    array[offset + 3] = (byte) (value >>> 24);
  }

  /**
   * Get a int from the given byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the int
   */
  public static int getIntBE(final byte[] array, final int offset) {
    return  ( array[offset + 3] & 0XFF       )
          | ((array[offset + 2] & 0XFF) <<  8)
          | ((array[offset + 1] & 0XFF) << 16)
          | ((array[offset    ] & 0XFF) << 24);
  }

  /**
   * Put the source int into the destination byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source int
   */
  public static void putIntBE(final byte[] array, final int offset, final int value) {
    array[offset + 3] = (byte) (value       );
    array[offset + 2] = (byte) (value >>>  8);
    array[offset + 1] = (byte) (value >>> 16);
    array[offset    ] = (byte) (value >>> 24);
  }

  /**
   * Get a long from the given byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the long
   */
  public static long getLongLE(final byte[] array, final int offset) {
    return  ( array[offset    ] & 0XFFL       )
          | ((array[offset + 1] & 0XFFL) <<  8)
          | ((array[offset + 2] & 0XFFL) << 16)
          | ((array[offset + 3] & 0XFFL) << 24)
          | ((array[offset + 4] & 0XFFL) << 32)
          | ((array[offset + 5] & 0XFFL) << 40)
          | ((array[offset + 6] & 0XFFL) << 48)
          | ((array[offset + 7] & 0XFFL) << 56);
  }

  /**
   * Put the source long into the destination byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source long
   */
  public static void putLongLE(final byte[] array, final int offset, final long value) {
    array[offset    ] = (byte) (value       );
    array[offset + 1] = (byte) (value >>>  8);
    array[offset + 2] = (byte) (value >>> 16);
    array[offset + 3] = (byte) (value >>> 24);
    array[offset + 4] = (byte) (value >>> 32);
    array[offset + 5] = (byte) (value >>> 40);
    array[offset + 6] = (byte) (value >>> 48);
    array[offset + 7] = (byte) (value >>> 56);
  }

  /**
   * Get a long from the source byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source starting point
   * @return the long
   */
  public static long getLongBE(final byte[] array, final int offset) {
    return  ( array[offset + 7] & 0XFFL       )
          | ((array[offset + 6] & 0XFFL) <<  8)
          | ((array[offset + 5] & 0XFFL) << 16)
          | ((array[offset + 4] & 0XFFL) << 24)
          | ((array[offset + 3] & 0XFFL) << 32)
          | ((array[offset + 2] & 0XFFL) << 40)
          | ((array[offset + 1] & 0XFFL) << 48)
          | ((array[offset    ] & 0XFFL) << 56);
  }

  /**
   * Put the source long into the destination byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination starting point
   * @param value source long
   */
  public static void putLongBE(final byte[] array, final int offset, final long value) {
    array[offset + 7] = (byte) (value       );
    array[offset + 6] = (byte) (value >>>  8);
    array[offset + 5] = (byte) (value >>> 16);
    array[offset + 4] = (byte) (value >>> 24);
    array[offset + 3] = (byte) (value >>> 32);
    array[offset + 2] = (byte) (value >>> 40);
    array[offset + 1] = (byte) (value >>> 48);
    array[offset    ] = (byte) (value >>> 56);
  }

  /**
   * Get a float from the given byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the float
   */
  public static float getFloatLE(final byte[] array, final int offset) {
    return Float.intBitsToFloat(getIntLE(array, offset));
  }

  /**
   * Put the source float into the destination byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source float
   */
  public static void putFloatLE(final byte[] array, final int offset, final float value) {
    putIntLE(array, offset, Float.floatToRawIntBits(value));
  }

  /**
   * Get a float from the given byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the float
   */
  public static float getFloatBE(final byte[] array, final int offset) {
    return Float.intBitsToFloat(getIntBE(array, offset));
  }

  /**
   * Put the source float into the destination byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source float
   */
  public static void putFloatBE(final byte[] array, final int offset, final float value) {
    putIntBE(array, offset, Float.floatToRawIntBits(value));
  }

  /**
   * Get a double from the given byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the double
   */
  public static double getDoubleLE(final byte[] array, final int offset) {
    return Double.longBitsToDouble(getLongLE(array, offset));
  }

  /**
   * Put the source double into the destination byte array starting at the given offset
   * in little endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source double
   */
  public static void putDoubleLE(final byte[] array, final int offset, final double value) {
    putLongLE(array, offset, Double.doubleToRawLongBits(value));
  }

  /**
   * Get a double from the given byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array source byte array
   * @param offset source offset
   * @return the double
   */
  public static double getDoubleBE(final byte[] array, final int offset) {
    return Double.longBitsToDouble(getLongBE(array, offset));
  }

  /**
   * Put the source double into the destination byte array starting at the given offset
   * in big endian order.
   * There is no bounds checking.
   * @param array destination byte array
   * @param offset destination offset
   * @param value source double
   */
  public static void putDoubleBE(final byte[] array, final int offset, final double value) {
    putLongBE(array, offset, Double.doubleToRawLongBits(value));
  }

}