text:
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <XnUSB.h>

#if (XN_PLATFORM == XN_PLATFORM_ANDROID_ARM)
#include <libusb.h>
#else
#include <libusb-1.0/libusb.h>
#endif

#include "XnLinuxUSB.h"
#include "../XnUSBInternal.h"
#include <XnOS.h>
#include <XnLog.h>
#include <XnOSCpp.h>
#include <XnList.h>

//---------------------------------------------------------------------------
// Types
//---------------------------------------------------------------------------
typedef struct XnUSBEventCallback
{
	XnUSBDeviceCallbackFunctionPtr pFunc;
	void* pCookie;
} XnUSBEventCallback;

typedef xnl::List<XnUSBEventCallback*> XnUSBEventCallbackList;

XnUSBEventCallbackList g_connectivityEvent;

//---------------------------------------------------------------------------
// Defines
//---------------------------------------------------------------------------
#define MAX_DEVPATH_LENGTH 256
#define USB_TYPE_STANDARD		(0x00 << 5)
#define USB_TYPE_CLASS			(0x01 << 5)
#define USB_TYPE_VENDOR			(0x02 << 5)
#define USB_ENDPOINT_IN			0x80

#define XN_MASK_USB "xnUSB"

#define XN_USB_HANDLE_EVENTS_TIMEOUT 500

#define XN_VALIDATE_DEVICE_HANDLE(x)				\
	if (x == NULL)									\
		return (XN_STATUS_USB_DEVICE_NOT_VALID);

#define XN_VALIDATE_EP_HANDLE(x)					\
	if (x == NULL)									\
		return (XN_STATUS_USB_ENDPOINT_NOT_VALID);

struct xnUSBInitData
{
	libusb_context* pContext;
	XN_THREAD_HANDLE hThread;
	XnBool bShouldThreadRun;
	XnUInt32 nOpenDevices;
	XN_CRITICAL_SECTION_HANDLE hLock;
} g_InitData = {NULL, NULL, FALSE, 0, NULL};

XnStatus xnUSBPlatformSpecificShutdown();

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
XN_THREAD_PROC xnUSBHandleEventsThread(XN_THREAD_PARAM pThreadParam)
{
	// init timeout
	struct timeval timeout;
	timeout.tv_sec = XN_USB_HANDLE_EVENTS_TIMEOUT / 1000;
	timeout.tv_usec = XN_USB_HANDLE_EVENTS_TIMEOUT % 1000;

	while (g_InitData.bShouldThreadRun)
	{
		// let libusb process its asynchronous events
		libusb_handle_events_timeout(g_InitData.pContext, &timeout);
	}

	XN_THREAD_PROC_RETURN(XN_STATUS_OK);
}

XnStatus xnUSBPlatformSpecificInit()
{
	xnLogVerbose(XN_MASK_USB, "Initializing USB...");

	// initialize the library
	int rc = libusb_init(&g_InitData.pContext);
	if (rc != 0)
	{
		return (XN_STATUS_USB_INIT_FAILED);
	}

	XnStatus nRetVal = xnOSCreateCriticalSection(&g_InitData.hLock);
	XN_IS_STATUS_OK(nRetVal);

	//libusb_set_debug(g_InitData.pContext, 3);

	xnLogInfo(XN_MASK_USB, "USB is initialized.");
	return (XN_STATUS_OK);
}

XnStatus xnUSBAsynchThreadAddRef()
{
	XnStatus nRetVal = XN_STATUS_OK;

	xnl::AutoCSLocker locker(g_InitData.hLock);

	++g_InitData.nOpenDevices;

	if (g_InitData.hThread == NULL)
	{
		xnLogVerbose(XN_MASK_USB, "Starting libusb asynch thread...");

		// mark thread should run
		g_InitData.bShouldThreadRun = TRUE;

		// and start thread
		nRetVal = xnOSCreateThread(xnUSBHandleEventsThread, NULL, &g_InitData.hThread);
		if (nRetVal != XN_STATUS_OK)
		{
			// clean-up
			xnUSBPlatformSpecificShutdown();
			return nRetVal;
		}

		// set thread priority to critical
		nRetVal = xnOSSetThreadPriority(g_InitData.hThread, XN_PRIORITY_CRITICAL);
		if (nRetVal != 0)
		{
			xnLogWarning(XN_MASK_USB, "USB events thread: Failed to set thread priority to critical. This might cause loss of data...");
			printf("Warning: USB events thread - failed to set priority. This might cause loss of data...\n");
		}
	}

	return (XN_STATUS_OK);
}

void xnUSBAsynchThreadStop()
{
	if (g_InitData.hThread != NULL)
	{
		// mark for thread to exit
		g_InitData.bShouldThreadRun = FALSE;

		// wait for it to exit
		xnLogVerbose(XN_MASK_USB, "Shutting down USB events thread...");
		XnStatus nRetVal = xnOSWaitForThreadExit(g_InitData.hThread, XN_USB_HANDLE_EVENTS_TIMEOUT * 2);
		if (nRetVal != XN_STATUS_OK)
		{
			xnLogWarning(XN_MASK_USB, "USB events thread didn't shutdown. Terminating it...");
			xnOSTerminateThread(&g_InitData.hThread);
		}
		else
		{
			xnOSCloseThread(&g_InitData.hThread);
		}

		g_InitData.hThread = NULL;
	}
}

void xnUSBAsynchThreadRelease()
{
	xnl::AutoCSLocker locker(g_InitData.hLock);

	--g_InitData.nOpenDevices;

	if (g_InitData.nOpenDevices == 0)
	{
		xnUSBAsynchThreadStop();
	}
}

XnStatus xnUSBPlatformSpecificShutdown()
{
	xnUSBAsynchThreadStop();

	if (g_InitData.hLock != NULL)
	{
		xnOSCloseCriticalSection(&g_InitData.hLock);
		g_InitData.hLock = NULL;
	}

	if (g_InitData.pContext != NULL)
	{
		// close the library
		libusb_exit(g_InitData.pContext);
		g_InitData.pContext = NULL;
	}

	return (XN_STATUS_OK);
}

