text:
#define WIN32_LEAN_AND_MEAN

#undef inline
#define inline inline

//  IIS7 Server API header file
#include <Windows.h>
#include <sal.h>
#include <strsafe.h>
#include "httpserv.h"

//  Project header files
#include "mymodule.h"
#include "mymodulefactory.h"

#include "api.h"
#include "moduleconfig.h"

#include "winsock2.h"

class REQUEST_STORED_CONTEXT : public IHttpStoredContext
{
 public:
    REQUEST_STORED_CONTEXT()
	{
		m_pConnRec = NULL;
		m_pRequestRec = NULL;
		m_pHttpContext = NULL;
		m_pProvider = NULL;
		m_pResponseBuffer = NULL;
		m_pResponseLength = 0;
		m_pResponsePosition = 0;
	}

    ~REQUEST_STORED_CONTEXT()
	{
		FinishRequest();
	}

    // virtual
    VOID
    CleanupStoredContext(
        VOID
    )
    {
		FinishRequest();
        delete this;
    }

	void FinishRequest()
	{
		if(m_pRequestRec != NULL)
		{
			modsecFinishRequest(m_pRequestRec);
			m_pRequestRec = NULL;
		}
		if(m_pConnRec != NULL)
		{
			modsecFinishConnection(m_pConnRec);
			m_pConnRec = NULL;
		}
	}

	conn_rec			*m_pConnRec;
	request_rec			*m_pRequestRec;
	IHttpContext		*m_pHttpContext;
	IHttpEventProvider	*m_pProvider;
	char				*m_pResponseBuffer;
	ULONGLONG			m_pResponseLength;
	ULONGLONG			m_pResponsePosition;
};

//----------------------------------------------------------------------------

char *GetIpAddr(apr_pool_t *pool, PSOCKADDR pAddr)
{
	const char *format = "%15[0-9.]:%5[0-9]";
	char ip[16] = { 0 };  // ip4 addresses have max len 15
	char port[6] = { 0 }; // port numbers are 16bit, ie 5 digits max

	DWORD len = 50;
	char *buf = (char *)apr_palloc(pool, len);

	if(buf == NULL)
		return "";

	buf[0] = 0;

	WSAAddressToString(pAddr, sizeof(SOCKADDR), NULL, buf, &len);

	// test for IPV4 with port on the end
	if (sscanf(buf, format, ip, port) == 2) {
		// IPV4 but with port - remove the port
		char* input = ":";
		char* ipv4 = strtok(buf, input);
		return ipv4;
	}

	return buf;
}

apr_sockaddr_t *CopySockAddr(apr_pool_t *pool, PSOCKADDR pAddr)
{
    apr_sockaddr_t *addr = (apr_sockaddr_t *)apr_palloc(pool, sizeof(apr_sockaddr_t));
	int adrlen = 16, iplen = 4;

	if(pAddr->sa_family == AF_INET6)
	{
		adrlen = 46;
		iplen = 16;
	}

	addr->addr_str_len = adrlen;
	addr->family = pAddr->sa_family;

	addr->hostname = "unknown";
#ifdef WIN32
    addr->ipaddr_len = sizeof(IN_ADDR);
#else
    addr->ipaddr_len = sizeof(struct in_addr);
#endif
    addr->ipaddr_ptr = &addr->sa.sin.sin_addr;
    addr->pool = pool;
    addr->port = 80;
#ifdef WIN32
	memcpy(&addr->sa.sin.sin_addr.S_un.S_addr, pAddr->sa_data, iplen);
#else
    memcpy(&addr->sa.sin.sin_addr.s_addr, pAddr->sa_data, iplen);
#endif
	addr->sa.sin.sin_family = pAddr->sa_family;
    addr->sa.sin.sin_port = 80;
    addr->salen = sizeof(addr->sa);
	addr->servname = addr->hostname;

	return addr;
}

//----------------------------------------------------------------------------

char *ZeroTerminate(const char *str, size_t len, apr_pool_t *pool)
{
	char *_n = (char *)apr_palloc(pool, len + 1);

	memcpy(_n, str, len);

	_n[len] = 0;

	return _n;
}

//----------------------------------------------------------------------------
// FUNCTION: ConvertUTF16ToUTF8
// DESC: Converts Unicode UTF-16 (Windows default) text to Unicode UTF-8.
//----------------------------------------------------------------------------

char *ConvertUTF16ToUTF8( __in const WCHAR * pszTextUTF16, size_t cchUTF16, apr_pool_t *pool )
{
    //
    // Special case of NULL or empty input string
    //
    if ( (pszTextUTF16 == NULL) || (*pszTextUTF16 == L'\0') || cchUTF16 == 0 )
    {
        // Return empty string
        return "";
    }

    //
    // Get size of destination UTF-8 buffer, in CHAR's (= bytes)
    //
    int cbUTF8 = ::WideCharToMultiByte(
        CP_UTF8,                // convert to UTF-8
        0,      // specify conversion behavior
        pszTextUTF16,           // source UTF-16 string
        static_cast<int>( cchUTF16 ),   // total source string length, in WCHAR's,
        NULL,                   // unused - no conversion required in this step
        0,                      // request buffer size
        NULL, NULL              // unused
        );

    if ( cbUTF8 == 0 )
    {
		return "";
    }

    //
    // Allocate destination buffer for UTF-8 string
    //

    int cchUTF8 = cbUTF8; // sizeof(CHAR) = 1 byte

    char *pszUTF8 = (char *)apr_palloc(pool, cchUTF8 + 1 );

    //
    // Do the conversion from UTF-16 to UTF-8
    //
    int result = ::WideCharToMultiByte(
        CP_UTF8,                // convert to UTF-8
        0,      // specify conversion behavior
        pszTextUTF16,           // source UTF-16 string
        static_cast<int>( cchUTF16 ),   // total source string length, in WCHAR's,
                                        // including end-of-string \0
        pszUTF8,                // destination buffer
        cbUTF8,                 // destination buffer size, in bytes
        NULL, NULL              // unused
        );

    if ( result == 0 )
    {
		return "";
    }

	pszUTF8[cchUTF8] =  0;

    return pszUTF8;
}

void Log(void *obj, int level, char *str)
{
	CMyHttpModule *mod = (CMyHttpModule *)obj;
	WORD logcat = EVENTLOG_INFORMATION_TYPE;

	level &= APLOG_LEVELMASK;

	if(level <= APLOG_ERR)
		logcat = EVENTLOG_ERROR_TYPE;

	if(level == APLOG_WARNING || strstr(str, "Warning.") != NULL)
		logcat = EVENTLOG_WARNING_TYPE;

	mod->WriteEventViewerLog(str, logcat);
}

#define NOTE_IIS "iis-tx-context"

void StoreIISContext(request_rec *r, REQUEST_STORED_CONTEXT *rsc)
{
    apr_table_setn(r->notes, NOTE_IIS, (const char *)rsc);
}

REQUEST_STORED_CONTEXT *RetrieveIISContext(request_rec *r)
{
    REQUEST_STORED_CONTEXT *msr = NULL;
    request_rec *rx = NULL;

    /* Look in the current request first. */
    msr = (REQUEST_STORED_CONTEXT *)apr_table_get(r->notes, NOTE_IIS);
    if (msr != NULL) {
        //msr->r = r;
        return msr;
    }

    /* If this is a subrequest then look in the main request. */
    if (r->main != NULL) {
        msr = (REQUEST_STORED_CONTEXT *)apr_table_get(r->main->notes, NOTE_IIS);
        if (msr != NULL) {
            //msr->r = r;
            return msr;
        }
    }

    /* If the request was redirected then look in the previous requests. */
    rx = r->prev;
    while(rx != NULL) {
        msr = (REQUEST_STORED_CONTEXT *)apr_table_get(rx->notes, NOTE_IIS);
        if (msr != NULL) {
            //msr->r = r;
            return msr;
        }
        rx = rx->prev;
    }

    return NULL;
}

HRESULT CMyHttpModule::ReadFileChunk(HTTP_DATA_CHUNK *chunk, char *buf)
{
    OVERLAPPED ovl;
    DWORD dwDataStartOffset;
    ULONGLONG bytesTotal = 0;
	BYTE *	pIoBuffer = NULL;
	HANDLE	hIoEvent = INVALID_HANDLE_VALUE;
	HRESULT hr = S_OK;

    pIoBuffer = (BYTE *)VirtualAlloc(NULL,
                                        1,
                                        MEM_COMMIT | MEM_RESERVE,
                                        PAGE_READWRITE);
    if (pIoBuffer == NULL)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
		goto Done;
    }

    hIoEvent = CreateEvent(NULL,  // security attr
                                FALSE, // manual reset
                                FALSE, // initial state
                                NULL); // name
    if (hIoEvent == NULL)
    {
        hr = HRESULT_FROM_WIN32(GetLastError());
		goto Done;
    }

	while(bytesTotal < chunk->FromFileHandle.ByteRange.Length.QuadPart)
	{
		DWORD bytesRead = 0;
		int was_eof = 0;
		ULONGLONG offset = chunk->FromFileHandle.ByteRange.StartingOffset.QuadPart + bytesTotal;

		ZeroMemory(&ovl, sizeof ovl);
		ovl.hEvent     = hIoEvent;
		ovl.Offset = (DWORD)offset;
		dwDataStartOffset = ovl.Offset & (m_dwPageSize - 1);
		ovl.Offset &= ~(m_dwPageSize - 1);
		ovl.OffsetHigh = offset >> 32;

		if (!ReadFile(chunk->FromFileHandle.FileHandle,
					  pIoBuffer,
					  m_dwPageSize,
					  &bytesRead,
					  &ovl))
		{
			DWORD dwErr = GetLastError();

			switch (dwErr)
			{
			case ERROR_IO_PENDING:
				//
				// GetOverlappedResult can return without waiting for the
				// event thus leaving it signalled and causing problems
				// with future use of that event handle, so just wait ourselves
				//
				WaitForSingleObject(ovl.hEvent, INFINITE); // == WAIT_OBJECT_0);

				if (!GetOverlappedResult(
						 chunk->FromFileHandle.FileHandle,
						 &ovl,
						 &bytesRead,
						 TRUE))
				{
					dwErr = GetLastError();

					switch(dwErr)
					{
					case ERROR_HANDLE_EOF:
						was_eof = 1;
						break;

					default:
						hr = HRESULT_FROM_WIN32(dwErr);
						goto Done;
					}
				}
				break;

			case ERROR_HANDLE_EOF:
				was_eof = 1;
				break;

			default:
				hr = HRESULT_FROM_WIN32(dwErr);
				goto Done;
			}
		}

		bytesRead -= dwDataStartOffset;

		if (bytesRead > chunk->FromFileHandle.ByteRange.Length.QuadPart)
		{
			bytesRead = (DWORD)chunk->FromFileHandle.ByteRange.Length.QuadPart;
		}
		if ((bytesTotal + bytesRead) > chunk->FromFileHandle.ByteRange.Length.QuadPart)
		{
			bytesRead = chunk->FromFileHandle.ByteRange.Length.QuadPart - bytesTotal;
		}

		memcpy(buf, pIoBuffer + dwDataStartOffset, bytesRead);

		buf += bytesRead;
		bytesTotal += bytesRead;

		if(was_eof != 0)
			chunk->FromFileHandle.ByteRange.Length.QuadPart = bytesTotal;
	}

