text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/file.h>
#include <winpr/path.h>
#include <winpr/synch.h>
#include <winpr/thread.h>
#include <winpr/sysinfo.h>

#include <freerdp/log.h>

#include "shadow.h"

#define TAG CLIENT_TAG("shadow")

BOOL shadow_client_context_new(freerdp_peer* peer, rdpShadowClient* client)
{
	rdpSettings* settings;
	rdpShadowServer* server;

	server = (rdpShadowServer*) peer->ContextExtra;
	client->server = server;
	client->subsystem = server->subsystem;

	settings = peer->settings;

	settings->ColorDepth = 32;
	settings->NSCodec = TRUE;
	settings->RemoteFxCodec = TRUE;
	settings->BitmapCacheV3Enabled = TRUE;
	settings->FrameMarkerCommandEnabled = TRUE;
	settings->SurfaceFrameMarkerEnabled = TRUE;
	settings->SupportGraphicsPipeline = FALSE;

	settings->DrawAllowSkipAlpha = TRUE;
	settings->DrawAllowColorSubsampling = TRUE;
	settings->DrawAllowDynamicColorFidelity = TRUE;

	settings->CompressionLevel = PACKET_COMPR_TYPE_RDP6;

	settings->RdpSecurity = TRUE;
	settings->TlsSecurity = TRUE;
	settings->NlaSecurity = FALSE;

	if (!(settings->CertificateFile = _strdup(server->CertificateFile)))
		goto fail_cert_file;
	if (!(settings->PrivateKeyFile = _strdup(server->PrivateKeyFile)))
		goto fail_privkey_file;
	if (!(settings->RdpKeyFile = _strdup(settings->PrivateKeyFile)))
		goto fail_rdpkey_file;

	if (server->ipcSocket)
	{
		settings->LyncRdpMode = TRUE;
		settings->CompressionEnabled = FALSE;
	}

	client->inLobby = TRUE;
	client->mayView = server->mayView;
	client->mayInteract = server->mayInteract;

	if (!InitializeCriticalSectionAndSpinCount(&(client->lock), 4000))
		goto fail_client_lock;

	region16_init(&(client->invalidRegion));

	client->vcm = WTSOpenServerA((LPSTR) peer->context);
	if (!client->vcm || client->vcm == INVALID_HANDLE_VALUE)
		goto fail_open_server;

	if (!(client->StopEvent = CreateEvent(NULL, TRUE, FALSE, NULL)))
		goto fail_stop_event;

	if (!(client->encoder = shadow_encoder_new(client)))
		goto fail_encoder_new;

	if (ArrayList_Add(server->clients, (void*) client) >= 0)
		return TRUE;

	shadow_encoder_free(client->encoder);
	client->encoder = NULL;
fail_encoder_new:
	CloseHandle(client->StopEvent);
	client->StopEvent = NULL;
fail_stop_event:
	WTSCloseServer((HANDLE) client->vcm);
	client->vcm = NULL;
fail_open_server:
	DeleteCriticalSection(&(client->lock));
fail_client_lock:
	free(settings->RdpKeyFile);
	settings->RdpKeyFile = NULL;
fail_rdpkey_file:
	free(settings->PrivateKeyFile);
	settings->PrivateKeyFile = NULL;
fail_privkey_file:
	free(settings->CertificateFile);
	settings->CertificateFile = NULL;
fail_cert_file:

	return FALSE;
}

void shadow_client_context_free(freerdp_peer* peer, rdpShadowClient* client)
{
	rdpShadowServer* server = client->server;

	ArrayList_Remove(server->clients, (void*) client);

	DeleteCriticalSection(&(client->lock));

	region16_uninit(&(client->invalidRegion));

	WTSCloseServer((HANDLE) client->vcm);

	CloseHandle(client->StopEvent);

	if (client->lobby)
	{
		shadow_surface_free(client->lobby);
		client->lobby = NULL;
	}

	if (client->encoder)
	{
		shadow_encoder_free(client->encoder);
		client->encoder = NULL;
	}

	shadow_client_encomsp_uninit(client);

	shadow_client_remdesk_uninit(client);
}

void shadow_client_message_free(wMessage* message)
{
	if (message->id == SHADOW_MSG_IN_REFRESH_OUTPUT_ID)
	{
		SHADOW_MSG_IN_REFRESH_OUTPUT* wParam = (SHADOW_MSG_IN_REFRESH_OUTPUT*) message->wParam;

		free(wParam->rects);
		free(wParam);
	}
	else if (message->id == SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID)
	{
		SHADOW_MSG_IN_SUPPRESS_OUTPUT* wParam = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) message->wParam;
		free(wParam);
	}
}

BOOL shadow_client_capabilities(freerdp_peer* peer)
{
	return TRUE;
}

BOOL shadow_client_post_connect(freerdp_peer* peer)
{
	int authStatus;
	int width, height;
	rdpSettings* settings;
	rdpShadowClient* client;
	rdpShadowServer* server;
	RECTANGLE_16 invalidRect;
	rdpShadowSubsystem* subsystem;

	client = (rdpShadowClient*) peer->context;
	settings = peer->settings;
	server = client->server;
	subsystem = server->subsystem;

	if (!server->shareSubRect)
	{
		width = server->screen->width;
		height = server->screen->height;
	}
	else
	{
		width = server->subRect.right - server->subRect.left;
		height = server->subRect.bottom - server->subRect.top;
	}

	settings->DesktopWidth = width;
	settings->DesktopHeight = height;

	if (settings->ColorDepth == 24)
		settings->ColorDepth = 16; /* disable 24bpp */

	if (settings->MultifragMaxRequestSize < 0x3F0000)
		settings->NSCodec = FALSE; /* NSCodec compressor does not support fragmentation yet */

	WLog_ERR(TAG, "Client from %s is activated (%dx%d@%d)",
			peer->hostname, settings->DesktopWidth, settings->DesktopHeight, settings->ColorDepth);

	peer->update->DesktopResize(peer->update->context);

	shadow_client_channels_post_connect(client);

	invalidRect.left = 0;
	invalidRect.top = 0;
	invalidRect.right = width;
	invalidRect.bottom = height;

	region16_union_rect(&(client->invalidRegion), &(client->invalidRegion), &invalidRect);

	shadow_client_init_lobby(client);

	authStatus = -1;

	if (settings->Username && settings->Password)
		settings->AutoLogonEnabled = TRUE;

	if (settings->AutoLogonEnabled && server->authentication)
	{
		if (subsystem->Authenticate)
		{
			authStatus = subsystem->Authenticate(subsystem,
					settings->Username, settings->Domain, settings->Password);
		}
	}

	if (server->authentication)
	{
		if (authStatus < 0)
		{
			WLog_ERR(TAG, "client authentication failure: %d", authStatus);
			return FALSE;
		}
	}

	return TRUE;
}

void shadow_client_refresh_rect(rdpShadowClient* client, BYTE count, RECTANGLE_16* areas)
{
	wMessage message = { 0 };
	SHADOW_MSG_IN_REFRESH_OUTPUT* wParam;
	wMessagePipe* MsgPipe = client->subsystem->MsgPipe;

	if (!areas)
		return;

	if (!(wParam = (SHADOW_MSG_IN_REFRESH_OUTPUT*) calloc(1, sizeof(SHADOW_MSG_IN_REFRESH_OUTPUT))))
		return;

	wParam->numRects = (UINT32) count;

	if (wParam->numRects)
	{
		wParam->rects = (RECTANGLE_16*) calloc(wParam->numRects, sizeof(RECTANGLE_16));

		if (!wParam->rects)
		{
			free (wParam);
			return;
		}
	}

	CopyMemory(wParam->rects, areas, wParam->numRects * sizeof(RECTANGLE_16));

	message.id = SHADOW_MSG_IN_REFRESH_OUTPUT_ID;
	message.wParam = (void*) wParam;
	message.lParam = NULL;
	message.context = (void*) client;
	message.Free = shadow_client_message_free;

	MessageQueue_Dispatch(MsgPipe->In, &message);
}

void shadow_client_suppress_output(rdpShadowClient* client, BYTE allow, RECTANGLE_16* area)
{
	wMessage message = { 0 };
	SHADOW_MSG_IN_SUPPRESS_OUTPUT* wParam;
	wMessagePipe* MsgPipe = client->subsystem->MsgPipe;

	wParam = (SHADOW_MSG_IN_SUPPRESS_OUTPUT*) calloc(1, sizeof(SHADOW_MSG_IN_SUPPRESS_OUTPUT));

	if (!wParam)
		return;

	wParam->allow = (UINT32) allow;

	if (area)
		CopyMemory(&(wParam->rect), area, sizeof(RECTANGLE_16));

	message.id = SHADOW_MSG_IN_SUPPRESS_OUTPUT_ID;
	message.wParam = (void*) wParam;
	message.lParam = NULL;
	message.context = (void*) client;
	message.Free = shadow_client_message_free;

	MessageQueue_Dispatch(MsgPipe->In, &message);
}

BOOL shadow_client_activate(freerdp_peer* peer)
{
	rdpSettings* settings = peer->settings;
	rdpShadowClient* client = (rdpShadowClient*) peer->context;

	if (settings->ClientDir && (strcmp(settings->ClientDir, "librdp") == 0))
	{
		/* Hack for Mac/iOS/Android Microsoft RDP clients */

		settings->RemoteFxCodec = FALSE;

		settings->NSCodec = FALSE;
		settings->NSCodecAllowSubsampling = FALSE;

		settings->SurfaceFrameMarkerEnabled = FALSE;
	}

	client->activated = TRUE;
	client->inLobby = client->mayView ? FALSE : TRUE;

	shadow_encoder_reset(client->encoder);

	shadow_client_refresh_rect(client, 0, NULL);

	return TRUE;
}

void shadow_client_surface_frame_acknowledge(rdpShadowClient* client, UINT32 frameId)
{
	SURFACE_FRAME* frame;
	wListDictionary* frameList;

	frameList = client->encoder->frameList;
	frame = (SURFACE_FRAME*) ListDictionary_GetItemValue(frameList, (void*) (size_t) frameId);

	if (frame)
	{
		ListDictionary_Remove(frameList, (void*) (size_t) frameId);
		free(frame);
	}
}

int shadow_client_send_surface_frame_marker(rdpShadowClient* client, UINT32 action, UINT32 id)
{
	SURFACE_FRAME_MARKER surfaceFrameMarker;
	rdpContext* context = (rdpContext*) client;
	rdpUpdate* update = context->update;

	surfaceFrameMarker.frameAction = action;
	surfaceFrameMarker.frameId = id;

	IFCALL(update->SurfaceFrameMarker, context, &surfaceFrameMarker);

	return 1;
}