/*
* Finds a USB device.
* the returned device must be unreferenced when it is no longer needed using libusb_unref_device.
*/
XnStatus FindDevice(XnUInt16 nVendorID, XnUInt16 nProductID, void* pExtraParam, libusb_device** ppDevice)
{
	*ppDevice = NULL;

	// get device list
	libusb_device** ppDevices;
	ssize_t nDeviceCount = libusb_get_device_list(g_InitData.pContext, &ppDevices);

	// check for error
	if (nDeviceCount < 0)
	{
		return (XN_STATUS_USB_ENUMERATE_FAILED);
	}

	// enumerate over the devices
	for (ssize_t i = 0; i < nDeviceCount; ++i)
	{
		libusb_device* pDevice = ppDevices[i];

		// get device descriptor
		libusb_device_descriptor desc;
		int rc = libusb_get_device_descriptor(pDevice, &desc);
		if (rc != 0)
		{
			return (XN_STATUS_USB_ENUMERATE_FAILED);
		}

		// check if this is the requested device
		if (desc.idVendor == nVendorID && desc.idProduct == nProductID)
		{
			// add a reference to the device (so it won't be destroyed when list is freed)
			libusb_ref_device(pDevice);
			*ppDevice = pDevice;
			break;
		}
	}

	// free the list (also dereference each device)
	libusb_free_device_list(ppDevices, 1);

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBIsDevicePresent(XnUInt16 nVendorID, XnUInt16 nProductID, void* pExtraParam, XnBool* pbDevicePresent)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// make sure library was initialized
	XN_VALIDATE_USB_INIT();

	// Validate parameters
	XN_VALIDATE_OUTPUT_PTR(pbDevicePresent);

	*pbDevicePresent = FALSE;

	libusb_device* pDevice;
	nRetVal = FindDevice(nVendorID, nProductID, pExtraParam, &pDevice);
	XN_IS_STATUS_OK(nRetVal);

	if (pDevice != NULL)
	{
		*pbDevicePresent = TRUE;

		// unref device
		libusb_unref_device(pDevice);
	}

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBEnumerateDevices(XnUInt16 nVendorID, XnUInt16 nProductID, const XnUSBConnectionString** pastrDevicePaths, XnUInt32* pnCount)
{
	// get device list
	libusb_device** ppDevices;
	ssize_t nDeviceCount = libusb_get_device_list(g_InitData.pContext, &ppDevices);

	// first enumeration - count
	XnUInt32 nCount = 0;

	for (ssize_t i = 0; i < nDeviceCount; ++i)
	{
		libusb_device* pDevice = ppDevices[i];

		// get device descriptor
		libusb_device_descriptor desc;
		int rc = libusb_get_device_descriptor(pDevice, &desc);
		if (rc != 0)
		{
			libusb_free_device_list(ppDevices, 1);
			return (XN_STATUS_USB_ENUMERATE_FAILED);
		}

		// check if this is the requested device
		if (desc.idVendor == nVendorID && desc.idProduct == nProductID)
		{
			++nCount;
		}
	}

	// allocate array
	XnUSBConnectionString* aResult = (XnUSBConnectionString*)xnOSCalloc(nCount, sizeof(XnUSBConnectionString));
	if (aResult == NULL)
	{
		libusb_free_device_list(ppDevices, 1);
		return XN_STATUS_ALLOC_FAILED;
	}

	// second enumeration - fill
	XnUInt32 nCurrent = 0;
	for (ssize_t i = 0; i < nDeviceCount; ++i)
	{
		libusb_device* pDevice = ppDevices[i];

		// get device descriptor
		libusb_device_descriptor desc;
		int rc = libusb_get_device_descriptor(pDevice, &desc);
		if (rc != 0)
		{
			libusb_free_device_list(ppDevices, 1);
			return (XN_STATUS_USB_ENUMERATE_FAILED);
		}

		// check if this is the requested device
		if (desc.idVendor == nVendorID && desc.idProduct == nProductID)
		{
			sprintf(aResult[nCurrent], "%04hx/%04hx@%hhu/%hhu", nVendorID, nProductID, libusb_get_bus_number(pDevice), libusb_get_device_address(pDevice));
			nCurrent++;
		}
	}

	*pastrDevicePaths = aResult;
	*pnCount = nCount;

	// free the list (also dereference each device)
	libusb_free_device_list(ppDevices, 1);

	return XN_STATUS_OK;
}

XN_C_API void xnUSBFreeDevicesList(const XnUSBConnectionString* astrDevicePaths)
{
	xnOSFree(astrDevicePaths);
}

XN_C_API XnStatus xnUSBOpenDeviceImpl(libusb_device* pDevice, XN_USB_DEV_HANDLE* pDevHandlePtr)
{
	XnStatus nRetVal = XN_STATUS_OK;

	if (pDevice == NULL)
	{
		return (XN_STATUS_USB_DEVICE_NOT_FOUND);
	}

	// allocate device handle
	libusb_device_handle* handle;

	// open device
	int rc = libusb_open(pDevice, &handle);

	// in any case, unref the device (we don't need it anymore)
	libusb_unref_device(pDevice);
	pDevice = NULL;

	// now check if open failed
	if (rc != 0)
	{
		return (XN_STATUS_USB_DEVICE_OPEN_FAILED);
	}

/*
	// set for the first (and only) configuration (this will perform a light-weight reset)
	rc = libusb_set_configuration(handle, 1);
	if (rc != 0)
	{
		libusb_close(handle);
		return (XN_STATUS_USB_SET_CONFIG_FAILED);
	}
*/
	// claim the interface (you cannot open any end point before claiming the interface)
	rc = libusb_claim_interface(handle, 0);
	if (rc != 0)
	{
		libusb_close(handle);
		return (XN_STATUS_USB_SET_INTERFACE_FAILED);
	}

/*
	// set the alternate setting to default
	rc = libusb_set_interface_alt_setting(handle, 0, 0);
	if (rc != 0)
	{
		libusb_close(handle);
		return (XN_STATUS_USB_SET_INTERFACE_FAILED);
	}
*/
	XN_VALIDATE_ALLOC(*pDevHandlePtr, XnUSBDeviceHandle);
	XN_USB_DEV_HANDLE pDevHandle = *pDevHandlePtr;
	pDevHandle->hDevice = handle;
	pDevHandle->nInterface = 0;
	pDevHandle->nAltSetting = 0;

	// mark the device is of high-speed
	pDevHandle->nDevSpeed = XN_USB_DEVICE_HIGH_SPEED;

	nRetVal = xnUSBAsynchThreadAddRef();
	if (nRetVal != XN_STATUS_OK)
	{
		xnOSFree(*pDevHandlePtr);
		return (nRetVal);
	}

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBOpenDevice(XnUInt16 nVendorID, XnUInt16 nProductID, void* pExtraParam, void* pExtraParam2, XN_USB_DEV_HANDLE* pDevHandlePtr)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// make sure library was initialized
	XN_VALIDATE_USB_INIT();

	// Validate parameters
	XN_VALIDATE_OUTPUT_PTR(pDevHandlePtr);

	libusb_device* pDevice;
	nRetVal = FindDevice(nVendorID, nProductID, pExtraParam, &pDevice);
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = xnUSBOpenDeviceImpl(pDevice, pDevHandlePtr);
	XN_IS_STATUS_OK(nRetVal);

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBOpenDeviceByPath(const XnUSBConnectionString strDevicePath, XN_USB_DEV_HANDLE* pDevHandlePtr)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// parse connection string
	XnUInt16 nVendorID = 0;
	XnUInt16 nProductID = 0;
	XnUInt8 nBus = 0;
	XnUInt8 nAddress = 0;
	sscanf(strDevicePath, "%hx/%hx@%hhu/%hhu", &nVendorID, &nProductID, &nBus, &nAddress);

	if (nVendorID == 0 || nProductID == 0 || nBus == 0 || nAddress == 0)
	{
		XN_LOG_WARNING_RETURN(XN_STATUS_USB_DEVICE_OPEN_FAILED, "Invalid connection string: %s", strDevicePath);
	}

	// find device
	libusb_device** ppDevices;
	ssize_t nDeviceCount = libusb_get_device_list(g_InitData.pContext, &ppDevices);

	libusb_device* pRequestedDevice = NULL;

	for (ssize_t i = 0; i < nDeviceCount; ++i)
	{
		libusb_device* pDevice = ppDevices[i];

		// get device descriptor
		libusb_device_descriptor desc;
		int rc = libusb_get_device_descriptor(pDevice, &desc);
		if (rc != 0)
		{
			libusb_free_device_list(ppDevices, 1);
			return (XN_STATUS_USB_ENUMERATE_FAILED);
		}

		// check if this is the requested device
		if (desc.idVendor == nVendorID && desc.idProduct == nProductID && libusb_get_bus_number(pDevice) == nBus && libusb_get_device_address(pDevice) == nAddress)
		{
			// add a reference to the device (so it won't be destroyed when list is freed)
			libusb_ref_device(pDevice);
			pRequestedDevice = pDevice;
			break;
		}
	}

	libusb_free_device_list(ppDevices, 1);

	nRetVal = xnUSBOpenDeviceImpl(pRequestedDevice, pDevHandlePtr);
	XN_IS_STATUS_OK(nRetVal);

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBCloseDevice(XN_USB_DEV_HANDLE pDevHandle)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_DEVICE_HANDLE(pDevHandle);

	int rc = libusb_release_interface(pDevHandle->hDevice, pDevHandle->nInterface);
	if (0 != rc)
	{
		return (XN_STATUS_USB_DEVICE_CLOSE_FAILED);
	}

	libusb_close(pDevHandle->hDevice);

	XN_FREE_AND_NULL(pDevHandle);

	xnUSBAsynchThreadRelease();

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBGetDeviceSpeed(XN_USB_DEV_HANDLE pDevHandle, XnUSBDeviceSpeed* pDevSpeed)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_DEVICE_HANDLE(pDevHandle);
	XN_VALIDATE_OUTPUT_PTR(pDevSpeed);

	*pDevSpeed = pDevHandle->nDevSpeed;

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBSetConfig(XN_USB_DEV_HANDLE pDevHandle, XnUInt8 nConfig)
{
	return (XN_STATUS_OS_UNSUPPORTED_FUNCTION);
}

XN_C_API XnStatus xnUSBGetConfig(XN_USB_DEV_HANDLE pDevHandle, XnUInt8* pnConfig)
{
	return (XN_STATUS_OS_UNSUPPORTED_FUNCTION);
}

XN_C_API XnStatus xnUSBSetInterface(XN_USB_DEV_HANDLE pDevHandle, XnUInt8 nInterface, XnUInt8 nAltInterface)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_DEVICE_HANDLE(pDevHandle);

	int rc = libusb_set_interface_alt_setting(pDevHandle->hDevice, nInterface, nAltInterface);
	if (rc != 0)
	{
		return (XN_STATUS_USB_SET_INTERFACE_FAILED);
	}

	pDevHandle->nInterface = nInterface;
	pDevHandle->nAltSetting = nAltInterface;

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBGetInterface(XN_USB_DEV_HANDLE pDevHandle, XnUInt8* pnInterface, XnUInt8* pnAltInterface)
{
	return XN_STATUS_OS_UNSUPPORTED_FUNCTION;
}

XN_C_API XnStatus xnUSBOpenEndPoint(XN_USB_DEV_HANDLE pDevHandle, XnUInt16 nEndPointID, XnUSBEndPointType nEPType, XnUSBDirectionType nDirType, XN_USB_EP_HANDLE* pEPHandlePtr)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_DEVICE_HANDLE(pDevHandle);
	XN_VALIDATE_OUTPUT_PTR(pEPHandlePtr);

	// get the device from the handle
	libusb_device* pDevice = libusb_get_device(pDevHandle->hDevice);

	// get the configuration descriptor
	libusb_config_descriptor* pConfig;
	int rc = libusb_get_active_config_descriptor(pDevice, &pConfig);
	if (rc != 0)
	{
		return (XN_STATUS_USB_CONFIG_QUERY_FAILED);
	}

	// make sure configuration contains the interface we need
	if (pConfig->bNumInterfaces <= pDevHandle->nInterface)
	{
		libusb_free_config_descriptor(pConfig);
		return (XN_STATUS_USB_INTERFACE_QUERY_FAILED);
	}

	// take that interface
	const libusb_interface* pInterface = &pConfig->interface[pDevHandle->nInterface];

	// make sure interface contains the alternate setting we work with
	if (pInterface->num_altsetting <= pDevHandle->nAltSetting)
	{
		libusb_free_config_descriptor(pConfig);
		return (XN_STATUS_USB_INTERFACE_QUERY_FAILED);
	}

	// take that setting
	const libusb_interface_descriptor* pInterfaceDesc = &pInterface->altsetting[pDevHandle->nAltSetting];

	// search for the requested endpoint
	const libusb_endpoint_descriptor* pEndpointDesc = NULL;

	for (uint8_t i = 0; i < pInterfaceDesc->bNumEndpoints; ++i)
	{
		if (pInterfaceDesc->endpoint[i].bEndpointAddress == nEndPointID)
		{
			pEndpointDesc = &pInterfaceDesc->endpoint[i];
			break;
		}
	}

	if (pEndpointDesc == NULL)
	{
		libusb_free_config_descriptor(pConfig);
		return (XN_STATUS_USB_ENDPOINT_NOT_FOUND);
	}

	libusb_transfer_type transfer_type = (libusb_transfer_type)(pEndpointDesc->bmAttributes & 0x3); // lower 2-bits

    // calculate max packet size
	// NOTE: we do not use libusb functions (libusb_get_max_packet_size/libusb_get_max_iso_packet_size) because
	// they hace a bug and does not consider alternative interface
    XnUInt32 nMaxPacketSize = 0;

	if (transfer_type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
	{
		XnUInt32 wMaxPacketSize = pEndpointDesc->wMaxPacketSize;
		// bits 11 and 12 mark the number of additional transactions, bits 0-10 mark the size
		XnUInt32 nAdditionalTransactions = wMaxPacketSize >> 11;
		XnUInt32 nPacketSize = wMaxPacketSize & 0x7FF;
		nMaxPacketSize = (nAdditionalTransactions + 1) * (nPacketSize);
	}
	else
	{
		nMaxPacketSize = pEndpointDesc->wMaxPacketSize;
	}

	// free the configuration descriptor. no need of it anymore
	libusb_free_config_descriptor(pConfig);
	pConfig = NULL;

	// Make sure the endpoint matches the required endpoint type
	if (nEPType == XN_USB_EP_BULK)
	{
		if (transfer_type != LIBUSB_TRANSFER_TYPE_BULK)
		{
			return (XN_STATUS_USB_WRONG_ENDPOINT_TYPE);
		}
	}
	else if (nEPType == XN_USB_EP_INTERRUPT)
	{
		if (transfer_type != LIBUSB_TRANSFER_TYPE_INTERRUPT)
		{
			return (XN_STATUS_USB_WRONG_ENDPOINT_TYPE);
		}
	}
	else if (nEPType == XN_USB_EP_ISOCHRONOUS)
	{
		if (transfer_type != LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
		{
			return (XN_STATUS_USB_WRONG_ENDPOINT_TYPE);
		}
	}
	else
	{
		return (XN_STATUS_USB_UNKNOWN_ENDPOINT_TYPE);
	}

	// Make sure the endpoint matches the required direction
	libusb_endpoint_direction direction = (libusb_endpoint_direction)(nEndPointID & 0x80); // 8th bit
	if (nDirType == XN_USB_DIRECTION_IN)
	{
		if (direction != LIBUSB_ENDPOINT_IN)
		{
			return (XN_STATUS_USB_WRONG_ENDPOINT_DIRECTION);
		}
	}
	else if (nDirType == XN_USB_DIRECTION_OUT)
	{
		if (direction != LIBUSB_ENDPOINT_OUT)
		{
			return (XN_STATUS_USB_WRONG_ENDPOINT_DIRECTION);
		}
	}
	else
	{
		return (XN_STATUS_USB_UNKNOWN_ENDPOINT_DIRECTION);
	}

	// allocate handle
	XN_VALIDATE_ALIGNED_CALLOC(*pEPHandlePtr, XnUSBEPHandle, 1, XN_DEFAULT_MEM_ALIGN);
	XN_USB_EP_HANDLE pHandle = *pEPHandlePtr;
	pHandle->hDevice = pDevHandle->hDevice;
	pHandle->nAddress = nEndPointID;
	pHandle->nType = nEPType;
	pHandle->nDirection = nDirType;
	pHandle->nMaxPacketSize = nMaxPacketSize;

	return XN_STATUS_OK;
}

XN_C_API XnStatus xnUSBCloseEndPoint(XN_USB_EP_HANDLE pEPHandle)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_EP_HANDLE(pEPHandle);

	XN_ALIGNED_FREE_AND_NULL(pEPHandle);

	return XN_STATUS_OK;
}

XN_C_API XnStatus xnUSBGetEndPointMaxPacketSize(XN_USB_EP_HANDLE pEPHandle, XnUInt32* pnMaxPacketSize)
{
	// Validate xnUSB
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_EP_HANDLE(pEPHandle);

	// Validate the input/output pointers
	XN_VALIDATE_INPUT_PTR(pEPHandle);
	XN_VALIDATE_OUTPUT_PTR(pnMaxPacketSize);

	*pnMaxPacketSize = pEPHandle->nMaxPacketSize;

	// All is good...
	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBAbortEndPoint(XN_USB_EP_HANDLE pEPHandle)
{
	return XN_STATUS_OS_UNSUPPORTED_FUNCTION;
}

XN_C_API XnStatus xnUSBFlushEndPoint(XN_USB_EP_HANDLE pEPHandle)
{
	return XN_STATUS_OS_UNSUPPORTED_FUNCTION;
}

XN_C_API XnStatus xnUSBResetEndPoint(XN_USB_EP_HANDLE pEPHandle)
{
	return XN_STATUS_OS_UNSUPPORTED_FUNCTION;
}

XN_C_API XnStatus xnUSBSendControl(XN_USB_DEV_HANDLE pDevHandle, XnUSBControlType nType, XnUInt8 nRequest, XnUInt16 nValue, XnUInt16 nIndex, XnUChar* pBuffer, XnUInt32 nBufferSize, XnUInt32 nTimeOut)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_DEVICE_HANDLE(pDevHandle);

	if (nBufferSize != 0)
	{
		XN_VALIDATE_INPUT_PTR(pBuffer);
	}

	uint8_t bmRequestType;

	if (nType == XN_USB_CONTROL_TYPE_VENDOR )
	{
		bmRequestType = LIBUSB_REQUEST_TYPE_VENDOR;
	}
	else if (nType == XN_USB_CONTROL_TYPE_CLASS)
	{
		bmRequestType = LIBUSB_REQUEST_TYPE_CLASS;
	}
	else if (nType == XN_USB_CONTROL_TYPE_STANDARD)
	{
		bmRequestType = LIBUSB_REQUEST_TYPE_STANDARD;
	}
	else
	{
		return (XN_STATUS_USB_WRONG_CONTROL_TYPE);
	}

	bmRequestType |= LIBUSB_ENDPOINT_OUT;

	// send
	int nBytesSent = libusb_control_transfer(pDevHandle->hDevice, bmRequestType, nRequest, nValue, nIndex, pBuffer, nBufferSize, nTimeOut);

	// check everything went OK
	if (nBytesSent == LIBUSB_ERROR_TIMEOUT)
	{
		return (XN_STATUS_USB_TRANSFER_TIMEOUT);
	}
	else if (nBytesSent < 0)
	{
		return (XN_STATUS_USB_CONTROL_SEND_FAILED);
	}

	if ((XnUInt32)nBytesSent != nBufferSize)
	{
		return (XN_STATUS_USB_GOT_UNEXPECTED_BYTES);
	}

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBReceiveControl(XN_USB_DEV_HANDLE pDevHandle, XnUSBControlType nType, XnUInt8 nRequest, XnUInt16 nValue, XnUInt16 nIndex, XnUChar* pBuffer, XnUInt32 nBufferSize, XnUInt32* pnBytesReceived, XnUInt32 nTimeOut)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_DEVICE_HANDLE(pDevHandle);
	XN_VALIDATE_OUTPUT_PTR(pBuffer);
	XN_VALIDATE_OUTPUT_PTR(pnBytesReceived);

	if (nBufferSize == 0)
	{
		return (XN_STATUS_USB_BUFFER_TOO_SMALL);
	}

	*pnBytesReceived = 0;

	uint8_t bmRequestType;

	if (nType == XN_USB_CONTROL_TYPE_VENDOR )
	{
		bmRequestType = LIBUSB_REQUEST_TYPE_VENDOR;
	}
	else if (nType == XN_USB_CONTROL_TYPE_CLASS)
	{
		bmRequestType = LIBUSB_REQUEST_TYPE_CLASS;
	}
	else if (nType == XN_USB_CONTROL_TYPE_STANDARD)
	{
		bmRequestType = LIBUSB_REQUEST_TYPE_STANDARD;
	}
	else
	{
		return (XN_STATUS_USB_WRONG_CONTROL_TYPE);
	}

	bmRequestType |= LIBUSB_ENDPOINT_IN;

	// send
	int nBytesReceived = libusb_control_transfer(pDevHandle->hDevice, bmRequestType, nRequest, nValue, nIndex, pBuffer, nBufferSize, nTimeOut);

	// check everything went OK
	if (nBytesReceived == LIBUSB_ERROR_TIMEOUT)
	{
		return (XN_STATUS_USB_TRANSFER_TIMEOUT);
	}
	else if (nBytesReceived < 0) // error
	{
		xnLogWarning(XN_MASK_USB, "Failed to receive from USB control endpoint (%d)", nBytesReceived);
		return (XN_STATUS_USB_CONTROL_RECV_FAILED);
	}
	else if (nBytesReceived == 0) // nothing received
	{
		// received empty message
		return (XN_STATUS_USB_NOT_ENOUGH_DATA);
	}
	else if ((XnUInt32)nBytesReceived > nBufferSize) // too much
	{
		xnLogWarning(XN_MASK_USB, "Too many bytes!!!");
		return (XN_STATUS_USB_TOO_MUCH_DATA);
	}

	// return number of bytes received
	*pnBytesReceived = nBytesReceived;

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBWriteEndPoint(XN_USB_EP_HANDLE pEPHandle, XnUChar* pBuffer, XnUInt32 nBufferSize, XnUInt32 nTimeOut)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_EP_HANDLE(pEPHandle);
	XN_VALIDATE_INPUT_PTR(pBuffer);

	if (pEPHandle->nDirection != XN_USB_DIRECTION_OUT)
	{
		return (XN_STATUS_USB_WRONG_ENDPOINT_DIRECTION);
	}

	if (nBufferSize == 0)
	{
		return (XN_STATUS_USB_BUFFER_TOO_SMALL);
	}

	// send (according to EP type)
	int nBytesSent = 0;
	int rc = 0;

	if (pEPHandle->nType == XN_USB_EP_BULK)
	{
		rc = libusb_bulk_transfer(pEPHandle->hDevice, pEPHandle->nAddress, pBuffer, nBufferSize, &nBytesSent, nTimeOut);
	}
	else if (pEPHandle->nType == XN_USB_EP_INTERRUPT)
	{
		rc = libusb_interrupt_transfer(pEPHandle->hDevice, pEPHandle->nAddress, pBuffer, nBufferSize, &nBytesSent, nTimeOut);
	}
	else
	{
		return (XN_STATUS_USB_UNSUPPORTED_ENDPOINT_TYPE);
	}

	// check result
	if (rc == LIBUSB_ERROR_TIMEOUT)
	{
		return (XN_STATUS_USB_TRANSFER_TIMEOUT);
	}
	else if (rc != 0)
	{
		return (XN_STATUS_USB_ENDPOINT_WRITE_FAILED);
	}

	if ((XnUInt32)nBytesSent != nBufferSize)
	{
		return (XN_STATUS_USB_GOT_UNEXPECTED_BYTES);
	}

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBReadEndPoint(XN_USB_EP_HANDLE pEPHandle, XnUChar* pBuffer, XnUInt32 nBufferSize, XnUInt32* pnBytesReceived, XnUInt32 nTimeOut)
{
	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_EP_HANDLE(pEPHandle);
	XN_VALIDATE_OUTPUT_PTR(pBuffer);
	XN_VALIDATE_OUTPUT_PTR(pnBytesReceived);

	if (pEPHandle->nDirection != XN_USB_DIRECTION_IN)
	{
		return (XN_STATUS_USB_WRONG_ENDPOINT_DIRECTION);
	}

	if (nBufferSize == 0)
	{
		return (XN_STATUS_USB_BUFFER_TOO_SMALL);
	}

	// receive (according to EP type)
	*pnBytesReceived = 0;

	int nBytesReceived = 0;
	int rc = 0;

	if (pEPHandle->nType == XN_USB_EP_BULK)
	{
		rc = libusb_bulk_transfer(pEPHandle->hDevice, pEPHandle->nAddress, pBuffer, nBufferSize, &nBytesReceived, nTimeOut);
	}
	else if (pEPHandle->nType == XN_USB_EP_INTERRUPT)
	{
		rc = libusb_interrupt_transfer(pEPHandle->hDevice, pEPHandle->nAddress, pBuffer, nBufferSize, &nBytesReceived, nTimeOut);
	}
	else
	{
		return (XN_STATUS_USB_UNSUPPORTED_ENDPOINT_TYPE);
	}

	// check result
	if (rc == LIBUSB_ERROR_TIMEOUT)
	{
		return (XN_STATUS_USB_TRANSFER_TIMEOUT);
	}
	else if (rc != 0)
	{
		return (XN_STATUS_USB_ENDPOINT_WRITE_FAILED);
	}

	if (nBytesReceived == 0)
	{
		return (XN_STATUS_USB_NOT_ENOUGH_DATA);
	}

	*pnBytesReceived = nBytesReceived;

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBQueueReadEndPoint(XN_USB_EP_HANDLE pEPHandle, XnUChar* pBuffer, XnUInt32 nBufferSize, XnUInt32 nTimeOut)
{
	return XN_STATUS_OS_UNSUPPORTED_FUNCTION;
}

XN_C_API XnStatus xnUSBFinishReadEndPoint(XN_USB_EP_HANDLE pEPHandle, XnUInt32* pnBytesReceived, XnUInt32 nTimeOut)
{
	return XN_STATUS_OS_UNSUPPORTED_FUNCTION;
}

void xnCleanupThreadData(XnUSBReadThreadData* pThreadData)
{
	for (XnUInt32 i = 0; i < pThreadData->nNumBuffers; ++i)
	{
		if (pThreadData->pBuffersInfo[i].transfer != NULL)
		{
			XN_ALIGNED_FREE_AND_NULL(pThreadData->pBuffersInfo[i].transfer->buffer);
			libusb_free_transfer(pThreadData->pBuffersInfo[i].transfer);
			pThreadData->pBuffersInfo[i].transfer = NULL;
			xnOSCloseEvent(&pThreadData->pBuffersInfo[i].hEvent);
		}
	}

	XN_ALIGNED_FREE_AND_NULL(pThreadData->pBuffersInfo);
}

/** Checks if any transfer of the thread is queued. */
XnBool xnIsAnyTransferQueued(XnUSBReadThreadData* pThreadData)
{
	for (XnUInt32 i = 0; i < pThreadData->nNumBuffers; ++i)
	{
		if (pThreadData->pBuffersInfo[i].bIsQueued)
			return (TRUE);
	}

	return (FALSE);
}

XN_THREAD_PROC xnUSBReadThreadMain(XN_THREAD_PARAM pThreadParam)
{
	XnUSBReadThreadData* pThreadData = (XnUSBReadThreadData*)pThreadParam;

	// set thread priority to critical
	XnStatus nRetVal = xnOSSetThreadPriority(pThreadData->hReadThread, XN_PRIORITY_CRITICAL);
	if (nRetVal != 0)
	{
		xnLogWarning(XN_MASK_USB, "Failed to set thread priority to critical. This might cause loss of data...");
	}

	// first of all, submit all transfers
	for (XnUInt32 i = 0; i < pThreadData->nNumBuffers; ++i)
	{
		XnUSBBuffersInfo* pBufferInfo = &pThreadData->pBuffersInfo[i];
		libusb_transfer* pTransfer = pBufferInfo->transfer;

		// submit request
		pBufferInfo->bIsQueued = TRUE;
		int rc = libusb_submit_transfer(pTransfer);
		if (rc != 0)
		{
			xnLogError(XN_MASK_USB, "Endpoint 0x%x, Buffer %d: Failed to submit asynch I/O transfer (err=%d)!", pTransfer->endpoint, pBufferInfo->nBufferID, rc);
		}
	}

	// now let libusb process asynchornous I/O

	while (TRUE)
	{
		for (XnUInt32 i = 0; i < pThreadData->nNumBuffers; ++i)
		{
			// check if thread can exit (only after kill was requested, and all transfers returned)
			if (pThreadData->bKillReadThread && !xnIsAnyTransferQueued(pThreadData))
			{
				XN_THREAD_PROC_RETURN(XN_STATUS_OK);
			}

			XnUSBBuffersInfo* pBufferInfo = &pThreadData->pBuffersInfo[i];
			libusb_transfer* pTransfer = pBufferInfo->transfer;

			// wait for the next transfer to be completed, and process it
			nRetVal = xnOSWaitEvent(pBufferInfo->hEvent, pThreadData->bKillReadThread ? 0 : pThreadData->nTimeOut);
			if (nRetVal == XN_STATUS_OS_EVENT_TIMEOUT)
			{
//				xnLogWarning(XN_MASK_USB, "Endpoint 0x%x, Buffer %d: timeout. cancelling transfer...", pTransfer->endpoint, pBufferInfo->nBufferID);

				// cancel it
				int rc = libusb_cancel_transfer(pBufferInfo->transfer);
				if (rc != 0)
				{
					xnLogError(XN_MASK_USB, "Endpoint 0x%x, Buffer %d: Failed to cancel asynch I/O transfer (err=%d)!", pTransfer->endpoint, pBufferInfo->nBufferID, rc);
				}

				// wait for it to cancel
				nRetVal = xnOSWaitEvent(pBufferInfo->hEvent, XN_WAIT_INFINITE);
			}

			if (nRetVal != XN_STATUS_OK)
			{
				// not much we can do
				xnLogWarning(XN_MASK_USB, "Endpoint 0x%x, Buffer %d: Failed waiting on asynch transfer event: %s", pTransfer->endpoint, pBufferInfo->nBufferID, xnGetStatusString(nRetVal));
			}

			// check the result of the transfer
			if (pBufferInfo->bIsQueued)
			{
				xnLogWarning(XN_MASK_USB, "Endpoint 0x%x, Buffer %d: Transfer is still queued though event was raised!", pTransfer->endpoint, pBufferInfo->nBufferID);
				// TODO: cancel it?
			}
			else // transfer done
			{
				if (pBufferInfo->nLastStatus == LIBUSB_TRANSFER_COMPLETED || // read succeeded
					pBufferInfo->nLastStatus == LIBUSB_TRANSFER_CANCELLED)   // cancelled, but maybe some data arrived
				{
					if (pTransfer->type == LIBUSB_TRANSFER_TYPE_ISOCHRONOUS)
					{
						XnUInt32 nTotalBytes = 0;

						// some packets may return empty, so we need to remove spaces, and make the buffer sequential
						for (XnInt32 i = 0; i < pTransfer->num_iso_packets; ++i)
						{
							struct libusb_iso_packet_descriptor* pPacket = &pTransfer->iso_packet_desc[i];
							if (pPacket->status == LIBUSB_TRANSFER_COMPLETED && pPacket->actual_length != 0)
							{
								XnUChar* pBuffer = libusb_get_iso_packet_buffer_simple(pTransfer, i);
								// if buffer is not at same offset, move it
								if (pTransfer->buffer + nTotalBytes != pBuffer)
								{
//									printf("buffer %d has %d bytes. Moving to offset %d...\n", i, pPacket->actual_length, nTotalBytes);
									memmove(pTransfer->buffer + nTotalBytes, pBuffer, pPacket->actual_length);
								}
								nTotalBytes += pPacket->actual_length;
							}
							else if (pPacket->status != LIBUSB_TRANSFER_COMPLETED)
							{
								xnLogWarning(XN_MASK_USB, "Endpoint 0x%x, Buffer %d, packet %d Asynch transfer failed (status: %d)", pTransfer->endpoint, pBufferInfo->nBufferID, i, pPacket->status);
							}
						}

						if (nTotalBytes != 0)
						{
							// call callback method
							pBufferInfo->pThreadData->pCallbackFunction(pTransfer->buffer, nTotalBytes, pBufferInfo->pThreadData->pCallbackData);
						}
					}
					else
					{
						// call callback method
						pBufferInfo->pThreadData->pCallbackFunction(pTransfer->buffer, pTransfer->actual_length, pBufferInfo->pThreadData->pCallbackData);
					}
				}
				else if (pBufferInfo->nLastStatus == LIBUSB_TRANSFER_TIMED_OUT)
				{
					// no need to do anything.
				}
				else
				{
					xnLogWarning(XN_MASK_USB, "Endpoint 0x%x, Buffer %d: Asynch transfer failed (status: %d)", pTransfer->endpoint, pBufferInfo->nBufferID, pTransfer->status);
				}

				// as long as running should continue, resubmit transfer
				if (!pBufferInfo->pThreadData->bKillReadThread)
				{
					pBufferInfo->bIsQueued = TRUE;
					int rc = libusb_submit_transfer(pTransfer);
					if (rc != 0)
					{
						xnLogError(XN_MASK_USB, "Endpoint 0x%x, Buffer %d: Failed to re-submit asynch I/O transfer (err=%d)!", pTransfer->endpoint, pBufferInfo->nBufferID, rc);
						if (rc == LIBUSB_ERROR_NO_DEVICE)
						{
							for (XnUSBEventCallbackList::Iterator it = g_connectivityEvent.Begin(); it != g_connectivityEvent.End(); ++it)
							{
								XnUSBEventCallback* pCallback = *it;
								XnUSBEventArgs args;
								args.strDevicePath = NULL;
								args.eventType = XN_USB_EVENT_DEVICE_DISCONNECT;
								pCallback->pFunc(&args, pCallback->pCookie);
							}
						}

					}
				}
			}
		}
	}

	XN_THREAD_PROC_RETURN(XN_STATUS_OK);
}

/* This function is called whenever transfer is done (successfully or with an error). */
void xnTransferCallback(libusb_transfer *pTransfer)
{
	XnUSBBuffersInfo* pBufferInfo = (XnUSBBuffersInfo*)pTransfer->user_data;

	// mark that buffer is done
	pBufferInfo->bIsQueued = FALSE;

	// keep the status (according to libusb documentation, this field is invalid outside the callback method)
	pBufferInfo->nLastStatus = pTransfer->status;

	// notify endpoint thread this buffer is done
	XnStatus nRetVal = xnOSSetEvent(pBufferInfo->hEvent);
	if (nRetVal != XN_STATUS_OK)
	{
		// we don't have much to do if set event failed, log a warning
		xnLogWarning(XN_MASK_USB, "Failed to set event for buffer: %s", xnGetStatusString(nRetVal));
	}
}

XN_C_API XnStatus xnUSBInitReadThread(XN_USB_EP_HANDLE pEPHandle, XnUInt32 nBufferSize, XnUInt32 nNumBuffers, XnUInt32 nTimeOut, XnUSBReadCallbackFunctionPtr pCallbackFunction, void* pCallbackData)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// validate parameters
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_EP_HANDLE(pEPHandle);
	XN_VALIDATE_INPUT_PTR(pCallbackFunction);

	xnLogVerbose(XN_MASK_USB, "Starting a USB read thread...");

	XnUSBReadThreadData* pThreadData = &pEPHandle->ThreadData;

	if (pThreadData->bIsRunning == TRUE)
	{
		return (XN_STATUS_USB_READTHREAD_ALREADY_INIT);
	}

	memset(pThreadData, 0, sizeof(XnUSBReadThreadData));
	pThreadData->nNumBuffers = nNumBuffers;
	pThreadData->pCallbackFunction = pCallbackFunction;
	pThreadData->pCallbackData = pCallbackData;
	pThreadData->bKillReadThread = FALSE;
	pThreadData->nTimeOut = nTimeOut;

	// allocate buffers
	pThreadData->pBuffersInfo = (XnUSBBuffersInfo*)xnOSCallocAligned(nNumBuffers, sizeof(XnUSBBuffersInfo), XN_DEFAULT_MEM_ALIGN);
	if (pThreadData->pBuffersInfo == NULL)
	{
		xnCleanupThreadData(pThreadData);
		return XN_STATUS_ALLOC_FAILED;
	}

	int nNumIsoPackets = 0;
	int nMaxPacketSize = 0;

	if (pEPHandle->nType == XN_USB_EP_ISOCHRONOUS)
	{
		// calculate how many packets can be set in this buffer
		nMaxPacketSize = pEPHandle->nMaxPacketSize;
		nNumIsoPackets = nBufferSize / nMaxPacketSize;
	}

	for (XnUInt32 i = 0; i < nNumBuffers; i++)
	{
		XnUSBBuffersInfo* pBufferInfo = &pThreadData->pBuffersInfo[i];
		pBufferInfo->nBufferID = i;
		pBufferInfo->pThreadData = pThreadData;

		// allocate transfer
		pBufferInfo->transfer = libusb_alloc_transfer(nNumIsoPackets);

		libusb_transfer* pTransfer = pBufferInfo->transfer;

		if (pTransfer == NULL)
		{
			xnCleanupThreadData(pThreadData);
			return (XN_STATUS_ALLOC_FAILED);
		}

		// allocate buffer
		XnUChar* pBuffer = (unsigned char*)xnOSCallocAligned(nBufferSize, sizeof(XnUChar), XN_DEFAULT_MEM_ALIGN);
		if (pBuffer == NULL)
		{
			xnCleanupThreadData(pThreadData);
			return (XN_STATUS_ALLOC_FAILED);
		}

		// fill transfer params
		if (pEPHandle->nType == XN_USB_EP_BULK)
		{
			libusb_fill_bulk_transfer(pTransfer, pEPHandle->hDevice, pEPHandle->nAddress, pBuffer, nBufferSize, xnTransferCallback, pBufferInfo, 0);
		}
		else if (pEPHandle->nType == XN_USB_EP_INTERRUPT)
		{
			libusb_fill_interrupt_transfer(pTransfer, pEPHandle->hDevice, pEPHandle->nAddress, pBuffer, nBufferSize, xnTransferCallback, pBufferInfo, 0);
		}
		else if (pEPHandle->nType == XN_USB_EP_ISOCHRONOUS)
		{
			libusb_fill_iso_transfer(pTransfer, pEPHandle->hDevice, pEPHandle->nAddress, pBuffer, nBufferSize, nNumIsoPackets, xnTransferCallback, pBufferInfo, 0);
			libusb_set_iso_packet_lengths(pTransfer, nMaxPacketSize);
		}
		else
		{
			return (XN_STATUS_USB_UNSUPPORTED_ENDPOINT_TYPE);
		}

		// create event
		nRetVal = xnOSCreateEvent(&pBufferInfo->hEvent,FALSE);
		if (nRetVal != XN_STATUS_OK)
		{
			xnCleanupThreadData(pThreadData);
			return (nRetVal);
		}
	}

	// create a thread to perform the asynchronous read operations
	nRetVal = xnOSCreateThread(xnUSBReadThreadMain, &pEPHandle->ThreadData, &pThreadData->hReadThread);
	if (nRetVal != XN_STATUS_OK)
	{
		xnCleanupThreadData(pThreadData);
		return (nRetVal);
	}

	pThreadData->bIsRunning = TRUE;

	xnLogInfo(XN_MASK_USB, "USB read thread was started.");

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBShutdownReadThread(XN_USB_EP_HANDLE pEPHandle)
{
	XN_VALIDATE_USB_INIT();
	XN_VALIDATE_EP_HANDLE(pEPHandle);

	XnUSBReadThreadData* pThreadData = &pEPHandle->ThreadData;

	if (pThreadData->bIsRunning == FALSE)
	{
		return (XN_STATUS_USB_READTHREAD_NOT_INIT);
	}

	if (pThreadData->hReadThread != NULL)
	{
		// mark thread should be killed
		pThreadData->bKillReadThread = TRUE;

		// PATCH: we don't cancel the requests, because there is a bug causing segmentation fault.
#if XN_PLATFORM == XN_PLATFORM_ANDROID_ARM
		// cancel all pending requests
		for (XnUInt32 i = 0; i < pThreadData->nNumBuffers; ++i)
		{
			if (pThreadData->pBuffersInfo[i].bIsQueued)
			{
				libusb_cancel_transfer(pThreadData->pBuffersInfo[i].transfer);
				// NOTE: we don't check error code. In any case we still need to wait for all transfers to complete. If cancelling was succeeded, they will
				// return immediately. If not, they will reach timeout and return
			}
		}
#endif

		// now wait for thread to exit (we wait the timeout of all buffers + an extra second)
		XnStatus nRetVal = xnOSWaitForThreadExit(pThreadData->hReadThread, pThreadData->nTimeOut * pThreadData->nNumBuffers + 1000);
		if (nRetVal != XN_STATUS_OK)
		{
			xnOSTerminateThread(&pThreadData->hReadThread);
		}
		else
		{
			xnOSCloseThread(&pThreadData->hReadThread);
		}
	}

	xnCleanupThreadData(pThreadData);

	pThreadData->bIsRunning = FALSE;

	return (XN_STATUS_OK);
}

XN_C_API XnStatus xnUSBSetCallbackHandler(XnUInt16 nVendorID, XnUInt16 /*nProductID*/, void* pExtraParam, XnUSBEventCallbackFunctionPtr pCallbackFunction, void* pCallbackData)
{
	return (XN_STATUS_OS_UNSUPPORTED_FUNCTION);
}

XN_C_API XnStatus XN_C_DECL xnUSBRegisterToConnectivityEvents(XnUInt16 nVendorID, XnUInt16 nProductID, XnUSBDeviceCallbackFunctionPtr pFunc, void* pCookie, XnRegistrationHandle* phRegistration)
{
	XnStatus nRetVal = XN_STATUS_OK;

	XN_VALIDATE_INPUT_PTR(pFunc);
	XN_VALIDATE_OUTPUT_PTR(phRegistration);

	XnUSBEventCallback* pCallback;
	XN_VALIDATE_NEW(pCallback, XnUSBEventCallback);
	pCallback->pFunc = pFunc;
	pCallback->pCookie = pCookie;

	nRetVal = g_connectivityEvent.AddLast(pCallback);
	if (nRetVal != XN_STATUS_OK)
	{
		XN_DELETE(pCallback);
		return (nRetVal);
	}

	*phRegistration = (XnRegistrationHandle)pCallback;

	return XN_STATUS_OK;
}

XN_C_API void XN_C_DECL xnUSBUnregisterFromConnectivityEvents(XnRegistrationHandle hRegistration)
{
	XnUSBEventCallback* pCallback = reinterpret_cast<XnUSBEventCallback*>(hRegistration);
	XnUSBEventCallbackList::Iterator it = g_connectivityEvent.Find(pCallback);
	if (it != g_connectivityEvent.End())
	{
		g_connectivityEvent.Remove(it);
		XN_DELETE(pCallback);
	}
}


text:
package com.eaw1805.www.client.events.map;

import com.google.gwt.event.shared.EventHandler;

public interface ZoomHandler
        extends EventHandler {

    void onZoom(final ZoomEvent event);

}

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Getreue Darstell. Gew. 9: t. 7. 1825

#### Original name
null

### Remarks
null


text:
package com.twitter.finagle.netty3

import com.twitter.io.Buf
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.jboss.netty.buffer.ChannelBuffers

@RunWith(classOf[JUnitRunner])
class BufTest extends FunSuite {
  test("ChannelBufferBuf.slice: slices according to the underlying ChannelBuffer") {
    val cb = ChannelBuffers.buffer(128)
    cb.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    val buf = ChannelBufferBuf.Owned(cb)
    assert(buf.length === 9)
    assert(buf.slice(2,4) === Buf.ByteArray(3,4))
    assert(buf === Buf.ByteArray(1,2,3,4,5,6,7,8,9))
  }

  test("ChannelBufferBuf.slice: truncates on out-of-bounds indices") {
    val cb = ChannelBuffers.buffer(128)
    cb.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    val buf = ChannelBufferBuf.Owned(cb)
    buf.slice(1, Int.MaxValue)
  }

  test("ChannelBufferBuf.Shared.apply") {
    val bytes = Array[Byte](1,2,3,4,5,6,7,8,9)
    val cb = ChannelBuffers.wrappedBuffer(bytes)
    val buf = ChannelBufferBuf.Shared(cb)
    bytes(0) = 0.toByte
    assert(buf === Buf.ByteArray(1,2,3,4,5,6,7,8,9))
    cb.clear()
    assert(buf === Buf.ByteArray(1,2,3,4,5,6,7,8,9))
  }

  test("ChannelBufferBuf.Direct.apply") {
    val bytes = Array[Byte](1,2,3,4,5,6,7,8,9)
    val cb = ChannelBuffers.wrappedBuffer(bytes)
    val buf = ChannelBufferBuf.Owned(cb)
    bytes(0) = 0.toByte
    assert(buf === Buf.ByteArray(0,2,3,4,5,6,7,8,9))
    cb.clear()
    assert(buf.length === 0)
  }

  test("ChannelBufferBuf.Shared.unapply") {
    val cb0 = ChannelBuffers.buffer(128)
    cb0.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    val ChannelBufferBuf.Shared(cb1) = ChannelBufferBuf.Owned(cb0)
    cb0.clear()
    assert(cb1.readableBytes() === 9)
  }

  test("ChannelBufferBuf.Direct.unapply") {
    val cb0 = ChannelBuffers.buffer(128)
    cb0.writeBytes(Array[Byte](1,2,3,4,5,6,7,8,9))
    val ChannelBufferBuf.Owned(cb1) = ChannelBufferBuf.Owned(cb0)
    cb0.clear()
    assert(cb1.readableBytes() === 0)
  }

  test("ChannelBufferBuf.coerce(ChannelBufferBuf)") {
    val cb = ChannelBuffers.wrappedBuffer(Array[Byte](1,2,3,4,5,6,7,8,9))
    val orig = ChannelBufferBuf.Owned(cb)
    val coerced = ChannelBufferBuf.coerce(orig)
    assert(coerced eq orig)
  }

  test("ChannelBufferBuf.coerce(ByteArray)") {
    val orig = Buf.ByteArray(1,2,3,4,5,6,7,8,9)
    val coerced = ChannelBufferBuf.coerce(orig)
    assert(coerced === orig)
  }

  test("ByteArray.coerce(ChannelBufferBuf)") {
    val orig = ChannelBufferBuf.Owned(
      ChannelBuffers.wrappedBuffer(Array[Byte](1,2,3,4,5,6,7,8,9), 2, 4))
    val coerced = Buf.ByteArray.coerce(orig)
    assert(coerced === orig)
    val Buf.ByteArray.Owned(bytes, begin, end) = coerced
    assert(bytes.length === 9)
    assert(begin === 2)
    assert(end === 6)
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>ViolatedConstraintNameExtracter (Hibernate JavaDocs)</title>
<meta name="date" content="2014-03-03">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.hibernate.exception.spi

Interface ViolatedConstraintNameExtracter

All Known Implementing Classes:

TemplatedViolatedConstraintNameExtracter

public interface ViolatedConstraintNameExtracter

Defines a contract for implementations that can extract the name of a violated
constraint from a SQLException that is the result of that constraint violation.

Method Summary

Methods

Modifier and Type
Method and Description

String
extractConstraintName(SQLException sqle)

Method Detail

extractConstraintName

String extractConstraintName(SQLException sqle)

Extract the name of the violated constraint from the given SQLException.

Parameters:

sqle - The exception that was the result of the constraint violation.

Returns:

The extracted constraint name.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2001-2014 Red Hat, Inc.  All Rights Reserved.


text:
layout: post
title: "Find (and kill) all processes listening on a port"
date: "2016-04-26 23:56:37 -0400"
---

To search for processes that listen on a specific port use the `lsof` or "List Open Files". The `-n` argument makes the command run faster by preventing it from doing a ip to hostname conversion. Use grep to show only lines containing the word LISTEN.

```bash
lsof -n | grep LISTEN
```

To filter for a specific port use the following:

```bash
lsof -n -i4TCP:[PORT] | grep LISTEN
```

To kill all processes listening on a specific port use:

```bash
lsof -n -i4TCP:[PORT] | grep LISTEN | awk '{ print $2 }' | xargs kill
```

The `awk` command returns only the second column (PID), and the `xargs` executes `kill` on each line returned.


text:
#include <sstream>

#include "gazebo/msgs/msgs.hh"

#include "gazebo/transport/TransportIface.hh"
#include "gazebo/transport/Node.hh"
#include "gazebo/transport/Publisher.hh"

#include "gazebo/util/OpenAL.hh"
#include "gazebo/common/Events.hh"
#include "gazebo/math/Quaternion.hh"
#include "gazebo/common/Console.hh"
#include "gazebo/common/Exception.hh"
#include "gazebo/common/Assert.hh"

#include "gazebo/sensors/SensorsIface.hh"
#include "gazebo/sensors/Sensor.hh"

#include "gazebo/physics/PhysicsIface.hh"
#include "gazebo/physics/Model.hh"
#include "gazebo/physics/World.hh"
#include "gazebo/physics/ContactManager.hh"
#include "gazebo/physics/PhysicsEngine.hh"
#include "gazebo/physics/Collision.hh"
#include "gazebo/physics/Link.hh"

using namespace gazebo;
using namespace physics;

//////////////////////////////////////////////////
Link::Link(EntityPtr _parent)
    : Entity(_parent)
{
  this->AddType(Base::LINK);
  this->inertial.reset(new Inertial);
  this->parentJoints.clear();
  this->childJoints.clear();
  this->publishData = false;
  this->publishDataMutex = new boost::recursive_mutex();
}

//////////////////////////////////////////////////
Link::~Link()
{
  this->attachedModels.clear();

  for (Visuals_M::iterator iter = this->visuals.begin();
      iter != this->visuals.end(); ++iter)
  {
    msgs::Visual msg;
    msg.set_name(iter->second.name());
    msg.set_id(iter->second.id());
    if (this->parent)
    {
      msg.set_parent_name(this->parent->GetScopedName());
      msg.set_parent_id(this->parent->GetId());
    }
    else
    {
      msg.set_parent_name("");
      msg.set_parent_id(0);
    }
    msg.set_delete_me(true);
    this->visPub->Publish(msg);
  }
  this->visuals.clear();

  if (this->cgVisuals.size() > 0)
  {
    for (unsigned int i = 0; i < this->cgVisuals.size(); i++)
    {
      msgs::Visual msg;
      msg.set_name(this->cgVisuals[i]);
      if (this->parent)
        msg.set_parent_name(this->parent->GetScopedName());
      else
        msg.set_parent_name("");
      msg.set_delete_me(true);
      this->visPub->Publish(msg);
    }
    this->cgVisuals.clear();
  }

  this->visPub.reset();
  this->sensors.clear();

  this->requestPub.reset();
  this->dataPub.reset();
  this->connections.clear();

  delete this->publishDataMutex;
  this->publishDataMutex = NULL;

  this->collisions.clear();
}

//////////////////////////////////////////////////
void Link::Load(sdf::ElementPtr _sdf)
{
  bool needUpdate = false;

  Entity::Load(_sdf);

  // before loading child collsion, we have to figure out of selfCollide is true
  // and modify parent class Entity so this body has its own spaceId
  this->SetSelfCollide(this->sdf->Get<bool>("self_collide"));
  this->sdf->GetElement("self_collide")->GetValue()->SetUpdateFunc(
      boost::bind(&Link::GetSelfCollide, this));

  // Parse visuals from SDF
  this->ParseVisuals();

  // Load the geometries
  if (this->sdf->HasElement("collision"))
  {
    sdf::ElementPtr collisionElem = this->sdf->GetElement("collision");
    while (collisionElem)
    {
      // Create and Load a collision, which will belong to this body.
      this->LoadCollision(collisionElem);
      collisionElem = collisionElem->GetNextElement("collision");
    }
  }

  if (this->sdf->HasElement("sensor"))
  {
    sdf::ElementPtr sensorElem = this->sdf->GetElement("sensor");
    while (sensorElem)
    {
      /// \todo This if statement is a hack to prevent Links from creating
      /// a force torque sensor. We should make this more generic.
      if (sensorElem->Get<std::string>("type") == "force_torque")
      {
        gzerr << "A link cannot load a [" <<
          sensorElem->Get<std::string>("type") << "] sensor.\n";
      }
      else if (sensorElem->Get<std::string>("type") != "__default__")
      {
        std::string sensorName =
          sensors::create_sensor(sensorElem, this->GetWorld()->GetName(),
              this->GetScopedName(), this->GetId());
        this->sensors.push_back(sensorName);
      }
      sensorElem = sensorElem->GetNextElement("sensor");
    }
  }

  if (!this->IsStatic())
  {
    this->inertial->Load(this->sdf->GetElement("inertial"));
  }

#ifdef HAVE_OPENAL
  if (_sdf->HasElement("audio_source"))
  {
    // bool onContact = false;
    sdf::ElementPtr audioElem = this->sdf->GetElement("audio_source");
    std::vector<std::string> collisionNames;

    while (audioElem)
    {
      util::OpenALSourcePtr source = util::OpenAL::Instance()->CreateSource(
          audioElem);

      std::vector<std::string> names = source->GetCollisionNames();
      std::copy(names.begin(), names.end(), std::back_inserter(collisionNames));

      audioElem = audioElem->GetNextElement("audio_source");
      this->audioSources.push_back(source);
    }

    if (!collisionNames.empty())
    {
      for (std::vector<std::string>::iterator iter = collisionNames.begin();
          iter != collisionNames.end(); ++iter)
      {
        (*iter) = this->GetScopedName() + "::" + (*iter);
      }

      std::string topic =
        this->world->GetPhysicsEngine()->GetContactManager()->CreateFilter(
            this->GetScopedName() + "/audio_collision", collisionNames);
      this->audioContactsSub = this->node->Subscribe(topic,
          &Link::OnCollision, this);
    }

    needUpdate = true;
  }

  if (_sdf->HasElement("audio_sink"))
  {
    needUpdate = true;
    this->audioSink = util::OpenAL::Instance()->CreateSink(
        _sdf->GetElement("audio_sink"));
  }
#endif

  if (needUpdate)
    this->connections.push_back(event::Events::ConnectWorldUpdateBegin(
          boost::bind(&Link::Update, this, _1)));
}

//////////////////////////////////////////////////
void Link::Init()
{
  this->linearAccel.Set(0, 0, 0);
  this->angularAccel.Set(0, 0, 0);

  this->enabled = true;

  // Set Link pose before setting pose of child collisions
  this->SetRelativePose(this->sdf->Get<math::Pose>("pose"));
  this->SetInitialRelativePose(this->sdf->Get<math::Pose>("pose"));

  // Call Init for child collisions, which whill set their pose
  Base_V::iterator iter;
  for (iter = this->children.begin(); iter != this->children.end(); ++iter)
  {
    if ((*iter)->HasType(Base::COLLISION))
    {
      CollisionPtr collision = boost::static_pointer_cast<Collision>(*iter);
      this->collisions.push_back(collision);
      collision->Init();
    }
  }
}

//////////////////////////////////////////////////
void Link::Fini()
{
  this->parentJoints.clear();
  this->childJoints.clear();
  this->collisions.clear();
  this->inertial.reset();

  for (std::vector<std::string>::iterator iter = this->sensors.begin();
       iter != this->sensors.end(); ++iter)
  {
    sensors::remove_sensor(*iter);
  }
  this->sensors.clear();

  for (Visuals_M::iterator iter = this->visuals.begin();
       iter != this->visuals.end(); ++iter)
  {
    msgs::Request *msg = msgs::CreateRequest("entity_delete",
        boost::lexical_cast<std::string>(iter->second.id()));
    this->requestPub->Publish(*msg, true);
  }

  for (std::vector<std::string>::iterator iter = this->cgVisuals.begin();
       iter != this->cgVisuals.end(); ++iter)
  {
    msgs::Request *msg = msgs::CreateRequest("entity_delete", *iter);
    this->requestPub->Publish(*msg, true);
  }

#ifdef HAVE_OPENAL
  this->audioSink.reset();
#endif

  Entity::Fini();
}

//////////////////////////////////////////////////
void Link::Reset()
{
  // resets pose
  Entity::Reset();

  // resets velocity, acceleration, wrench
  this->ResetPhysicsStates();
}

//////////////////////////////////////////////////
void Link::ResetPhysicsStates()
{
  this->SetAngularVel(math::Vector3(0, 0, 0));
  this->SetLinearVel(math::Vector3(0, 0, 0));
  this->SetAngularAccel(math::Vector3(0, 0, 0));
  this->SetLinearAccel(math::Vector3(0, 0, 0));
  this->SetForce(math::Vector3(0, 0, 0));
  this->SetTorque(math::Vector3(0, 0, 0));
}

//////////////////////////////////////////////////
void Link::UpdateParameters(sdf::ElementPtr _sdf)
{
  Entity::UpdateParameters(_sdf);

  if (this->sdf->HasElement("inertial"))
  {
    sdf::ElementPtr inertialElem = this->sdf->GetElement("inertial");
    this->inertial->UpdateParameters(inertialElem);
  }

  this->sdf->GetElement("gravity")->GetValue()->SetUpdateFunc(
      boost::bind(&Link::GetGravityMode, this));
  this->sdf->GetElement("kinematic")->GetValue()->SetUpdateFunc(
      boost::bind(&Link::GetKinematic, this));

  if (this->sdf->Get<bool>("gravity") != this->GetGravityMode())
    this->SetGravityMode(this->sdf->Get<bool>("gravity"));

  // before loading child collsiion, we have to figure out if
  // selfCollide is true and modify parent class Entity so this
  // body has its own spaceId
  this->SetSelfCollide(this->sdf->Get<bool>("self_collide"));

  // TODO: this shouldn't be in the physics sim
  if (this->sdf->HasElement("visual"))
  {
    sdf::ElementPtr visualElem = this->sdf->GetElement("visual");
    while (visualElem)
    {
      // TODO: Update visuals properly
      msgs::Visual msg = msgs::VisualFromSDF(visualElem);

      msg.set_name(this->GetScopedName() + "::" + msg.name());
      msg.set_parent_name(this->GetScopedName());
      msg.set_is_static(this->IsStatic());

      this->visPub->Publish(msg);

      visualElem = visualElem->GetNextElement("visual");
    }
  }

  if (this->sdf->HasElement("collision"))
  {
    sdf::ElementPtr collisionElem = this->sdf->GetElement("collision");
    while (collisionElem)
    {
      CollisionPtr collision = boost::dynamic_pointer_cast<Collision>(
          this->GetChild(collisionElem->Get<std::string>("name")));

      if (collision)
        collision->UpdateParameters(collisionElem);
      collisionElem = collisionElem->GetNextElement("collision");
    }
  }
}

//////////////////////////////////////////////////
void Link::SetCollideMode(const std::string &_mode)
{
  unsigned int categoryBits;
  unsigned int collideBits;

  if (_mode == "all")
  {
    categoryBits =  GZ_ALL_COLLIDE;
    collideBits =  GZ_ALL_COLLIDE;
  }
  else if (_mode == "none")
  {
    categoryBits =  GZ_NONE_COLLIDE;
    collideBits =  GZ_NONE_COLLIDE;
  }
  else if (_mode == "sensors")
  {
    categoryBits = GZ_SENSOR_COLLIDE;
    collideBits = ~GZ_SENSOR_COLLIDE;
  }
  else if (_mode == "fixed")
  {
    categoryBits = GZ_FIXED_COLLIDE;
    collideBits = ~GZ_FIXED_COLLIDE;
  }
  else if (_mode == "ghost")
  {
    categoryBits = GZ_GHOST_COLLIDE;
    collideBits = ~GZ_GHOST_COLLIDE;
  }
  else
  {
    gzerr << "Unknown collide mode[" << _mode << "]\n";
    return;
  }

  for (Collision_V::iterator iter = this->collisions.begin();
       iter != this->collisions.end(); ++iter)
  {
    if ((*iter))
    {
      (*iter)->SetCategoryBits(categoryBits);
      (*iter)->SetCollideBits(collideBits);
    }
  }
}

//////////////////////////////////////////////////
bool Link::GetSelfCollide() const
{
  GZ_ASSERT(this->sdf != NULL, "Link sdf member is NULL");
  if (this->sdf->HasElement("self_collide"))
    return this->sdf->Get<bool>("self_collide");
  else
    return false;
}

//////////////////////////////////////////////////
void Link::SetLaserRetro(float _retro)
{
  for (Collision_V::iterator iter = this->collisions.begin();
       iter != this->collisions.end(); ++iter)
  {
    (*iter)->SetLaserRetro(_retro);
  }
}

//////////////////////////////////////////////////
void Link::Update(const common::UpdateInfo & /*_info*/)
{
#ifdef HAVE_OPENAL
  if (this->audioSink)
  {
    this->audioSink->SetPose(this->GetWorldPose());
    this->audioSink->SetVelocity(this->GetWorldLinearVel());
  }

  // Update all the audio sources
  for (std::vector<util::OpenALSourcePtr>::iterator iter =
      this->audioSources.begin(); iter != this->audioSources.end(); ++iter)
  {
    (*iter)->SetPose(this->GetWorldPose());
    (*iter)->SetVelocity(this->GetWorldLinearVel());
  }
#endif

  // Apply our linear accel
  // this->SetForce(this->linearAccel);

  // Apply our angular accel
  // this->SetTorque(this->angularAccel);

  // FIXME: race condition on factory-based model loading!!!!!
   /*if (this->GetEnabled() != this->enabled)
   {
     this->enabled = this->GetEnabled();
     this->enabledSignal(this->enabled);
   }*/
}

/////////////////////////////////////////////////
Joint_V Link::GetParentJoints() const
{
  return this->parentJoints;
}

/////////////////////////////////////////////////
Joint_V Link::GetChildJoints() const
{
  return this->childJoints;
}

/////////////////////////////////////////////////
Link_V Link::GetChildJointsLinks() const
{
  Link_V links;
  for (std::vector<JointPtr>::const_iterator iter = this->childJoints.begin();
                                             iter != this->childJoints.end();
                                             ++iter)
  {
    if ((*iter)->GetChild())
      links.push_back((*iter)->GetChild());
  }
  return links;
}

/////////////////////////////////////////////////
Link_V Link::GetParentJointsLinks() const
{
  Link_V links;
  for (std::vector<JointPtr>::const_iterator iter = this->parentJoints.begin();
                                             iter != this->parentJoints.end();
                                             ++iter)
  {
    if ((*iter)->GetParent())
      links.push_back((*iter)->GetParent());
  }
  return links;
}

//////////////////////////////////////////////////
void Link::LoadCollision(sdf::ElementPtr _sdf)
{
  CollisionPtr collision;
  std::string geomType =
    _sdf->GetElement("geometry")->GetFirstElement()->GetName();

  if (geomType == "heightmap" || geomType == "map")
    this->SetStatic(true);

  collision = this->GetWorld()->GetPhysicsEngine()->CreateCollision(geomType,
      boost::static_pointer_cast<Link>(shared_from_this()));

  if (!collision)
    gzthrow("Unknown Collisionetry Type[" + geomType + "]");

  collision->Load(_sdf);
}

//////////////////////////////////////////////////
CollisionPtr Link::GetCollisionById(unsigned int _id) const
{
  return boost::dynamic_pointer_cast<Collision>(this->GetById(_id));
}

//////////////////////////////////////////////////
CollisionPtr Link::GetCollision(const std::string &_name)
{
  CollisionPtr result;
  Base_V::const_iterator biter;
  for (biter = this->children.begin(); biter != this->children.end(); ++biter)
  {
    if ((*biter)->GetName() == _name)
    {
      result = boost::dynamic_pointer_cast<Collision>(*biter);
      break;
    }
  }

  return result;
}

//////////////////////////////////////////////////
Collision_V Link::GetCollisions() const
{
  return this->collisions;
}

//////////////////////////////////////////////////
CollisionPtr Link::GetCollision(unsigned int _index) const
{
  CollisionPtr collision;
  if (_index <= this->GetChildCount())
    collision = boost::static_pointer_cast<Collision>(this->GetChild(_index));
  else
    gzerr << "Index is out of range\n";

  return collision;
}

//////////////////////////////////////////////////
void Link::SetLinearAccel(const math::Vector3 &_accel)
{
  this->SetEnabled(true);
  this->linearAccel = _accel;
}

//////////////////////////////////////////////////
void Link::SetAngularAccel(const math::Vector3 &_accel)
{
  this->SetEnabled(true);
  this->angularAccel = _accel * this->inertial->GetMass();
}

//////////////////////////////////////////////////
math::Pose Link::GetWorldCoGPose() const
{
  math::Pose pose = this->GetWorldPose();
  pose.pos += pose.rot.RotateVector(this->inertial->GetCoG());
  return pose;
}

//////////////////////////////////////////////////
math::Vector3 Link::GetRelativeLinearVel() const
{
  return this->GetWorldPose().rot.RotateVectorReverse(
      this->GetWorldLinearVel());
}

//////////////////////////////////////////////////
math::Vector3 Link::GetRelativeAngularVel() const
{
  return this->GetWorldPose().rot.RotateVectorReverse(
         this->GetWorldAngularVel());
}

//////////////////////////////////////////////////
math::Vector3 Link::GetRelativeLinearAccel() const
{
  return this->GetRelativeForce() / this->inertial->GetMass();
}

//////////////////////////////////////////////////
math::Vector3 Link::GetWorldLinearAccel() const
{
  return this->GetWorldForce() / this->inertial->GetMass();
}

//////////////////////////////////////////////////
math::Vector3 Link::GetRelativeAngularAccel() const
{
  return this->GetRelativeTorque() / this->inertial->GetMass();
}

//////////////////////////////////////////////////
math::Vector3 Link::GetWorldAngularAccel() const
{
  return this->GetWorldTorque() / this->inertial->GetMass();
}

//////////////////////////////////////////////////
math::Vector3 Link::GetRelativeForce() const
{
  return this->GetWorldPose().rot.RotateVectorReverse(this->GetWorldForce());
}

//////////////////////////////////////////////////
math::Vector3 Link::GetRelativeTorque() const
{
  return this->GetWorldPose().rot.RotateVectorReverse(this->GetWorldTorque());
}

//////////////////////////////////////////////////
ModelPtr Link::GetModel() const
{
  return boost::dynamic_pointer_cast<Model>(this->GetParent());
}

//////////////////////////////////////////////////
math::Box Link::GetBoundingBox() const
{
  math::Box box;

  box.min.Set(GZ_DBL_MAX, GZ_DBL_MAX, GZ_DBL_MAX);
  box.max.Set(0, 0, 0);

  for (Collision_V::const_iterator iter = this->collisions.begin();
       iter != this->collisions.end(); ++iter)
  {
    box += (*iter)->GetBoundingBox();
  }

  return box;
}

//////////////////////////////////////////////////
bool Link::SetSelected(bool _s)
{
  Entity::SetSelected(_s);

  if (_s == false)
    this->SetEnabled(true);

  return true;
}

//////////////////////////////////////////////////
void Link::SetInertial(const InertialPtr &/*_inertial*/)
{
  gzwarn << "Link::SetMass is empty\n";
}

//////////////////////////////////////////////////
void Link::AddParentJoint(JointPtr _joint)
{
  this->parentJoints.push_back(_joint);
}

//////////////////////////////////////////////////
void Link::AddChildJoint(JointPtr _joint)
{
  this->childJoints.push_back(_joint);
}

//////////////////////////////////////////////////
void Link::RemoveParentJoint(const std::string &_jointName)
{
  for (std::vector<JointPtr>::iterator iter = this->parentJoints.begin();
                                       iter != this->parentJoints.end();
                                       ++iter)
  {
    /// @todo: can we assume there are no repeats?
    if ((*iter)->GetName() == _jointName)
    {
      this->parentJoints.erase(iter);
      break;
    }
  }
}

//////////////////////////////////////////////////
void Link::RemoveChildJoint(const std::string &_jointName)
{
  for (std::vector<JointPtr>::iterator iter = this->childJoints.begin();
                                       iter != this->childJoints.end();
                                       ++iter)
  {
    /// @todo: can we assume there are no repeats?
    if ((*iter)->GetName() == _jointName)
    {
      this->childJoints.erase(iter);
      break;
    }
  }
}

//////////////////////////////////////////////////
void Link::FillMsg(msgs::Link &_msg)
{
  math::Pose relPose = this->GetRelativePose();

  _msg.set_id(this->GetId());
  _msg.set_name(this->GetScopedName());
  _msg.set_self_collide(this->GetSelfCollide());
  _msg.set_gravity(this->GetGravityMode());
  _msg.set_kinematic(this->GetKinematic());
  _msg.set_enabled(this->GetEnabled());
  msgs::Set(_msg.mutable_pose(), relPose);

  msgs::Set(this->visualMsg->mutable_pose(), relPose);
  _msg.add_visual()->CopyFrom(*this->visualMsg);

  _msg.mutable_inertial()->set_mass(this->inertial->GetMass());
  _msg.mutable_inertial()->set_ixx(this->inertial->GetIXX());
  _msg.mutable_inertial()->set_ixy(this->inertial->GetIXY());
  _msg.mutable_inertial()->set_ixz(this->inertial->GetIXZ());
  _msg.mutable_inertial()->set_iyy(this->inertial->GetIYY());
  _msg.mutable_inertial()->set_iyz(this->inertial->GetIYZ());
  _msg.mutable_inertial()->set_izz(this->inertial->GetIZZ());
  msgs::Set(_msg.mutable_inertial()->mutable_pose(), this->inertial->GetPose());

  for (Collision_V::iterator iter = this->collisions.begin();
      iter != this->collisions.end(); ++iter)
  {
    (*iter)->FillMsg(*_msg.add_collision());
  }

  for (std::vector<std::string>::iterator iter = this->sensors.begin();
      iter != this->sensors.end(); ++iter)
  {
    sensors::SensorPtr sensor = sensors::get_sensor(*iter);
    if (sensor)
      sensor->FillMsg(*_msg.add_sensor());
  }

  // Parse visuals from SDF
  if (this->visuals.empty())
    this->ParseVisuals();

  for (Visuals_M::iterator iter = this->visuals.begin();
      iter != this->visuals.end(); ++iter)
  {
    msgs::Visual *vis = _msg.add_visual();
    vis->CopyFrom(iter->second);
  }

  if (this->sdf->HasElement("projector"))
  {
    sdf::ElementPtr elem = this->sdf->GetElement("projector");

    msgs::Projector *proj = _msg.add_projector();
    proj->set_name(
        this->GetScopedName() + "::" + elem->Get<std::string>("name"));
    proj->set_texture(elem->Get<std::string>("texture"));
    proj->set_fov(elem->Get<double>("fov"));
    proj->set_near_clip(elem->Get<double>("near_clip"));
    proj->set_far_clip(elem->Get<double>("far_clip"));
    msgs::Set(proj->mutable_pose(), elem->Get<math::Pose>("pose"));
  }
}

//////////////////////////////////////////////////
void Link::ProcessMsg(const msgs::Link &_msg)
{
  if (_msg.id() != this->GetId())
  {
    return;
  }

  this->SetName(_msg.name());

  if (_msg.has_self_collide())
    this->SetSelfCollide(_msg.self_collide());
  if (_msg.has_gravity())
  {
    this->SetGravityMode(_msg.gravity());
    this->SetEnabled(true);
  }
  if (_msg.has_kinematic())
  {
    this->SetKinematic(_msg.kinematic());
    this->SetEnabled(true);
  }
  if (_msg.has_inertial())
  {
    this->inertial->ProcessMsg(_msg.inertial());
    this->SetEnabled(true);
    this->UpdateMass();
  }

  if (_msg.has_pose())
  {
    this->SetEnabled(true);
    this->SetRelativePose(msgs::Convert(_msg.pose()));
  }

  for (int i = 0; i < _msg.collision_size(); i++)
  {
    CollisionPtr coll = this->GetCollisionById(_msg.collision(i).id());
    if (coll)
      coll->ProcessMsg(_msg.collision(i));
  }
  if (_msg.collision_size()>0)
    this->UpdateSurface();
}

//////////////////////////////////////////////////
unsigned int Link::GetSensorCount() const
{
  return this->sensors.size();
}

//////////////////////////////////////////////////
std::string Link::GetSensorName(unsigned int _i) const
{
  if (_i < this->sensors.size())
    return this->sensors[_i];

  return std::string();
}

//////////////////////////////////////////////////
void Link::AttachStaticModel(ModelPtr &_model, const math::Pose &_offset)
{
  if (!_model->IsStatic())
  {
    gzerr << "AttachStaticModel requires a static model\n";
    return;
  }

  this->attachedModels.push_back(_model);
  this->attachedModelsOffset.push_back(_offset);
}

//////////////////////////////////////////////////
void Link::DetachStaticModel(const std::string &_modelName)
{
  for (unsigned int i = 0; i < this->attachedModels.size(); i++)
  {
    if (this->attachedModels[i]->GetName() == _modelName)
    {
      this->attachedModels.erase(this->attachedModels.begin()+i);
      this->attachedModelsOffset.erase(this->attachedModelsOffset.begin()+i);
      break;
    }
  }
}

//////////////////////////////////////////////////
void Link::DetachAllStaticModels()
{
  this->attachedModels.clear();
  this->attachedModelsOffset.clear();
}

//////////////////////////////////////////////////
void Link::OnPoseChange()
{
  math::Pose p;
  for (unsigned int i = 0; i < this->attachedModels.size(); i++)
  {
    p = this->GetWorldPose();
    p.pos += this->attachedModelsOffset[i].pos;
    p.rot = p.rot * this->attachedModelsOffset[i].rot;

    this->attachedModels[i]->SetWorldPose(p, true);
  }
}

//////////////////////////////////////////////////
void Link::SetState(const LinkState &_state)
{
  this->SetWorldPose(_state.GetPose());

  /*
  for (unsigned int i = 0; i < _state.GetCollisionStateCount(); ++i)
  {
    CollisionState collisionState = _state.GetCollisionState(i);
    CollisionPtr collision = this->GetCollision(collisionState.GetName());
    if (collision)
      collision->SetState(collisionState);
    else
      gzerr << "Unable to find collision[" << collisionState.GetName() << "]\n";
  }*/
}

/////////////////////////////////////////////////
double Link::GetLinearDamping() const
{
  if (this->sdf->HasElement("velocity_decay"))
    return this->sdf->GetElement("velocity_decay")->Get<double>("linear");
  else
    return 0.0;
}

/////////////////////////////////////////////////
double Link::GetAngularDamping() const
{
  if (this->sdf->HasElement("velocity_decay"))
    return this->sdf->GetElement("velocity_decay")->Get<double>("angular");
  else
    return 0.0;
}

/////////////////////////////////////////////////
void Link::SetKinematic(const bool &/*_kinematic*/)
{
}

/////////////////////////////////////////////////
void Link::SetPublishData(bool _enable)
{
  {
    boost::recursive_mutex::scoped_lock lock(*this->publishDataMutex);
    if (this->publishData == _enable)
      return;

    this->publishData = _enable;
  }
  if (_enable)
  {
    std::string topic = "~/" + this->GetScopedName();
    this->dataPub = this->node->Advertise<msgs::LinkData>(topic);
    this->connections.push_back(
      event::Events::ConnectWorldUpdateEnd(
        boost::bind(&Link::PublishData, this)));
  }
  else
  {
    this->dataPub.reset();
    this->connections.clear();
  }
}

/////////////////////////////////////////////////
void Link::PublishData()
{
  if (this->publishData && this->dataPub->HasConnections())
  {
    msgs::Set(this->linkDataMsg.mutable_time(), this->world->GetSimTime());
    linkDataMsg.set_name(this->GetScopedName());
    msgs::Set(this->linkDataMsg.mutable_linear_velocity(),
        this->GetWorldLinearVel());
    msgs::Set(this->linkDataMsg.mutable_angular_velocity(),
        this->GetWorldAngularVel());
    this->dataPub->Publish(this->linkDataMsg);
  }
}

//////////////////////////////////////////////////
void Link::OnCollision(ConstContactsPtr &_msg)
{
  std::string collisionName1;
  std::string collisionName2;
  std::string::size_type pos1, pos2;

  for (int i = 0; i < _msg->contact_size(); ++i)
  {
    collisionName1 = _msg->contact(i).collision1();
    collisionName2 = _msg->contact(i).collision2();
    pos1 = collisionName1.rfind("::");
    pos2 = collisionName2.rfind("::");

    GZ_ASSERT(pos1 != std::string::npos, "Invalid collision name");
    GZ_ASSERT(pos2 != std::string::npos, "Invalid collision name");

    collisionName1 = collisionName1.substr(pos1+2);
    collisionName2 = collisionName2.substr(pos2+2);

#ifdef HAVE_OPENAL
    for (std::vector<util::OpenALSourcePtr>::iterator iter =
        this->audioSources.begin(); iter != this->audioSources.end(); ++iter)
    {
      if ((*iter)->HasCollisionName(collisionName1) ||
          (*iter)->HasCollisionName(collisionName2))
        (*iter)->Play();
    }
#endif
  }
}

/////////////////////////////////////////////////
void Link::ParseVisuals()
{
  // TODO: this shouldn't be in the physics sim
  if (this->sdf->HasElement("visual"))
  {
    sdf::ElementPtr visualElem = this->sdf->GetElement("visual");
    while (visualElem)
    {
      msgs::Visual msg = msgs::VisualFromSDF(visualElem);

      std::string visName = this->GetScopedName() + "::" + msg.name();
      msg.set_name(visName);
      msg.set_id(physics::getUniqueId());
      msg.set_parent_name(this->GetScopedName());
      msg.set_parent_id(this->GetId());
      msg.set_is_static(this->IsStatic());

      this->visPub->Publish(msg);

      Visuals_M::iterator iter = this->visuals.find(msg.id());
      if (iter != this->visuals.end())
        gzthrow(std::string("Duplicate visual name[")+msg.name()+"]\n");

      this->visuals[msg.id()] = msg;

      visualElem = visualElem->GetNextElement("visual");
    }
  }
}

/////////////////////////////////////////////////
void Link::RemoveChild(EntityPtr _child)
{
  if (_child->HasType(COLLISION))
  {
    this->RemoveCollision(_child->GetScopedName());
  }

  Entity::RemoveChild(_child->GetId());

  this->SetEnabled(true);
}

/////////////////////////////////////////////////
void Link::RemoveCollision(const std::string &_name)
{
  for (Collision_V::iterator iter = this->collisions.begin();
       iter != this->collisions.end(); ++iter)
  {
    if ((*iter)->GetName() == _name || (*iter)->GetScopedName() == _name)
    {
      this->collisions.erase(iter);
      break;
    }
  }
}

/////////////////////////////////////////////////
void Link::SetScale(const math::Vector3 &_scale)
{
  Base_V::const_iterator biter;
  for (biter = this->children.begin(); biter != this->children.end(); ++biter)
  {
    if ((*biter)->HasType(Base::COLLISION))
    {
      boost::static_pointer_cast<Collision>(*biter)->SetScale(_scale);
    }
  }

/*  for (unsigned int i = 0; i < this->visuals.size(); ++i)
  {
    msgs::Visual msg;
    msg.set_name(this->visuals[i]);
    if (this->parent)
      msg.set_parent_name(this->parent->GetScopedName());
    else
      msg.set_parent_name("");

    msgs::Set(msg.mutable_scale(), _scale);

    this->visPub->Publish(msg);
  }*/
}


text:
package org.springframework.boot.devtools.autoconfigure;

/**
 * Configuration properties for remote Spring Boot applications.
 *
 * @author Phillip Webb
 * @author Rob Winch
 * @since 1.3.0
 * @see DevToolsProperties
 */
public class RemoteDevToolsProperties {

	public static final String DEFAULT_CONTEXT_PATH = "/.~~spring-boot!~";

	public static final String DEFAULT_SECRET_HEADER_NAME = "X-AUTH-TOKEN";

	/**
	 * Context path used to handle the remote connection.
	 */
	private String contextPath = DEFAULT_CONTEXT_PATH;

	/**
	 * A shared secret required to establish a connection (required to enable remote
	 * support).
	 */
	private String secret;

	/**
	 * HTTP header used to transfer the shared secret.
	 */
	private String secretHeaderName = DEFAULT_SECRET_HEADER_NAME;

	private Restart restart = new Restart();

	private Proxy proxy = new Proxy();

	public String getContextPath() {
		return this.contextPath;
	}

	public void setContextPath(String contextPath) {
		this.contextPath = contextPath;
	}

	public String getSecret() {
		return this.secret;
	}

	public void setSecret(String secret) {
		this.secret = secret;
	}

	public String getSecretHeaderName() {
		return this.secretHeaderName;
	}

	public void setSecretHeaderName(String secretHeaderName) {
		this.secretHeaderName = secretHeaderName;
	}

	public Restart getRestart() {
		return this.restart;
	}

	public Proxy getProxy() {
		return this.proxy;
	}

	public static class Restart {

		/**
		 * Whether to enable remote restart.
		 */
		private boolean enabled = true;

		public boolean isEnabled() {
			return this.enabled;
		}

		public void setEnabled(boolean enabled) {
			this.enabled = enabled;
		}

	}

	public static class Proxy {

		/**
		 * The host of the proxy to use to connect to the remote application.
		 */
		private String host;

		/**
		 * The port of the proxy to use to connect to the remote application.
		 */
		private Integer port;

		public String getHost() {
			return this.host;
		}

		public void setHost(String host) {
			this.host = host;
		}

		public Integer getPort() {
			return this.port;
		}

		public void setPort(Integer port) {
			this.port = port;
		}

	}

}


text:
const capture = require('./src/main/capture/capture');
const sortCss = require('./src/main/sortCss/sortCss');
const index = require('./src/main/index/index');
const getValue = require('./src/main/getValue/getValue');

function cleanCss(props) {
  let settings = {
    buffer : { string : props.css.trim() },
    lineBreak : props.lineBreak || 80,
    tabSize : props.tabSize || 2,
    tabChar : ' ',
  };

  let cssObject = capture(settings, [], 0);

  sortCss(settings, cssObject);
  index(cssObject, 0);

  return getValue(settings, cssObject);
}

module.exports = function (props) {
  return cleanCss(props);
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.databoxedge.models;

import com.azure.core.annotation.Immutable;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.databoxedge.fluent.models.ResourceTypeSkuInner;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** List of SKU Information objects. */
@Immutable
public final class SkuInformationList {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(SkuInformationList.class);

    /*
     * List of ResourceType Sku
     */
    @JsonProperty(value = "value", access = JsonProperty.Access.WRITE_ONLY)
    private List<ResourceTypeSkuInner> value;

    /*
     * Links to the next set of results
     */
    @JsonProperty(value = "nextLink", access = JsonProperty.Access.WRITE_ONLY)
    private String nextLink;

    /**
     * Get the value property: List of ResourceType Sku.
     *
     * @return the value value.
     */
    public List<ResourceTypeSkuInner> value() {
        return this.value;
    }

    /**
     * Get the nextLink property: Links to the next set of results.
     *
     * @return the nextLink value.
     */
    public String nextLink() {
        return this.nextLink;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (value() != null) {
            value().forEach(e -> e.validate());
        }
    }
}


text:
import warnings

from django import forms
from django.forms.models import modelform_factory
from django.utils.translation import ugettext as _

from wagtail.utils.deprecation import RemovedInWagtail11Warning
from wagtail.wagtailimages.formats import get_image_formats
from wagtail.wagtailimages.fields import WagtailImageField

# Callback to allow us to override the default form field for the image file field
def formfield_for_dbfield(db_field, **kwargs):
    # Check if this is the file field
    if db_field.name == 'file':
        return WagtailImageField(**kwargs)

    # For all other fields, just call its formfield() method.
    return db_field.formfield(**kwargs)

def get_image_form(model):
    if hasattr(model, 'admin_form_fields'):
        fields = model.admin_form_fields
    else:
        fields = '__all__'

        warnings.warn(
            "Custom image models without an 'admin_form_fields' attribute are now deprecated. "
            "Add admin_form_fields = (tuple of field names) to {classname}".format(
                classname=model.__name__
            ), RemovedInWagtail11Warning, stacklevel=2)

    return modelform_factory(
        model,
        fields=fields,
        formfield_callback=formfield_for_dbfield,
        # set the 'file' widget to a FileInput rather than the default ClearableFileInput
        # so that when editing, we don't get the 'currently: ...' banner which is
        # a bit pointless here
        widgets={
            'file': forms.FileInput(),
            'focal_point_x': forms.HiddenInput(attrs={'class': 'focal_point_x'}),
            'focal_point_y': forms.HiddenInput(attrs={'class': 'focal_point_y'}),
            'focal_point_width': forms.HiddenInput(attrs={'class': 'focal_point_width'}),
            'focal_point_height': forms.HiddenInput(attrs={'class': 'focal_point_height'}),
        })

class ImageInsertionForm(forms.Form):
    """
    Form for selecting parameters of the image (e.g. format) prior to insertion
    into a rich text area
    """
    format = forms.ChoiceField(
        choices=[(format.name, format.label) for format in get_image_formats()],
        widget=forms.RadioSelect
    )
    alt_text = forms.CharField()

class URLGeneratorForm(forms.Form):
    filter_method = forms.ChoiceField(
        label=_("Filter"),
        choices=(
            ('original', _("Original size")),
            ('width', _("Resize to width")),
            ('height', _("Resize to height")),
            ('min', _("Resize to min")),
            ('max', _("Resize to max")),
            ('fill', _("Resize to fill")),
        ),
    )
    width = forms.IntegerField(_("Width"), min_value=0)
    height = forms.IntegerField(_("Height"), min_value=0)
    closeness = forms.IntegerField(_("Closeness"), min_value=0, initial=0)


text:
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.settings;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.options.Configurable;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.Collections;

/**
 * Allows to register custom debugger-related settings
 * @see DebuggerSettingsCategory
 */
public abstract class DebuggerConfigurableProvider {
  public static final ExtensionPointName<DebuggerConfigurableProvider> EXTENSION_POINT = ExtensionPointName.create("com.intellij.xdebugger.configurableProvider");

  @NotNull
  public Collection<? extends Configurable> getConfigurables(@NotNull DebuggerSettingsCategory category) {
    return Collections.emptyList();
  }

  /**
   * General settings of category were applied
   */
  public void generalApplied(@NotNull DebuggerSettingsCategory category) {
  }

  public boolean isTargetedToProduct(@NotNull Configurable configurable) {
    return false;
  }
}


text:
//$Id: JTATransactionFactory.java 10339 2006-08-24 15:07:03Z steve.ebersole@jboss.com $
package org.hibernate.transaction;

import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.ConnectionReleaseMode;
import org.hibernate.HibernateException;
import org.hibernate.Transaction;
import org.hibernate.TransactionException;
import org.hibernate.jdbc.JDBCContext;
import org.hibernate.cfg.Environment;
import org.hibernate.util.NamingHelper;
import org.hibernate.util.JTAHelper;

/**
 * Factory for <tt>JTATransaction</tt>.
 *
 * @see JTATransaction
 * @author Gavin King
 */
public class JTATransactionFactory implements TransactionFactory {

	private static final Log log = LogFactory.getLog(JTATransactionFactory.class);
	private static final String DEFAULT_USER_TRANSACTION_NAME = "java:comp/UserTransaction";

	protected InitialContext context;
	protected String utName;

	public void configure(Properties props) throws HibernateException {
		try {
			context = NamingHelper.getInitialContext(props);
		}
		catch (NamingException ne) {
			log.error("Could not obtain initial context", ne);
			throw new HibernateException( "Could not obtain initial context", ne );
		}

		utName = props.getProperty(Environment.USER_TRANSACTION);

		if (utName==null) {
			TransactionManagerLookup lookup = TransactionManagerLookupFactory.getTransactionManagerLookup(props);
			if (lookup!=null) utName = lookup.getUserTransactionName();
		}

		if (utName==null) utName = DEFAULT_USER_TRANSACTION_NAME;
	}

	public Transaction createTransaction(JDBCContext jdbcContext, Context transactionContext)
	throws HibernateException {
		return new JTATransaction(context, utName, jdbcContext, transactionContext);
	}

	public ConnectionReleaseMode getDefaultReleaseMode() {
		return ConnectionReleaseMode.AFTER_STATEMENT;
	}

	public boolean isTransactionManagerRequired() {
		return false;
	}

	public boolean areCallbacksLocalToHibernateTransactions() {
		return false;
	}

	public boolean isTransactionInProgress(
			JDBCContext jdbcContext,
	        Context transactionContext,
	        Transaction transaction) {
		try {
            // Essentially:
			// 1) If we have a local (Hibernate) transaction in progress
			//      and it already has the UserTransaction cached, use that
			//      UserTransaction to determine the status.
			// 2) If a transaction manager has been located, use
			//      that transaction manager to determine the status.
			// 3) Finally, as the last resort, try to lookup the
			//      UserTransaction via JNDI and use that to determine the
			//      status.
            if ( transaction != null ) {
				UserTransaction ut = ( ( JTATransaction ) transaction ).getUserTransaction();
                if ( ut != null ) {
                    return JTAHelper.isInProgress( ut.getStatus() );
                }
            }

            if ( jdbcContext.getFactory().getTransactionManager() != null ) {
                return JTAHelper.isInProgress( jdbcContext.getFactory().getTransactionManager().getStatus() );
            }
            else {
                try {
					UserTransaction ut = ( UserTransaction ) context.lookup( utName );
			        return ut != null && JTAHelper.isInProgress( ut.getStatus() );
				}
				catch ( NamingException ne ) {
					throw new TransactionException( "Unable to locate UserTransaction to check status", ne );
				}
            }
		}
		catch( SystemException se ) {
			throw new TransactionException( "Unable to check transaction status", se );
		}
	}

}


text:
Pay4App WHMCS Plugin
===================

## Install

Install the module as you would any other WHMCS plugin. Then in the Pay4App module settings enter your Pay4App Merchant details as they are provided you in your Pay4App merchant dashboard.

## Configure callback

You must configure a callback URL in your Pay4App merchant dashboard. You can do this from the *API Setting* menu to the left under the *Settings* menu.

If your clients access your WHMCS from http://example.com/whmcs, then the callback is at http://example.com/whmcs/modules/gateways/callback/pay4app.php

Don't forget to check *Confirm change* before clicking Save, and make sure Callback Maintenance Mode is *off*


text:
/*	$NetBSD: mech_locl.h,v 1.1.1.3 2014/04/24 12:45:29 pettai Exp $	*/

/*
 * Copyright (c) 2006 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/* Id */

#include <config.h>

#include <krb5/krb5-types.h>

#include <sys/types.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>

#include <gssapi_asn1.h>
#include <krb5/der.h>

#include <krb5/roken.h>

#include <gssapi/gssapi.h>
#include <gssapi_mech.h>
#include <gssapi/gssapi_krb5.h>

#include "mechqueue.h"

#include "context.h"
#include "cred.h"
#include "mech_switch.h"
#include "name.h"
#include "utils.h"
#include "compat.h"

#define _mg_buffer_zero(buffer) \
	do {					\
		if (buffer) {			\
			(buffer)->value = NULL;	\
			(buffer)->length = 0;	\
		 }				\
	} while(0)

#define _mg_oid_set_zero(oid_set) \
	do {						\
		if (oid_set) {				\
			(oid_set)->elements = NULL;	\
			(oid_set)->count = 0;		\
		 }					\
	} while(0)


text:
<?php /* Smarty version 2.6.18, created on 2008-08-13 17:30:09
         compiled from fr/_quisuisje/nuagetag.tpl */ ?>

		Pour terminer, voici quelques mots qui résument parfaitement mon monde.

		<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
   				codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,24"
   				width="550" height="350">
		<param name="movie" value="images/tagcloud.swf"  />
		<param name="quality" value="high"  />
		<param name="menu" value="false"  />
		<param name="wmode" value="transparent"  />
		<param name="flashvars" value="tcolor=0xffffff&tagcloud=<?php echo $this->_tpl_vars['tags']; ?>
" />

		 <object data="images/tagcloud.swf"
		         width="550" height="350" type="application/x-shockwave-flash">
		     <param name="quality" value="high"  />
		     <param name="menu" value="false"  />
			 <param name="wmode" value="transparent"  />
		     <param name="pluginurl" value="http://www.macromedia.com/go/getflashplayer"  />
		     <param name="flashvars" value="tcolor=0xffffff&tagcloud=<?php echo $this->_tpl_vars['tags']; ?>
" />
		 </object>

	  </object>

		Cliquez sur un tag pour avoir plus d'infos ( flash nécessaire )

		 ‹ Mon projet : Page précédente ‹


text:
package mvm.rya.joinselect.mr.utils;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.WritableComparable;

public class TripleCard implements WritableComparable<TripleCard> {

  private CardinalityType card = null;
  private TripleEntry te = null;

  private CardinalityType tempCard = new CardinalityType();
  private TripleEntry tempTe = new TripleEntry();

  public TripleCard() {}

  public TripleCard(CardinalityType card) {
    this.setCard(card);
  }

  public TripleCard(TripleEntry te) {
    this.setTE(te);
  }

  public void setCard(CardinalityType card) {
    tempCard.set(card);
    this.card = tempCard;
    this.te = null;
  }

  public void setTE(TripleEntry te) {
    tempTe.setTE(te);
    this.te = tempTe;
    this.card = null;
  }

  public CardinalityType getCard() {
    return this.card;
  }

  public TripleEntry getTE() {
    return this.te;
  }

  public boolean isCardNull() {
    return (card == null);
  }

  public boolean isTeNull() {
    return (te == null);
  }

  @Override
  public void write(DataOutput out) throws IOException {
    if (card != null) {
      out.writeBoolean(true);
      card.write(out);
    } else {
      out.writeBoolean(false);
      te.write(out);
    }

  }

  @Override
  public void readFields(DataInput in) throws IOException {
    if (in.readBoolean()) {
      tempCard.readFields(in);
      card = tempCard;
      te = null;
    } else {
      tempTe.readFields(in);
      te = tempTe;
      card = null;
    }
  }

  @Override
  public int hashCode() {
    int result = 7;
    if (card != null) {
      result = result * 17 + card.hashCode();
    } else {
      result = result * 17 + te.hashCode();
    }
    return result;

  }

  @Override
  public boolean equals(Object o) {
    if (o instanceof TripleCard) {
      TripleCard comp = (TripleCard) o;
      if (card != null) {
        return card.equals(comp.card);
      } else {
        return te.equals(comp.te);
      }
    }
    return false;
  }

  @Override
  public String toString() {
    if (card != null) {
      return card.toString();
    } else {
      return te.toString();
    }
  }

  @Override
  public int compareTo(TripleCard o) {

    if (card != null) {
      return card.compareTo(o.card);
    } else {
      return te.compareTo(o.te);
    }
  }

}


text:
namespace tw = transwarp;

#ifdef TRANSWARP_CPP11
template<typename T>
T get_any_data(const transwarp::any_data& d) {
    return d.get<T>();
}
#else
template<typename T>
T get_any_data(const transwarp::any_data& d) {
    return std::any_cast<T>(d);
}
#endif

inline
bool any_data_ok(const transwarp::any_data& d) {
    return d.has_value();
}

struct no_op_func {
    template<typename... Args>
    void operator()(Args&&...) const {}
};


text:
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
  <application>tu-van-bao-hiem</application>
  <version>1-0-0</version>
  <threadsafe>true</threadsafe>
  <sessions-enabled>true</sessions-enabled>

  <system-properties>
    <!-- Configure java.util.logging -->
    <property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
    <!--
    <property name="hibernate.show_sql" value="true"/>
    <property name="hibernate.format_sql" value="true"/>
    -->

    <!--
    <property name="delme_org.springframework.boot.logging.LoggingSystem" value="org.springframework.boot.logging.log4j2.Log4J2LoggingSystem"/>
      <property name="org.springframework.boot.logging.LoggingSystem" value="org.springframework.boot.logging.java.JavaLoggingSystem"/>
    <property name="log4j2.disable.jmx" value="true"/>
    -->
  </system-properties>

  <static-files>
    <include path="/**.js" />
    <include path="/**.css" expiration="14d" />
    <include path="/**.png" expiration="14d" />
    <include path="/**.jpg" expiration="14d" />
    <include path="/**.gif" expiration="14d" />
    <include path="/**.ico" expiration="14d" />
    <include path="/favicon.ico" expiration="14d" />
    <include path="/**.xsl" expiration="14d" />
    <include path="/**.txt" expiration="14d" />
    <include path="/VAADIN/**" expiration="14d" />

    <!-- Font files -->
    <include path="/**.otf" expiration="14d" />
    <include path="/**.eot" expiration="14d" />
    <include path="/**.svg" expiration="14d" />
    <include path="/**.ttf" expiration="14d" />
    <include path="/**.woff" expiration="14d" />

    <include path="/static/**.*" expiration="14d" />
  </static-files>
</appengine-web-app>


text:
const QString InstXYPlot::TAG_NAME = "XY_PLOT";

bool InstXYPlot::updateProperties(const QString& key, const QString& value)
{
    mProperties[key] = value;
    InstXYPlot::loadProperties();
    return VisuInstrument::refresh(key);
}

void InstXYPlot::loadProperties()
{
    VisuInstrument::loadProperties();

    GET_PROPERTY(cSignalIdY, mProperties, mPropertiesMeta);
    GET_PROPERTY(cBallSize, mProperties, mPropertiesMeta);
    GET_PROPERTY(cMajorCntX, mProperties, mPropertiesMeta);
    GET_PROPERTY(cMajorCntY, mProperties, mPropertiesMeta);
    GET_PROPERTY(cMajorLenX, mProperties, mPropertiesMeta);
    GET_PROPERTY(cMajorLenY, mProperties, mPropertiesMeta);
    GET_PROPERTY(cPadding, mProperties, mPropertiesMeta);
    GET_PROPERTY(cDecimals, mProperties, mPropertiesMeta);
    GET_PROPERTY(cReverseX, mProperties, mPropertiesMeta);
    GET_PROPERTY(cReverseY, mProperties, mPropertiesMeta);

    mTagName = InstXYPlot::TAG_NAME;
}

void InstXYPlot::renderSingleAxis(QPainter* painter, int sigInd, int divisions, int length)
{
    VisuSignal* sig = connectedSignals[sigInd];

    double pos = cPadding;
    double posDelta = (double)(length - 2*cPadding) / divisions;
    double lbl = sig->getMin();
    double lblDelta = (sig->getMax() - sig->getMin()) / divisions;

    QFontMetrics fm = painter->fontMetrics();

    if (cReverseX && sigInd == SIGNAL_FIRST)
    {
        pos = cWidth - cPadding;
        posDelta = -posDelta;
    }
    else if (cReverseY && sigInd == SIGNAL_SECOND)
    {
        pos = cHeight - cPadding;
        posDelta = -posDelta;
    }

    for (int i=0; i<divisions + 1; ++i)
    {
        QString lblStr = QString::number(lbl, 'f', cDecimals);

        if (sigInd == SIGNAL_FIRST)
        {
            int lblHalfWidth = fm.width(lblStr) / 2;
            painter->drawLine(pos, mCenterY-cMajorLenY, pos, mCenterY+cMajorLenY);
            painter->drawText(pos - lblHalfWidth, mCenterY-cMajorLenY-MARGIN, lblStr);
        }
        else
        {
            int lblHalfHeight = fm.height()/3;
            painter->drawLine(mCenterX-cMajorLenX, pos, mCenterX+cMajorLenX, pos);
            painter->drawText(mCenterX+cMajorLenX+MARGIN, pos + lblHalfHeight, lblStr);
        }

        pos += posDelta;
        lbl += lblDelta;
    }
}

void InstXYPlot::renderAxis(QPainter* painter)
{
    renderSingleAxis(painter, SIGNAL_FIRST, cMajorCntX, cWidth);
    renderSingleAxis(painter, SIGNAL_SECOND, cMajorCntY, cHeight);
}

void InstXYPlot::renderBall(QPainter* painter)
{
    setPen(painter, cColorStatic);
    setBrush(painter, cColorForeground);

    int x = mLastValX * (cWidth - 2 * cPadding) + cPadding - cBallSize / 2;
    int y = mLastValY * (cHeight - 2 * cPadding) + cPadding - cBallSize / 2;

    if (cReverseX)
    {
        x = cWidth - cBallSize - x;
    }

    if (cReverseY)
    {
        y = cHeight - cBallSize - y;
    }

    QRect rect(x, y, cBallSize, cBallSize);
    painter->drawEllipse(rect);
}

void InstXYPlot::renderStatic(QPainter *painter)
{
    setFont(painter);
    setPen(painter, cColorStatic);
    clear(painter);

    mCenterX = cWidth / 2;
    mCenterY = cHeight / 2;

    painter->drawLine(cPadding, mCenterY, cWidth - cPadding, mCenterY);
    painter->drawLine(mCenterX, cPadding, mCenterX, cHeight - cPadding);

    renderAxis(painter);
}

void InstXYPlot::renderDynamic(QPainter *painter)
{
    if (mSignal->getId() == cSignalId)
    {
        mLastValX = mSignal->getNormalizedValue();   // primary signal shown on X axis
        mSignalX = mSignal;
    }
    else
    {
        mLastValY = mSignal->getNormalizedValue();   // additional signal shown on Y axis
        mSignalY = mSignal;
    }

    renderBall(painter);
}


text:
#include <aws/kinesis/model/StreamMode.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>

using namespace Aws::Utils;

namespace Aws
{
  namespace Kinesis
  {
    namespace Model
    {
      namespace StreamModeMapper
      {

        static const int PROVISIONED_HASH = HashingUtils::HashString("PROVISIONED");
        static const int ON_DEMAND_HASH = HashingUtils::HashString("ON_DEMAND");

        StreamMode GetStreamModeForName(const Aws::String& name)
        {
          int hashCode = HashingUtils::HashString(name.c_str());
          if (hashCode == PROVISIONED_HASH)
          {
            return StreamMode::PROVISIONED;
          }
          else if (hashCode == ON_DEMAND_HASH)
          {
            return StreamMode::ON_DEMAND;
          }
          EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
          if(overflowContainer)
          {
            overflowContainer->StoreOverflow(hashCode, name);
            return static_cast<StreamMode>(hashCode);
          }

          return StreamMode::NOT_SET;
        }

        Aws::String GetNameForStreamMode(StreamMode enumValue)
        {
          switch(enumValue)
          {
          case StreamMode::PROVISIONED:
            return "PROVISIONED";
          case StreamMode::ON_DEMAND:
            return "ON_DEMAND";
          default:
            EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
            if(overflowContainer)
            {
              return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
            }

            return {};
          }
        }

      } // namespace StreamModeMapper
    } // namespace Model
  } // namespace Kinesis
} // namespace Aws