Done:
	if(NULL != pIoBuffer)
	{
		VirtualFree(pIoBuffer, 0, MEM_RELEASE);
	}

	if(INVALID_HANDLE_VALUE != hIoEvent)
	{
		CloseHandle(hIoEvent);
	}

	return hr;
}

REQUEST_NOTIFICATION_STATUS
CMyHttpModule::OnSendResponse(
    IN IHttpContext * pHttpContext,
    IN ISendResponseProvider * pResponseProvider
)
{
	REQUEST_STORED_CONTEXT *rsc = NULL;

	rsc = (REQUEST_STORED_CONTEXT *)pHttpContext->GetModuleContextContainer()->GetModuleContext(g_pModuleContext);

	EnterCriticalSection(&m_csLock);

	// here we must check if response body processing is enabled
	//
	if(rsc == NULL || rsc->m_pRequestRec == NULL || rsc->m_pResponseBuffer != NULL || !modsecIsResponseBodyAccessEnabled(rsc->m_pRequestRec))
	{
		goto Exit;
	}

    HRESULT hr = S_OK;
	IHttpResponse *pHttpResponse = NULL;
    HTTP_RESPONSE *pRawHttpResponse = NULL;
    HTTP_BYTE_RANGE *pFileByteRange = NULL;
    HTTP_DATA_CHUNK *pSourceDataChunk = NULL;
    LARGE_INTEGER  lFileSize;
    REQUEST_NOTIFICATION_STATUS ret = RQ_NOTIFICATION_CONTINUE;
	ULONGLONG ulTotalLength = 0;
	DWORD c;
	request_rec *r = rsc->m_pRequestRec;

	pHttpResponse = pHttpContext->GetResponse();
	pRawHttpResponse = pHttpResponse->GetRawHttpResponse();

	// here we must add handling of chunked response
	// apparently IIS 7 calls this handler once per chunk
	// see: http://stackoverflow.com/questions/4385249/how-to-buffer-and-process-chunked-data-before-sending-headers-in-iis7-native-mod

	if(pRawHttpResponse->EntityChunkCount == 0)
		goto Exit;

	// here we must transfer response headers
	//
	USHORT ctcch = 0;
	char *ct = (char *)pHttpResponse->GetHeader(HttpHeaderContentType, &ctcch);
	char *ctz = ZeroTerminate(ct, ctcch, r->pool);

	// assume HTML if content type not set
	// without this output filter would not buffer response and processing would hang
	//
	if(ctz[0] == 0)
		ctz = "text/html";

	r->content_type = ctz;

#define _TRANSHEADER(id,str) if(pRawHttpResponse->Headers.KnownHeaders[id].pRawValue != NULL) \
	{\
		apr_table_setn(r->headers_out, str, \
			ZeroTerminate(pRawHttpResponse->Headers.KnownHeaders[id].pRawValue, pRawHttpResponse->Headers.KnownHeaders[id].RawValueLength, r->pool)); \
	}

    _TRANSHEADER(HttpHeaderCacheControl, "Cache-Control");
    _TRANSHEADER(HttpHeaderConnection, "Connection");
    _TRANSHEADER(HttpHeaderDate, "Date");
    _TRANSHEADER(HttpHeaderKeepAlive, "Keep-Alive");
    _TRANSHEADER(HttpHeaderPragma, "Pragma");
    _TRANSHEADER(HttpHeaderTrailer, "Trailer");
    _TRANSHEADER(HttpHeaderTransferEncoding, "Transfer-Encoding");
    _TRANSHEADER(HttpHeaderUpgrade, "Upgrade");
    _TRANSHEADER(HttpHeaderVia, "Via");
    _TRANSHEADER(HttpHeaderWarning, "Warning");
    _TRANSHEADER(HttpHeaderAllow, "Allow");
    _TRANSHEADER(HttpHeaderContentLength, "Content-Length");
    _TRANSHEADER(HttpHeaderContentType, "Content-Type");
    _TRANSHEADER(HttpHeaderContentEncoding, "Content-Encoding");
    _TRANSHEADER(HttpHeaderContentLanguage, "Content-Language");
    _TRANSHEADER(HttpHeaderContentLocation, "Content-Location");
    _TRANSHEADER(HttpHeaderContentMd5, "Content-Md5");
    _TRANSHEADER(HttpHeaderContentRange, "Content-Range");
    _TRANSHEADER(HttpHeaderExpires, "Expires");
    _TRANSHEADER(HttpHeaderLastModified, "Last-Modified");
	_TRANSHEADER(HttpHeaderAcceptRanges, "Accept-Ranges");
    _TRANSHEADER(HttpHeaderAge, "Age");
    _TRANSHEADER(HttpHeaderEtag, "Etag");
    _TRANSHEADER(HttpHeaderLocation, "Location");
    _TRANSHEADER(HttpHeaderProxyAuthenticate, "Proxy-Authenticate");
    _TRANSHEADER(HttpHeaderRetryAfter, "Retry-After");
    _TRANSHEADER(HttpHeaderServer, "Server");
    _TRANSHEADER(HttpHeaderSetCookie, "Set-Cookie");
    _TRANSHEADER(HttpHeaderVary, "Vary");
    _TRANSHEADER(HttpHeaderWwwAuthenticate, "Www-Authenticate");

#undef	_TRANSHEADER

	for(int i = 0; i < pRawHttpResponse->Headers.UnknownHeaderCount; i++)
	{
		apr_table_setn(r->headers_out,
			ZeroTerminate(pRawHttpResponse->Headers.pUnknownHeaders[i].pName, pRawHttpResponse->Headers.pUnknownHeaders[i].NameLength, r->pool),
			ZeroTerminate(pRawHttpResponse->Headers.pUnknownHeaders[i].pRawValue, pRawHttpResponse->Headers.pUnknownHeaders[i].RawValueLength, r->pool));
	}

	r->content_encoding = apr_table_get(r->headers_out, "Content-Encoding");
	//r->content_type = apr_table_get(r->headers_out, "Content-Type");		-- already set above

	const char *lng = apr_table_get(r->headers_out, "Content-Languages");

	if(lng != NULL)
	{
		r->content_languages = apr_array_make(r->pool, 1, sizeof(const char *));

		*(const char **)apr_array_push(r->content_languages) = lng;
	}

	// Disable kernel caching for this response
	// Probably we don't have to do it for ModSecurity

    //pHttpContext->GetResponse()->DisableKernelCache(
    //        IISCacheEvents::HTTPSYS_CACHEABLE::HANDLER_HTTPSYS_UNFRIENDLY);

    for(c = 0; c < pRawHttpResponse->EntityChunkCount; c++ )
    {
        pSourceDataChunk = &pRawHttpResponse->pEntityChunks[ c ];

        switch( pSourceDataChunk->DataChunkType )
        {
            case HttpDataChunkFromMemory:
                ulTotalLength += pSourceDataChunk->FromMemory.BufferLength;
                break;
            case HttpDataChunkFromFileHandle:
                pFileByteRange = &pSourceDataChunk->FromFileHandle.ByteRange;
                //
                // File chunks may contain by ranges with unspecified length
                // (HTTP_BYTE_RANGE_TO_EOF).  In order to send parts of such a chunk,
                // its necessary to know when the chunk is finished, and
                // we need to move to the next chunk.
                //
                if ( pFileByteRange->Length.QuadPart == HTTP_BYTE_RANGE_TO_EOF)
                {
                    if ( GetFileType( pSourceDataChunk->FromFileHandle.FileHandle ) ==
                                    FILE_TYPE_DISK )
                    {
                        if ( !GetFileSizeEx( pSourceDataChunk->FromFileHandle.FileHandle,
                                             &lFileSize ) )
                        {
                            DWORD dwError = GetLastError();
                            hr = HRESULT_FROM_WIN32(dwError);
                            goto Finished;
                        }

                        // put the resolved file length in the chunk, replacing
                        // HTTP_BYTE_RANGE_TO_EOF
                        pFileByteRange->Length.QuadPart =
                              lFileSize.QuadPart - pFileByteRange->StartingOffset.QuadPart;
                    }
                    else
                    {
                        hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
                        goto Finished;
                    }
                }

                ulTotalLength += pFileByteRange->Length.QuadPart;
                break;
            default:
                // TBD: consider implementing HttpDataChunkFromFragmentCache,
                // and HttpDataChunkFromFragmentCacheEx
                hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
                goto Finished;
        }
    }

	rsc->m_pResponseBuffer = (char *)apr_palloc(rsc->m_pRequestRec->pool, ulTotalLength);

	ulTotalLength = 0;

    for(c = 0; c < pRawHttpResponse->EntityChunkCount; c++ )
    {
        pSourceDataChunk = &pRawHttpResponse->pEntityChunks[ c ];

        switch( pSourceDataChunk->DataChunkType )
        {
            case HttpDataChunkFromMemory:
				memcpy(rsc->m_pResponseBuffer + ulTotalLength, pSourceDataChunk->FromMemory.pBuffer, pSourceDataChunk->FromMemory.BufferLength);
                ulTotalLength += pSourceDataChunk->FromMemory.BufferLength;
                break;
            case HttpDataChunkFromFileHandle:
                pFileByteRange = &pSourceDataChunk->FromFileHandle.ByteRange;

				if(ReadFileChunk(pSourceDataChunk, rsc->m_pResponseBuffer + ulTotalLength) != S_OK)
				{
			        DWORD dwErr = GetLastError();

					hr = HRESULT_FROM_WIN32(dwErr);
	                goto Finished;
				}

                ulTotalLength += pFileByteRange->Length.QuadPart;
                break;
            default:
                // TBD: consider implementing HttpDataChunkFromFragmentCache,
                // and HttpDataChunkFromFragmentCacheEx
                hr = HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
                goto Finished;
        }
    }

	rsc->m_pResponseLength = ulTotalLength;

	//
    // If there's no content-length set, we need to set it to avoid chunked transfer mode
    // We can only do it if there is it's the only response to be sent.
    //

    DWORD dwFlags = pResponseProvider->GetFlags();

	if (pResponseProvider->GetHeadersBeingSent() &&
         (dwFlags & HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0 &&
         pHttpContext->GetResponse()->GetHeader(HttpHeaderContentLength) == NULL)
    {
        CHAR szLength[21]; //Max length for a 64 bit int is 20

         ZeroMemory(szLength, sizeof(szLength));

         hr = StringCchPrintfA(
                    szLength,
                    sizeof(szLength) / sizeof(CHAR) - 1, "%d",
                    ulTotalLength);

        if(FAILED(hr))
        {
            goto Finished;
        }

         hr = pHttpContext->GetResponse()->SetHeader(
                    HttpHeaderContentLength,
                    szLength,
                    (USHORT)strlen(szLength),
                    TRUE);

        if(FAILED(hr))
        {
            goto Finished;
        }
    }

Finished:

	int status = modsecProcessResponse(rsc->m_pRequestRec);

	// the logic here is temporary, needs clarification
	//
	if(status != 0 && status != -1)
	{
		pHttpContext->GetResponse()->Clear();
		pHttpContext->GetResponse()->SetStatus(status, "ModSecurity Action");
		pHttpContext->SetRequestHandled();

		rsc->FinishRequest();

		LeaveCriticalSection(&m_csLock);

		return RQ_NOTIFICATION_FINISH_REQUEST;
	}
Exit:
	// temporary hack, in reality OnSendRequest theoretically could possibly come before OnEndRequest
	//
	if(rsc != NULL)
		rsc->FinishRequest();

	LeaveCriticalSection(&m_csLock);

	return RQ_NOTIFICATION_CONTINUE;
}

REQUEST_NOTIFICATION_STATUS
CMyHttpModule::OnPostEndRequest(
    IN IHttpContext * pHttpContext,
    IN IHttpEventProvider * pProvider
)
{
	REQUEST_STORED_CONTEXT *rsc = NULL;

	rsc = (REQUEST_STORED_CONTEXT *)pHttpContext->GetModuleContextContainer()->GetModuleContext(g_pModuleContext);

	// only finish request if OnSendResponse have been called already
	//
	if(rsc != NULL && rsc->m_pResponseBuffer != NULL)
	{
		EnterCriticalSection(&m_csLock);

		rsc->FinishRequest();

		LeaveCriticalSection(&m_csLock);
	}

	return RQ_NOTIFICATION_CONTINUE;
}

REQUEST_NOTIFICATION_STATUS
CMyHttpModule::OnBeginRequest(
    IN IHttpContext * pHttpContext,
    IN IHttpEventProvider * pProvider
)
{
    HRESULT                         hr                  = S_OK;
    IHttpRequest*                   pRequest            = NULL;
	MODSECURITY_STORED_CONTEXT*		pConfig = NULL;

    UNREFERENCED_PARAMETER ( pProvider );

	EnterCriticalSection(&m_csLock);

    if ( pHttpContext == NULL )
    {
        hr = E_UNEXPECTED;
        goto Finished;
    }

    pRequest = pHttpContext->GetRequest();

    if ( pRequest == NULL )
    {
        hr = E_UNEXPECTED;
        goto Finished;
    }

    hr = MODSECURITY_STORED_CONTEXT::GetConfig(pHttpContext, &pConfig );

    if ( FAILED( hr ) )
    {
        //hr = E_UNEXPECTED;
		hr = S_OK;
        goto Finished;
    }

	// If module is disabled, dont go any further
	//
	if( pConfig->GetIsEnabled() == false )
	{
        goto Finished;
	}

	if(pConfig->m_Config == NULL)
	{
		char *path;
		USHORT pathlen;

		hr = pConfig->GlobalWideCharToMultiByte(pConfig->GetPath(), wcslen(pConfig->GetPath()), &path, &pathlen);

		if ( FAILED( hr ) )
		{
			hr = E_UNEXPECTED;
			goto Finished;
		}

		pConfig->m_Config = modsecGetDefaultConfig();

		PCWSTR servpath = pHttpContext->GetApplication()->GetApplicationPhysicalPath();
		char *apppath;
		USHORT apppathlen;

		hr = pConfig->GlobalWideCharToMultiByte((WCHAR *)servpath, wcslen(servpath), &apppath, &apppathlen);

		if ( FAILED( hr ) )
		{
			delete path;
			hr = E_UNEXPECTED;
			goto Finished;
		}

		if(path[0] != 0)
		{
			const char * err = modsecProcessConfig((directory_config *)pConfig->m_Config, path, apppath);

			if(err != NULL)
			{
				WriteEventViewerLog(err, EVENTLOG_ERROR_TYPE);
				delete apppath;
				delete path;
				goto Finished;
			}

			modsecReportRemoteLoadedRules();
			if (this->status_call_already_sent == false)
			{
				this->status_call_already_sent = true;
				modsecStatusEngineCall();
			}
		}

		delete apppath;
		delete path;
	}

	conn_rec *c;
	request_rec *r;

	c = modsecNewConnection();

	modsecProcessConnection(c);

	r = modsecNewRequest(c, (directory_config *)pConfig->m_Config);

	// on IIS we force input stream inspection flag, because its absence does not add any performance gain
	// it's because on IIS request body must be restored each time it was read
	//
	modsecSetConfigForIISRequestBody(r);

	REQUEST_STORED_CONTEXT *rsc = new REQUEST_STORED_CONTEXT();

	rsc->m_pConnRec = c;
	rsc->m_pRequestRec = r;
	rsc->m_pHttpContext = pHttpContext;
	rsc->m_pProvider = pProvider;

	pHttpContext->GetModuleContextContainer()->SetModuleContext(rsc, g_pModuleContext);

	StoreIISContext(r, rsc);

	HTTP_REQUEST *req = pRequest->GetRawHttpRequest();

	r->hostname = ConvertUTF16ToUTF8(req->CookedUrl.pHost, req->CookedUrl.HostLength / sizeof(WCHAR), r->pool);
	r->path_info = ConvertUTF16ToUTF8(req->CookedUrl.pAbsPath, req->CookedUrl.AbsPathLength / sizeof(WCHAR), r->pool);

	if(r->hostname == NULL)
	{
		if(req->Headers.KnownHeaders[HttpHeaderHost].pRawValue != NULL)
			r->hostname = ZeroTerminate(req->Headers.KnownHeaders[HttpHeaderHost].pRawValue,
										req->Headers.KnownHeaders[HttpHeaderHost].RawValueLength, r->pool);
	}

	int port = 0;
	char *port_str = NULL;

	if(r->hostname != NULL)
	{
		int k = 0;
		char *ptr = (char *)r->hostname;

		while(*ptr != 0 && *ptr != ':')
			ptr++;

		if(*ptr == ':')
		{
			*ptr = 0;
			port_str = ptr + 1;
			port = atoi(port_str);
		}
	}

	if(req->CookedUrl.pQueryString != NULL && req->CookedUrl.QueryStringLength > 0)
		r->args = ConvertUTF16ToUTF8(req->CookedUrl.pQueryString + 1, (req->CookedUrl.QueryStringLength / sizeof(WCHAR)) - 1, r->pool);

#define _TRANSHEADER(id,str) if(req->Headers.KnownHeaders[id].pRawValue != NULL) \
	{\
		apr_table_setn(r->headers_in, str, \
			ZeroTerminate(req->Headers.KnownHeaders[id].pRawValue, req->Headers.KnownHeaders[id].RawValueLength, r->pool)); \
	}

    _TRANSHEADER(HttpHeaderCacheControl, "Cache-Control");
    _TRANSHEADER(HttpHeaderConnection, "Connection");
    _TRANSHEADER(HttpHeaderDate, "Date");
    _TRANSHEADER(HttpHeaderKeepAlive, "Keep-Alive");
    _TRANSHEADER(HttpHeaderPragma, "Pragma");
    _TRANSHEADER(HttpHeaderTrailer, "Trailer");
    _TRANSHEADER(HttpHeaderTransferEncoding, "Transfer-Encoding");
    _TRANSHEADER(HttpHeaderUpgrade, "Upgrade");
    _TRANSHEADER(HttpHeaderVia, "Via");
    _TRANSHEADER(HttpHeaderWarning, "Warning");
    _TRANSHEADER(HttpHeaderAllow, "Allow");
    _TRANSHEADER(HttpHeaderContentLength, "Content-Length");
    _TRANSHEADER(HttpHeaderContentType, "Content-Type");
    _TRANSHEADER(HttpHeaderContentEncoding, "Content-Encoding");
    _TRANSHEADER(HttpHeaderContentLanguage, "Content-Language");
    _TRANSHEADER(HttpHeaderContentLocation, "Content-Location");
    _TRANSHEADER(HttpHeaderContentMd5, "Content-Md5");
    _TRANSHEADER(HttpHeaderContentRange, "Content-Range");
    _TRANSHEADER(HttpHeaderExpires, "Expires");
    _TRANSHEADER(HttpHeaderLastModified, "Last-Modified");
    _TRANSHEADER(HttpHeaderAccept, "Accept");
    _TRANSHEADER(HttpHeaderAcceptCharset, "Accept-Charset");
    _TRANSHEADER(HttpHeaderAcceptEncoding, "Accept-Encoding");
    _TRANSHEADER(HttpHeaderAcceptLanguage, "Accept-Language");
    _TRANSHEADER(HttpHeaderAuthorization, "Authorization");
    _TRANSHEADER(HttpHeaderCookie, "Cookie");
    _TRANSHEADER(HttpHeaderExpect, "Expect");
    _TRANSHEADER(HttpHeaderFrom, "From");
    _TRANSHEADER(HttpHeaderHost, "Host");
    _TRANSHEADER(HttpHeaderIfMatch, "If-Match");
    _TRANSHEADER(HttpHeaderIfModifiedSince, "If-Modified-Since");
    _TRANSHEADER(HttpHeaderIfNoneMatch, "If-None-Match");
    _TRANSHEADER(HttpHeaderIfRange, "If-Range");
    _TRANSHEADER(HttpHeaderIfUnmodifiedSince, "If-Unmodified-Since");
    _TRANSHEADER(HttpHeaderMaxForwards, "Max-Forwards");
    _TRANSHEADER(HttpHeaderProxyAuthorization, "Proxy-Authorization");
    _TRANSHEADER(HttpHeaderReferer, "Referer");
    _TRANSHEADER(HttpHeaderRange, "Range");
    _TRANSHEADER(HttpHeaderTe, "TE");
    _TRANSHEADER(HttpHeaderTranslate, "Translate");
    _TRANSHEADER(HttpHeaderUserAgent, "User-Agent");

#undef _TRANSHEADER

	for(int i = 0; i < req->Headers.UnknownHeaderCount; i++)
	{
		apr_table_setn(r->headers_in,
			ZeroTerminate(req->Headers.pUnknownHeaders[i].pName, req->Headers.pUnknownHeaders[i].NameLength, r->pool),
			ZeroTerminate(req->Headers.pUnknownHeaders[i].pRawValue, req->Headers.pUnknownHeaders[i].RawValueLength, r->pool));
	}

	r->content_encoding = apr_table_get(r->headers_in, "Content-Encoding");
	r->content_type = apr_table_get(r->headers_in, "Content-Type");

	const char *lng = apr_table_get(r->headers_in, "Content-Languages");

	if(lng != NULL)
	{
		r->content_languages = apr_array_make(r->pool, 1, sizeof(const char *));

		*(const char **)apr_array_push(r->content_languages) = lng;
	}

	switch(req->Verb)
	{
	case HttpVerbUnparsed:
	case HttpVerbUnknown:
	case HttpVerbInvalid:
    case HttpVerbTRACK:  // used by Microsoft Cluster Server for a non-logged trace
    case HttpVerbSEARCH:
	default:
		r->method = "INVALID";
		r->method_number = M_INVALID;
		break;
	case HttpVerbOPTIONS:
		r->method = "OPTIONS";
		r->method_number = M_OPTIONS;
		break;
	case HttpVerbGET:
	case HttpVerbHEAD:
		r->method = "GET";
		r->method_number = M_GET;
		break;
	case HttpVerbPOST:
		r->method = "POST";
		r->method_number = M_POST;
		break;
    case HttpVerbPUT:
		r->method = "PUT";
		r->method_number = M_PUT;
		break;
    case HttpVerbDELETE:
		r->method = "DELETE";
		r->method_number = M_DELETE;
		break;
    case HttpVerbTRACE:
		r->method = "TRACE";
		r->method_number = M_TRACE;
		break;
    case HttpVerbCONNECT:
		r->method = "CONNECT";
		r->method_number = M_CONNECT;
		break;
    case HttpVerbMOVE:
		r->method = "MOVE";
		r->method_number = M_MOVE;
		break;
    case HttpVerbCOPY:
		r->method = "COPY";
		r->method_number = M_COPY;
		break;
    case HttpVerbPROPFIND:
		r->method = "PROPFIND";
		r->method_number = M_PROPFIND;
		break;
    case HttpVerbPROPPATCH:
		r->method = "PROPPATCH";
		r->method_number = M_PROPPATCH;
		break;
    case HttpVerbMKCOL:
		r->method = "MKCOL";
		r->method_number = M_MKCOL;
		break;
    case HttpVerbLOCK:
		r->method = "LOCK";
		r->method_number = M_LOCK;
		break;
    case HttpVerbUNLOCK:
		r->method = "UNLOCK";
		r->method_number = M_UNLOCK;
		break;
	}

	if(HTTP_EQUAL_VERSION(req->Version, 0, 9))
		r->protocol = "HTTP/0.9";
	else if(HTTP_EQUAL_VERSION(req->Version, 1, 0))
		r->protocol = "HTTP/1.0";
	else
		r->protocol = "HTTP/1.1";

	r->request_time = apr_time_now();

	r->parsed_uri.scheme = "http";
	r->parsed_uri.path = r->path_info;
	r->parsed_uri.hostname = (char *)r->hostname;
	r->parsed_uri.is_initialized = 1;
	r->parsed_uri.port = port;
	r->parsed_uri.port_str = port_str;
	r->parsed_uri.query = r->args;
	r->parsed_uri.dns_looked_up = 0;
	r->parsed_uri.dns_resolved = 0;
	r->parsed_uri.password = NULL;
	r->parsed_uri.user = NULL;
	r->parsed_uri.fragment = NULL;

	r->unparsed_uri = ZeroTerminate(req->pRawUrl, req->RawUrlLength, r->pool);
	r->uri = r->unparsed_uri;

	r->the_request = (char *)apr_palloc(r->pool, strlen(r->method) + 1 + req->RawUrlLength + 1 + strlen(r->protocol) + 1);

	strcpy(r->the_request, r->method);
	strcat(r->the_request, " ");
	strcat(r->the_request, r->uri);
	strcat(r->the_request, " ");
	strcat(r->the_request, r->protocol);

	HTTP_REQUEST_ID httpRequestID;
	char *pszValue = (char *)apr_palloc(r->pool, 24);

	httpRequestID = pRequest->GetRawHttpRequest()->RequestId;

	_ui64toa(httpRequestID, pszValue, 10);

	apr_table_setn(r->subprocess_env, "UNIQUE_ID", pszValue);

	PSOCKADDR pAddr = pRequest->GetRemoteAddress();

#if AP_SERVER_MAJORVERSION_NUMBER > 1 && AP_SERVER_MINORVERSION_NUMBER < 3
    c->remote_addr = CopySockAddr(r->pool, pAddr);
    c->remote_ip = GetIpAddr(r->pool, pAddr);
#else
    c->client_addr = CopySockAddr(r->pool, pAddr);
	c->client_ip = GetIpAddr(r->pool, pAddr);
#endif
	c->remote_host = NULL;

    LeaveCriticalSection(&m_csLock);
	int status = modsecProcessRequest(r);
    EnterCriticalSection(&m_csLock);

	if(status != DECLINED)
	{
		pHttpContext->GetResponse()->SetStatus(status, "ModSecurity Action");
		pHttpContext->SetRequestHandled();

		hr = E_FAIL;
		goto Finished;
	}

Finished:
	LeaveCriticalSection(&m_csLock);

    if ( FAILED( hr )  )
    {
        return RQ_NOTIFICATION_FINISH_REQUEST;
    }
	return RQ_NOTIFICATION_CONTINUE;
}

apr_status_t ReadBodyCallback(request_rec *r, char *buf, unsigned int length, unsigned int *readcnt, int *is_eos)
{
    REQUEST_STORED_CONTEXT *rsc = RetrieveIISContext(r);

    *readcnt = 0;

    if (rsc == NULL)
    {
        *is_eos = 1;
        return APR_SUCCESS;
    }

    IHttpContext *pHttpContext = rsc->m_pHttpContext;
    IHttpRequest *pRequest = pHttpContext->GetRequest();

    if (pRequest->GetRemainingEntityBytes() == 0)
    {
        *is_eos = 1;
        return APR_SUCCESS;
    }

    HRESULT hr = pRequest->ReadEntityBody(buf, length, false, (DWORD *)readcnt, NULL);

    if (FAILED(hr))
    {
        // End of data is okay.
        if (ERROR_HANDLE_EOF != (hr & 0x0000FFFF))
        {
            // Set the error status.
            rsc->m_pProvider->SetErrorStatus(hr);
        }

        *is_eos = 1;
    }

    return APR_SUCCESS;
}

apr_status_t WriteBodyCallback(request_rec *r, char *buf, unsigned int length)
{
	REQUEST_STORED_CONTEXT *rsc = RetrieveIISContext(r);

	if(rsc == NULL || rsc->m_pRequestRec == NULL)
		return APR_SUCCESS;

	IHttpContext *pHttpContext = rsc->m_pHttpContext;
	IHttpRequest *pHttpRequest = pHttpContext->GetRequest();

    CHAR szLength[21]; //Max length for a 64 bit int is 20

    ZeroMemory(szLength, sizeof(szLength));

    HRESULT hr = StringCchPrintfA(
            szLength,
            sizeof(szLength) / sizeof(CHAR) - 1, "%d",
            length);

    if(FAILED(hr))
    {
		// not possible
    }

    hr = pHttpRequest->SetHeader(
            HttpHeaderContentLength,
            szLength,
            (USHORT)strlen(szLength),
            TRUE);

    if(FAILED(hr))
    {
		// possible, but there's nothing we can do
    }

	// since we clean the APR pool at the end of OnSendRequest, we must get IIS-managed memory chunk
	//
	void *reqbuf = pHttpContext->AllocateRequestMemory(length);

	memcpy(reqbuf, buf, length);

	pHttpRequest->InsertEntityBody(reqbuf, length);

	return APR_SUCCESS;
}

apr_status_t ReadResponseCallback(request_rec *r, char *buf, unsigned int length, unsigned int *readcnt, int *is_eos)
{
	REQUEST_STORED_CONTEXT *rsc = RetrieveIISContext(r);

	*readcnt = 0;

	if(rsc == NULL || rsc->m_pResponseBuffer == NULL)
	{
		*is_eos = 1;
		return APR_SUCCESS;
	}

	unsigned int size = length;

	if(size > rsc->m_pResponseLength - rsc->m_pResponsePosition)
		size = rsc->m_pResponseLength - rsc->m_pResponsePosition;

	memcpy(buf, rsc->m_pResponseBuffer + rsc->m_pResponsePosition, size);

	*readcnt = size;
	rsc->m_pResponsePosition += size;

	if(rsc->m_pResponsePosition >= rsc->m_pResponseLength)
		*is_eos = 1;

	return APR_SUCCESS;
}

apr_status_t WriteResponseCallback(request_rec *r, char *buf, unsigned int length)
{
	REQUEST_STORED_CONTEXT *rsc = RetrieveIISContext(r);

	if(rsc == NULL || rsc->m_pRequestRec == NULL || rsc->m_pResponseBuffer == NULL)
		return APR_SUCCESS;

	IHttpContext *pHttpContext = rsc->m_pHttpContext;
	IHttpResponse *pHttpResponse = pHttpContext->GetResponse();
	HTTP_RESPONSE *pRawHttpResponse = pHttpResponse->GetRawHttpResponse();
	HTTP_DATA_CHUNK *pDataChunk = (HTTP_DATA_CHUNK *)apr_palloc(rsc->m_pRequestRec->pool, sizeof(HTTP_DATA_CHUNK));

	pRawHttpResponse->EntityChunkCount = 0;

	// since we clean the APR pool at the end of OnSendRequest, we must get IIS-managed memory chunk
	//
	void *reqbuf = pHttpContext->AllocateRequestMemory(length);

	memcpy(reqbuf, buf, length);

	pDataChunk->DataChunkType = HttpDataChunkFromMemory;
	pDataChunk->FromMemory.pBuffer = reqbuf;
	pDataChunk->FromMemory.BufferLength = length;

    CHAR szLength[21]; //Max length for a 64 bit int is 20

    ZeroMemory(szLength, sizeof(szLength));

    HRESULT hr = StringCchPrintfA(
            szLength,
            sizeof(szLength) / sizeof(CHAR) - 1, "%d",
            length);

    if(FAILED(hr))
    {
		// not possible
    }

    hr = pHttpResponse->SetHeader(
            HttpHeaderContentLength,
            szLength,
            (USHORT)strlen(szLength),
            TRUE);

    if(FAILED(hr))
    {
		// possible, but there's nothing we can do
    }

	pHttpResponse->WriteEntityChunkByReference(pDataChunk);

	return APR_SUCCESS;
}

CMyHttpModule::CMyHttpModule()
{
    // Open a handle to the Event Viewer.
    m_hEventLog = RegisterEventSource( NULL, "ModSecurity" );

    SYSTEM_INFO         sysInfo;

    GetSystemInfo(&sysInfo);
    m_dwPageSize = sysInfo.dwPageSize;

    this->status_call_already_sent = false;

	InitializeCriticalSection(&m_csLock);

	modsecSetLogHook(this, Log);

	modsecSetReadBody(ReadBodyCallback);
	modsecSetReadResponse(ReadResponseCallback);
	modsecSetWriteBody(WriteBodyCallback);
	modsecSetWriteResponse(WriteResponseCallback);

	server_rec *s = modsecInit();
	char *compname = (char *)malloc(128);
	DWORD size = 128;

	GetComputerName(compname, &size);

	s->server_hostname = compname;

	modsecStartConfig();

	modsecFinalizeConfig();

	modsecInitProcess();
}

CMyHttpModule::~CMyHttpModule()
{
	// ModSecurity registers APR pool cleanups, which interfere with APR pool tear down process
	// this causes crashes and since we are exiting the process here, so this is a temporary solution
	//
	//modsecTerminate();

	//WriteEventViewerLog("Module deleted.");

	// Test whether the handle for the Event Viewer is open.
    if (NULL != m_hEventLog)
    {
        // Close the handle to the Event Viewer.
        DeregisterEventSource( m_hEventLog );
        m_hEventLog = NULL;

		DeleteCriticalSection(&m_csLock);
    }
}

void CMyHttpModule::Dispose()
{
}

BOOL CMyHttpModule::WriteEventViewerLog(LPCSTR szNotification, WORD category)
{
    // Test whether the handle for the Event Viewer is open.
    if (NULL != m_hEventLog)
    {
        // Write any strings to the Event Viewer and return.
        return ReportEvent(
            m_hEventLog,
            category, 0, 0x1,
            NULL, 1, 0, &szNotification, NULL );
    }
    return FALSE;
}


text:
package gribbit.model.field.visibility.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Prevents a field in a data model from being rendered as a template parameter. Prevents the user from ever seeing
 * the value in the data model when a template is rendered, but allows them to set the value in a POST request.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface PrivateGet {
}

redpajama_set_name: RedPajamaGithub


text:
package org.qi4j.test.indexing;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.junit.Ignore;
import org.junit.Test;
import org.qi4j.api.query.NotQueryableException;
import org.qi4j.api.query.Query;
import org.qi4j.api.query.QueryBuilder;
import org.qi4j.api.query.grammar.OrderBy;
import org.qi4j.spi.query.EntityFinderException;
import org.qi4j.spi.query.IndexExporter;
import org.qi4j.test.indexing.model.Account;
import org.qi4j.test.indexing.model.City;
import org.qi4j.test.indexing.model.Domain;
import org.qi4j.test.indexing.model.Female;
import org.qi4j.test.indexing.model.File;
import org.qi4j.test.indexing.model.Male;
import org.qi4j.test.indexing.model.Nameable;
import org.qi4j.test.indexing.model.Person;
import org.qi4j.test.indexing.model.QueryParam;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.joda.time.DateTimeZone.UTC;
import static org.joda.time.DateTimeZone.forID;
import static org.junit.Assert.assertThat;
import static org.qi4j.api.query.QueryExpressions.and;
import static org.qi4j.api.query.QueryExpressions.contains;
import static org.qi4j.api.query.QueryExpressions.containsName;
import static org.qi4j.api.query.QueryExpressions.eq;
import static org.qi4j.api.query.QueryExpressions.ge;
import static org.qi4j.api.query.QueryExpressions.gt;
import static org.qi4j.api.query.QueryExpressions.isNotNull;
import static org.qi4j.api.query.QueryExpressions.isNull;
import static org.qi4j.api.query.QueryExpressions.lt;
import static org.qi4j.api.query.QueryExpressions.matches;
import static org.qi4j.api.query.QueryExpressions.ne;
import static org.qi4j.api.query.QueryExpressions.not;
import static org.qi4j.api.query.QueryExpressions.oneOf;
import static org.qi4j.api.query.QueryExpressions.or;
import static org.qi4j.api.query.QueryExpressions.orderBy;
import static org.qi4j.api.query.QueryExpressions.templateFor;
import static org.qi4j.test.indexing.NameableAssert.verifyOrderedResults;
import static org.qi4j.test.indexing.NameableAssert.verifyUnorderedResults;

/**
 * Abstract satisfiedBy with tests for simple queries against Index/Query engines.
 */
public abstract class AbstractQueryTest
    extends AbstractAnyQueryTest
{

    @Test
    public void showNetwork()
        throws IOException
    {
        IndexExporter indexerExporter = module.findService( IndexExporter.class ).get();
        indexerExporter.exportReadableToStream( System.out );
    }

    @Test
    public void script01()
        throws EntityFinderException
    {
        final QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        final Query<Person> query = unitOfWork.newQuery( qb );
        System.out.println( "*** script01: " + query );
        verifyUnorderedResults( query, "Joe Doe", "Ann Doe", "Jack Doe" );
    }

    @Test
    public void script02()
        throws EntityFinderException
    {
        final QueryBuilder<Domain> qb = this.module.newQueryBuilder( Domain.class );
        final Nameable nameable = templateFor( Nameable.class );
        final Query<Domain> query = unitOfWork.newQuery( qb.where( eq( nameable.name(), "Gaming" ) ) );
        System.out.println( "*** script02: " + query );
        verifyUnorderedResults( query, "Gaming" );
    }

    @Test
    public void script03()
        throws EntityFinderException
    {
        QueryBuilder<Nameable> qb = this.module.newQueryBuilder( Nameable.class );
        Query<Nameable> query = unitOfWork.newQuery( qb );
        System.out.println( "*** script03: " + query );
        verifyUnorderedResults( query, "Joe Doe", "Ann Doe", "Jack Doe", "Penang", "Kuala Lumpur", "Cooking", "Gaming",
                                "Programming", "Cars" );
    }

    @Test
    public void script04()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person personTemplate = templateFor( Person.class );
        City placeOfBirth = personTemplate.placeOfBirth().get();
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( placeOfBirth.name(), "Kuala Lumpur" ) ) );
        System.out.println( "*** script04: " + query );
        verifyUnorderedResults( query, "Joe Doe", "Ann Doe" );
    }

    @Test
    public void script04_ne()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person personTemplate = templateFor( Person.class );
        City placeOfBirth = personTemplate.placeOfBirth().get();
        Query<Person> query = unitOfWork.newQuery( qb.where( ne( placeOfBirth.name(), "Kuala Lumpur" ) ) );
        System.out.println( "*** script04_ne: " + query );
        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script05()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( person.mother()
            .get()
            .placeOfBirth()
            .get()
            .name(), "Kuala Lumpur" ) )
        );
        System.out.println( "*** script05: " + query );
        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script06()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( ge( person.yearOfBirth(), 1973 ) ) );
        System.out.println( "*** script06: " + query );
        verifyUnorderedResults( query, "Joe Doe", "Ann Doe" );
    }

    @Test
    @SuppressWarnings( "unchecked" )
    public void script07()
        throws EntityFinderException
    {
        QueryBuilder<Nameable> qb = this.module.newQueryBuilder( Nameable.class );
        Person person = templateFor( Person.class );
        Query<Nameable> query = unitOfWork.newQuery( qb.where(
            and( ge( person.yearOfBirth(), 1900 ), eq( person.placeOfBirth().get().name(), "Penang" ) ) ) );
        System.out.println( "*** script07: " + query );
        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    @SuppressWarnings( "unchecked" )
    public void script08()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( or( eq( person.yearOfBirth(), 1970 ), eq( person.yearOfBirth(), 1975 ) ) )
        );
        System.out.println( "*** script08: " + query );
        verifyUnorderedResults( query, "Jack Doe", "Ann Doe" );
    }

    @Test
    @SuppressWarnings( "unchecked" )
    public void script09()
        throws EntityFinderException
    {
        QueryBuilder<Female> qb = this.module.newQueryBuilder( Female.class );
        Person person = templateFor( Person.class );
        Query<Female> query = unitOfWork.newQuery( qb.where( or( eq( person.yearOfBirth(), 1970 ), eq( person.yearOfBirth(), 1975 ) ) )
        );
        System.out.println( "*** script09: " + query );
        verifyUnorderedResults( query, "Ann Doe" );
    }

    @Test
    public void script10()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( not( eq( person.yearOfBirth(), 1975 ) ) ) );
        System.out.println( "*** script10: " + query );
        verifyUnorderedResults( query, "Jack Doe", "Joe Doe" );
    }

    @Test
    public void script11()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( isNotNull( person.email() ) ) );
        System.out.println( "*** script11: " + query );
        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script12()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( isNull( person.email() ) ) );
        System.out.println( "*** script12: " + query );
        verifyUnorderedResults( query, "Ann Doe", "Jack Doe" );
    }

    @Test
    public void script12_ne()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( ne( person.email(), "joe@thedoes.net" ) ) );
        System.out.println( "*** script12_ne: " + query );
        verifyUnorderedResults( query );
    }

    @Test
    public void script13()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Male person = templateFor( Male.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( isNotNull( person.wife() ) ) );
        System.out.println( "*** script13: " + query );
        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script14()
        throws EntityFinderException
    {
        QueryBuilder<Male> qb = this.module.newQueryBuilder( Male.class );
        Male person = templateFor( Male.class );
        Query<Male> query = unitOfWork.newQuery( qb.where( isNull( person.wife() ) ) );
        System.out.println( "*** script14: " + query );
        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script15()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Male person = templateFor( Male.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( isNull( person.wife() ) ) );
        System.out.println( "*** script15: " + query );
        verifyUnorderedResults( query, "Joe Doe", "Ann Doe" );
    }

    @Test
    public void script16()
        throws EntityFinderException
    {
        QueryBuilder<Nameable> qb = this.module.newQueryBuilder( Nameable.class );
        // should return only 2 entities
        Nameable nameable = templateFor( Nameable.class );
        Query<Nameable> query = unitOfWork.newQuery( qb );
        query.orderBy( orderBy( nameable.name() ) );
        query.maxResults( 2 );
        System.out.println( "*** script16: " + query );
        verifyOrderedResults( query, "Ann Doe", "Cars" );
    }

    @Test
    public void script17()
        throws EntityFinderException
    {
        QueryBuilder<Nameable> qb = this.module.newQueryBuilder( Nameable.class );
        // should return only 3 entities starting with forth one
        Nameable nameable = templateFor( Nameable.class );
        Query<Nameable> query = unitOfWork.newQuery( qb );
        query.orderBy( orderBy( nameable.name() ) );
        query.firstResult( 3 );
        query.maxResults( 2 );
        System.out.println( "*** script17: " + query );
        verifyOrderedResults( query, "Gaming", "Jack Doe" );
    }

    @Test
    public void script18()
        throws EntityFinderException
    {
        QueryBuilder<Nameable> qb = this.module.newQueryBuilder( Nameable.class );
        // should return all Nameable entities sorted by name
        Nameable nameable = templateFor( Nameable.class );
        Query<Nameable> query = unitOfWork.newQuery( qb );
        query.orderBy( orderBy( nameable.name() ) );
        System.out.println( "*** script18: " + query );
        verifyOrderedResults( query, "Ann Doe", "Cars", "Cooking", "Gaming", "Jack Doe", "Joe Doe", "Kuala Lumpur",
                              "Penang", "Programming" );
    }

    @Test
    public void script19()
        throws EntityFinderException
    {
        QueryBuilder<Nameable> qb = this.module.newQueryBuilder( Nameable.class );
        // should return all Nameable entities with a name > "D" sorted by name
        Nameable nameable = templateFor( Nameable.class );
        Query<Nameable> query = unitOfWork.newQuery( qb.where( gt( nameable.name(), "D" ) ) );
        query.orderBy( orderBy( nameable.name() ) );
        System.out.println( "*** script19: " + query );
        verifyOrderedResults( query, "Gaming", "Jack Doe", "Joe Doe", "Kuala Lumpur", "Penang", "Programming" );
    }

    @Test
    public void script20()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        // should return all Persons born after 1973 (Ann and Joe Doe) sorted descending by name
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( gt( person.yearOfBirth(), 1973 ) ) );
        query.orderBy( orderBy( person.name(), OrderBy.Order.DESCENDING ) );
        System.out.println( "*** script20: " + query );
        verifyOrderedResults( query, "Joe Doe", "Ann Doe" );
    }

    @Test
    public void script21()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        // should return all Persons sorted by name of the city they were born, and then by year they were born
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb );
        query.orderBy( orderBy( person.placeOfBirth().get().name() ), orderBy( person.yearOfBirth() ) );
        System.out.println( "*** script21: " + query );
        verifyOrderedResults( query, "Ann Doe", "Joe Doe", "Jack Doe" );
    }

    @Test
    public void script22()
        throws EntityFinderException
    {
        QueryBuilder<Nameable> qb = this.module.newQueryBuilder( Nameable.class );
        Nameable nameable = templateFor( Nameable.class );
        // should return Jack and Joe Doe
        Query<Nameable> query = unitOfWork.newQuery( qb.where( matches( nameable.name(), "J.*Doe" ) ) );
        System.out.println( "*** script22: " + query );
        verifyUnorderedResults( query, "Jack Doe", "Joe Doe" );
    }

    @Test
    public void script23()
        throws EntityFinderException
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Domain interests = oneOf( person.interests() );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( interests.name(), "Cars" ) ) );
        System.out.println( "*** script23: " + query );
        verifyOrderedResults( query, "Jack Doe" );
    }

    @Test
    public void script24()
        throws EntityFinderException
    {
        final QueryBuilder<Domain> qb = this.module.newQueryBuilder( Domain.class );
        final Nameable nameable = templateFor( Nameable.class );
        final Query<Domain> query = unitOfWork.newQuery( qb.where( eq( nameable.name(), "Gaming" ) ) );
        System.out.println( "*** script24: " + query );
        assertThat( query.find().name().get(), is( equalTo( "Gaming" ) ) );
    }

    @Test( expected = NotQueryableException.class )
    public void script25()
    {
        this.module.newQueryBuilder( File.class );
    }

    @Test( expected = NotQueryableException.class )
    public void script26()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        qb.where( eq( person.personalWebsite().get().file().get().value(), "some/path" ) );
    }

    @Test( expected = NotQueryableException.class )
    public void script27()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        qb.where( eq( person.personalWebsite().get().host().get().value(), "www.qi4j.org" ) );
    }

    @Test( expected = NotQueryableException.class )
    public void script28()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        qb.where( eq( person.personalWebsite().get().port().get().value(), 8080 ) );
    }

    @Test
    public void script29()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( person.personalWebsite()
            .get()
            .protocol()
            .get()
            .value(), "http" ) )
        );
        System.out.println( "*** script29: " + query );
        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    @Ignore( "Wait till 1.1?" )
    // Paul: I don't understand this test
    @SuppressWarnings( "unchecked" )
    public void script30()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        QueryParam queryParam = null; // oneOf( person.personalWebsite().get().queryParams() );
        Query<Person> query = unitOfWork.newQuery( qb.where( and( eq( queryParam.name(), "foo" ), eq( queryParam.value(), "bar" ) ) ) );
        System.out.println( "*** script30: " + query );
        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    @Ignore( "Equality on Property<Map<?,?>> not implemented" )
    public void script31()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Map<String, String> info = new HashMap<>( 0 );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( person.additionalInfo(), info ) ) );
        System.out.println( "*** script31: " + query );
        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script32()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( person.address().get().line1(), "Qi Alley 4j" ) ) );
        System.out.println( "*** script32: " + query );
        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script33()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Domain gaming = unitOfWork.get( Domain.class, "Gaming" );
        Query<Person> query = unitOfWork.newQuery( qb.where( contains( person.interests(), gaming ) ) );
        System.out.println( "*** script33: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script34()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Female annDoe = unitOfWork.get( Female.class, "anndoe" );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( person.mother(), annDoe ) ) );
        System.out.println( "*** script34: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script35()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( containsName( person.accounts(), "anns" ) ) );
        System.out.println( "*** script35: " + query );

        verifyUnorderedResults( query, "Jack Doe", "Ann Doe" );
    }

    @Test
    public void script36()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Account anns = unitOfWork.get( Account.class, "accountOfAnnDoe" );
        Query<Person> query = unitOfWork.newQuery( qb.where( contains( person.accounts(), anns ) ) );
        System.out.println( "*** script36: " + query );

        verifyUnorderedResults( query, "Jack Doe", "Ann Doe" );
    }

    @Test
    @Ignore( "Traversing of NamedAssociations is not implemented" )
    public void script37()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( person.accounts().get( "anns" ).number(),
                                                                 "accountOfAnnDoe" ) ) );
        System.out.println( "*** script37: " + query );

        verifyUnorderedResults( query, "Jack Doe", "Ann Doe" );
    }

    @Test
    public void script38()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( eq( person.title(), Person.Title.DR ) ) );
        System.out.println( "*** script38: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script39()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where( ne( person.title(), Person.Title.DR ) ) );
        System.out.println( "*** script39: " + query );

        verifyUnorderedResults( query, "Ann Doe", "Joe Doe" );
    }

    @Test
    public void script40_Date()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            eq( person.dateValue(), new DateTime( "2010-03-04T13:24:35", UTC ).toDate() ) ) );
        System.out.println( "*** script40_Date: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script41_Date()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.dateValue(), new DateTime( "2010-03-04T13:24:35", UTC ).toDate() ) ) );
        System.out.println( "*** script41_Date: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script42_Date()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.dateValue(), new DateTime( "2010-03-04T14:24:35", forID( "CET" ) ).toDate() ) ) );
        System.out.println( "*** script42_Date: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script43_Date()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            and( gt( person.dateValue(), new DateTime( "2005-03-04T13:24:35", UTC ).toDate() ),
                 lt( person.dateValue(), new DateTime( "2015-03-04T13:24:35", UTC ).toDate() ) ) ) );
        System.out.println( "*** script43_Date: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script40_DateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            eq( person.dateTimeValue(), new DateTime( "2010-03-04T13:24:35", UTC ) ) ) );
        System.out.println( "*** script40_DateTime: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script41_DateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.dateTimeValue(), new DateTime( "2010-03-04T13:24:35", UTC ) ) ) );
        System.out.println( "*** script41_DateTime: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script42_DateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.dateTimeValue(), new DateTime( "2010-03-04T14:24:35", forID( "CET" ) ) ) ) );
        System.out.println( "*** script42_DateTime: " + query );

        verifyUnorderedResults( query, "Jack Doe", "Joe Doe" );
    }

    @Test
    public void script43_DateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            and( gt( person.dateTimeValue(), new DateTime( "2005-03-04T13:24:35", UTC ) ),
                 lt( person.dateTimeValue(), new DateTime( "2015-03-04T13:24:35", UTC ) ) ) ) );
        System.out.println( "*** script43_DateTime: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script40_LocalDateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            eq( person.localDateTimeValue(), new LocalDateTime( "2010-03-04T13:23:00", UTC ) ) ) );
        System.out.println( "*** script40_LocalDateTime: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script41_LocalDateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.localDateTimeValue(), new LocalDateTime( "2010-03-04T13:23:00", UTC ) ) ) );
        System.out.println( "*** script41_LocalDateTime: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script42_LocalDateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.localDateTimeValue(), new LocalDateTime( "2010-03-04T13:23:00", forID( "CET" ) ) ) ) );
        System.out.println( "*** script42_LocalDateTime: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script43_LocalDateTime()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            and( gt( person.localDateTimeValue(), new LocalDateTime( "2005-03-04T13:24:35", UTC ) ),
                 lt( person.localDateTimeValue(), new LocalDateTime( "2015-03-04T13:24:35", UTC ) ) ) ) );
        System.out.println( "*** script43_LocalDateTime: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script40_LocalDate()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            eq( person.localDateValue(), new LocalDate( "2010-03-04", UTC ) ) ) );
        System.out.println( "*** script40_LocalDate: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script41_LocalDate()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.localDateValue(), new LocalDate( "2010-03-04", UTC ) ) ) );
        System.out.println( "*** script41_LocalDate: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script42_LocalDate()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.localDateValue(), new LocalDate( "2010-03-04", forID( "CET" ) ) ) ) );
        System.out.println( "*** script42_LocalDate: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script43_LocalDate()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            and( gt( person.localDateValue(), new LocalDate( "2005-03-04", UTC ) ),
                 lt( person.localDateValue(), new LocalDate( "2015-03-04", UTC ) ) ) ) );
        System.out.println( "*** script43_LocalDate: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script50_BigInteger()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            eq( person.bigInteger(), new BigInteger( "23232323232323232323232323" ) ) ) );
        System.out.println( "*** script50_BigInteger: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script51_BigInteger()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.bigInteger(), new BigInteger( "23232323232323232323232323" ) ) ) );
        System.out.println( "*** script51_BigInteger: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script52_BigInteger()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ge( person.bigInteger(), new BigInteger( "23232323232323232323232323" ) ) ) );
        System.out.println( "*** script52_BigInteger: " + query );

        verifyUnorderedResults( query, "Jack Doe", "Joe Doe" );
    }

    @Test
    public void script50_BigDecimal()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            eq( person.bigDecimal(), new BigDecimal( "2342.76931348623157e+307" ) ) ) );
        System.out.println( "*** script50_BigDecimal: " + query );

        verifyUnorderedResults( query, "Joe Doe" );
    }

    @Test
    public void script51_BigDecimal()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ne( person.bigDecimal(), new BigDecimal( "2342.76931348623157e+307" ) ) ) );
        System.out.println( "*** script51_BigDecimal: " + query );

        verifyUnorderedResults( query, "Jack Doe" );
    }

    @Test
    public void script52_BigDecimal()
    {
        QueryBuilder<Person> qb = this.module.newQueryBuilder( Person.class );
        Person person = templateFor( Person.class );
        Query<Person> query = unitOfWork.newQuery( qb.where(
            ge( person.bigDecimal(), new BigDecimal( "2342.76931348623157e+307" ) ) ) );
        System.out.println( "*** script52_BigDecimal: " + query );

        verifyUnorderedResults( query, "Jack Doe", "Joe Doe" );
    }
}