int shadow_client_send_surface_bits(rdpShadowClient* client, rdpShadowSurface* surface, int nXSrc, int nYSrc, int nWidth, int nHeight)
{
	int i;
	BOOL first;
	BOOL last;
	wStream* s;
	int nSrcStep;
	BYTE* pSrcData;
	int numMessages;
	UINT32 frameId = 0;
	rdpUpdate* update;
	rdpContext* context;
	rdpSettings* settings;
	rdpShadowServer* server;
	rdpShadowEncoder* encoder;
	SURFACE_BITS_COMMAND cmd;

	context = (rdpContext*) client;
	update = context->update;
	settings = context->settings;

	server = client->server;
	encoder = client->encoder;

	pSrcData = surface->data;
	nSrcStep = surface->scanline;

	if (server->shareSubRect)
	{
		int subX, subY;
		int subWidth, subHeight;

		subX = server->subRect.left;
		subY = server->subRect.top;
		subWidth = server->subRect.right - server->subRect.left;
		subHeight = server->subRect.bottom - server->subRect.top;

		nXSrc -= subX;
		nYSrc -= subY;
		pSrcData = &pSrcData[(subY * nSrcStep) + (subX * 4)];
	}

	if (encoder->frameAck)
		frameId = (UINT32) shadow_encoder_create_frame_id(encoder);

	if (settings->RemoteFxCodec)
	{
		RFX_RECT rect;
		RFX_MESSAGE* messages;
		RFX_RECT *messageRects = NULL;

		shadow_encoder_prepare(encoder, FREERDP_CODEC_REMOTEFX);

		s = encoder->bs;

		rect.x = nXSrc;
		rect.y = nYSrc;
		rect.width = nWidth;
		rect.height = nHeight;

		if (!(messages = rfx_encode_messages(encoder->rfx, &rect, 1, pSrcData,
				surface->width, surface->height, nSrcStep, &numMessages,
				settings->MultifragMaxRequestSize)))
		{
			return 0;
		}

		cmd.codecID = settings->RemoteFxCodecId;

		cmd.destLeft = 0;
		cmd.destTop = 0;
		cmd.destRight = surface->width;
		cmd.destBottom = surface->height;

		cmd.bpp = 32;
		cmd.width = surface->width;
		cmd.height = surface->height;

		if (numMessages > 0)
			messageRects = messages[0].rects;

		for (i = 0; i < numMessages; i++)
		{
			Stream_SetPosition(s, 0);
			if (!rfx_write_message(encoder->rfx, s, &messages[i]))
			{
				while (i < numMessages)
				{
					rfx_message_free(encoder->rfx, &messages[i++]);
				}
				break;
			}
			rfx_message_free(encoder->rfx, &messages[i]);

			cmd.bitmapDataLength = Stream_GetPosition(s);
			cmd.bitmapData = Stream_Buffer(s);

			first = (i == 0) ? TRUE : FALSE;
			last = ((i + 1) == numMessages) ? TRUE : FALSE;

			if (!encoder->frameAck)
				IFCALL(update->SurfaceBits, update->context, &cmd);
			else
				IFCALL(update->SurfaceFrameBits, update->context, &cmd, first, last, frameId);
		}

		free(messageRects);
		free(messages);
	}
	else if (settings->NSCodec)
	{
		shadow_encoder_prepare(encoder, FREERDP_CODEC_NSCODEC);

		s = encoder->bs;
		Stream_SetPosition(s, 0);

		pSrcData = &pSrcData[(nYSrc * nSrcStep) + (nXSrc * 4)];

		nsc_compose_message(encoder->nsc, s, pSrcData, nWidth, nHeight, nSrcStep);

		cmd.bpp = 32;
		cmd.codecID = settings->NSCodecId;
		cmd.destLeft = nXSrc;
		cmd.destTop = nYSrc;
		cmd.destRight = cmd.destLeft + nWidth;
		cmd.destBottom = cmd.destTop + nHeight;
		cmd.width = nWidth;
		cmd.height = nHeight;

		cmd.bitmapDataLength = Stream_GetPosition(s);
		cmd.bitmapData = Stream_Buffer(s);

		first = TRUE;
		last = TRUE;

		if (!encoder->frameAck)
			IFCALL(update->SurfaceBits, update->context, &cmd);
		else
			IFCALL(update->SurfaceFrameBits, update->context, &cmd, first, last, frameId);
	}

	return 1;
}

int shadow_client_send_bitmap_update(rdpShadowClient* client, rdpShadowSurface* surface, int nXSrc, int nYSrc, int nWidth, int nHeight)
{
	BYTE* data;
	BYTE* buffer;
	int yIdx, xIdx, k;
	int rows, cols;
	int nSrcStep;
	BYTE* pSrcData;
	UINT32 DstSize;
	UINT32 SrcFormat;
	BITMAP_DATA* bitmap;
	rdpUpdate* update;
	rdpContext* context;
	rdpSettings* settings;
	UINT32 maxUpdateSize;
	UINT32 totalBitmapSize;
	UINT32 updateSizeEstimate;
	BITMAP_DATA* bitmapData;
	BITMAP_UPDATE bitmapUpdate;
	rdpShadowServer* server;
	rdpShadowEncoder* encoder;

	context = (rdpContext*) client;
	update = context->update;
	settings = context->settings;

	server = client->server;
	encoder = client->encoder;

	maxUpdateSize = settings->MultifragMaxRequestSize;

	if (settings->ColorDepth < 32)
		shadow_encoder_prepare(encoder, FREERDP_CODEC_INTERLEAVED);
	else
		shadow_encoder_prepare(encoder, FREERDP_CODEC_PLANAR);

	pSrcData = surface->data;
	nSrcStep = surface->scanline;
	SrcFormat = PIXEL_FORMAT_RGB32;

	if ((nXSrc % 4) != 0)
	{
		nWidth += (nXSrc % 4);
		nXSrc -= (nXSrc % 4);
	}

	if ((nYSrc % 4) != 0)
	{
		nHeight += (nYSrc % 4);
		nYSrc -= (nYSrc % 4);
	}

	rows = (nHeight / 64) + ((nHeight % 64) ? 1 : 0);
	cols = (nWidth / 64) + ((nWidth % 64) ? 1 : 0);

	k = 0;
	totalBitmapSize = 0;

	bitmapUpdate.count = bitmapUpdate.number = rows * cols;
	bitmapData = (BITMAP_DATA*) malloc(sizeof(BITMAP_DATA) * bitmapUpdate.number);
	bitmapUpdate.rectangles = bitmapData;

	if (!bitmapData)
		return -1;

	if ((nWidth % 4) != 0)
	{
		nXSrc -= (nWidth % 4);
		nWidth += (nWidth % 4);
	}

	if ((nHeight % 4) != 0)
	{
		nYSrc -= (nHeight % 4);
		nHeight += (nHeight % 4);
	}

	for (yIdx = 0; yIdx < rows; yIdx++)
	{
		for (xIdx = 0; xIdx < cols; xIdx++)
		{
			bitmap = &bitmapData[k];

			bitmap->width = 64;
			bitmap->height = 64;
			bitmap->destLeft = nXSrc + (xIdx * 64);
			bitmap->destTop = nYSrc + (yIdx * 64);

			if ((bitmap->destLeft + bitmap->width) > (nXSrc + nWidth))
				bitmap->width = (nXSrc + nWidth) - bitmap->destLeft;

			if ((bitmap->destTop + bitmap->height) > (nYSrc + nHeight))
				bitmap->height = (nYSrc + nHeight) - bitmap->destTop;

			bitmap->destRight = bitmap->destLeft + bitmap->width - 1;
			bitmap->destBottom = bitmap->destTop + bitmap->height - 1;
			bitmap->compressed = TRUE;

			if ((bitmap->width < 4) || (bitmap->height < 4))
				continue;

			if (settings->ColorDepth < 32)
			{
				int bitsPerPixel = settings->ColorDepth;
				int bytesPerPixel = (bitsPerPixel + 7) / 8;

				DstSize = 64 * 64 * 4;
				buffer = encoder->grid[k];

				interleaved_compress(encoder->interleaved, buffer, &DstSize, bitmap->width, bitmap->height,
						pSrcData, SrcFormat, nSrcStep, bitmap->destLeft, bitmap->destTop, NULL, bitsPerPixel);

				bitmap->bitmapDataStream = buffer;
				bitmap->bitmapLength = DstSize;
				bitmap->bitsPerPixel = bitsPerPixel;
				bitmap->cbScanWidth = bitmap->width * bytesPerPixel;
				bitmap->cbUncompressedSize = bitmap->width * bitmap->height * bytesPerPixel;
			}
			else
			{
				int dstSize;

				buffer = encoder->grid[k];
				data = &pSrcData[(bitmap->destTop * nSrcStep) + (bitmap->destLeft * 4)];

				buffer = freerdp_bitmap_compress_planar(encoder->planar, data, SrcFormat,
						bitmap->width, bitmap->height, nSrcStep, buffer, &dstSize);

				bitmap->bitmapDataStream = buffer;
				bitmap->bitmapLength = dstSize;
				bitmap->bitsPerPixel = 32;
				bitmap->cbScanWidth = bitmap->width * 4;
				bitmap->cbUncompressedSize = bitmap->width * bitmap->height * 4;
			}

			bitmap->cbCompFirstRowSize = 0;
			bitmap->cbCompMainBodySize = bitmap->bitmapLength;

			totalBitmapSize += bitmap->bitmapLength;
			k++;
		}
	}

	bitmapUpdate.count = bitmapUpdate.number = k;

	updateSizeEstimate = totalBitmapSize + (k * bitmapUpdate.count) + 16;

	if (updateSizeEstimate > maxUpdateSize)
	{
		UINT32 i, j;
		UINT32 updateSize;
		UINT32 newUpdateSize;
		BITMAP_DATA* fragBitmapData;

		fragBitmapData = (BITMAP_DATA*) malloc(sizeof(BITMAP_DATA) * k);
		bitmapUpdate.rectangles = fragBitmapData;

		i = j = 0;
		updateSize = 1024;

		while (i < k)
		{
			newUpdateSize = updateSize + (bitmapData[i].bitmapLength + 16);

			if ((newUpdateSize < maxUpdateSize) && ((i + 1) < k))
			{
				CopyMemory(&fragBitmapData[j++], &bitmapData[i++], sizeof(BITMAP_DATA));
				updateSize = newUpdateSize;
			}
			else
			{
				if ((i + 1) >= k)
				{
					CopyMemory(&fragBitmapData[j++], &bitmapData[i++], sizeof(BITMAP_DATA));
					updateSize = newUpdateSize;
				}

				bitmapUpdate.count = bitmapUpdate.number = j;
				IFCALL(update->BitmapUpdate, context, &bitmapUpdate);
				updateSize = 1024;
				j = 0;
			}
		}

		free(fragBitmapData);
	}
	else
	{
		IFCALL(update->BitmapUpdate, context, &bitmapUpdate);
	}

	free(bitmapData);

	return 1;
}

int shadow_client_send_surface_update(rdpShadowClient* client)
{
	int status = -1;
	int nXSrc, nYSrc;
	int nWidth, nHeight;
	rdpContext* context;
	rdpSettings* settings;
	rdpShadowServer* server;
	rdpShadowSurface* surface;
	rdpShadowEncoder* encoder;
	REGION16 invalidRegion;
	RECTANGLE_16 surfaceRect;
	const RECTANGLE_16* extents;

	context = (rdpContext*) client;
	settings = context->settings;
	server = client->server;
	encoder = client->encoder;

	surface = client->inLobby ? client->lobby : server->surface;

	EnterCriticalSection(&(client->lock));

	region16_init(&invalidRegion);
	region16_copy(&invalidRegion, &(client->invalidRegion));
	region16_clear(&(client->invalidRegion));

	LeaveCriticalSection(&(client->lock));

	surfaceRect.left = 0;
	surfaceRect.top = 0;
	surfaceRect.right = surface->width;
	surfaceRect.bottom = surface->height;

	region16_intersect_rect(&invalidRegion, &invalidRegion, &surfaceRect);

	if (server->shareSubRect)
	{
		region16_intersect_rect(&invalidRegion, &invalidRegion, &(server->subRect));
	}

	if (region16_is_empty(&invalidRegion))
	{
		region16_uninit(&invalidRegion);
		return 1;
	}

	extents = region16_extents(&invalidRegion);

	nXSrc = extents->left - 0;
	nYSrc = extents->top - 0;
	nWidth = extents->right - extents->left;
	nHeight = extents->bottom - extents->top;

	//WLog_INFO(TAG, "shadow_client_send_surface_update: x: %d y: %d width: %d height: %d right: %d bottom: %d",
	//	nXSrc, nYSrc, nWidth, nHeight, nXSrc + nWidth, nYSrc + nHeight);

	if (settings->RemoteFxCodec || settings->NSCodec)
	{
		status = shadow_client_send_surface_bits(client, surface, nXSrc, nYSrc, nWidth, nHeight);
	}
	else
	{
		status = shadow_client_send_bitmap_update(client, surface, nXSrc, nYSrc, nWidth, nHeight);
	}

	region16_uninit(&invalidRegion);

	return status;
}

int shadow_client_surface_update(rdpShadowClient* client, REGION16* region)
{
	int index;
	int numRects = 0;
	const RECTANGLE_16* rects;

	EnterCriticalSection(&(client->lock));

	rects = region16_rects(region, &numRects);

	for (index = 0; index < numRects; index++)
	{
		region16_union_rect(&(client->invalidRegion), &(client->invalidRegion), &rects[index]);
	}

	LeaveCriticalSection(&(client->lock));

	return 1;
}