text:
namespace drive {
namespace util {

namespace {

// Sets up ProfileManager for testing and marks the current thread as UI by
// TestBrowserThreadBundle. We need the thread since Profile objects must be
// touched from UI and hence has CHECK/DCHECKs for it.
class ProfileRelatedFileSystemUtilTest : public testing::Test {
 protected:
  ProfileRelatedFileSystemUtilTest()
      : testing_profile_manager_(TestingBrowserProcess::GetGlobal()) {}

  void SetUp() override { ASSERT_TRUE(testing_profile_manager_.SetUp()); }

  TestingProfileManager& testing_profile_manager() {
    return testing_profile_manager_;
  }

 private:
  content::TestBrowserThreadBundle thread_bundle_;
  TestingProfileManager testing_profile_manager_;
};

}  // namespace

TEST_F(ProfileRelatedFileSystemUtilTest, GetDriveMountPointPath) {
  Profile* profile = testing_profile_manager().CreateTestingProfile("user1");
  const std::string user_id_hash =
      chromeos::ProfileHelper::GetUserIdHashByUserIdForTesting("user1");
  EXPECT_EQ(base::FilePath::FromUTF8Unsafe("/special/drive-" + user_id_hash),
            GetDriveMountPointPath(profile));
}

TEST_F(ProfileRelatedFileSystemUtilTest, IsUnderDriveMountPoint) {
  EXPECT_FALSE(IsUnderDriveMountPoint(
      base::FilePath::FromUTF8Unsafe("/wherever/foo.txt")));
  EXPECT_FALSE(IsUnderDriveMountPoint(
      base::FilePath::FromUTF8Unsafe("/special/foo.txt")));
  EXPECT_FALSE(IsUnderDriveMountPoint(
      base::FilePath::FromUTF8Unsafe("special/drive/foo.txt")));

  EXPECT_TRUE(
      IsUnderDriveMountPoint(base::FilePath::FromUTF8Unsafe("/special/drive")));
  EXPECT_TRUE(IsUnderDriveMountPoint(
      base::FilePath::FromUTF8Unsafe("/special/drive/foo.txt")));
  EXPECT_TRUE(IsUnderDriveMountPoint(
      base::FilePath::FromUTF8Unsafe("/special/drive/subdir/foo.txt")));
  EXPECT_TRUE(IsUnderDriveMountPoint(
      base::FilePath::FromUTF8Unsafe("/special/drive-xxx/foo.txt")));
}

TEST_F(ProfileRelatedFileSystemUtilTest, ExtractDrivePath) {
  EXPECT_EQ(
      base::FilePath(),
      ExtractDrivePath(base::FilePath::FromUTF8Unsafe("/wherever/foo.txt")));
  EXPECT_EQ(
      base::FilePath(),
      ExtractDrivePath(base::FilePath::FromUTF8Unsafe("/special/foo.txt")));

  EXPECT_EQ(base::FilePath::FromUTF8Unsafe("drive"),
            ExtractDrivePath(base::FilePath::FromUTF8Unsafe("/special/drive")));
  EXPECT_EQ(base::FilePath::FromUTF8Unsafe("drive/foo.txt"),
            ExtractDrivePath(
                base::FilePath::FromUTF8Unsafe("/special/drive/foo.txt")));
  EXPECT_EQ(base::FilePath::FromUTF8Unsafe("drive/subdir/foo.txt"),
            ExtractDrivePath(base::FilePath::FromUTF8Unsafe(
                "/special/drive/subdir/foo.txt")));
  EXPECT_EQ(base::FilePath::FromUTF8Unsafe("drive/foo.txt"),
            ExtractDrivePath(
                base::FilePath::FromUTF8Unsafe("/special/drive-xxx/foo.txt")));
}

TEST_F(ProfileRelatedFileSystemUtilTest, ExtractProfileFromPath) {
  Profile* profile1 = testing_profile_manager().CreateTestingProfile("user1");
  Profile* profile2 = testing_profile_manager().CreateTestingProfile("user2");
  const std::string user1_id_hash =
      chromeos::ProfileHelper::GetUserIdHashByUserIdForTesting("user1");
  const std::string user2_id_hash =
      chromeos::ProfileHelper::GetUserIdHashByUserIdForTesting("user2");
  EXPECT_EQ(profile1, ExtractProfileFromPath(base::FilePath::FromUTF8Unsafe(
                          "/special/drive-" + user1_id_hash)));
  EXPECT_EQ(profile2, ExtractProfileFromPath(base::FilePath::FromUTF8Unsafe(
                          "/special/drive-" + user2_id_hash + "/root/xxx")));
  EXPECT_EQ(NULL, ExtractProfileFromPath(base::FilePath::FromUTF8Unsafe(
                      "/special/non-drive-path")));
}

TEST_F(ProfileRelatedFileSystemUtilTest, ExtractDrivePathFromFileSystemUrl) {
  TestingProfile profile;

  // Set up file system context for testing.
  base::ScopedTempDir temp_dir_;
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

  scoped_refptr<storage::ExternalMountPoints> mount_points =
      storage::ExternalMountPoints::CreateRefCounted();
  scoped_refptr<storage::FileSystemContext> context(
      new storage::FileSystemContext(
          base::ThreadTaskRunnerHandle::Get().get(),
          base::ThreadTaskRunnerHandle::Get().get(), mount_points.get(),
          NULL,  // special_storage_policy
          NULL,  // quota_manager_proxy,
          ScopedVector<storage::FileSystemBackend>(),
          std::vector<storage::URLRequestAutoMountHandler>(),
          temp_dir_.path(),  // partition_path
          content::CreateAllowFileAccessOptions()));

  // Type:"external" + virtual_path:"drive/foo/bar" resolves to "drive/foo/bar".
  const std::string& drive_mount_name =
      GetDriveMountPointPath(&profile).BaseName().AsUTF8Unsafe();
  mount_points->RegisterFileSystem(
      drive_mount_name, storage::kFileSystemTypeDrive,
      storage::FileSystemMountOption(), GetDriveMountPointPath(&profile));
  EXPECT_EQ(base::FilePath::FromUTF8Unsafe("drive/foo/bar"),
            ExtractDrivePathFromFileSystemUrl(context->CrackURL(
                GURL("filesystem:chrome-extension://dummy-id/external/" +
                     drive_mount_name + "/foo/bar"))));

  // Virtual mount name should not affect the extracted path.
  mount_points->RevokeFileSystem(drive_mount_name);
  mount_points->RegisterFileSystem("drive2", storage::kFileSystemTypeDrive,
                                   storage::FileSystemMountOption(),
                                   GetDriveMountPointPath(&profile));
  EXPECT_EQ(
      base::FilePath::FromUTF8Unsafe("drive/foo/bar"),
      ExtractDrivePathFromFileSystemUrl(context->CrackURL(GURL(
          "filesystem:chrome-extension://dummy-id/external/drive2/foo/bar"))));

  // Type:"external" + virtual_path:"Downloads/foo" is not a Drive path.
  mount_points->RegisterFileSystem(
      "Downloads", storage::kFileSystemTypeNativeLocal,
      storage::FileSystemMountOption(), temp_dir_.path());
  EXPECT_EQ(
      base::FilePath(),
      ExtractDrivePathFromFileSystemUrl(context->CrackURL(GURL(
          "filesystem:chrome-extension://dummy-id/external/Downloads/foo"))));

  // Type:"isolated" + virtual_path:"isolated_id/name" mapped on a Drive path.
  std::string isolated_name;
  std::string isolated_id =
      storage::IsolatedContext::GetInstance()->RegisterFileSystemForPath(
          storage::kFileSystemTypeNativeForPlatformApp, std::string(),
          GetDriveMountPointPath(&profile).AppendASCII("bar/buz"),
          &isolated_name);
  EXPECT_EQ(base::FilePath::FromUTF8Unsafe("drive/bar/buz"),
            ExtractDrivePathFromFileSystemUrl(context->CrackURL(
                GURL("filesystem:chrome-extension://dummy-id/isolated/" +
                     isolated_id + "/" + isolated_name))));
}

TEST_F(ProfileRelatedFileSystemUtilTest, GetCacheRootPath) {
  TestingProfile profile;
  base::FilePath profile_path = profile.GetPath();
  EXPECT_EQ(profile_path.AppendASCII("GCache/v1"),
            util::GetCacheRootPath(&profile));
}

}  // namespace util
}  // namespace drive


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:baselineAligned="false"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btnCameraActivity"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/takePict" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <TextView android:id="@+id/tvCameraActivity"
            android:textColor="#BA3232"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="@string/progress"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_marginTop="16dp" />

        <CheckBox android:id="@+id/cbCameraActivity"
            android:theme="@style/checkBoxStyle"
            android:clickable="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:scaleX="1.70"
            android:scaleY="1.70"
            android:layout_toEndOf="@+id/tvCameraActivity"
            android:layout_toRightOf="@+id/tvCameraActivity" />

    </RelativeLayout>

    <Button
        android:id="@+id/btnAgeActivity"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="@string/information" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <TextView android:id="@+id/tvAgeActivity"
            android:textColor="#BA3232"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="@string/progress"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_marginTop="16dp" />

        <CheckBox android:id="@+id/cbAgeActivity"
            android:theme="@style/checkBoxStyle"
            android:clickable="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:scaleX="1.70"
            android:scaleY="1.70"
            android:layout_toEndOf="@+id/tvAgeActivity"
            android:layout_toRightOf="@+id/tvAgeActivity" />

    </RelativeLayout>

    <Button
        android:id="@+id/btnSymptomActivity"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="@string/symptoms" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <TextView android:id="@+id/tvSymptomActivity"
            android:textColor="#BA3232"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="@string/progress"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_marginTop="16dp" />

        <CheckBox android:id="@+id/cbSymptomActivity"
            android:theme="@style/checkBoxStyle"
            android:clickable="false"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:scaleX="1.70"
            android:scaleY="1.70"
            android:layout_toEndOf="@+id/tvSymptomActivity"
            android:layout_toRightOf="@+id/tvSymptomActivity" />

    </RelativeLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
        android:gravity="center|bottom"
        android:orientation="vertical" >

        <Button
            android:id="@+id/btnResults"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/results" />

        </LinearLayout>

</LinearLayout>


text:
package com.aquarianz.aqlib;

import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;

public class ExtensionLoader<ClassName> {

    public ClassName loadClass(File jar, String classpath, Class<ClassName> parentClass) throws ClassNotFoundException {
            try {
                ClassLoader loader = URLClassLoader.newInstance(
                        new URL[] { jar.toURI().toURL() },
                        getClass().getClassLoader()
                );

                Class<?> clazz = Class.forName(classpath, true, loader);
                Class<? extends ClassName> newClass = clazz.asSubclass(parentClass);

                // Apparently its bad to use Class.newInstance, so we use newClass.getConstructor() instead
                Constructor<? extends ClassName> constructor = newClass.getConstructor();
                return constructor.newInstance();
            } catch (Exception ex) {
                throw new RuntimeException("Class " + classpath + " not found in jar " + jar.getPath(), ex);
            }
    }
}


text:
package com.example.greatbook.local.presenter.contract;

import com.example.greatbook.base.BasePresenter;
import com.example.greatbook.base.BaseView;
import com.example.greatbook.nethot.model.DiscoveryRecord;
import com.example.greatbook.nethot.model.DiscoveryTopGroup;

import java.util.List;

/**
 * Created by MDove on 2017/8/13.
 */

public interface MiddleDiscoveryContract {
    interface Presenter extends BasePresenter<MiddleDiscoveryContract.View> {
        void initDiscoveryTop();
        void initDiscoveryRecord();
    }