int shadow_client_convert_alpha_pointer_data(BYTE* pixels, BOOL premultiplied,
		UINT32 width, UINT32 height, POINTER_COLOR_UPDATE* pointerColor)
{
	UINT32 x, y;
	BYTE* pSrc8;
	BYTE* pDst8;
	int xorStep;
	int andStep;
	UINT32 andBit;
	BYTE* andBits;
	UINT32 andPixel;
	BYTE A, R, G, B;

	xorStep = (width * 3);
	xorStep += (xorStep % 2);

	andStep = ((width + 7) / 8);
	andStep += (andStep % 2);

	pointerColor->lengthXorMask = height * xorStep;
	pointerColor->xorMaskData = (BYTE*) calloc(1, pointerColor->lengthXorMask);

	if (!pointerColor->xorMaskData)
		return -1;

	pointerColor->lengthAndMask = height * andStep;
	pointerColor->andMaskData = (BYTE*) calloc(1, pointerColor->lengthAndMask);

	if (!pointerColor->andMaskData)
		return -1;

	for (y = 0; y < height; y++)
	{
		pSrc8 = &pixels[(width * 4) * (height - 1 - y)];
		pDst8 = &(pointerColor->xorMaskData[y * xorStep]);

		andBit = 0x80;
		andBits = &(pointerColor->andMaskData[andStep * y]);

		for (x = 0; x < width; x++)
		{
			B = *pSrc8++;
			G = *pSrc8++;
			R = *pSrc8++;
			A = *pSrc8++;

			andPixel = 0;

			if (A < 64)
				A = 0; /* pixel cannot be partially transparent */

			if (!A)
			{
				/* transparent pixel: XOR = black, AND = 1 */
				andPixel = 1;
				B = G = R = 0;
			}
			else
			{
				if (premultiplied)
				{
					B = (B * 0xFF ) / A;
					G = (G * 0xFF ) / A;
					R = (R * 0xFF ) / A;
				}
			}

			*pDst8++ = B;
			*pDst8++ = G;
			*pDst8++ = R;

			if (andPixel) *andBits |= andBit;
			if (!(andBit >>= 1)) { andBits++; andBit = 0x80; }
		}
	}

	return 1;
}

int shadow_client_subsystem_process_message(rdpShadowClient* client, wMessage* message)
{
	rdpContext* context = (rdpContext*) client;
	rdpUpdate* update = context->update;

	/* FIXME: the pointer updates appear to be broken when used with bulk compression and mstsc */

	if (message->id == SHADOW_MSG_OUT_POINTER_POSITION_UPDATE_ID)
	{
		POINTER_POSITION_UPDATE pointerPosition;
		SHADOW_MSG_OUT_POINTER_POSITION_UPDATE* msg = (SHADOW_MSG_OUT_POINTER_POSITION_UPDATE*) message->wParam;

		pointerPosition.xPos = msg->xPos;
		pointerPosition.yPos = msg->yPos;

		if (client->activated)
		{
			if ((msg->xPos != client->pointerX) || (msg->yPos != client->pointerY))
			{
				IFCALL(update->pointer->PointerPosition, context, &pointerPosition);

				client->pointerX = msg->xPos;
				client->pointerY = msg->yPos;
			}
		}

		free(msg);
	}
	else if (message->id == SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE_ID)
	{
		POINTER_NEW_UPDATE pointerNew;
		POINTER_COLOR_UPDATE* pointerColor;
		POINTER_CACHED_UPDATE pointerCached;
		SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE* msg = (SHADOW_MSG_OUT_POINTER_ALPHA_UPDATE*) message->wParam;

		ZeroMemory(&pointerNew, sizeof(POINTER_NEW_UPDATE));

		pointerNew.xorBpp = 24;
		pointerColor = &(pointerNew.colorPtrAttr);

		pointerColor->cacheIndex = 0;
		pointerColor->xPos = msg->xHot;
		pointerColor->yPos = msg->yHot;
		pointerColor->width = msg->width;
		pointerColor->height = msg->height;

		pointerCached.cacheIndex = pointerColor->cacheIndex;

		if (client->activated)
		{
			shadow_client_convert_alpha_pointer_data(msg->pixels, msg->premultiplied,
					msg->width, msg->height, pointerColor);

			IFCALL(update->pointer->PointerNew, context, &pointerNew);
			IFCALL(update->pointer->PointerCached, context, &pointerCached);

			free(pointerColor->xorMaskData);
			free(pointerColor->andMaskData);
		}

		free(msg->pixels);
		free(msg);
	}

	return 1;
}

void* shadow_client_thread(rdpShadowClient* client)
{
	DWORD status;
	DWORD nCount;
	wMessage message;
	HANDLE events[32];
	HANDLE StopEvent;
	HANDLE ClientEvent;
	HANDLE ChannelEvent;
	void* UpdateSubscriber;
	HANDLE UpdateEvent;
	freerdp_peer* peer;
	rdpContext* context;
	rdpSettings* settings;
	rdpShadowServer* server;
	rdpShadowScreen* screen;
	rdpShadowEncoder* encoder;
	rdpShadowSubsystem* subsystem;
	wMessagePipe* MsgPipe = client->subsystem->MsgPipe;

	server = client->server;
	screen = server->screen;
	encoder = client->encoder;
	subsystem = server->subsystem;

	context = (rdpContext*) client;
	peer = context->peer;
	settings = peer->settings;

	peer->Capabilities = shadow_client_capabilities;
	peer->PostConnect = shadow_client_post_connect;
	peer->Activate = shadow_client_activate;

	shadow_input_register_callbacks(peer->input);

	peer->Initialize(peer);

	peer->update->RefreshRect = (pRefreshRect) shadow_client_refresh_rect;
	peer->update->SuppressOutput = (pSuppressOutput) shadow_client_suppress_output;
	peer->update->SurfaceFrameAcknowledge = (pSurfaceFrameAcknowledge) shadow_client_surface_frame_acknowledge;

	if ((!client->StopEvent) || (!client->vcm) || (!subsystem->updateEvent))
		goto out;

	UpdateSubscriber = shadow_multiclient_get_subscriber(subsystem->updateEvent);
	if (!UpdateSubscriber)
		goto out;

	StopEvent = client->StopEvent;
	UpdateEvent = shadow_multiclient_getevent(UpdateSubscriber);
	ClientEvent = peer->GetEventHandle(peer);
	ChannelEvent = WTSVirtualChannelManagerGetEventHandle(client->vcm);

	while (1)
	{
		nCount = 0;
		events[nCount++] = StopEvent;
		events[nCount++] = UpdateEvent;
		events[nCount++] = ClientEvent;
		events[nCount++] = ChannelEvent;
		events[nCount++] = MessageQueue_Event(MsgPipe->Out);

		status = WaitForMultipleObjects(nCount, events, FALSE, INFINITE);

		if (WaitForSingleObject(StopEvent, 0) == WAIT_OBJECT_0)
		{
			break;
		}

		if (WaitForSingleObject(UpdateEvent, 0) == WAIT_OBJECT_0)
		{
			if (client->activated)
			{
				int index;
				int numRects = 0;
				const RECTANGLE_16* rects;

				rects = region16_rects(&(subsystem->invalidRegion), &numRects);

				for (index = 0; index < numRects; index++)
				{
					region16_union_rect(&(client->invalidRegion), &(client->invalidRegion), &rects[index]);
				}

				shadow_client_send_surface_update(client);
			}

			/*
			 * The return value of shadow_multiclient_consume is whether or not the subscriber really consumes the event.
			 * It's not cared currently.
			 */
			(void)shadow_multiclient_consume(UpdateSubscriber);
		}

		if (WaitForSingleObject(ClientEvent, 0) == WAIT_OBJECT_0)
		{
			if (!peer->CheckFileDescriptor(peer))
			{
				WLog_ERR(TAG, "Failed to check FreeRDP file descriptor");
				break;
			}
		}

		if (WaitForSingleObject(ChannelEvent, 0) == WAIT_OBJECT_0)
		{
			if (!WTSVirtualChannelManagerCheckFileDescriptor(client->vcm))
			{
				WLog_ERR(TAG, "WTSVirtualChannelManagerCheckFileDescriptor failure");
				break;
			}
		}

		if (WaitForSingleObject(MessageQueue_Event(MsgPipe->Out), 0) == WAIT_OBJECT_0)
		{
			if (MessageQueue_Peek(MsgPipe->Out, &message, TRUE))
			{
				if (message.id == WMQ_QUIT)
					break;

				shadow_client_subsystem_process_message(client, &message);
			}
		}
	}

	if (UpdateSubscriber)
	{
		shadow_multiclient_release_subscriber(UpdateSubscriber);
		UpdateSubscriber = NULL;
	}

out:
	peer->Disconnect(peer);

	freerdp_peer_context_free(peer);
	freerdp_peer_free(peer);
	ExitThread(0);
	return NULL;
}

BOOL shadow_client_accepted(freerdp_listener* listener, freerdp_peer* peer)
{
	rdpShadowClient* client;
	rdpShadowServer* server;

	server = (rdpShadowServer*) listener->info;

	peer->ContextExtra = (void*) server;
	peer->ContextSize = sizeof(rdpShadowClient);
	peer->ContextNew = (psPeerContextNew) shadow_client_context_new;
	peer->ContextFree = (psPeerContextFree) shadow_client_context_free;

	if (!freerdp_peer_context_new(peer))
		return FALSE;

	client = (rdpShadowClient*) peer->context;

	if (!(client->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)
			shadow_client_thread, client, 0, NULL)))
	{
		freerdp_peer_context_free(peer);
		return FALSE;
	}

	return TRUE;
}


text:
<?php

namespace SofaChamps\Bundle\SuperBowlChallengeBundle\Form\Type;

use Doctrine\Common\Persistence\ObjectManager;
use JMS\DiExtraBundle\Annotation as DI;
use SofaChamps\Bundle\SuperBowlChallengeBundle\Form\DataTransformer\QuestionTransformer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

/**
 * @DI\FormType(alias="hidden_question")
 */
class HiddenQuestionType extends AbstractType
{
    private $transformer;

    /**
     * @DI\InjectParams({
     *      "transformer" = @DI\Inject("transformer.question")
     * })
     */
    public function __construct(QuestionTransformer $transformer)
    {
        $this->transformer = $transformer;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addModelTransformer($this->transformer);
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'invalid_message' => 'The question does not exist',
        ));
    }

    public function getParent()
    {
        return 'hidden';
    }

    public function getName()
    {
        return 'hidden_question';
    }
}

redpajama_set_name: RedPajamaGithub


text:
package de.rkraneis.rtree;

import java.util.Arrays;
import java.util.List;

import de.rkraneis.rtree.geometry.Point;
import static java.util.stream.Collectors.toList;

public class GalleryMain {

    public static void main(String[] args) {
        List<Entry<Object, Point>> entries = GreekEarthquakes.entries().collect(toList());

        List<Integer> sizes = Arrays.asList(100, 1000, 10000, 1000000);
        List<Integer> maxChildrenValues = Arrays.asList(4, 8, 16, 32, 64, 128);
        for (int size : sizes)
            for (int maxChildren : maxChildrenValues) {
                if (size > maxChildren) {
                    System.out.println("saving " + size + " m=" + maxChildren);
                    RTree<Object, Point> tree = RTree.maxChildren(maxChildren)
                            .<Object, Point> create().add(entries.get(size-1));
                    tree.visualize(600, 600).save(
                            "target/greek-" + size + "-" + maxChildren + "-quad.png");
                    RTree<Object, Point> tree2 = RTree.star().maxChildren(maxChildren)
                            .<Object, Point> create().add(entries.get(size-1));
                    tree2.visualize(600, 600).save(
                            "target/greek-" + size + "-" + maxChildren + "-star.png");
                }
            }
    }
}


text:
var assert = require('assert');
var fs = require('fs');
var tv4 = require('tv4');

var metaSchema = JSON.parse(
  fs.readFileSync(__dirname + '/../../node_modules/json-schema/draft-04/schema').toString()
);
console.log(metaSchema);