    interface View extends BaseView {
        void initDiscoveryGroupError(String error);
        void initDiscoveryRecordError(String error);
        void initDiscoveryGroupSuc(List<DiscoveryTopGroup> topGroups);
        void initDiscoveryRecordSuc(List<DiscoveryRecord> topGroups);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations

def change_locale_bn_bd_to_bn_forwards(apps, schema_editor):
    Question = apps.get_model("questions", "Question")
    QuestionLocale = apps.get_model("questions", "QuestionLocale")
    Question.objects.filter(locale='bn-BD').update(locale='bn')
    QuestionLocale.objects.filter(locale='bn-BD').update(locale='bn')

def change_locale_bn_to_bn_bd_backwards(apps, schema_editor):
    pass

class Migration(migrations.Migration):

    dependencies = [
        ('questions', '0008_auto_20190507_1052'),
    ]

    operations = [
        migrations.RunPython(change_locale_bn_bd_to_bn_forwards,
                             change_locale_bn_to_bn_bd_backwards)
    ]


text:
namespace TypeSafeClientTests
{
    using System;
    using System.Linq.Expressions;
    using NUnit.Framework;
    using TypeSafeClient.Reflection;

    [TestFixture]
    public class ExpressionToolsTests
    {
        private readonly object _three = "three";

        public interface ISampleInterface
        {
            void PlainMethod();
            void ComplexMethod(int i, string two, object three);
            int Returns(int i);
        }

        public class SampleClass
        {
            public void PlainMethod() { }
            public void ComplexMethod(int i, string two, object three) { }
            public int Returns(int i) { return i; }
        }

        [Test]
        public void can_get_invocation_name_from_interface()
        {
            var result = ExpressionTools.GetInvocation<ISampleInterface>(i => i.PlainMethod());

            Assert.AreEqual("PlainMethod", result.MethodName);
            Assert.AreEqual(0, result.ParameterValues.Length);
        }

        [Test]
        public void can_get_invocation_name_and_parameters_from_interface()
        {
            var result = ExpressionTools.GetInvocation<ISampleInterface>(
                i => i.ComplexMethod(1, "two", _three)
                );

            Assert.AreEqual("ComplexMethod", result.MethodName);
            Assert.AreEqual(1, result.ParameterValues[0]);
            Assert.AreEqual("two", result.ParameterValues[1]);
            Assert.AreEqual(_three, result.ParameterValues[2]);
        }

        [Test]
        public void can_get_invocation_name_and_parameters_from_returning_functions_on_interfaces()
        {
            var result = ExpressionTools.GetInvocation<ISampleInterface>(i => i.Returns(1));

            Assert.AreEqual("Returns", result.MethodName);
            Assert.AreEqual(1, result.ParameterValues[0]);
        }