//
// 現在、バグで本家のメタスキーマを解釈出来ない模様
// https://github.com/geraintluff/tv4/issues/198
//
(function() {
  var schema = {
    type: 'number',
  };
  var validated = tv4.validateMultiple(schema, metaSchema);
  console.log(validated);
})();


text:
layout: page
title: "Under Construction"
permalink: 404.html
---

Just waiting for some spare time to fill in the details. Please

expore other stuff and hopefully I will have something useful on this page soon.


text:
delimiter //

drop procedure if exists _consume_if_exists //

create procedure _consume_if_exists(
   in   id_from      int unsigned,
   in   id_to      int unsigned,
   inout  consumed_to_id int unsigned,
   in   expected_token text charset utf8,
   in   expected_states text charset utf8,
   out  token_has_matched tinyint unsigned,
   out  matched_token text charset utf8
)
comment 'Consumes token or state if indeed exists'
language SQL
deterministic
reads sql data
sql security invoker

main_body: begin
  call _skip_spaces(id_from, id_to);
  set token_has_matched := FALSE;
  set @_matched_token=null, @_token_has_matched=FALSE;
  SELECT token, ((token = expected_token) OR FIND_IN_SET(state, REPLACE(expected_states, '|', ','))) IS TRUE FROM _sql_tokens WHERE id = id_from INTO @_matched_token, @_token_has_matched;
  set matched_token=@_matched_token;
  set token_has_matched=@_token_has_matched;
  if token_has_matched then
    set consumed_to_id = id_from;
  end if;
end;
//

delimiter ;


text:
#ifndef LOADER_H
#define LOADER_H

#include <stdio.h>

#ifndef _WIN32
#  include <dlfcn.h>
#  define HANDLE void*
#  define load_lib(i) dlopen((i), RTLD_LAZY | RTLD_GLOBAL)
#  define symbol_from_lib dlsym
#  define close_lib dlclose
#else
#  include <windows.h>
#  define load_lib xvalid_load_lib
#  define symbol_from_lib GetProcAddress
#  define close_lib FreeLibrary
#endif /* _WIN32 */

HANDLE xvalid_load_lib(char *filename);

#endif /* LOADER_H */


text:
require File.join(File.dirname(__FILE__), 'new_image.rb')

include Magick

fill = GradientFill.new(200, 0, 200, 300,'#000000','#ff8844')

image = Image.new(300,300,fill)

image.write('gradient_fill_vertical_fill.jpg')


text:
// CONTROLLER
// =============================================================================
class RemoveButtonController {
	/**
	 * @constructor
	 * @param {object} Store
	 * @param {object} Modal
	 * @param {object} Errors
	 */
	constructor(Store, Modal, Errors) {
		"ngInject";

		// injected dependencies
		this._Store = Store;
		this._Modal = Modal;
		this._Errors = Errors;
	}

	/**
	 * Fires when the controller is finished initializing.
	 *
	 * @method $onInit
	 */
	$onInit() {
		// controller name
		this.name = "removeButton";
	}

	/**
	 * When the form is submitted.
	 *
	 * @method onSubmit
	 */
	onSubmit() {
		// modal options
		const modalOptions = {
			actionButtonText: "Delete",
			bodyText: `Really delete ${this.item.name}?`,
		};
		// confirm delete
		this._Modal.confirm(modalOptions)
			.then(() => this._Store.remove(this.item.id))
			// errors
			.catch(err => this._Errors.catch(err));
	}
}

// EXPORT
// =============================================================================
export default RemoveButtonController;


text:
import { Mixin } from './api';

/**
 * Behaviour that adds a hook for performing initial rendering when the
 * element is first connected to the DOM.
 */
const hasBeenRendered = Symbol('hasBeenRendered');
export const InitialRender = Mixin(superclass => class extends superclass {
	connectedCallback() {
		super.connectedCallback();
		if(! this[hasBeenRendered]) {
			this[hasBeenRendered] = true;
			this.initialRenderCallback();
		}
	}

	initialRenderCallback() {
	}
});


text:
"""
Support for Google Maps location sharing.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/device_tracker.google_maps/
"""
from datetime import timedelta
import logging

import voluptuous as vol

from homeassistant.components.device_tracker import (
    PLATFORM_SCHEMA, SOURCE_TYPE_GPS)
from homeassistant.const import ATTR_ID, CONF_PASSWORD, CONF_USERNAME
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.event import track_time_interval
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import slugify, dt as dt_util

REQUIREMENTS = ['locationsharinglib==2.0.11']

_LOGGER = logging.getLogger(__name__)

ATTR_ADDRESS = 'address'
ATTR_FULL_NAME = 'full_name'
ATTR_LAST_SEEN = 'last_seen'
ATTR_NICKNAME = 'nickname'

CONF_MAX_GPS_ACCURACY = 'max_gps_accuracy'

CREDENTIALS_FILE = '.google_maps_location_sharing.cookies'

MIN_TIME_BETWEEN_SCANS = timedelta(seconds=30)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_PASSWORD): cv.string,
    vol.Required(CONF_USERNAME): cv.string,
    vol.Optional(CONF_MAX_GPS_ACCURACY, default=100000): vol.Coerce(float),
})

def setup_scanner(hass, config: ConfigType, see, discovery_info=None):
    """Set up the Google Maps Location sharing scanner."""
    scanner = GoogleMapsScanner(hass, config, see)
    return scanner.success_init

class GoogleMapsScanner:
    """Representation of an Google Maps location sharing account."""

    def __init__(self, hass, config: ConfigType, see) -> None:
        """Initialize the scanner."""
        from locationsharinglib import Service
        from locationsharinglib.locationsharinglibexceptions import InvalidUser

        self.see = see
        self.username = config[CONF_USERNAME]
        self.password = config[CONF_PASSWORD]
        self.max_gps_accuracy = config[CONF_MAX_GPS_ACCURACY]

        try:
            self.service = Service(self.username, self.password,
                                   hass.config.path(CREDENTIALS_FILE))
            self._update_info()

            track_time_interval(
                hass, self._update_info, MIN_TIME_BETWEEN_SCANS)

            self.success_init = True

        except InvalidUser:
            _LOGGER.error("You have specified invalid login credentials")
            self.success_init = False

    def _update_info(self, now=None):
        for person in self.service.get_all_people():
            try:
                dev_id = 'google_maps_{0}'.format(slugify(person.id))
            except TypeError:
                _LOGGER.warning("No location(s) shared with this account")
                return

            if self.max_gps_accuracy is not None and \
                    person.accuracy > self.max_gps_accuracy:
                _LOGGER.info("Ignoring %s update because expected GPS "
                             "accuracy %s is not met: %s",
                             person.nickname, self.max_gps_accuracy,
                             person.accuracy)
                continue

            attrs = {
                ATTR_ADDRESS: person.address,
                ATTR_FULL_NAME: person.full_name,
                ATTR_ID: person.id,
                ATTR_LAST_SEEN: dt_util.as_utc(person.datetime),
                ATTR_NICKNAME: person.nickname,
            }
            self.see(
                dev_id=dev_id,
                gps=(person.latitude, person.longitude),
                picture=person.picture_url,
                source_type=SOURCE_TYPE_GPS,
                gps_accuracy=person.accuracy,
                attributes=attrs,
            )


text:
package fib;

import java.io.IOException;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

import fib.FibClient;

public class FibClient {
	private String address;
	private int port;
	private int fib;

	public FibClient(String address, int port, int fib) {
		this.address = address;
		this.port = port;
		this.fib = fib;
	}