        [Test]
        public void variable_values_are_returned_as_at_call_time()
        {
            // ReSharper disable AccessToModifiedClosure
            var v = 1;
            var result = ExpressionTools.GetInvocation<ISampleInterface>(i => i.Returns(v));
            v = 2;
            // ReSharper restore AccessToModifiedClosure

            Assert.AreEqual("Returns", result.MethodName);
            Assert.AreEqual(1, result.ParameterValues[0]);
            Assert.AreNotEqual(v, result.ParameterValues[0]);
        }

        [Test]
        public void can_get_invocation_name_from_class()
        {
            var result = ExpressionTools.GetInvocation<SampleClass>(i => i.PlainMethod());

            Assert.AreEqual("PlainMethod", result.MethodName);
            Assert.AreEqual(0, result.ParameterValues.Length);
        }

        [Test]
        public void can_get_invocation_name_and_parameters_from_class()
        {
            var result = ExpressionTools.GetInvocation<SampleClass>(
                i => i.ComplexMethod(1, "two", _three)
                );

            Assert.AreEqual("ComplexMethod", result.MethodName);
            Assert.AreEqual(1, result.ParameterValues[0]);
            Assert.AreEqual("two", result.ParameterValues[1]);
            Assert.AreEqual(_three, result.ParameterValues[2]);
        }

        [Test]
        public void can_get_invocation_name_and_parameters_from_returning_functions_on_class()
        {
            var result = ExpressionTools.GetInvocation<SampleClass>(i => i.Returns(1));

            Assert.AreEqual("Returns", result.MethodName);
            Assert.AreEqual(1, result.ParameterValues[0]);
        }

        [Test]
        public void can_get_method_name_and_parameter_types_for_a_method_for_binding()
        {
            var result = E(i => i.ComplexMethod).GetBinding();

            Assert.AreEqual("ComplexMethod", result.MethodName);
            Assert.AreEqual(typeof(int), result.ParameterTypes[0]);
            Assert.AreEqual(typeof(string), result.ParameterTypes[1]);
            Assert.AreEqual(typeof(object), result.ParameterTypes[2]);
        }

        static LambdaExpression E(Expression<Func<ISampleInterface, Action<int, string, object>>> e)
        {
            return e;
        }
    }
}


text:
<link href="../css/module.css" rel="stylesheet" type="text/css">

index

module components.blinker.main

Blinker

Main module for Blinker, the rule-based Tlink generation component.

Responsible for loading the libraries and other top-level processing.

class Blinker

Inherits from: TarsqiComponent

Implements the Blinker component of Tarsqi. Blinker takes the shallow
tree implemented in the TarsqiTree object and applies rules that capture
regularities between events and times as well as between events.

Instance variables:
   NAME         -  a string
   dct          -  document creation time: a string of the form YYYYMMDD
   rules        -  a BlinkerRuleDictionary
   rule2_index  -  a dictionary, quick access to type 2 rules
   tarsqidoc    -  a TarsqiDOcument
   doctree      -  a TarsqiTree

Public Functions

__init__(self, tarsqidoc)

Set component name and load rules into a BlinkerRuleDictionary
object, this object knows where the rules are stored.

process_element(self, element)

Apply the Blinker rules to the element. Creates a TarsqiTree instance
and then applies the Blinker rules.

run_timex_linking(self)

Apply the rules that govern relations between TIMEX3 tags. Only
applies to TIMEX3 tags with type=DATE.

Private Functions

_add_tlink(self, reltype, id1, id2, source)

Add a TLINK to self.tarsqidoc.

_apply_event_anchoring_rules(self, sentence, timex, i)

Anchor events to a given timex that occurs in the sentence at index
i. The method proceeds by looking for some simple syntactic patterns
with and without prepositions. If a pattern with a preposition occurs,
then the preposition is looked up in self.rule2_index. If no signal is
found, then the default INCLUDES rule will apply (rule 1), this is not
yet implemented.

_apply_event_ordering_with_signal_rules(self)

Some more rules without using any rules, basically a placeholder
for event ordering rules that use a signal.

_apply_type3_rules(self, event1, event2)

Creates a TLINK between two main events

_apply_type5_rules(self, sentence, event1, position)

Creates TLINKs between the reporting event and reported events

Takes as arguments sentence, reporting event constituent, and
position of that constituent within the sentence list

_create_timex_link(self, timex1, timex2)

Try to create a TLINK between two timexes.

_index_rules(self)

Rules of type 2 (timex-signal-event) can be simply put in a hash
keyed on the signals.

_run_blinker(self)

Apply BLinker rules to the sentences in the doctree variable. This
currently only deals with rule type 2, anchoring an event to a timex in
those cases where there is a signal (that is, a preposition). New
Tlinks are added just before the closing tag of the fragment.

module functions


text:
gsnamnd.controls.mapPanel = function () {
    var that = wui.controls.panels.standard();

    that.titlebar = wui.controls.titleBar();
    that.titlebar.setText("Map");

    that.mainPanel = wui.controls.panels.scroll();

    that.appendControl(that.titlebar);
    that.appendControl(that.mainPanel);
    return that;
};


text:
using Igneel.Assets;
using Igneel.Collections;
using Igneel.Graphics;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Igneel.Rendering
{
    public abstract class Technique :ResourceAllocator,  IEnabletable
    {
        internal bool enable = true;

        public Technique()
        {

        }

        public bool Enable
        {
            get
            {
                return enable;
            }
            set
            {
                enable = value;
            }
        }

        public abstract void Apply();

        public static void Require<T>() where T : class, IResourceAllocator, new()
        {
            var tech = Service.Get<T>();
            if (tech == null)
            {
                var factory = Service.Get<IFactory<T>>();
                if (factory == null)
                {
                    Service.Set<IFactory<T>>(new SingletonDisposableFactoryNew<T>());
                }
            }
        }

        public static void Dispose<T>() where T : class, IDisposable
        {
            var tech = Service.Get<T>();
            if (tech != null)
                tech.Dispose();
        }

        public virtual void Bind(Render render) { }

        public virtual void UnBind(Render render) { }

    }

    public abstract class Technique<TEffect> : Technique
        where TEffect:Effect
    {
        protected Effect effect;

        public Effect Effect { get { return effect; } }

        public Technique(GraphicDevice device)
        {
            effect = Rendering.Effect.GetEffect<TEffect>(device);
        }
    }
}


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("GoogleMusic.NET")]
[assembly: AssemblyDescription("GoogleMusic.NET is an unofficial API for Google Music")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("Copyright © 2015, Lutz Bürkle")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]

// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("1b79fe4a-1fb2-4b9b-81c6-16370a9b7365")]

// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
//      Hauptversion
//      Nebenversion
//      Buildnummer
//      Revision
//
[assembly: AssemblyVersion("1.8.0.55")]
[assembly: AssemblyFileVersion("1.8.0.55")]


text:
using Zametek.Maths.Graphs;

namespace Zametek.Data.ProjectPlan.v0_1_0
{
    [Serializable]
    public record ActivityNodeModel
    {
        public NodeType NodeType { get; init; }

        public ActivityModel? Content { get; init; }

        public List<int> IncomingEdges { get; init; } = new List<int>();

        public List<int> OutgoingEdges { get; init; } = new List<int>();
    }
}


text:
using System.Windows;
using System.Windows.Controls;
using Huddle.Engine.Util;

namespace Huddle.Engine.Controls
{
    /// <summary>
    /// Interaction logic for RemovableExpander.xaml
    /// </summary>
    public partial class RemovableExpander : Expander
    {
        #region Routed Events

        #region Remove

        /// <summary>
        /// Remove Routed Event
        /// </summary>
        public static readonly RoutedEvent RemoveEvent = EventManager.RegisterRoutedEvent("Remove",
            RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(RemovableExpander));

        /// <summary>
        /// Occurs when ...
        /// </summary>
        public event RoutedEventHandler Remove
        {
            add { AddHandler(RemoveEvent, value); }
            remove { RemoveHandler(RemoveEvent, value); }
        }

        /// <summary>
        /// A helper method to raise the Remove event.
        /// </summary>
        protected RoutedEventArgs RaiseRemoveEvent()
        {
            return RaiseRemoveEvent(this);
        }

        /// <summary>
        /// A static helper method to raise the Remove event on a target element.
        /// </summary>
        /// <param name="target">UIElement or ContentElement on which to raise the event</param>
        internal static RoutedEventArgs RaiseRemoveEvent(DependencyObject target)
        {
            if (target == null) return null;

            RoutedEventArgs args = new RoutedEventArgs();
            args.RoutedEvent = RemoveEvent;
            RoutedEventHelper.RaiseEvent(target, args);
            return args;
        }

        #endregion

        #endregion

        #region dependency properties

        #region HeaderContentTemplate

        public DataTemplate HeaderContentTemplate
        {
            get { return (DataTemplate)GetValue(HeaderContentTemplateProperty); }
            set { SetValue(HeaderContentTemplateProperty, value); }
        }

        // Using a DependencyProperty as the backing store for HeaderContentTemplate.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HeaderContentTemplateProperty =
            DependencyProperty.Register("HeaderContentTemplate", typeof(DataTemplate), typeof(RemovableExpander), new PropertyMetadata(null));

        #endregion

        #region HeaderContent

        public object HeaderContent
        {
            get { return (object)GetValue(HeaderContentProperty); }
            set { SetValue(HeaderContentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for HeaderContent.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HeaderContentProperty =
            DependencyProperty.Register("HeaderContent", typeof(object), typeof(RemovableExpander), new PropertyMetadata(null));

        #endregion

        #endregion

        public RemovableExpander()
        {
            InitializeComponent();
        }

        private void RemoveSite_OnClick(object sender, RoutedEventArgs e)
        {
            RaiseRemoveEvent(this);
        }
    }
}