	public int askFib() {
		InetAddress address;
		Socket socket;
		try {
			address = InetAddress.getByName(this.address);
			socket = new Socket(address, this.port);
			PrintStream output = new PrintStream(socket.getOutputStream());
			Scanner input = new Scanner(socket.getInputStream());
			output.println(this.fib);
			this.fib = input.nextInt();
			socket.close();
			input.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return this.fib;
	}

	public static void main(String argv[]) {
		try {
			int input;
			System.out.println("Entrez le nombre dont vous voulez le résultat de fibonacci :\n");
			Scanner sc = new Scanner(System.in);
			input = sc.nextInt();
			while(input < 0 || input%1 != 0) {
				System.out.println("Veuillez entrer une valeur positive ou nulle ! \n");
				input = Integer.parseInt(sc.nextLine());
			}
			FibClient client = new FibClient(argv[0], Integer.parseInt(argv[1]), input);
			System.out.println("Résultat : " + client.askFib());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}


text:
using Database;
using Flyingpie.Storm.Execution;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Storm.Test.Dto;
using System.Linq;

namespace Flyingpie.Storm.Test.IntegrationTests
{
    [TestClass]
    public class QueryTests
    {
        private IQueryChain _queryChain;
        private IIntegrationTest _it;

        [TestInitialize]
        public void Initialize()
        {
            _queryChain = new QueryChain()
                .UseDapper(new Dapper.DapperConfiguration()
                {
                    ConnectionString = "server=.;database=Storm;integrated security=true;"
                });

            _it = new IntegrationTest(_queryChain);
        }

        [TestMethod]
        public void IntegrationTest_Query_NoParameters()
        {
            var result = _it.QueryNoParameters().Query<Brand>();

            Assert.IsNotNull(result);
            Assert.AreEqual(5, result.Count());

            var audi = result.FirstOrDefault(r => r.Id == 1);
            Assert.IsNotNull(audi);
            Assert.AreEqual("Audi", audi.Name);
            Assert.AreEqual("Never follow", audi.Description);
            Assert.AreEqual(150, audi.HorsePower);

            var bmw = result.FirstOrDefault(r => r.Id == 2);
            Assert.IsNotNull(bmw);
            Assert.AreEqual("BMW", bmw.Name);
            Assert.AreEqual("The ultimate driving machine", bmw.Description);
        }

        [TestMethod]
        public void IntegrationTest_Query_SingleParameter_NotNull()
        {
            Assert.Inconclusive();
        }

        [TestMethod]
        public void IntegrationTest_Query_SingleParameter_Null()
        {
            Assert.Inconclusive();
        }

        [TestMethod]
        public void IntegrationTest_Query_MultipleParameters_NotNull()
        {
            Assert.Inconclusive();
        }

        [TestMethod]
        public void IntegrationTest_Query_MultipleParameters_Null()
        {
            Assert.Inconclusive();
        }
    }
}


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

<TITLE>
Uses of Interface java.util.Enumeration (IM Profile)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

IM Profile

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
java.util.Enumeration

Packages that use Enumeration

com.siemens.icm.io.file

java.util
Contains the collection classes, and the date and time facilities.

Uses of Enumeration in com.siemens.icm.io.file

Methods in com.siemens.icm.io.file that return Enumeration

static Enumeration
FileSystemRegistry.listRoots()

          This method returns the currently mounted root file systems on a device
 as String objects in an Enumeration.

 Enumeration
FileConnection.list()

          Gets a list of all files and directories contained in a directory.

 Enumeration
FileConnection.list(String filter,
     boolean includeHidden)

          Gets a filtered list of files and directories contained in a directory.

Uses of Enumeration in java.util

Methods in java.util that return Enumeration

 Enumeration
Vector.elements()

          Returns an enumeration of the components of this vector.

 Enumeration
Hashtable.keys()

          Returns an enumeration of the keys in this hashtable.

 Enumeration
Hashtable.elements()

          Returns an enumeration of the values in this hashtable.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

IM Profile

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Submit a comment or suggestion Version 2.0 of IM Profile Specification
Java is a trademark or registered trademark of Sun Microsystems,  Inc. in the US and other countries. Copyright (c) 1993-2002 Sun Microsystems, Inc. 901 San Antonio Road,Palo Alto, California, 94303, U.S.A.  All Rights Reserved.


text:
*********
_eafi_: signal filtering made - apparently - simple
*********

_eafi_ is a C++ filtering library aimed to easly setup and run filters
on sampled signals.
It provides a single access point and requires a few IoC classes to be
implemented by the client; this allows for an easy setup and at the same
time it leaves some control to the users.
The library comes as-is with some filters;
clients can extend the functionality by adding their own.

## Table of Contents

- [Introduction](#introduction)
- [Main Features](#main-features)
- [Installation](#installation)
- [Use Case](#use-case)
   - [How (not) to use](#how-not-to-use)
- [Basic Example](#basic-example)
- [License](#license)

=======
Introduction
=======

_eafi_ is an extendable C++ library for processing sampled signals.
The client has to instruct _eafi_ with the signal waveform and a noise model.
Many different filters can be applied, and
clients can add their own or use those already implemented in _eafi_.
The result of the application of the filter is composed by the extracted
signal amplitude, timing, pedestal and correlation matrix
for the parameters. Additional results are the number of iterations
needed by the filter (1 for non-iterative filters), the chi-square value
and the number of degree of freedom for the chi-square.

Additional information, specific for the applied filter or user-defined,
can be inspected by injecting _inspector_ object.

=======
Main Features
=======

 * IoC (Inversion of Control) for signal waveform, noise and sampled signal
 * simple selection of the filter
 * shipped filters:
   - OF (iterative and non-iterative)
   - least min-square
 * possibility to extend the set of filters using client-side code
 * easy to use result interface
 * possibility to log the internal operations of the filters

=======
Installation
=======

 * download the project
 * create a build directory and step-in: `mkdir eafi-build && cd eafi-build`
 * run cmake: `cmake path-to-eafi-CMakeLists.txt`
 * compile lib and test: `make DESTDIR=install-dir`
 * run tests: `make test`
 * install: `make install`

=======
Use Case
=======

The image below introduces the typical use-case for _eafi_:
![signal](https://cloud.githubusercontent.com/assets/12675120/18185419/e065d3e0-709d-11e6-82a6-c9afd5ef5782.png)
The red line is a _reference signal waveform_, that is,
a waveform representing the signal of interest; for example, it may be
the output signal of some electronic filter, normalized to unit area.

The blue line represents the _actual signal_, as it is presented at the
output of the same electric circuitry when some sort of input
is used. Said differently, the blue line can be obtained from the
red one by adding a constant pedestal, amplifying the whole
signal by some factor, and shifting the timing.

The blue signal is then digitized by some ADC, which may also
introduce noise: this is represented by the blue
histogram in the same image. Each of its bins is the result
of a _sampling_ of the blue curve, plus a gaussian noise with zero mean.
Gaussian noise is used just for sake of the example, while
it is important for _eafi_ to work correctly that the noise
has zero average. By the way, this noise model presents no correlations
among the bins, but it is not a requirement for _eafi_ to correctly work.

The _eafi_ purpose is to reconstruct the scale factor that normalizes
the blue curve to the red one (amplitude), the timing shift and the
pedestal of the blue line, starting from the sampled signal and
just assuming that the actual signal has not distortion with
respect to the reference waveform.
The library also evaluates the correlation matrix for the extracted
parameters.

Referring to the example above, starting from the sampled signal
and knowing the signal shape and the noise model, _eafi_ is
able to evaluate a scaling factor of about 1.2, a temporal shift of
1.25 and a pedestal of 0.25 units, plus the correlations among
these parameters.

===
How (not) to use
===

The client cannot expect _eafi_ to solve all the problems related to signal
filtering and fitting. In particular, it assumes that:

  * the client provides the signal shape and the noise model
     * the measured signal is not deformed (i.e. the shape is the same as the waveform)
     * the noise model has zero mean
     * the reference signal points are known at a larger time scale wrt the sampled signal
  * the client specifies which filter to use

On the other side, _eafi_ exposes an uniform interface for all the
passed filters (even if implementation specific details can be obtained).
There are no limitations concerning
the noise correlation among samples: the noise in some sample
can be correlated to the noise in other, which is not so
infrequent in electronics.

The main misunderstanding with _eafi_ is that usually the
client expects it to fit also the signal _width_: once again,
this library is not a complete fitter, therefore it is not suitable
for cases in which the signal shape varies with its amplitude,
even if in a predictable way.

=======
Basic Example
=======

![code example](https://cloud.githubusercontent.com/assets/12675120/18502747/3650af86-7a59-11e6-9484-1ec6e3fc36b4.png)

=======
License
=======

_eafi_ is released under the [MIT LICENSE](http://www.opensource.org/licenses/MIT).


text:
'use strict';

const sinon = require('sinon');
const proxyquire = require('proxyquire').noCallThru();
const assert = require('assert');

const getSample = () => {
  const firestoreMock = {
    doc: sinon.stub().returnsThis(),
    set: sinon.stub(),
  };

  return {
    program: proxyquire('../', {
      '@google-cloud/firestore': sinon.stub().returns(firestoreMock),
    }),
    mocks: {
      firestore: firestoreMock,
    },
  };
};

const stubConsole = function () {
  sinon.stub(console, 'error');
  sinon.stub(console, 'log');
};

const restoreConsole = function () {
  console.log.restore();
  console.error.restore();
};

beforeEach(stubConsole);
afterEach(restoreConsole);

describe('functions_firebase_rtdb', () => {
  it('should listen to RTDB', () => {
    const sample = getSample();

    const delta = {
      foo: 'bar',
    };

    const event = {
      delta: delta,
    };
    const context = {
      resource: 'resource',
      auth: {
        admin: true,
      },
    };

    sample.program.helloRTDB(event, context);

    assert.strictEqual(
      console.log.calledWith('Function triggered by change to: resource'),
      true
    );
    assert.strictEqual(console.log.calledWith('Admin?: true'), true);
    assert.strictEqual(
      console.log.calledWith(JSON.stringify(delta, null, 2)),
      true
    );
  });
});


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20110607152956 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("CREATE TABLE buchungen (id INT AUTO_INCREMENT NOT NULL, reise_id INT DEFAULT NULL, anzahl_reisende INT NOT NULL, buchungs_datum DATE NOT NULL, anrede VARCHAR(20) NOT NULL, vorname VARCHAR(45) NOT NULL, name VARCHAR(45) NOT NULL, strasse VARCHAR(80) NOT NULL, ort VARCHAR(80) NOT NULL, plz VARCHAR(5) NOT NULL, telefon_nr VARCHAR(80) DEFAULT NULL, email VARCHAR(80) DEFAULT NULL, INDEX IDX_3B0618A056A8F558 (reise_id), PRIMARY KEY(id)) ENGINE = InnoDB");
        $this->addSql("ALTER TABLE buchungen ADD FOREIGN KEY (reise_id) REFERENCES reisen(id)");
    }

    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("DROP TABLE buchungen");
    }
}


text:
var isDesktopView = true;

var commonSetting = (function() {
    'use strict';
    var commonSetting = {
        init: function() {
            commonSetting.setupParallaxScroll();
        },
        mobileMaxReserlution: function() {
            return 720;
        },
        isMobile: function() {
            if ($(window).width() <= commonSetting.mobileMaxReserlution()) {
                return true;
            } else {
                return false;
            }
        },
        isPrototypeHost: function() {
            var returnResult = false,
                hostName = location.host;
            if (hostName.indexOf('p1.htc.com') > -1 || hostName.indexOf('prototype-www.htc.com') > -1 || hostName.indexOf('rawgit.com') > -1) {
                returnResult = true;
            }
            return returnResult;
        },
        setupParallaxScroll: function() {
            // parallax scroll
            // $(window).scroll(function(event) {
            //     var parallaxImg = $('.parallax-img'),
            //         scrollTopPosition = $(this).scrollTop();
            //     if (parallaxImg.length > 0) {
            //         $('.parallax-img').css('top', -parseInt(scrollTopPosition / 2.5, 10) + 'px');
            //     }
            // });
        },
        forcePageReload: function() {
            //Force page reload when desktop and mobile switch
            if (commonSetting.switchResolution()) {
                location.reload();
            }
        },
        switchResolution: function() {
            var resultSwitch = false;
            if ($(window).width() <= commonSetting.mobileMaxReserlution() && isDesktopView) {
                resultSwitch = true;
            }
            if ($(window).width() > commonSetting.mobileMaxReserlution() && !isDesktopView) {
                resultSwitch = true;
            }
            return resultSwitch;
        },
        addMobilePopupFix: function() {
            $('body').addClass('m-support-popup-fixed');
            $('.htc-main').addClass('m-support-popup-fixed');
            $('.listing-detailed-container').addClass('m-support-popup-fixed');
            if ($('body').hasClass('backuptransfer-page')) {
                $('.backup-transfer-list').addClass('m-support-popup-fixed');
            }
        },
        removeMobilePopupFix: function() {
            $('body').removeClass('m-support-popup-fixed');
            $('.htc-main').removeClass('m-support-popup-fixed');
            $('.listing-detailed-container').removeClass('m-support-popup-fixed');
            if ($('body').hasClass('backuptransfer-page')) {
                $('.backup-transfer-list').removeClass('m-support-popup-fixed');
            }
        }
    };
    return commonSetting;
}());
$(document).ready(function() {
    'use strict';
    var width = $(window).width();
    if (commonSetting.isMobile()) {
        isDesktopView = false;
    }
    commonSetting.init();
});


text:
name | install name | description |
-|-|-
[yarn](https://www.npmjs.com/package/yarn) | `yarn` | Dependancy manager for node modules `yarn add package`
[jQuery](https://jquery.com/) | `jquery` | DOM manipulation and AJAX requests
[jsdom](https://www.npmjs.com/package/jquery) | `jsdom` | Dom simulator for jquery in node.js
[babel](https://babeljs.io/) | `babel` | ES6 transpiler
[bower](https://bower.io/) | `bower` | web package manager
[express](http://expressjs.com/) | `express` | Web framework
[crypto-js](https://github.com/brix/crypto-js) | `crypto-js` | for creating encrypted passwords
[passport](https://pugjs.org/api/getting-started.html) | `passport` | User authentication library
[grunt](https://gruntjs.com/) | `grunt` | JS task runner
[lodash](https://lodash.com/) | `lodash` | Utility library

### User Interface
||||
-|-|-
[jQuery UI](http://jqueryui.com/) | `jquery-ui` | DOM UI widgets and events
[bootstrap](https://v4-alpha.getbootstrap.com/) | `bootstrap` | Web framework
[toastr](https://github.com/CodeSeven/toastr) | `toastr` | Web notifications
[pixi JS](https://github.com/pixijs/pixi.js) | `pixi`  | 2D JavaScript Renderer

### Frontend
||||
-|-|-
[system JS](https://github.com/systemjs/systemjs) | `systemjs` | Dynamic module loader
[sammy JS](http://sammyjs.org/) | `sammy` | lib for Routing, requires jQuery
[navigo](https://github.com/krasimir/navigo) | `navigo` | lib for Routing

### View Engines
||||
-|-|-
[handlebars](http://handlebarsjs.com/) | `handlebars` | HTML templates
[pug](https://pugjs.org/api/getting-started.html) | `pug` |  View engine like handlebars

### Test frameworks
||||
-|-|-
[mocha](http://mochajs.org/) | `mocha` | JS unit testing framework
[chai](http://chaijs.com/) | `chai` | JS unit testing framework
[selenium](http://www.seleniumhq.org/) | `selenium-webdriver` | Browser automation tests
[istanbul](https://github.com/gotwarlost/istanbul) | `istanbul` | Code coverage tool
[supertest](https://www.npmjs.com/package/supertest) | `supertest` | Integration tests

### HTTP and Requests
||||
-|-|-
[node-fetch](https://www.npmjs.com/package/node-fetch) | `node-fetch` | Make http requests
[socket.io](https://github.com/socketio/socket.io) | `socket.io` | Another http request library
[http-server](https://www.npmjs.com/package/http-server) | `http-server` | JS HTTP Server
[live-server](https://github.com/tapio/live-server) | `live-server` | JS live reloading HTTP server


text:
package org.apache.wink.server;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.wink.common.AbstractDynamicResource;
import org.apache.wink.common.WinkApplication;
import org.apache.wink.server.internal.servlet.MockServletInvocationTest;
import org.apache.wink.test.mock.MockRequestConstructor;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class AbstractResourceWithEmptyPathTest extends MockServletInvocationTest {

    public static class InnerApplication extends WinkApplication {

        @Override
        public Set<Object> getInstances() {
            AbstractTestCollectionResource emptyPath = new AbstractTestCollectionResource();
            emptyPath.setPath("/a");

            AbstractTestCollectionResource2 emptyParent = new AbstractTestCollectionResource2();
            emptyParent.setPath("/emptyParent");
            Set<Object> set = new HashSet<Object>();
            set.add(emptyPath);
            set.add(emptyParent);
            return set;
        }
    }

    @Override
    protected String getApplicationClassName() {
        return InnerApplication.class.getName();
    }

    private static final String EXPECTED_SERVICE_COLLECTION_1 = "expected service collection 1";

    private static final String EXPECTED_SERVICE_COLLECTION_2 = "expected service collection 2";

    public static class AbstractTestCollectionResource extends AbstractDynamicResource {

        @GET
        @Produces( {MediaType.APPLICATION_ATOM_XML})
        public String getServiceCollection() {
            return EXPECTED_SERVICE_COLLECTION_1;
        }
    }

    public static class AbstractTestCollectionResource2 extends AbstractDynamicResource {

        @GET
        @Produces( {MediaType.APPLICATION_ATOM_XML})
        public String getServiceCollection() {
            return EXPECTED_SERVICE_COLLECTION_2;
        }
    }

    public void testBeanWithEmptyPath() throws Exception {
        MockHttpServletRequest mockRequest =
            MockRequestConstructor.constructMockRequest("GET",
                                                        "/a",
                                                        MediaType.APPLICATION_ATOM_XML_TYPE);
        MockHttpServletResponse response = invoke(mockRequest);
        String responseContent = response.getContentAsString();
        assertEquals(EXPECTED_SERVICE_COLLECTION_1, responseContent);
    }

    public void testBeanWithEmptyParent() throws Exception {
        MockHttpServletRequest mockRequest =
            MockRequestConstructor.constructMockRequest("GET",
                                                        "/emptyParent",
                                                        MediaType.APPLICATION_ATOM_XML_TYPE);
        MockHttpServletResponse response = invoke(mockRequest);
        String responseContent = response.getContentAsString();
        assertEquals(EXPECTED_SERVICE_COLLECTION_2, responseContent);
    }

}


text:
namespace SelfLoadSoftDelete.DataAccess.ERLevel
{
    public partial class G05_SubContinent_ChildDto
    {
    }
}


text:
<readable><title>1164765687_7aca07bbe7</title><content>
A man in a red shirt and glasses is bending down towards a small dog on a blanket with several stuffed animals .
A man in a red shirt is giving toys to a small dog .
A man is playing tug of war with his dog .
A man playing with a black dog on a white blanket .
A man playing with his dog on the blanket on the floor .
</content></readable>


text:
@extends('layouts.master')

@section('content-header')

    {{ trans('menu::menu.titles.edit menu item') }}

 {{ trans('core::core.breadcrumb.home') }}

{{ trans('menu::menu.breadcrumb.menu') }}

{{ trans('menu::menu.breadcrumb.edit menu item') }}

@stop

@section('styles')
    {!! Theme::style('css/vendor/iCheck/flat/blue.css') !!}
@stop

@section('content')
{!! Form::open(['route' => ['dashboard.menuitem.update', $menu->id, $menuItem->id], 'method' => 'put']) !!}

{{ trans('core::core.title.translatable fields') }}

                        <?php $i = 0; ?>
                        <?php foreach (LaravelLocalization::getSupportedLocales() as $locale => $language): ?>
                            <?php $i++; ?>

                                {{ trans('core::core.tab.'. strtolower($language['name'])) }}

                        <?php endforeach; ?>

                        <?php $i = 0; ?>
                        <?php foreach (LaravelLocalization::getSupportedLocales() as $locale => $language): ?>
                            <?php $i++; ?>

                                @include('menu::admin.menuitems.partials.edit-trans-fields', ['lang' => $locale])

                        <?php endforeach; ?>

{{ trans('core::core.title.non translatable fields') }}

                @include('menu::admin.menuitems.partials.edit-fields')

            <button type="submit" class="btn btn-primary btn-flat">{{ trans('core::core.button.update') }}</button>
            <button class="btn btn-default btn-flat" name="button" type="reset">{{ trans('core::core.button.reset') }}</button>
            id])}}"> {{ trans('core::core.button.cancel') }}

{!! Form::close() !!}
@stop

@section('footer')

@stop
@section('shortcuts')

b

{{ trans('core::core.back to index', ['name' => 'menu']) }}

@stop

@section('scripts')

@stop


text:
package com.google.zxing.oned;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;
import com.google.zxing.common.GenericResultPoint;

import java.util.Hashtable;

/**
 *
Implements decoding of the ITF format.

 *
 *
"ITF" stands for Interleaved Two of Five. This Reader will scan ITF barcode with 6, 10 or 14 digits.
 * The checksum is optional and is not applied by this Reader. The consumer of the decoded value
 * will have to apply a checksum if required.

 *
 *
http://en.wikipedia.org/wiki/Interleaved_2_of_5
 * is a great reference for Interleaved 2 of 5 information.

 *
 * @author kevin.osullivan@sita.aero, SITA Lab.
 */
public final class ITFReader extends AbstractOneDReader {

  private static final int MAX_AVG_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.42f);
  private static final int MAX_INDIVIDUAL_VARIANCE = (int) (PATTERN_MATCH_RESULT_SCALE_FACTOR * 0.8f);

  private static final int W = 3; // Pixel width of a wide line
  private static final int N = 1; // Pixed width of a narrow line

  // Stores the actual narrow line width of the image being decoded.
  private int narrowLineWidth = -1;

  /**
   * Start/end guard pattern.
   *
   * Note: The end pattern is reversed because the row is reversed before
   * searching for the END_PATTERN
   */
  private static final int[] START_PATTERN = {N, N, N, N};
  private static final int[] END_PATTERN_REVERSED = {N, N, W};

  /**
   * Patterns of Wide / Narrow lines to indicate each digit
   */
  static final int[][] PATTERNS = {
      {N, N, W, W, N}, // 0
      {W, N, N, N, W}, // 1
      {N, W, N, N, W}, // 2
      {W, W, N, N, N}, // 3
      {N, N, W, N, W}, // 4
      {W, N, W, N, N}, // 5
      {N, W, W, N, N}, // 6
      {N, N, N, W, W}, // 7
      {W, N, N, W, N}, // 8
      {N, W, N, W, N}  // 9
  };

  public final Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws ReaderException {

    StringBuffer result = new StringBuffer(20);

    // Find out where the Middle section (payload) starts & ends
    int[] startRange = decodeStart(row);
    int[] endRange = decodeEnd(row);

    decodeMiddle(row, startRange[1], endRange[0], result);

    String resultString = result.toString();

    // To avoid false positives with 2D barcodes (and other patterns), make
    // an assumption that the decoded string must be 6, 10 or 14 digits.
    int length = resultString.length();
    if (length != 6 && length != 10 && length != 14) {
      throw ReaderException.getInstance();
    }

    return new Result(
        resultString,
        null, // no natural byte representation for these barcodes
        new ResultPoint[] { new GenericResultPoint(startRange[1], (float) rowNumber),
                            new GenericResultPoint(startRange[0], (float) rowNumber)},
        BarcodeFormat.ITF);
  }

  /**
   * @param row          row of black/white values to search
   * @param payloadStart offset of start pattern
   * @param resultString {@link StringBuffer} to append decoded chars to
   * @throws ReaderException if decoding could not complete successfully
   */
  protected void decodeMiddle(BitArray row, int payloadStart, int payloadEnd, StringBuffer resultString) throws ReaderException {

    // Digits are interleaved in pairs - 5 black lines for one digit, and the
    // 5
    // interleaved white lines for the second digit.
    // Therefore, need to scan 10 lines and then
    // split these into two arrays
    int[] counterDigitPair = new int[10];
    int[] counterBlack = new int[5];
    int[] counterWhite = new int[5];

    while (payloadStart < payloadEnd) {

      // Get 10 runs of black/white.
      recordPattern(row, payloadStart, counterDigitPair);
      // Split them into each array
      for (int k = 0; k < 5; k++) {
        int twoK = k << 1;
        counterBlack[k] = counterDigitPair[twoK];
        counterWhite[k] = counterDigitPair[twoK + 1];
      }

      int bestMatch = decodeDigit(counterBlack);
      resultString.append((char) ('0' + bestMatch % 10));
      bestMatch = decodeDigit(counterWhite);
      resultString.append((char) ('0' + bestMatch % 10));

      for (int i = 0; i < counterDigitPair.length; i++) {
        payloadStart += counterDigitPair[i];
      }
    }
  }

  /**
   * Identify where the start of the middle / payload section starts.
   *
   * @param row row of black/white values to search
   * @return Array, containing index of start of 'start block' and end of
   *         'start block'
   * @throws ReaderException
   */
  int[] decodeStart(BitArray row) throws ReaderException {
    int endStart = skipWhiteSpace(row);
    int startPattern[] = findGuardPattern(row, endStart, START_PATTERN);

    // Determine the width of a narrow line in pixels. We can do this by
    // getting the width of the start pattern and dividing by 4 because its
    // made up of 4 narrow lines.
    this.narrowLineWidth = (startPattern[1] - startPattern[0]) >> 2;

    validateQuietZone(row, startPattern[0]);

    return startPattern;
  }

  /**
   * The start & end patterns must be pre/post fixed by a quiet zone. This
   * zone must be at least 10 times the width of a narrow line.  Scan back until
   * we either get to the start of the barcode or match the necessary number of
   * quiet zone pixels.
   *
   * Note: Its assumed the row is reversed when using this method to find
   * quiet zone after the end pattern.
   *
   * ref: http://www.barcode-1.net/i25code.html
   *
   * @param row bit array representing the scanned barcode.
   * @param startPattern index into row of the start or end pattern.
   * @throws ReaderException if the quiet zone cannot be found, a ReaderException is thrown.
   */
  private void validateQuietZone(BitArray row, int startPattern) throws ReaderException {

    int quietCount = this.narrowLineWidth * 10;  // expect to find this many pixels of quiet zone

    for (int i = startPattern - 1; quietCount > 0 && i >= 0; i--) {
      if (row.get(i)) {
        break;
      }
      quietCount--;
    }
    if (quietCount != 0) {
      // Unable to find the necessary number of quiet zone pixels.
      throw ReaderException.getInstance();
    }
  }

  /**
   * Skip all whitespace until we get to the first black line.
   *
   * @param row row of black/white values to search
   * @return index of the first black line.
   * @throws ReaderException Throws exception if no black lines are found in the row
   */
  private int skipWhiteSpace(BitArray row) throws ReaderException {
    int width = row.getSize();
    int endStart = 0;
    while (endStart < width) {
      if (row.get(endStart)) {
        break;
      }
      endStart++;
    }
    if (endStart == width) {
      throw ReaderException.getInstance();
    }

    return endStart;
  }

  /**
   * Identify where the end of the middle / payload section ends.
   *
   * @param row row of black/white values to search
   * @return Array, containing index of start of 'end block' and end of 'end
   *         block'
   * @throws ReaderException
   */

  int[] decodeEnd(BitArray row) throws ReaderException {

    // For convenience, reverse the row and then
    // search from 'the start' for the end block
    row.reverse();

    int endStart = skipWhiteSpace(row);
    int endPattern[];
    try {
      endPattern = findGuardPattern(row, endStart, END_PATTERN_REVERSED);
    } catch (ReaderException e) {
      // Put our row of data back the right way before throwing
      row.reverse();
      throw e;
    }

    // The start & end patterns must be pre/post fixed by a quiet zone. This
    // zone must be at least 10 times the width of a narrow line.
    // ref: http://www.barcode-1.net/i25code.html
    validateQuietZone(row, endPattern[0]);

    // Now recalc the indicies of where the 'endblock' starts & stops to
    // accomodate
    // the reversed nature of the search
    int temp = endPattern[0];
    endPattern[0] = row.getSize() - endPattern[1];
    endPattern[1] = row.getSize() - temp;

    // Put the row back the righ way.
    row.reverse();
    return endPattern;
  }

  /**
   * @param row       row of black/white values to search
   * @param rowOffset position to start search
   * @param pattern   pattern of counts of number of black and white pixels that are
   *                  being searched for as a pattern
   * @return start/end horizontal offset of guard pattern, as an array of two
   *         ints
   * @throws ReaderException if pattern is not found
   */
  int[] findGuardPattern(BitArray row, int rowOffset, int[] pattern) throws ReaderException {

    // TODO: This is very similar to implementation in AbstractUPCEANReader. Consider if they can be merged to
    // a single method.

    int patternLength = pattern.length;
    int[] counters = new int[patternLength];
    int width = row.getSize();
    boolean isWhite = false;

    int counterPosition = 0;
    int patternStart = rowOffset;
    for (int x = rowOffset; x < width; x++) {
      boolean pixel = row.get(x);
      if ((!pixel && isWhite) || (pixel && !isWhite)) {
        counters[counterPosition]++;
      } else {
        if (counterPosition == patternLength - 1) {
          if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) {
            return new int[]{patternStart, x};
          }
          patternStart += counters[0] + counters[1];
          for (int y = 2; y < patternLength; y++) {
            counters[y - 2] = counters[y];
          }
          counters[patternLength - 2] = 0;
          counters[patternLength - 1] = 0;
          counterPosition--;
        } else {
          counterPosition++;
        }
        counters[counterPosition] = 1;
        isWhite = !isWhite;
      }
    }
    throw ReaderException.getInstance();
  }

  /**
   * Attempts to decode a sequence of ITF black/white lines into single
   * digit.
   *
   * @param counters the counts of runs of observed black/white/black/... values
   * @return The decoded digit
   * @throws ReaderException if digit cannot be decoded
   */
  static int decodeDigit(int[] counters) throws ReaderException {

    int bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept
    int bestMatch = -1;
    int max = PATTERNS.length;
    for (int i = 0; i < max; i++) {
      int[] pattern = PATTERNS[i];
      int variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE);
      if (variance < bestVariance) {
        bestVariance = variance;
        bestMatch = i;
      }
    }
    if (bestMatch >= 0) {
      return bestMatch;
		} else {
			throw ReaderException.getInstance();
		}
	}

}


text:
<?php

declare(strict_types=1);

namespace Biplane\YandexDirect\Api\V5\Contract;

use AllowDynamicProperties;

/**
 * Auto-generated code.
 */
#[AllowDynamicProperties]
class GetRetargetingListsResponse extends GetResponseGeneral
{
//    Can be omitted.
//    protected $RetargetingLists = null;

    /**
     * @return RetargetingListGetItem[]|null
     */
    public function getRetargetingLists(): ?array
    {
        return $this->RetargetingLists ?? null;
    }

    /**
     * @param RetargetingListGetItem[]|null $value
     *
     * @return $this
     */
    public function setRetargetingLists(?array $value = null)
    {
        $this->RetargetingLists = $value;

        return $this;
    }
}


text:
/**
 * Created by atoui on 18/08/2017.
 */
export class Admin {
    constructor(
        _id?: string,
        email?: string,
        password?: string,
        fristname? : string,
        lastname? : string
    ){}
}


text:
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

/*
 *
 *
 *
 *
 *
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.List;
import java.util.Collection;

/**
 * An {@link Executor} that provides methods to manage termination and
 * methods that can produce a {@link Future} for tracking progress of
 * one or more asynchronous tasks.
 *
 *
An {@code ExecutorService} can be shut down, which will cause
 * it to reject new tasks.  Two different methods are provided for
 * shutting down an {@code ExecutorService}. The {@link #shutdown}
 * method will allow previously submitted tasks to execute before
 * terminating, while the {@link #shutdownNow} method prevents waiting
 * tasks from starting and attempts to stop currently executing tasks.
 * Upon termination, an executor has no tasks actively executing, no
 * tasks awaiting execution, and no new tasks can be submitted.  An
 * unused {@code ExecutorService} should be shut down to allow
 * reclamation of its resources.
 *
 *
Method {@code submit} extends base method {@link
 * Executor#execute(Runnable)} by creating and returning a {@link Future}
 * that can be used to cancel execution and/or wait for completion.
 * Methods {@code invokeAny} and {@code invokeAll} perform the most
 * commonly useful forms of bulk execution, executing a collection of
 * tasks and then waiting for at least one, or all, to
 * complete. (Class {@link ExecutorCompletionService} can be used to
 * write customized variants of these methods.)
 *
 *
The {@link Executors} class provides factory methods for the
 * executor services provided in this package.
 *
 *
Usage Examples

 *
 * Here is a sketch of a network service in which threads in a thread
 * pool service incoming requests. It uses the preconfigured {@link
 * Executors#newFixedThreadPool} factory method:
 *
 *
 {@code
 * class NetworkService implements Runnable {
 *   private final ServerSocket serverSocket;
 *   private final ExecutorService pool;
 *
 *   public NetworkService(int port, int poolSize)
 *       throws IOException {
 *     serverSocket = new ServerSocket(port);
 *     pool = Executors.newFixedThreadPool(poolSize);
 *   }
 *
 *   public void run() { // run the service
 *     try {
 *       for (;;) {
 *         pool.execute(new Handler(serverSocket.accept()));
 *       }
 *     } catch (IOException ex) {
 *       pool.shutdown();
 *     }
 *   }
 * }
 *
 * class Handler implements Runnable {
 *   private final Socket socket;
 *   Handler(Socket socket) { this.socket = socket; }
 *   public void run() {
 *     // read and service request on socket
 *   }
 * }}

 *
 * The following method shuts down an {@code ExecutorService} in two phases,
 * first by calling {@code shutdown} to reject incoming tasks, and then
 * calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:
 *
 *
 {@code
 * void shutdownAndAwaitTermination(ExecutorService pool) {
 *   pool.shutdown(); // Disable new tasks from being submitted
 *   try {
 *     // Wait a while for existing tasks to terminate
 *     if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
 *       pool.shutdownNow(); // Cancel currently executing tasks
 *       // Wait a while for tasks to respond to being cancelled
 *       if (!pool.awaitTermination(60, TimeUnit.SECONDS))
 *           System.err.println("Pool did not terminate");
 *     }
 *   } catch (InterruptedException ie) {
 *     // (Re-)Cancel if current thread also interrupted
 *     pool.shutdownNow();
 *     // Preserve interrupt status
 *     Thread.currentThread().interrupt();
 *   }
 * }}

 *
 *
Memory consistency effects: Actions in a thread prior to the
 * submission of a {@code Runnable} or {@code Callable} task to an
 * {@code ExecutorService}
 * happen-before
 * any actions taken by that task, which in turn happen-before the
 * result is retrieved via {@code Future.get()}.
 *
 * @since 1.5
 * @author Doug Lea
 */
public interface ExecutorService extends Executor {

    /**
     * Initiates an orderly shutdown in which previously submitted
     * tasks are executed, but no new tasks will be accepted.
     * Invocation has no additional effect if already shut down.
     *
     *
This method does not wait for previously submitted tasks to
     * complete execution.  Use {@link #awaitTermination awaitTermination}
     * to do that.
     *
     * @throws SecurityException if a security manager exists and
     *         shutting down this ExecutorService may manipulate
     *         threads that the caller is not permitted to modify
     *         because it does not hold {@link
     *         java.lang.RuntimePermission}{@code ("modifyThread")},
     *         or the security manager's {@code checkAccess} method
     *         denies access.
     */
    void shutdown();

    /**
     * Attempts to stop all actively executing tasks, halts the
     * processing of waiting tasks, and returns a list of the tasks
     * that were awaiting execution.
     *
     *
This method does not wait for actively executing tasks to
     * terminate.  Use {@link #awaitTermination awaitTermination} to
     * do that.
     *
     *
There are no guarantees beyond best-effort attempts to stop
     * processing actively executing tasks.  For example, typical
     * implementations will cancel via {@link Thread#interrupt}, so any
     * task that fails to respond to interrupts may never terminate.
     *
     * @return list of tasks that never commenced execution
     * @throws SecurityException if a security manager exists and
     *         shutting down this ExecutorService may manipulate
     *         threads that the caller is not permitted to modify
     *         because it does not hold {@link
     *         java.lang.RuntimePermission}{@code ("modifyThread")},
     *         or the security manager's {@code checkAccess} method
     *         denies access.
     */
    List<Runnable> shutdownNow();

    /**
     * Returns {@code true} if this executor has been shut down.
     *
     * @return {@code true} if this executor has been shut down
     */
    boolean isShutdown();

    /**
     * Returns {@code true} if all tasks have completed following shut down.
     * Note that {@code isTerminated} is never {@code true} unless
     * either {@code shutdown} or {@code shutdownNow} was called first.
     *
     * @return {@code true} if all tasks have completed following shut down
     */
    boolean isTerminated();

    /**
     * Blocks until all tasks have completed execution after a shutdown
     * request, or the timeout occurs, or the current thread is
     * interrupted, whichever happens first.
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return {@code true} if this executor terminated and
     *         {@code false} if the timeout elapsed before termination
     * @throws InterruptedException if interrupted while waiting
     */
    boolean awaitTermination(long timeout, TimeUnit unit)
        throws InterruptedException;

    /**
     * Submits a value-returning task for execution and returns a
     * Future representing the pending results of the task. The
     * Future's {@code get} method will return the task's result upon
     * successful completion.
     *
     *

     * If you would like to immediately block waiting
     * for a task, you can use constructions of the form
     * {@code result = exec.submit(aCallable).get();}
     *
     *
Note: The {@link Executors} class includes a set of methods
     * that can convert some other common closure-like objects,
     * for example, {@link java.security.PrivilegedAction} to
     * {@link Callable} form so they can be submitted.
     *
     * @param task the task to submit
     * @param <T> the type of the task's result
     * @return a Future representing pending completion of the task
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    <T> Future<T> submit(Callable<T> task);

    /**
     * Submits a Runnable task for execution and returns a Future
     * representing that task. The Future's {@code get} method will
     * return the given result upon successful completion.
     *
     * @param task the task to submit
     * @param result the result to return
     * @param <T> the type of the result
     * @return a Future representing pending completion of the task
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    <T> Future<T> submit(Runnable task, T result);

    /**
     * Submits a Runnable task for execution and returns a Future
     * representing that task. The Future's {@code get} method will
     * return {@code null} upon successful completion.
     *
     * @param task the task to submit
     * @return a Future representing pending completion of the task
     * @throws RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if the task is null
     */
    Future<?> submit(Runnable task);

    /**
     * Executes the given tasks, returning a list of Futures holding
     * their status and results when all complete.
     * {@link Future#isDone} is {@code true} for each
     * element of the returned list.
     * Note that a completed task could have
     * terminated either normally or by throwing an exception.
     * The results of this method are undefined if the given
     * collection is modified while this operation is in progress.
     *
     * @param tasks the collection of tasks
     * @param <T> the type of the values returned from the tasks
     * @return a list of Futures representing the tasks, in the same
     *         sequential order as produced by the iterator for the
     *         given task list, each of which has completed
     * @throws InterruptedException if interrupted while waiting, in
     *         which case unfinished tasks are cancelled
     * @throws NullPointerException if tasks or any of its elements are {@code null}
     * @throws RejectedExecutionException if any task cannot be
     *         scheduled for execution
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

    /**
     * Executes the given tasks, returning a list of Futures holding
     * their status and results
     * when all complete or the timeout expires, whichever happens first.
     * {@link Future#isDone} is {@code true} for each
     * element of the returned list.
     * Upon return, tasks that have not completed are cancelled.
     * Note that a completed task could have
     * terminated either normally or by throwing an exception.
     * The results of this method are undefined if the given
     * collection is modified while this operation is in progress.
     *
     * @param tasks the collection of tasks
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @param <T> the type of the values returned from the tasks
     * @return a list of Futures representing the tasks, in the same
     *         sequential order as produced by the iterator for the
     *         given task list. If the operation did not time out,
     *         each task will have completed. If it did time out, some
     *         of these tasks will not have completed.
     * @throws InterruptedException if interrupted while waiting, in
     *         which case unfinished tasks are cancelled
     * @throws NullPointerException if tasks, any of its elements, or
     *         unit are {@code null}
     * @throws RejectedExecutionException if any task cannot be scheduled
     *         for execution
     */
    <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
                                  long timeout, TimeUnit unit)
        throws InterruptedException;

    /**
     * Executes the given tasks, returning the result
     * of one that has completed successfully (i.e., without throwing
     * an exception), if any do. Upon normal or exceptional return,
     * tasks that have not completed are cancelled.
     * The results of this method are undefined if the given
     * collection is modified while this operation is in progress.
     *
     * @param tasks the collection of tasks
     * @param <T> the type of the values returned from the tasks
     * @return the result returned by one of the tasks
     * @throws InterruptedException if interrupted while waiting
     * @throws NullPointerException if tasks or any element task
     *         subject to execution is {@code null}
     * @throws IllegalArgumentException if tasks is empty
     * @throws ExecutionException if no task successfully completes
     * @throws RejectedExecutionException if tasks cannot be scheduled
     *         for execution
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks)
        throws InterruptedException, ExecutionException;

    /**
     * Executes the given tasks, returning the result
     * of one that has completed successfully (i.e., without throwing
     * an exception), if any do before the given timeout elapses.
     * Upon normal or exceptional return, tasks that have not
     * completed are cancelled.
     * The results of this method are undefined if the given
     * collection is modified while this operation is in progress.
     *
     * @param tasks the collection of tasks
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @param <T> the type of the values returned from the tasks
     * @return the result returned by one of the tasks
     * @throws InterruptedException if interrupted while waiting
     * @throws NullPointerException if tasks, or unit, or any element
     *         task subject to execution is {@code null}
     * @throws TimeoutException if the given timeout elapses before
     *         any task successfully completes
     * @throws ExecutionException if no task successfully completes
     * @throws RejectedExecutionException if tasks cannot be scheduled
     *         for execution
     */
    <T> T invokeAny(Collection<? extends Callable<T>> tasks,
                    long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Axis2/C: Axis2_rm_assertion_builder</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Modules

Classes

Files

Directories

Related Pages

Examples

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Axis2_rm_assertion_builder

Functions

AXIS2_EXTERN

neethi_assertion_t * 	axis2_rm_assertion_builder_build (const axutil_env_t *env, axiom_node_t *rm_assertion_node, axiom_element_t *rm_assertion_ele)

<address style="text-align: right;">Generated on Fri Apr 17 11:49:45 2009 for Axis2/C by

 1.5.3 </address>


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

using Xamarin.Forms;

using NUnit.Framework;

namespace Xamarin.Forms.Xaml.UnitTests.A
{
	public partial class Bz31234 : ContentPage
	{
		public Bz31234 ()
		{
			InitializeComponent ();
		}

		public Bz31234 (bool useCompiledXaml)
		{
			//this stub will be replaced at compile time
		}

		[TestFixture]
		public class Tests
		{
			[TestCase(true), TestCase(false)]
			public void ShouldPass (bool useCompiledXaml)
			{
				new Bz31234 (useCompiledXaml);
				Assert.Pass ();
			}
		}
	}
}


text:
package org.springframework.samples.mvc.mapping;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MappingController {

	@RequestMapping("/mapping/path")
	public @ResponseBody String byPath() {
		return "Mapped by path!";
	}

	@RequestMapping(value="/mapping/path/*", method=RequestMethod.GET)
	public @ResponseBody String byPathPattern(HttpServletRequest request) {
		return "Mapped by path pattern ('" + request.getRequestURI() + "')";
	}

	@RequestMapping(value="/mapping/method", method=RequestMethod.GET)
	public @ResponseBody String byMethod() {
		return "Mapped by path + method";
	}

	@RequestMapping(value="/mapping/parameter", method=RequestMethod.GET, params="foo")
	public @ResponseBody String byParameter() {
		return "Mapped by path + method + presence of query parameter!";
	}

	@RequestMapping(value="/mapping/parameter", method=RequestMethod.GET, params="!foo")
	public @ResponseBody String byParameterNegation() {
		return "Mapped by path + method + not presence of query parameter!";
	}

	@RequestMapping(value="/mapping/header", method=RequestMethod.GET, headers="FooHeader=foo")
	public @ResponseBody String byHeader() {
		return "Mapped by path + method + presence of header!";
	}

	@RequestMapping(value="/mapping/header", method=RequestMethod.GET, headers="!FooHeader")
	public @ResponseBody String byHeaderNegation() {
		return "Mapped by path + method + absence of header!";
	}

	@RequestMapping(value="/mapping/consumes", method=RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody String byConsumes(@RequestBody JavaBean javaBean) {
		return "Mapped by path + method + consumable media type (javaBean '" + javaBean + "')";
	}

	@RequestMapping(value="/mapping/produces", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
	public @ResponseBody JavaBean byProducesJson() {
		return new JavaBean();
	}

	@RequestMapping(value="/mapping/produces", method=RequestMethod.GET, produces=MediaType.APPLICATION_XML_VALUE)
	public @ResponseBody JavaBean byProducesXml() {
		return new JavaBean();
	}

}


text:
class ShopTransactionInfo < ActiveRecord::Migration
  def self.up
    add_column :shop_order_transactions, :end_user_id, :integer
    add_column :shop_order_transactions, :transaction_reference, :integer

    add_column :shop_orders, :payment_type, :string, :default => 'standard'
    add_column :shop_orders, :payment_identifier, :string, :default => ''
  end

  def self.down

    remove_column :shop_order_transactions, :end_user_id
    remove_column :shop_order_transactions, :transaction_reference

    remove_column :shop_orders, :payment_type
    remove_column :shop_orders, :payment_identifier
  end

end


text:
<bones>
<head>
  <link type ="xml" module="tabitem" file="tabitem.xml"></link>
  <link type ='script' module ='tabctrl' file ='tabctrl.lua'></link>
</head>
<body>
  <shape>
    <!--垂直的一条线-->
    <shape></shape>
    <tabitem></tabitem>
    <tabitem></tabitem>
    <tabitem></tabitem>
    <tabitem></tabitem>
    <tabitem></tabitem>
    <notify name ='onCreate' module='tabctrl' func='onCreate'></notify>
    <notify name ='onSizeChanged' module='tabctrl' func='onSizeChanged'></notify>
  </shape>
</body>
</bones>


text:
<!-- TITLE/ -->

# TypeChecker

<!-- /TITLE -->

<!-- BADGES/ -->

[![Build Status](http://img.shields.io/travis-ci/bevry/typechecker.png?branch=master)](http://travis-ci.org/bevry/typechecker "Check this project's build status on TravisCI")
[![NPM version](https://badge.fury.io/js/typechecker.png)](https://npmjs.org/package/typechecker "View this project on NPM")
[![Gittip donate button](http://img.shields.io/gittip/bevry.png)](https://www.gittip.com/bevry/ "Donate weekly to this project using Gittip")
[![Flattr donate button](https://raw.github.com/balupton/flattr-buttons/master/badge-89x18.gif)](http://flattr.com/thing/344188/balupton-on-Flattr "Donate monthly to this project using Flattr")
[![PayPayl donate button](https://www.paypalobjects.com/en_AU/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QB8GQPZAH84N6 "Donate once-off to this project using Paypal")

<!-- /BADGES -->

<!-- DESCRIPTION/ -->

Utilities to get and check variable types (isString, isPlainObject, isRegExp, etc)

<!-- /DESCRIPTION -->

<!-- INSTALL/ -->

## Install

### [Node](http://nodejs.org/), [Browserify](http://browserify.org/)
- Use: `require('typechecker')`
- Install: `npm install --save typechecker`

### [Ender](http://ender.jit.su/)
- Use: `require('typechecker')`
- Install: `ender add typechecker`

<!-- /INSTALL -->

## Usage

### Example

``` javascript
require('typechecker').isRegExp(/^a/)  // returns true
```

### Methods

- `getObjectType` - returns the object string of the value, e.g. when passed `/^a/` it'll return `"[object RegExp]"`
- `getType` - returns lower case string of the type, e.g. when passed `/^a/` it'll return `"regex"`
- `isPlainObject` - returns `true` if the value doesn't have a custom prototype
- `isError` - returns `true` if the value an error, otherwise `false`
- `isDate` - returns `true` if the value is a date, otherwise `false`
- `isArguments` - returns `true` if the value is function arguments, otherwise `false`
- `isFunction` - returns `true` if the value is a function, otherwise `false`
- `isRegExp` - returns `true` if the value is a regular expression instance, otherwise `false`
- `isArray` - returns `true` if the value is an array, otherwise `false`
- `isNumber` - returns `true` if the value is a number (`"2"` is a string), otherwise `false`
- `isString` - returns `true` if the value is a string, otherwise `false`
- `isBoolean` - returns `true` if the value is a boolean, otherwise `false`
- `isNull` - returns `true` if the value is null, otherwise `false`
- `isUndefined` - returns `true` if the value is undefined, otherwise `false`
- `isEmpty` - returns `true` if the value is `null` or `undefined`
- `isEmptyObject` - returns `true` if the object has no keys that are its own

### Notes

Why should I use this instead of say `instanceof`? Under certain circumstances `instanceof` may not return the correct results.
This occurs with [node's vm module](http://nodejs.org/api/vm.html#vm_globals) especially, and circumstances where an object's prototype has been dereferenced from the original.
As such, for basic `==` and `===` checks (like `a === null`), you're fine not using this, but for checks when you would have done `instanceof` (like `err instanceof Error`), you should try to use this instead.
Plus things like `isEmptyObject` and `isPlainObject` are darn useful!

<!-- HISTORY/ -->

## History
[Discover the change history by heading on over to the `History.md` file.](https://github.com/bevry/typechecker/blob/master/History.md#files)

<!-- /HISTORY -->

<!-- CONTRIBUTE/ -->

## Contribute

[Discover how you can contribute by heading on over to the `Contributing.md` file.](https://github.com/bevry/typechecker/blob/master/Contributing.md#files)

<!-- /CONTRIBUTE -->

<!-- BACKERS/ -->

## Backers

### Maintainers

These amazing people are maintaining this project:

- Benjamin Lupton <b@lupton.cc> (https://github.com/balupton)

### Sponsors

No sponsors yet! Will you be the first?

[![Gittip donate button](http://img.shields.io/gittip/bevry.png)](https://www.gittip.com/bevry/ "Donate weekly to this project using Gittip")
[![Flattr donate button](https://raw.github.com/balupton/flattr-buttons/master/badge-89x18.gif)](http://flattr.com/thing/344188/balupton-on-Flattr "Donate monthly to this project using Flattr")
[![PayPayl donate button](https://www.paypalobjects.com/en_AU/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=QB8GQPZAH84N6 "Donate once-off to this project using Paypal")

### Contributors

These amazing people have contributed code to this project:

- Benjamin Lupton <b@lupton.cc> (https://github.com/balupton) - [view contributions](https://github.com/bevry/typechecker/commits?author=balupton)
- sfrdmn (https://github.com/sfrdmn) - [view contributions](https://github.com/bevry/typechecker/commits?author=sfrdmn)

[Become a contributor!](https://github.com/bevry/typechecker/blob/master/Contributing.md#files)

<!-- /BACKERS -->

<!-- LICENSE/ -->

## License

Licensed under the incredibly [permissive](http://en.wikipedia.org/wiki/Permissive_free_software_licence) [MIT license](http://creativecommons.org/licenses/MIT/)

Copyright © 2013+ Bevry Pty Ltd <us@bevry.me> (http://bevry.me)
<br/>Copyright © 2011-2012 Benjamin Lupton <b@lupton.cc> (http://balupton.com)

<!-- /LICENSE -->


text:
package com.qmetry.qaf.automation.testng;

import org.testng.SkipException;

/**
 * exception class to indicate special skip
 *
 * @author chirag
 */
public class DataProviderException extends SkipException {

	public DataProviderException(String message) {
		super(message);

	}

	public DataProviderException(String message, Throwable cause) {
		super(message, cause);

	}

	@Override
	public boolean isSkip() {
		return true;
	}

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

}


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Model_users extends CI_Model {

	public function check_credential()
	{
		$email = set_value('email');
		$password = set_value('password');

		$hasil = $this->db->where('user_email', $email)
						  ->where('user_pass', md5($password))
						  ->limit(1)
						  ->get('users');

		if($hasil->num_rows() > 0){
			return $hasil->row();
		} else {
			return array();
		}
	}

}