text:
<?php

namespace OpenConext\EngineBlock\Http;

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\Psr7\Response;
use Mockery as m;
use OpenConext\EngineBlock\Http\Exception\AccessDeniedException;
use OpenConext\EngineBlock\Http\Exception\MalformedResponseException;
use OpenConext\EngineBlock\Http\Exception\RequestException;
use PHPUnit_Framework_TestCase as UnitTest;

class HttpClientTest extends UnitTest
{
    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function data_from_a_resource_can_be_read()
    {
        $data = 'My first resource';

        $mockHandler = new MockHandler(
            [
                new Response(200, [], json_encode($data))
            ]
        );
        $guzzle      = new Client(['handler' => $mockHandler]);
        $client      = new HttpClient($guzzle);

        $response = $client->read('/give-me/resource');

        $this->assertEquals($data, $response);
    }

    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function malformed_json_causes_a_malformed_response_exception_when_reading()
    {
        $malformedJson = '{';

        $mockHandler   = new MockHandler([
            new Response(200, [], $malformedJson)
        ]);
        $guzzle = new Client(['handler' => $mockHandler]);
        $client = new HttpClient($guzzle);

        $this->expectException(MalformedResponseException::class);

        $client->read('/give-me/malformed-json');
    }

    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function null_is_returned_when_the_response_status_code_is_404_when_reading()
    {
        $mockHandler   = new MockHandler([
            new Response(404, [])
        ]);
        $guzzle = new Client(['handler' => $mockHandler]);
        $client = new HttpClient($guzzle);

        $response = $client->read('give-me/404');

        $this->assertNull(
            $response,
            'The response should be null when encountering a 404 when reading, but it was not'
        );
    }

    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function an_access_denied_exception_is_thrown_if_the_response_status_code_is_403_when_reading()
    {
        $mockHandler   = new MockHandler([
            new Response(403, [])
        ]);
        $guzzle = new Client(['handler' => $mockHandler]);
        $client = new HttpClient($guzzle);

        $this->expectException(AccessDeniedException::class);

        $client->read('give-me/403');
    }

    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function data_from_a_resource_can_be_posted()
    {
        $data     = 'Received data';
        $mockHandler = new MockHandler(
            [
                new Response(200, [], json_encode($data))
            ]
        );
        $guzzle      = new Client(['handler' => $mockHandler]);
        $client      = new HttpClient($guzzle);

        $response = $client->post('/resource', 'Post body');

        $this->assertEquals($data, $response);
    }

    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function malformed_json_causes_a_malformed_response_exception_when_posting()
    {
        $malformedJson = '{';

        $mockHandler   = new MockHandler([
            new Response(200, [], $malformedJson)
        ]);
        $guzzle = new Client(['handler' => $mockHandler]);
        $client = new HttpClient($guzzle);

        $this->expectException(MalformedResponseException::class);

        $client->post('/post-and-give-me/malformed-json', 'Post body');
    }

    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function null_is_returned_when_the_response_status_code_is_404_when_posting()
    {
        $mockHandler   = new MockHandler([
            new Response(404, [])
        ]);
        $guzzle = new Client(['handler' => $mockHandler]);
        $client = new HttpClient($guzzle);

        $response = $client->post('post-and-give-me/404', 'Post body');

        $this->assertNull(
            $response,
            'The response should be null when encountering a 404 when reading, but it was not'
        );
    }

    /**
     * @test
     * @group EngineBlock
     * @group Http
     */
    public function an_access_denied_exception_is_thrown_if_the_response_status_code_is_403_when_posting()
    {
        $mockHandler   = new MockHandler([
            new Response(403, [])
        ]);
        $guzzle = new Client(['handler' => $mockHandler]);
        $client = new HttpClient($guzzle);

        $this->expectException(AccessDeniedException::class);

        $client->post('post-and-give-me/403', 'Post body');
    }
}


text:
Originally published: 2007-10-16 14:43:55
Last updated: 2007-10-19 22:33:18
Author: Symon Polley

a simple and useful script that uses signal to time out any function.

EDIT: use Jim Carrolls solution below

redpajama_set_name: RedPajamaGithub


text:
## MkDocs

  * http://www.mkdocs.org/user-guide/writing-your-docs/

MkDocs is a very simple site generator that reads in markdown files and auto generates a site
which can be auto published to a Git Repo's gh-pages branch.
Anything posted within a gh-pages branch on github is automatically visible as a static web site.

## Script commands

  * **build.py build** - Do a dummy build into the site sub directory
  * **build.py publish** - Generate and publish a site to github.io (gh-pages branch) for the repo
  * **build.py serve** - Auto Serv the site on http://127.0.0.1:8000

One of the advantages to the serve command is that any changes to the mark down files while viewing the site
cause the browser to auto refresh the site as it's being viewed.

## Install

  * Install python
  * pip install mkdocs
  * for the different themes - mkdocs-bootswatch, mkdocs-bootstrap, mkdocs-alabaster


text:
#include "urlmon_main.h"
#include "winreg.h"

#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(urlmon);

typedef struct {
    LPWSTR protocol;
    IClassFactory *cf;
    CLSID clsid;
    BOOL urlmon;

    struct list entry;
} name_space;

typedef struct {
    IClassFactory *cf;
    CLSID clsid;
    LPWSTR mime;

    struct list entry;
} mime_filter;

static struct list name_space_list = LIST_INIT(name_space_list);
static struct list mime_filter_list = LIST_INIT(mime_filter_list);

static CRITICAL_SECTION session_cs;
static CRITICAL_SECTION_DEBUG session_cs_dbg =
{
    0, 0, &session_cs,
    { &session_cs_dbg.ProcessLocksList, &session_cs_dbg.ProcessLocksList },
      0, 0, { (DWORD_PTR)(__FILE__ ": session") }
};
static CRITICAL_SECTION session_cs = { &session_cs_dbg, -1, 0, 0, 0, 0 };

static const WCHAR internet_settings_keyW[] =
    {'S','O','F','T','W','A','R','E',
     '\\','M','i','c','r','o','s','o','f','t',
     '\\','W','i','n','d','o','w','s',
     '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n',
     '\\','I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s',0};

static name_space *find_name_space(LPCWSTR protocol)
{
    name_space *iter;

    LIST_FOR_EACH_ENTRY(iter, &name_space_list, name_space, entry) {
        if(!strcmpiW(iter->protocol, protocol))
            return iter;
    }

    return NULL;
}

static HRESULT get_protocol_cf(LPCWSTR schema, DWORD schema_len, CLSID *pclsid, IClassFactory **ret)
{
    WCHAR str_clsid[64];
    HKEY hkey = NULL;
    DWORD res, type, size;
    CLSID clsid;
    LPWSTR wszKey;
    HRESULT hres;

    static const WCHAR wszProtocolsKey[] =
        {'P','R','O','T','O','C','O','L','S','\\','H','a','n','d','l','e','r','\\'};
    static const WCHAR wszCLSID[] = {'C','L','S','I','D',0};

    wszKey = heap_alloc(sizeof(wszProtocolsKey)+(schema_len+1)*sizeof(WCHAR));
    memcpy(wszKey, wszProtocolsKey, sizeof(wszProtocolsKey));
    memcpy(wszKey + sizeof(wszProtocolsKey)/sizeof(WCHAR), schema, (schema_len+1)*sizeof(WCHAR));

    res = RegOpenKeyW(HKEY_CLASSES_ROOT, wszKey, &hkey);
    heap_free(wszKey);
    if(res != ERROR_SUCCESS) {
        TRACE("Could not open protocol handler key\n");
        return MK_E_SYNTAX;
    }

    size = sizeof(str_clsid);
    res = RegQueryValueExW(hkey, wszCLSID, NULL, &type, (LPBYTE)str_clsid, &size);
    RegCloseKey(hkey);
    if(res != ERROR_SUCCESS || type != REG_SZ) {
        WARN("Could not get protocol CLSID res=%d\n", res);
        return MK_E_SYNTAX;
    }

    hres = CLSIDFromString(str_clsid, &clsid);
    if(FAILED(hres)) {
        WARN("CLSIDFromString failed: %08x\n", hres);
        return hres;
    }

    if(pclsid)
        *pclsid = clsid;

    if(!ret)
        return S_OK;

    hres = CoGetClassObject(&clsid, CLSCTX_INPROC_SERVER, NULL, &IID_IClassFactory, (void**)ret);
    return SUCCEEDED(hres) ? S_OK : MK_E_SYNTAX;
}

HRESULT register_namespace(IClassFactory *cf, REFIID clsid, LPCWSTR protocol, BOOL urlmon_protocol)
{
    name_space *new_name_space;

    new_name_space = heap_alloc(sizeof(name_space));

    if(!urlmon_protocol)
        IClassFactory_AddRef(cf);
    new_name_space->cf = cf;
    new_name_space->clsid = *clsid;
    new_name_space->urlmon = urlmon_protocol;
    new_name_space->protocol = heap_strdupW(protocol);

    EnterCriticalSection(&session_cs);

    list_add_head(&name_space_list, &new_name_space->entry);

    LeaveCriticalSection(&session_cs);

    return S_OK;
}

static HRESULT unregister_namespace(IClassFactory *cf, LPCWSTR protocol)
{
    name_space *iter;

    EnterCriticalSection(&session_cs);

    LIST_FOR_EACH_ENTRY(iter, &name_space_list, name_space, entry) {
        if(iter->cf == cf && !strcmpiW(iter->protocol, protocol)) {
            list_remove(&iter->entry);

            LeaveCriticalSection(&session_cs);

            if(!iter->urlmon)
                IClassFactory_Release(iter->cf);
            heap_free(iter->protocol);
            heap_free(iter);
            return S_OK;
        }
    }

    LeaveCriticalSection(&session_cs);
    return S_OK;
}

BOOL is_registered_protocol(LPCWSTR url)
{
    DWORD schema_len;
    WCHAR schema[64];
    HRESULT hres;

    hres = CoInternetParseUrl(url, PARSE_SCHEMA, 0, schema, sizeof(schema)/sizeof(schema[0]),
            &schema_len, 0);
    if(FAILED(hres))
        return FALSE;

    return get_protocol_cf(schema, schema_len, NULL, NULL) == S_OK;
}

IInternetProtocolInfo *get_protocol_info(LPCWSTR url)
{
    IInternetProtocolInfo *ret = NULL;
    IClassFactory *cf;
    name_space *ns;
    WCHAR schema[64];
    DWORD schema_len;
    HRESULT hres;

    hres = CoInternetParseUrl(url, PARSE_SCHEMA, 0, schema, sizeof(schema)/sizeof(schema[0]),
            &schema_len, 0);
    if(FAILED(hres) || !schema_len)
        return NULL;

    EnterCriticalSection(&session_cs);

    ns = find_name_space(schema);
    if(ns && !ns->urlmon) {
        hres = IClassFactory_QueryInterface(ns->cf, &IID_IInternetProtocolInfo, (void**)&ret);
        if(FAILED(hres))
            hres = IClassFactory_CreateInstance(ns->cf, NULL, &IID_IInternetProtocolInfo, (void**)&ret);
    }

    LeaveCriticalSection(&session_cs);

    if(ns && SUCCEEDED(hres))
        return ret;

    hres = get_protocol_cf(schema, schema_len, NULL, &cf);
    if(FAILED(hres))
        return NULL;

    hres = IClassFactory_QueryInterface(cf, &IID_IInternetProtocolInfo, (void**)&ret);
    if(FAILED(hres))
        IClassFactory_CreateInstance(cf, NULL, &IID_IInternetProtocolInfo, (void**)&ret);
    IClassFactory_Release(cf);

    return ret;
}

HRESULT get_protocol_handler(IUri *uri, CLSID *clsid, BOOL *urlmon_protocol, IClassFactory **ret)
{
    name_space *ns;
    BSTR scheme;
    HRESULT hres;

    *ret = NULL;

    /* FIXME: Avoid GetSchemeName call for known schemes */
    hres = IUri_GetSchemeName(uri, &scheme);
    if(FAILED(hres))
        return hres;

    EnterCriticalSection(&session_cs);

    ns = find_name_space(scheme);
    if(ns) {
        *ret = ns->cf;
        IClassFactory_AddRef(*ret);
        if(clsid)
            *clsid = ns->clsid;
        if(urlmon_protocol)
            *urlmon_protocol = ns->urlmon;
    }

    LeaveCriticalSection(&session_cs);

    if(*ret) {
        hres = S_OK;
    }else {
        if(urlmon_protocol)
            *urlmon_protocol = FALSE;
        hres = get_protocol_cf(scheme, SysStringLen(scheme), clsid, ret);
    }

    SysFreeString(scheme);
    return hres;
}

IInternetProtocol *get_mime_filter(LPCWSTR mime)
{
    static const WCHAR filtersW[] = {'P','r','o','t','o','c','o','l','s',
        '\\','F','i','l','t','e','r',0 };
    static const WCHAR CLSIDW[] = {'C','L','S','I','D',0};

    IClassFactory *cf = NULL;
    IInternetProtocol *ret;
    mime_filter *iter;
    HKEY hlist, hfilter;
    WCHAR clsidw[64];
    CLSID clsid;
    DWORD res, type, size;
    HRESULT hres;

    EnterCriticalSection(&session_cs);

    LIST_FOR_EACH_ENTRY(iter, &mime_filter_list, mime_filter, entry) {
        if(!strcmpW(iter->mime, mime)) {
            cf = iter->cf;
            break;
        }
    }

    LeaveCriticalSection(&session_cs);

    if(cf) {
        hres = IClassFactory_CreateInstance(cf, NULL, &IID_IInternetProtocol, (void**)&ret);
        if(FAILED(hres)) {
            WARN("CreateInstance failed: %08x\n", hres);
            return NULL;
        }

        return ret;
    }

    res = RegOpenKeyW(HKEY_CLASSES_ROOT, filtersW, &hlist);
    if(res != ERROR_SUCCESS) {
        TRACE("Could not open MIME filters key\n");
        return NULL;
    }

    res = RegOpenKeyW(hlist, mime, &hfilter);
    CloseHandle(hlist);
    if(res != ERROR_SUCCESS)
        return NULL;

    size = sizeof(clsidw);
    res = RegQueryValueExW(hfilter, CLSIDW, NULL, &type, (LPBYTE)clsidw, &size);
    CloseHandle(hfilter);
    if(res!=ERROR_SUCCESS || type!=REG_SZ) {
        WARN("Could not get filter CLSID for %s\n", debugstr_w(mime));
        return NULL;
    }

    hres = CLSIDFromString(clsidw, &clsid);
    if(FAILED(hres)) {
        WARN("CLSIDFromString failed for %s (%x)\n", debugstr_w(mime), hres);
        return NULL;
    }

    hres = CoCreateInstance(&clsid, NULL, CLSCTX_INPROC_SERVER, &IID_IInternetProtocol, (void**)&ret);
    if(FAILED(hres)) {
        WARN("CoCreateInstance failed: %08x\n", hres);
        return NULL;
    }

    return ret;
}

static HRESULT WINAPI InternetSession_QueryInterface(IInternetSession *iface,
        REFIID riid, void **ppv)
{
    TRACE("(%s %p)\n", debugstr_guid(riid), ppv);

    if(IsEqualGUID(&IID_IUnknown, riid) || IsEqualGUID(&IID_IInternetSession, riid)) {
        *ppv = iface;
        IInternetSession_AddRef(iface);
        return S_OK;
    }

    *ppv = NULL;
    return E_NOINTERFACE;
}

static ULONG WINAPI InternetSession_AddRef(IInternetSession *iface)
{
    TRACE("()\n");
    URLMON_LockModule();
    return 2;
}

static ULONG WINAPI InternetSession_Release(IInternetSession *iface)
{
    TRACE("()\n");
    URLMON_UnlockModule();
    return 1;
}

static HRESULT WINAPI InternetSession_RegisterNameSpace(IInternetSession *iface,
        IClassFactory *pCF, REFCLSID rclsid, LPCWSTR pwzProtocol, ULONG cPatterns,
        const LPCWSTR *ppwzPatterns, DWORD dwReserved)
{
    TRACE("(%p %s %s %d %p %d)\n", pCF, debugstr_guid(rclsid), debugstr_w(pwzProtocol),
          cPatterns, ppwzPatterns, dwReserved);

    if(cPatterns || ppwzPatterns)
        FIXME("patterns not supported\n");
    if(dwReserved)
        WARN("dwReserved = %d\n", dwReserved);

    if(!pCF || !pwzProtocol)
        return E_INVALIDARG;

    return register_namespace(pCF, rclsid, pwzProtocol, FALSE);
}

static HRESULT WINAPI InternetSession_UnregisterNameSpace(IInternetSession *iface,
        IClassFactory *pCF, LPCWSTR pszProtocol)
{
    TRACE("(%p %s)\n", pCF, debugstr_w(pszProtocol));

    if(!pCF || !pszProtocol)
        return E_INVALIDARG;

    return unregister_namespace(pCF, pszProtocol);
}

static HRESULT WINAPI InternetSession_RegisterMimeFilter(IInternetSession *iface,
        IClassFactory *pCF, REFCLSID rclsid, LPCWSTR pwzType)
{
    mime_filter *filter;

    TRACE("(%p %s %s)\n", pCF, debugstr_guid(rclsid), debugstr_w(pwzType));

    filter = heap_alloc(sizeof(mime_filter));

    IClassFactory_AddRef(pCF);
    filter->cf = pCF;
    filter->clsid = *rclsid;
    filter->mime = heap_strdupW(pwzType);

    EnterCriticalSection(&session_cs);

    list_add_head(&mime_filter_list, &filter->entry);

    LeaveCriticalSection(&session_cs);

    return S_OK;
}

static HRESULT WINAPI InternetSession_UnregisterMimeFilter(IInternetSession *iface,
        IClassFactory *pCF, LPCWSTR pwzType)
{
    mime_filter *iter;

    TRACE("(%p %s)\n", pCF, debugstr_w(pwzType));

    EnterCriticalSection(&session_cs);

    LIST_FOR_EACH_ENTRY(iter, &mime_filter_list, mime_filter, entry) {
        if(iter->cf == pCF && !strcmpW(iter->mime, pwzType)) {
            list_remove(&iter->entry);

            LeaveCriticalSection(&session_cs);

            IClassFactory_Release(iter->cf);
            heap_free(iter->mime);
            heap_free(iter);
            return S_OK;
        }
    }

    LeaveCriticalSection(&session_cs);
    return S_OK;
}

static HRESULT WINAPI InternetSession_CreateBinding(IInternetSession *iface,
        LPBC pBC, LPCWSTR szUrl, IUnknown *pUnkOuter, IUnknown **ppUnk,
        IInternetProtocol **ppOInetProt, DWORD dwOption)
{
    BindProtocol *protocol;
    HRESULT hres;

    TRACE("(%p %s %p %p %p %08x)\n", pBC, debugstr_w(szUrl), pUnkOuter, ppUnk,
            ppOInetProt, dwOption);

    if(pBC || pUnkOuter || ppUnk || dwOption)
        FIXME("Unsupported arguments\n");

    hres = create_binding_protocol(FALSE, &protocol);
    if(FAILED(hres))
        return hres;

    *ppOInetProt = (IInternetProtocol*)&protocol->IInternetProtocolEx_iface;
    return S_OK;
}

static HRESULT WINAPI InternetSession_SetSessionOption(IInternetSession *iface,
        DWORD dwOption, LPVOID pBuffer, DWORD dwBufferLength, DWORD dwReserved)
{
    FIXME("(%08x %p %d %d)\n", dwOption, pBuffer, dwBufferLength, dwReserved);
    return E_NOTIMPL;
}

static const IInternetSessionVtbl InternetSessionVtbl = {
    InternetSession_QueryInterface,
    InternetSession_AddRef,
    InternetSession_Release,
    InternetSession_RegisterNameSpace,
    InternetSession_UnregisterNameSpace,
    InternetSession_RegisterMimeFilter,
    InternetSession_UnregisterMimeFilter,
    InternetSession_CreateBinding,
    InternetSession_SetSessionOption
};

static IInternetSession InternetSession = { &InternetSessionVtbl };

/***********************************************************************
 *           CoInternetGetSession (URLMON.@)
 *
 * Create a new internet session and return an IInternetSession interface
 * representing it.
 *
 * PARAMS
 *    dwSessionMode      [I] Mode for the internet session
 *    ppIInternetSession [O] Destination for creates IInternetSession object
 *    dwReserved         [I] Reserved, must be 0.
 *
 * RETURNS
 *    Success: S_OK. ppIInternetSession contains the IInternetSession interface.
 *    Failure: E_INVALIDARG, if any argument is invalid, or
 *             E_OUTOFMEMORY if memory allocation fails.
 */
HRESULT WINAPI CoInternetGetSession(DWORD dwSessionMode, IInternetSession **ppIInternetSession,
        DWORD dwReserved)
{
    TRACE("(%d %p %d)\n", dwSessionMode, ppIInternetSession, dwReserved);

    if(dwSessionMode)
        ERR("dwSessionMode=%d\n", dwSessionMode);
    if(dwReserved)
        ERR("dwReserved=%d\n", dwReserved);

    IInternetSession_AddRef(&InternetSession);
    *ppIInternetSession = &InternetSession;
    return S_OK;
}

/**************************************************************************
 *                 UrlMkGetSessionOption (URLMON.@)
 */
static BOOL get_url_encoding(HKEY root, DWORD *encoding)
{
    DWORD size = sizeof(DWORD), res, type;
    HKEY hkey;

    static const WCHAR wszUrlEncoding[] = {'U','r','l','E','n','c','o','d','i','n','g',0};

    res = RegOpenKeyW(root, internet_settings_keyW, &hkey);
    if(res != ERROR_SUCCESS)
        return FALSE;

    res = RegQueryValueExW(hkey, wszUrlEncoding, NULL, &type, (LPBYTE)encoding, &size);
    RegCloseKey(hkey);

    return res == ERROR_SUCCESS;
}

static LPWSTR user_agent;

static void ensure_useragent(void)
{
    OSVERSIONINFOW info = {sizeof(info)};
    const WCHAR *os_type, *is_nt;
    WCHAR buf[512], *ret, *tmp;
    DWORD res, idx=0;
    size_t len, size;
    BOOL is_wow;
    HKEY key;

    static const WCHAR formatW[] =
        {'M','o','z','i','l','l','a','/','4','.','0',
         ' ','(','c','o','m','p','a','t','i','b','l','e',';',
         ' ','M','S','I','E',' ','8','.','0',';',
         ' ','W','i','n','d','o','w','s',' ','%','s','%','d','.','%','d',';',
         ' ','%','s',';',' ','T','r','i','d','e','n','t','/','5','.','0',0};
    static const WCHAR post_platform_keyW[] =
        {'S','O','F','T','W','A','R','E',
         '\\','M','i','c','r','o','s','o','f','t',
         '\\','W','i','n','d','o','w','s',
         '\\','C','u','r','r','e','n','t','V','e','r','s','i','o','n',
         '\\','I','n','t','e','r','n','e','t',' ','S','e','t','t','i','n','g','s',
         '\\','5','.','0','\\','U','s','e','r',' ','A','g','e','n','t',
         '\\','P','o','s','t',' ','P','l','a','t','f','o','r','m',0};
    static const WCHAR ntW[] = {'N','T',' ',0};
    static const WCHAR win32W[] = {'W','i','n','3','2',0};
    static const WCHAR win64W[] = {'W','i','n','6','4',0};
    static const WCHAR wow64W[] = {'W','O','W','6','4',0};
    static const WCHAR emptyW[] = {0};

    if(user_agent)
        return;

    GetVersionExW(&info);
    is_nt = info.dwPlatformId == VER_PLATFORM_WIN32_NT ? ntW : emptyW;

    if(sizeof(void*) == 8)
        os_type = win64W;
    else if(IsWow64Process(GetCurrentProcess(), &is_wow) && is_wow)
        os_type = wow64W;
    else
        os_type = win32W;

    sprintfW(buf, formatW, is_nt, info.dwMajorVersion, info.dwMinorVersion, os_type);
    len = strlenW(buf);

    size = len+40;
    ret = heap_alloc(size * sizeof(WCHAR));
    if(!ret)
        return;

    memcpy(ret, buf, len*sizeof(WCHAR));

    res = RegOpenKeyW(HKEY_LOCAL_MACHINE, post_platform_keyW, &key);
    if(res == ERROR_SUCCESS) {
        DWORD value_len;

        while(1) {
            value_len = sizeof(buf)/sizeof(WCHAR);
            res = RegEnumValueW(key, idx, buf, &value_len, NULL, NULL, NULL, NULL);
            if(res != ERROR_SUCCESS)
                break;
            idx++;

            if(len + value_len + 2 /* strlen("; ") */ + 1 /* trailing ')' */ >= size) {
                tmp = heap_realloc(ret, (size*2+value_len)*sizeof(WCHAR));
                if(!tmp)
                    break;
                ret = tmp;
                size = size*2+value_len;
            }

            ret[len++] = ';';
            ret[len++] = ' ';
            memcpy(ret+len, buf, value_len*sizeof(WCHAR));
            len += value_len;
        }

        RegCloseKey(key);
    }

    ret[len++] = ')';
    ret[len++] = 0;

    user_agent = ret;
    TRACE("Using user agent %s\n", debugstr_w(user_agent));
}

LPWSTR get_useragent(void)
{
    LPWSTR ret;

    ensure_useragent();

    EnterCriticalSection(&session_cs);
    ret = heap_strdupW(user_agent);
    LeaveCriticalSection(&session_cs);

    return ret;
}

HRESULT WINAPI UrlMkGetSessionOption(DWORD dwOption, LPVOID pBuffer, DWORD dwBufferLength,
                                     DWORD* pdwBufferLength, DWORD dwReserved)
{
    TRACE("(%x, %p, %d, %p)\n", dwOption, pBuffer, dwBufferLength, pdwBufferLength);

    if(dwReserved)
        WARN("dwReserved = %d\n", dwReserved);

    switch(dwOption) {
    case URLMON_OPTION_USERAGENT: {
        HRESULT hres = E_OUTOFMEMORY;
        DWORD size;

        if(!pdwBufferLength)
            return E_INVALIDARG;

        EnterCriticalSection(&session_cs);

        ensure_useragent();
        if(user_agent) {
            size = WideCharToMultiByte(CP_ACP, 0, user_agent, -1, NULL, 0, NULL, NULL);
            *pdwBufferLength = size;
            if(size <= dwBufferLength) {
                if(pBuffer)
                    WideCharToMultiByte(CP_ACP, 0, user_agent, -1, pBuffer, size, NULL, NULL);
                else
                    hres = E_INVALIDARG;
            }
        }

        LeaveCriticalSection(&session_cs);

        /* Tests prove that we have to return E_OUTOFMEMORY on success. */
        return hres;
    }
    case URLMON_OPTION_URL_ENCODING: {
        DWORD encoding = 0;

        if(!pBuffer || dwBufferLength < sizeof(DWORD) || !pdwBufferLength)
            return E_INVALIDARG;

        if(!get_url_encoding(HKEY_CURRENT_USER, &encoding))
            get_url_encoding(HKEY_LOCAL_MACHINE, &encoding);

        *pdwBufferLength = sizeof(DWORD);
        *(DWORD*)pBuffer = encoding ? URL_ENCODING_DISABLE_UTF8 : URL_ENCODING_ENABLE_UTF8;
        return S_OK;
    }
    default:
        FIXME("unsupported option %x\n", dwOption);
    }

    return E_INVALIDARG;
}

/**************************************************************************
 *                 UrlMkSetSessionOption (URLMON.@)
 */
HRESULT WINAPI UrlMkSetSessionOption(DWORD dwOption, LPVOID pBuffer, DWORD dwBufferLength,
        DWORD Reserved)
{
    TRACE("(%x %p %x)\n", dwOption, pBuffer, dwBufferLength);

    switch(dwOption) {
    case URLMON_OPTION_USERAGENT: {
        LPWSTR new_user_agent;
        char *buf = pBuffer;
        DWORD len, size;

        if(!pBuffer || !dwBufferLength)
            return E_INVALIDARG;

        for(len=0; len<dwBufferLength && buf[len]; len++);

        TRACE("Setting user agent %s\n", debugstr_an(buf, len));

        size = MultiByteToWideChar(CP_ACP, 0, buf, len, NULL, 0);
        new_user_agent = heap_alloc((size+1)*sizeof(WCHAR));
        if(!new_user_agent)
            return E_OUTOFMEMORY;
        MultiByteToWideChar(CP_ACP, 0, buf, len, new_user_agent, size);
        new_user_agent[size] = 0;

        EnterCriticalSection(&session_cs);

        heap_free(user_agent);
        user_agent = new_user_agent;

        LeaveCriticalSection(&session_cs);
        break;
    }
    default:
        FIXME("Unknown option %x\n", dwOption);
        return E_INVALIDARG;
    }

    return S_OK;
}

/**************************************************************************
 *                 ObtainUserAgentString (URLMON.@)
 */
HRESULT WINAPI ObtainUserAgentString(DWORD dwOption, LPSTR pcszUAOut, DWORD *cbSize)
{
    DWORD size;
    HRESULT hres = E_FAIL;

    TRACE("(%d %p %p)\n", dwOption, pcszUAOut, cbSize);

    if(!pcszUAOut || !cbSize)
        return E_INVALIDARG;

    EnterCriticalSection(&session_cs);

    ensure_useragent();
    if(user_agent) {
        size = WideCharToMultiByte(CP_ACP, 0, user_agent, -1, NULL, 0, NULL, NULL);

        if(size <= *cbSize) {
            WideCharToMultiByte(CP_ACP, 0, user_agent, -1, pcszUAOut, *cbSize, NULL, NULL);
            hres = S_OK;
        }else {
            hres = E_OUTOFMEMORY;
        }

        *cbSize = size;
    }

    LeaveCriticalSection(&session_cs);
    return hres;
}

void free_session(void)
{
    name_space *ns_iter, *ns_last;
    mime_filter *mf_iter, *mf_last;

    LIST_FOR_EACH_ENTRY_SAFE(ns_iter, ns_last, &name_space_list, name_space, entry) {
            if(!ns_iter->urlmon)
                IClassFactory_Release(ns_iter->cf);
            heap_free(ns_iter->protocol);
            heap_free(ns_iter);
    }

    LIST_FOR_EACH_ENTRY_SAFE(mf_iter, mf_last, &mime_filter_list, mime_filter, entry) {
            IClassFactory_Release(mf_iter->cf);
            heap_free(mf_iter->mime);
            heap_free(mf_iter);
    }

    heap_free(user_agent);
}


text:
"""
Created on Wed Apr 22 01:49:42 2015

@author: Wendy Tran
"""
'''
Sources:
https://play.google.com/store
https://docs.python.org/2/howto/urllib2.html
http://stackoverflow.com/questions/16870648/python-read-website-data-line-by-line-when-available
http://stackoverflow.com/questions/12943819/how-to-python-prettyprint-a-json-file
http://stackoverflow.com/questions/1080411/retrieve-links-from-web-page-using-python-and-beautifulsoup
http://www.crummy.com/software/BeautifulSoup/
http://www.crummy.com/software/BeautifulSoup/bs4/doc/
http://stackoverflow.com/questions/5041008/handling-class-attribute-in-beautifulsoup
http://stackoverflow.com/questions/18851325/adding-more-values-on-existing-python-dictionary-key
http://www.crummy.com/software/BeautifulSoup/bs4/doc/#next-sibling-and-previous-sibling
http://stackoverflow.com/questions/23380171/using-beautifulsoup-extract-text-without-tags
http://stackoverflow.com/questions/1024847/add-key-to-a-dictionary-in-python
http://www.crummy.com/software/BeautifulSoup/bs4/doc/
https://docs.python.org/2/library/uuid.html
https://github.com/behackett/presentations/blob/master/pycon_2012/Lesson%201.1:%20Getting%20Started.ipynb
http://stackoverflow.com/questions/12309269/write-json-data-to-file-in-python
http://stackoverflow.com/questions/4254039/how-to-retrieve-a-value-from-mongodb-by-its-key-name
http://stackoverflow.com/questions/7431422/find-in-dictionary-by-value-in-mongo
http://stackoverflow.com/questions/17360423/getting-a-dictionary-inside-a-list-by-key-in-mongodb-mongoengine
'''

import requests
#import pprint
import json
#import uuid
from bs4 import BeautifulSoup

class GooglePlay:

    def __init__(self):
        pass

    def visitWebPage(self, urlPage):
        webInfo = requests.get(urlPage)
        return webInfo

    def getTitleOfApps(self, wC):
        titles = []
        appInfo = {}
        links = wC.find_all('a', {'class' : 'title'})

        #top 10 apps
        for x in range(0, 10):
            titles.append(links[x].get('title').encode('ascii', 'ignore'))
            #print links[x].text.split()[0].replace('.', '')
            #appInfo[(links[x].get('title').encode('ascii', 'ignore'))] = {'AppLink':'https://play.google.com/'+links[x].get('href'), 'Rank':links[x].text.split()[0].replace('.', '')}
            appInfo[links[x].text.split()[0].replace('.', '')] = {'title':links[x].get('title').encode('ascii', 'ignore'), 'appLink':'https://play.google.com/'+links[x].get('href')}
        return (titles, appInfo)

    def getCompanies(self, aC):
        companies = aC.find_all('span', {'itemprop': 'name'})
        for a in companies:
            return str(a.text)

    def getGenre(self, aC):
        genres = aC.find_all('span', {'itemprop': 'genre'})
        for a in genres:
            return str(a.text)

    def getStarRating(self, aC):
        starRating = aC.find_all('div', {'class': 'score'})
        for a in starRating:
            return str(a.text)

    def getNumOfReviewers(self, aC):
        numOfReviews = aC.find_all('span', {'class': 'reviews-num'})
        for a in numOfReviews:
            return str(a.text)

    '''
    def getDescription(self, aC):
        def getNumOfReviewers(self, aC):
        appDesc = aC.find_all('div', {'class': 'id-app-orig-desc'})
        for a in appDesc:
            return str(a.text)
    '''

    def getReviews(self, aC):
        reviewDict = {}
        reviewInfo = {}
        counter = 0

        singleReviews = aC.findAll('div', {'class': 'single-review'})
        for eachReview in singleReviews:
            reviewInfo['user'] = eachReview.find('span', {'class': 'author-name'}).text
            reviewInfo['date'] = eachReview.find('span', {'class': 'review-date'}).text
            reviewInfo['rating'] = eachReview.find('div', {'class': 'tiny-star star-rating-non-editable-container'})['aria-label']
            reviewInfo['title'] = eachReview.find('span', {'class': 'review-title'}).text
            reviewInfo['comment'] = eachReview.find('span', {'class': 'review-title'}).next_sibling
            #print reviewInfo
            reviewDict['review_'+str(counter)] = reviewInfo
            reviewInfo = {}
            counter += 1
        #print json.dumps(reviewDict, indent=4)
        counter = 0
        return reviewDict

    def getLastUpdated(self, aC):
        lastUpdated = aC.find_all('div', {'itemprop': 'datePublished'})
        for a in lastUpdated:
            return str(a.text)

    def getNumOfInstalls(self, aC):
        numDownloads = aC.find_all('div', {'itemprop': 'numDownloads'})
        for a in numDownloads:
            return str(a.text)

    def getAndrOSReq(self, aC):
        AndroidReq = aC.find_all('div', {'itemprop': 'operatingSystems'})
        for a in AndroidReq:
            return str(a.text)

    def getContentRating(self, aC):
        contentRating = aC.find_all('div', {'itemprop': 'contentRating'})
        for a in contentRating:
            return str(a.text)

    def getInAppPurch(self, aC):
        inAppPurch = aC.find_all('div', {'class': 'inapp-msg'})
        for a in inAppPurch:
            return str(a.text)

    def getAppInfo(self, appKey, appURL, allAppInfo):
        appContent = self.visitWebPage(appURL)
        aC = BeautifulSoup(appContent.content)

        allAppInfo[appKey]['company'] = self.getCompanies(aC)
        allAppInfo[appKey]['genre'] = self.getGenre(aC)
        allAppInfo[appKey]['starRating'] = self.getStarRating(aC)
        allAppInfo[appKey]['numOfReviewers'] = self.getNumOfReviewers(aC)
        allAppInfo[appKey]['lastUpdated'] = self.getLastUpdated(aC)
        allAppInfo[appKey]['numOfInstalls'] = self.getNumOfInstalls(aC)
        allAppInfo[appKey]['androidOSReq'] = self.getAndrOSReq(aC)
        allAppInfo[appKey]['contentRating'] = self.getContentRating(aC)
        allAppInfo[appKey]['inAppPurchases'] = self.getInAppPurch(aC)
        allAppInfo[appKey]['reviews'] = self.getReviews(aC)
        return allAppInfo

    def printToJson(self, gpDict):
        with open('gp.txt', 'w') as outfile:
            json.dump(gpDict, outfile)

    def getGPInfo(self):
        urlPage = 'https://play.google.com/store/apps/collection/topselling_free?hl=en'
        webContent = self.visitWebPage(urlPage)
        wC = BeautifulSoup(webContent.content)

        appTitles = []
        allAppInfo = {}
        topApps = {}

        titles = self.getTitleOfApps(wC)

        #=============
        #---> List of Title of Apps: Send to all Other Classes to Search <---
        appTitles = titles[0]
        #=============

        allAppInfo = titles[1]

        #loops through all the apps to get app Info
        for appKey in allAppInfo.keys():
            allAppInfo = self.getAppInfo(appKey, allAppInfo[appKey]['appLink'], allAppInfo)

        #################################
        #########Test Value##############
        #allAppInfo = self.getAppInfo('Criminal Case', allAppInfo['Criminal Case']['AppLink'], allAppInfo)
        #################################

        topApps['googlePlay'] = allAppInfo
        #self.printToJson(topApps)
        #print json.dumps(topApps, indent=4)
        return (appTitles, topApps)


text:
<?php

declare(strict_types=1);

namespace DoctrineMigrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20201112220914 extends AbstractMigration
{
    public function getDescription(): string
    {
        return '';
    }

    public function up(Schema $schema): void
    {
        // this up() migration is auto-generated, please modify it to your needs

        $this->addSql(<<<SQL
create table lock_keys
(
	key_id varchar(64) not null
		constraint lock_keys_pkey
			primary key,
	key_token varchar(44) not null,
	key_expiration integer not null
);
SQL
        );
    }

    public function down(Schema $schema): void
    {
        // this down() migration is auto-generated, please modify it to your needs
    }
}


text:
package com.linkedin.pinot.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linkedin.pinot.common.Utils;
import com.linkedin.pinot.common.data.FieldSpec.DataType;
import com.linkedin.pinot.common.response.ProcessingException;
import com.linkedin.pinot.common.utils.DataTableBuilder.DataSchema;

/**
 *
 * Read only Datatable. Use DataTableBuilder to build the data table
 */
public class DataTable {
  private static final Charset UTF8 = Charset.forName("UTF-8");

  private static final Logger LOGGER = LoggerFactory.getLogger(DataTable.class);

  int numRows;

  int numCols;

  DataSchema schema;

  static int VERSION_1 = 1;
  static int VERSION = VERSION_1;

  private Map<String, Map<Integer, String>> dictionary;

  private Map<String, String> metadata;

  private ByteBuffer fixedSizeData;

  private ByteBuffer variableSizeData;

  private int[] columnOffsets;

  private int rowSizeInBytes;

  private byte[] fixedSizeDataBytes;

  private byte[] variableSizeDataBytes;

  /**
   *
   * @param numRows
   * @param dictionary
   * @param metadata
   * @param schema
   * @param fixedSizeDataBytes
   * @param variableSizeDataBytes
   * @throws Exception
   */
  public DataTable(int numRows, Map<String, Map<Integer, String>> dictionary, Map<String, String> metadata,
      DataSchema schema, byte[] fixedSizeDataBytes, byte[] variableSizeDataBytes) throws Exception {
    this.numRows = numRows;
    this.dictionary = dictionary;
    this.metadata = metadata;
    this.schema = schema;
    this.fixedSizeDataBytes = fixedSizeDataBytes;
    this.variableSizeDataBytes = variableSizeDataBytes;
    numCols = schema.columnNames.length;
    fixedSizeData = ByteBuffer.wrap(fixedSizeDataBytes);
    variableSizeData = ByteBuffer.wrap(variableSizeDataBytes);
    columnOffsets = computeColumnOffsets(schema);
  }

  /**
   *
   * @param metadata
   */
  public DataTable(Map<String, String> metadata) {
    this.metadata = metadata;
  }

  /**
   *
   * @param schema
   * @return
   */
  private int[] computeColumnOffsets(DataSchema schema) {
    if (schema == null) {
      return null;
    }
    final int[] columnOffsets = new int[schema.columnNames.length];
    for (int i = 0; i < schema.columnNames.length; i++) {
      final DataType type = schema.columnTypes[i];
      columnOffsets[i] = rowSizeInBytes;
      switch (type) {
        case BOOLEAN:
          rowSizeInBytes += 1;
          break;
        case BYTE:
          rowSizeInBytes += 1;
          break;
        case CHAR:
          rowSizeInBytes += 2;
          break;
        case SHORT:
          rowSizeInBytes += 2;
          break;
        case INT:
          rowSizeInBytes += 4;
          break;
        case LONG:
          rowSizeInBytes += 8;
          break;
        case FLOAT:
          rowSizeInBytes += 8;
          break;
        case DOUBLE:
          rowSizeInBytes += 8;
          break;
        case STRING:
          rowSizeInBytes += 4;
          break;
        case OBJECT:
          rowSizeInBytes += 8;
          break;
        case BYTE_ARRAY:
        case CHAR_ARRAY:
        case INT_ARRAY:
        case LONG_ARRAY:
        case FLOAT_ARRAY:
        case SHORT_ARRAY:
        case DOUBLE_ARRAY:
        case STRING_ARRAY:
          rowSizeInBytes += 8;
          break;

        default:
          throw new RuntimeException("Unsupported datatype:" + type);
      }
    }
    return columnOffsets;
  }

  /**
   *
   * @param buffer
   */
  public DataTable(byte[] buffer) {

    final ByteBuffer input = ByteBuffer.wrap(buffer);

    final int version = input.getInt();
    if (version == VERSION_1) {
      decodeV1(input);
      return;
    }
    throw new RuntimeException("Unknown version of DataTable encoding:" + version);
  }

  private void decodeV1(ByteBuffer input) {
    numRows = input.getInt();
    numCols = input.getInt();
    // READ dictionary
    final int dictionaryStart = input.getInt();
    final int dictionaryLength = input.getInt();
    final int metadataStart = input.getInt();
    final int metadataLength = input.getInt();
    final int schemaStart = input.getInt();
    final int schemaLength = input.getInt();
    final int fixedDataStart = input.getInt();
    final int fixedDataLength = input.getInt();
    final int variableDataStart = input.getInt();
    final int variableDataLength = input.getInt();

    // READ DICTIONARY

    byte[] dictionaryBytes = null;
    if (dictionaryLength != 0) {
      dictionaryBytes = new byte[dictionaryLength];
      input.position(dictionaryStart);
      input.get(dictionaryBytes);
      dictionary = (Map<String, Map<Integer, String>>) deserializeDictionary(dictionaryBytes);
    } else {
      dictionary = new HashMap<String, Map<Integer, String>>(1);
    }

    // READ METADATA
    byte[] metadataBytes;
    if (metadataLength != 0) {
      metadataBytes = new byte[metadataLength];
      input.position(metadataStart);
      input.get(metadataBytes);
      metadata = (Map<String, String>) deserializeMetadata(metadataBytes);
    } else {
      metadata = new HashMap<String, String>();
    }

    // READ SCHEMA
    byte[] schemaBytes;

    if (schemaLength != 0) {
      schemaBytes = new byte[schemaLength];
      input.position(schemaStart);
      input.get(schemaBytes);
      schema = DataSchema.fromBytes(schemaBytes);
      columnOffsets = computeColumnOffsets(schema);
    }

    // READ FIXED SIZE DATA BYTES
    if (fixedDataLength != 0) {
      fixedSizeDataBytes = new byte[fixedDataLength];
      input.position(fixedDataStart);
      input.get(fixedSizeDataBytes);
      fixedSizeData = ByteBuffer.wrap(fixedSizeDataBytes);
    }

    // READ VARIABLE SIZE DATA BYTES
    if (variableDataLength != 0) {
      variableSizeDataBytes = new byte[variableDataLength];
      input.position(variableDataStart);
      input.get(variableSizeDataBytes);
      variableSizeData = ByteBuffer.wrap(variableSizeDataBytes);
    }
  }

  public DataTable() {
    // Used for empty results.
    metadata = new HashMap<String, String>();
    metadata.put("numDocsScanned", "0");
    metadata.put("totalDocs", "0");
    metadata.put("timeUsedMs", "0");
  }

  /**
   *
   * @return
   * @throws Exception
   */
  public  byte[] toBytes() throws Exception {
    return toBytes(VERSION_1);
  }

  private byte[] toBytes(int version) throws Exception {
    final byte[] dictionaryBytes = serializeDictionary();
    final byte[] metadataBytes = serializeMetadata();
    byte[] schemaBytes = new byte[0];
    if (schema != null) {
      schemaBytes = schema.toBytes();
    }
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream out = new DataOutputStream(baos);
    // TODO: convert this format into a proper class
    // VERSION|NUM_ROW|NUM_COL|(START|SIZE) -- START|SIZE 5 PAIRS FOR
    // DICTIONARY, METADATA,
    // SCHEMA, DATATABLE, VARIABLE DATA BUFFER --> 4 + 4 + 4 + 5*8 = 52
    // bytes
    out.writeInt(version);
    out.writeInt(numRows);
    out.writeInt(numCols);
    // dictionary
    int baseOffset = 52;
    out.writeInt(baseOffset);
    out.writeInt(dictionaryBytes.length);
    baseOffset += dictionaryBytes.length;

    // metadata
    out.writeInt(baseOffset);
    out.writeInt(metadataBytes.length);
    baseOffset += metadataBytes.length;

    // schema
    out.writeInt(baseOffset);
    out.writeInt(schemaBytes.length);
    baseOffset += schemaBytes.length;

    // datatable
    out.writeInt(baseOffset);
    if (fixedSizeDataBytes == null) {
      out.writeInt(0);
    } else {
      out.writeInt(fixedSizeDataBytes.length);
      baseOffset += fixedSizeDataBytes.length;
    }

    // variable data
    out.writeInt(baseOffset);
    if (variableSizeDataBytes == null) {
      out.writeInt(0);
    } else {
      out.writeInt(variableSizeDataBytes.length);
    }

    // write them
    out.write(dictionaryBytes);
    out.write(metadataBytes);
    out.write(schemaBytes);
    if (fixedSizeDataBytes != null) {
      out.write(fixedSizeDataBytes);
    }
    if (variableSizeDataBytes != null) {
      out.write(variableSizeDataBytes);
    }
    byte[] byteArray = baos.toByteArray();
    long end = System.currentTimeMillis();
    return byteArray;
  }

  private byte[] serializeMetadata() throws Exception {
    if (metadata != null) {
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      final DataOutputStream out = new DataOutputStream(baos);
      out.writeInt(metadata.size());
      for (Entry<String, String> entry : metadata.entrySet()) {
        byte[] keyBytes = entry.getKey().getBytes(UTF8);
        out.writeInt(keyBytes.length);
        out.write(keyBytes);
        byte[] valueBytes = entry.getValue().getBytes(UTF8);
        out.writeInt(valueBytes.length);
        out.write(valueBytes);
      }
      return baos.toByteArray();
    }
    return new byte[0];
  }

  private Map<String, String> deserializeMetadata(byte[] buffer) {
    Map<String, String> map = new HashMap<String, String>();
    try {
      final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
      final DataInputStream in = new DataInputStream(bais);
      int size = in.readInt();
      for (int i = 0; i < size; i++) {
        Integer keyLength = in.readInt();
        byte[] keyBytes = new byte[keyLength];
        in.read(keyBytes);
        int valueLength = in.readInt();
        byte[] valueBytes = new byte[valueLength];
        in.read(valueBytes);
        map.put(new String(keyBytes, UTF8), new String(valueBytes, UTF8));
      }
    } catch (Exception e) {
      LOGGER.error("Exception while deserializing dictionary", e);
    }
    return map;
  }

  private byte[] serializeDictionary() throws Exception {
    if (dictionary != null) {
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      final DataOutputStream out = new DataOutputStream(baos);
      out.writeInt(dictionary.size());
      for (String key : dictionary.keySet()) {
        byte[] bytes = key.getBytes(UTF8);
        out.writeInt(bytes.length);
        out.write(bytes);
        Map<Integer, String> map = dictionary.get(key);
        out.writeInt(map.size());
        for (Entry<Integer, String> entry : map.entrySet()) {
          out.writeInt(entry.getKey());
          byte[] valueBytes = entry.getValue().getBytes(UTF8);
          out.writeInt(valueBytes.length);
          out.write(valueBytes);
        }
      }
      return baos.toByteArray();
    }
    return new byte[0];
  }

  private Map<String, Map<Integer, String>> deserializeDictionary(byte[] buffer) {
    Map<String, Map<Integer, String>> map = new HashMap<String, Map<Integer, String>>();
    try {
      final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
      final DataInputStream in = new DataInputStream(bais);
      int size = in.readInt();
      byte[] temp;
      for (int i = 0; i < size; i++) {
        int readLength = in.readInt();
        temp = new byte[readLength];
        in.read(temp);
        Map<Integer, String> childMap = new HashMap<Integer, String>();
        map.put(new String(temp, UTF8), childMap);
        int childMapSize = in.readInt();
        for (int j = 0; j < childMapSize; j++) {
          Integer key = in.readInt();
          int valueLength = in.readInt();
          temp = new byte[valueLength];
          in.read(temp);
          childMap.put(key, new String(temp, UTF8));
        }
      }
    } catch (Exception e) {
      LOGGER.error("Exception while deserializing dictionary", e);
    }
    return map;
  }

  /**
   *
   * @param value
   * @return
   */
  private byte[] serializeObject(Object value) {
    long start = System.nanoTime();

    byte[] bytes;
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;

    try {
      try {
        out = new ObjectOutputStream(bos);
        out.writeObject(value);
      } catch (final IOException e) {
        LOGGER.error("Caught exception", e);
        Utils.rethrowException(e);
      }
      bytes = bos.toByteArray();

    } finally {
      IOUtils.closeQuietly((Closeable) out);
      IOUtils.closeQuietly(bos);
    }
    long end = System.nanoTime();
    return bytes;
  }

  @SuppressWarnings("unchecked")
  private <T extends Serializable> T deserialize(byte[] value) {
    long start = System.nanoTime();
    final ByteArrayInputStream bais = new ByteArrayInputStream(value);
    ObjectInputStream out = null;
    Object readObject;
    try {
      try {
        out = new ObjectInputStream(bais);
        readObject = out.readObject();

      } catch (final Exception e) {
        LOGGER.error("Caught exception while deserializing DataTable", e);
        return null;
      }
    } finally {
      IOUtils.closeQuietly(out);
      IOUtils.closeQuietly(bais);
    }
    long end = System.nanoTime();
    return (T) readObject;

  }

  /**
   *
   * @return
   */
  public int getNumberOfRows() {
    return numRows;
  }

  /**
   *
   * @return
   */
  public int getNumberOfCols() {
    return numCols;
  }

  /**
   *
   * @return
   */
  public DataSchema getDataSchema() {
    return schema;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public boolean getBoolean(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return (byte) 1 == fixedSizeData.get();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public char getChar(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return fixedSizeData.getChar();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public byte getByte(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return fixedSizeData.get();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public short getShort(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return fixedSizeData.getShort();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public int getInt(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return fixedSizeData.getInt();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public long getLong(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return fixedSizeData.getLong();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public float getFloat(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return fixedSizeData.getFloat();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public double getDouble(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    return fixedSizeData.getDouble();
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public String getString(int rowId, int colId) {
    fixedSizeData.position(rowId * rowSizeInBytes + columnOffsets[colId]);
    final int id = fixedSizeData.getInt();
    final Map<Integer, String> map = dictionary.get(schema.columnNames[colId]);
    return map.get(id);
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public byte[] getByteArray(int rowId, int colId) {
    final int size = positionCursorInVariableBuffer(rowId, colId);
    byte[] ret = new byte[size];
    for (int i = 0; i < size; i++) {
      ret[i] = variableSizeData.get();
    }
    return ret;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public char[] getCharArray(int rowId, int colId) {
    final int size = positionCursorInVariableBuffer(rowId, colId);
    char[] ret = new char[size];
    for (int i = 0; i < size; i++) {
      ret[i] = variableSizeData.getChar();
    }
    return ret;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public int[] getIntArray(int rowId, int colId) {
    final int size = positionCursorInVariableBuffer(rowId, colId);
    int[] ret = new int[size];
    for (int i = 0; i < size; i++) {
      ret[i] = variableSizeData.getInt();
    }
    return ret;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public long[] getLongArray(int rowId, int colId) {
    final int size = positionCursorInVariableBuffer(rowId, colId);
    long[] ret = new long[size];
    for (int i = 0; i < size; i++) {
      ret[i] = variableSizeData.getLong();
    }
    return ret;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public float[] getFloatArray(int rowId, int colId) {
    final int size = positionCursorInVariableBuffer(rowId, colId);
    float[] ret = new float[size];
    for (int i = 0; i < size; i++) {
      ret[i] = variableSizeData.getFloat();
    }
    return ret;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public double[] getDoubleArray(int rowId, int colId) {
    final int size = positionCursorInVariableBuffer(rowId, colId);
    double[] ret = new double[size];
    for (int i = 0; i < size; i++) {
      ret[i] = variableSizeData.getDouble();
    }
    return ret;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  public String[] getStringArray(int rowId, int colId) {
    final int size = positionCursorInVariableBuffer(rowId, colId);
    String[] ret = new String[size];
    final Map<Integer, String> map = dictionary.get(schema.columnNames[colId]);

    for (int i = 0; i < size; i++) {
      ret[i] = map.get(variableSizeData.getInt());
    }
    return ret;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  private int positionCursorInVariableBuffer(int rowId, int colId) {
    int pos = rowId * rowSizeInBytes + columnOffsets[colId];
    fixedSizeData.position(pos);
    final int position = fixedSizeData.getInt();
    final int size = fixedSizeData.getInt();
    variableSizeData.position(position);
    return size;
  }

  /**
   *
   * @param rowId
   * @param colId
   * @return
   */
  @SuppressWarnings("unchecked")
  public <T extends Serializable> T getObject(int rowId, int colId) {
    final int length = positionCursorInVariableBuffer(rowId, colId);
    final byte[] serData = new byte[length];
    variableSizeData.get(serData);
    return (T) deserialize(serData);
  }

  /**
   *
   * @return
   */
  public Map<String, String> getMetadata() {
    return metadata;
  }

  /**
   * To string representation of datatable, contains the content of fixed data
   * size buffer
   */
  @Override
  public String toString() {
    if (schema == null) {
      return metadata.toString();
    }
    final StringBuilder b = new StringBuilder();
    b.append(schema.toString());
    b.append("\n");

    b.append("numRows : " + numRows + "\n");
    fixedSizeData.position(0);
    for (int rowId = 0; rowId < numRows; rowId++) {
      for (int colId = 0; colId < numCols; colId++) {
        final DataType type = schema.columnTypes[colId];
        switch (type) {
          case BOOLEAN:
            b.append(fixedSizeData.get());
            break;
          case BYTE:
            b.append(fixedSizeData.get());
            break;
          case CHAR:
            b.append(fixedSizeData.getChar());
            break;
          case SHORT:
            b.append(fixedSizeData.getShort());
            break;
          case INT:
            b.append(fixedSizeData.getInt());
            break;
          case LONG:
            b.append(fixedSizeData.getLong());
            break;
          case FLOAT:
            b.append(fixedSizeData.getFloat());
            break;
          case DOUBLE:
            b.append(fixedSizeData.getDouble());
            break;
          case STRING:
            b.append(fixedSizeData.getInt());
            break;
          case OBJECT:
            b.append(String.format("(%s:%s)", fixedSizeData.getInt(), fixedSizeData.getInt()));
            break;
          case BYTE_ARRAY:
          case CHAR_ARRAY:
          case SHORT_ARRAY:
          case INT_ARRAY:
          case LONG_ARRAY:
          case FLOAT_ARRAY:
          case DOUBLE_ARRAY:
          case STRING_ARRAY:
            b.append(String.format("(%s:%s)", fixedSizeData.getInt(), fixedSizeData.getInt()));
            break;
          default:
            throw new RuntimeException("Unsupported datatype:" + type);
        }
        b.append("\t");
      }
      b.append("\n");
    }
    return b.toString();
  }

  public void addException(ProcessingException exception) {
    if (metadata == null) {
      metadata = new HashMap<String, String>();
    }
    metadata.put("Exception" + exception.getErrorCode(), exception.getMessage());
  }
}


text:
<?php

namespace Core\DI;

use Core\EGObject;
use Exception\EGException;
class EGContainer extends EGObject{
	/**
	 * @var static
	 */
	public static $instance;
	public static $app;

	/**
	 * @var array singleton objects indexed by their types
	 */
	private $_singletons = [];
	/**
	 * @var array object definitions indexed by their types
	 */
	private $_definitions = [];

	/**
	 * @var array type aliases indexed by alias.
	 */
	private $_aliases = [];
	/**
	 * @var array constructor parameters indexed by object types
	 */
	private $_params = [];
	/**
	 * @var array cached ReflectionClass objects indexed by class/interface names
	 */
	private $_reflections = [];
	/**
	 * @var array cached dependencies indexed by class/interface names. Each class name
	 * is associated with a list of constructor parameter types or default values.
	 */
	private $_dependencies = [];

	/**
	 * Bind aliases for specified type.
	 *
	 * @param $type
	 * @param $alias
	 */
	public function alias($type, $alias)
	{
		$this->_aliases[$alias] = $type;
	}

	/**
	 * Returns the real type of a alias.
	 *
	 * @param $alias
	 * @return string The real type name
	 */
	public function getAlias($alias)
	{
		return isset($this->_aliases[$alias]) ? $this->_aliases[$alias] : $alias;
	}

	/**
	 * Returns an instance of the requested class.
	 *
	 * You may provide constructor parameters (`$params`) and object configurations (`$config`)
	 * that will be used during the creation of the instance.
	 *
	 * Note that if the class is declared to be singleton by calling [[setSingleton()]],
	 * the same instance of the class will be returned each time this method is called.
	 * In this case, the constructor parameters and object configurations will be used
	 * only if the class is instantiated the first time.
	 *
	 * @param string $class the class name or an alias name (e.g. `foo`) that was previously registered via [[set()]]
	 * or [[setSingleton()]].
	 * @param array $params a list of constructor parameter values. The parameters should be provided in the order
	 * they appear in the constructor declaration. If you want to skip some parameters, you should index the remaining
	 * ones with the integers that represent their positions in the constructor parameter list.
	 * @param array $config a list of name-value pairs that will be used to initialize the object properties.
	 * @return object an instance of the requested class.
	 * @throws InvalidConfigException if the class cannot be recognized or correspond to an invalid definition
	 */
	public function get($class, $params = [], $config = [])
	{
		$class = $this->getAlias($class);

		if (isset($this->_singletons[$class])) {
			// singleton
			return $this->_singletons[$class];
		} elseif (!isset($this->_definitions[$class])) {
			return $this->build($class, $params, $config);
		}

		$definition = $this->_definitions[$class];

		if (is_callable($definition, true)) {
			$params = $this->resolveDependencies($this->mergeParams($class, $params));
			$object = call_user_func($definition, $this, $params, $config);
		} elseif (is_array($definition)) {
			$concrete = $definition['class'];
			unset($definition['class']);

			$config = array_merge($definition, $config);
			$params = $this->mergeParams($class, $params);

			if ($concrete === $class) {
				$object = $this->build($class, $params, $config);
			} else {
				$object = $this->get($concrete, $params, $config);
			}
		} elseif (is_object($definition)) {
			return $this->_singletons[$class] = $definition;
		} else {
			throw new EGException("Unexpected object definition type: " . gettype($definition));
		}

		if (array_key_exists($class, $this->_singletons)) {
			// singleton
			$this->_singletons[$class] = $object;
		}

		return $object;
	}

	/**
	 * Registers a class definition with this container.
	 *
	 * For example,
	 *
	 * ```php
	 * // register a class name as is. This can be skipped.
	 * $container->set('yii\db\Connection');
	 *
	 * // register an interface
	 * // When a class depends on the interface, the corresponding class
	 * // will be instantiated as the dependent object
	 * $container->set('yii\mail\MailInterface', 'yii\swiftmailer\Mailer');
	 *
	 * // register an alias name. You can use $container->get('foo')
	 * // to create an instance of Connection
	 * $container->set('foo', 'yii\db\Connection');
	 *
	 * // register a class with configuration. The configuration
	 * // will be applied when the class is instantiated by get()
	 * $container->set('yii\db\Connection', [
	 *     'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
	 *     'username' => 'root',
	 *     'password' => '',
	 *     'charset' => 'utf8',
	 * ]);
	 *
	 * // register an alias name with class configuration
	 * // In this case, a "class" element is required to specify the class
	 * $container->set('db', [
	 *     'class' => 'yii\db\Connection',
	 *     'dsn' => 'mysql:host=127.0.0.1;dbname=demo',
	 *     'username' => 'root',
	 *     'password' => '',
	 *     'charset' => 'utf8',
	 * ]);
	 *
	 * // register a PHP callable
	 * // The callable will be executed when $container->get('db') is called
	 * $container->set('db', function ($container, $params, $config) {
	 *     return new \yii\db\Connection($config);
	 * });
	 * ```
	 *
	 * If a class definition with the same name already exists, it will be overwritten with the new one.
	 * You may use [[has()]] to check if a class definition already exists.
	 *
	 * @param string $class class name, interface name or alias name
	 * @param mixed $definition the definition associated with `$class`. It can be one of the followings:
	 *
	 * - a PHP callable: The callable will be executed when [[get()]] is invoked. The signature of the callable
	 *   should be `function ($container, $params, $config)`, where `$params` stands for the list of constructor
	 *   parameters, `$config` the object configuration, and `$container` the container object. The return value
	 *   of the callable will be returned by [[get()]] as the object instance requested.
	 * - a configuration array: the array contains name-value pairs that will be used to initialize the property
	 *   values of the newly created object when [[get()]] is called. The `class` element stands for the
	 *   the class of the object to be created. If `class` is not specified, `$class` will be used as the class name.
	 * - a string: a class name, an interface name or an alias name.
	 * @param array $params the list of constructor parameters. The parameters will be passed to the class
	 * constructor when [[get()]] is called.
	 * @return static the container itself
	 */
	public function set($class, $definition = [], array $params = [])
	{
		$normalizedDefinition = $this->normalizeDefinition($class, $definition);

		if (is_array($normalizedDefinition)) {
			$concrete = $normalizedDefinition['class'];
		} else {
			$concrete = $class;
		}

		if ($class !== $concrete) {
			$this->alias($concrete, $class);
		}

		$this->_definitions[$concrete] = $normalizedDefinition;
		$this->_params[$concrete] = $params;
		unset($this->_singletons[$concrete]);

		return $this;
	}

	/**
	 * Registers a class definition with this container and marks the class as a singleton class.
	 *
	 * This method is similar to [[set()]] except that classes registered via this method will only have one
	 * instance. Each time [[get()]] is called, the same instance of the specified class will be returned.
	 *
	 * @param string $class class name, interface name or alias name
	 * @param mixed $definition the definition associated with `$class`. See [[set()]] for more details.
	 * @param array $params the list of constructor parameters. The parameters will be passed to the class
	 * constructor when [[get()]] is called.
	 * @return static the container itself
	 * @see set()
	 */
	public function setSingleton($class, $definition = [], array $params = [])
	{
		$normalizedDefinition = $this->normalizeDefinition($class, $definition);

		if (is_array($normalizedDefinition)) {
			$concrete = $normalizedDefinition['class'];
		} else {
			$concrete = $class;
		}

		if ($class !== $concrete) {
			$this->alias($concrete, $class);
		}

		$this->_definitions[$concrete] = $normalizedDefinition;
		$this->_params[$concrete] = $params;
		$this->_singletons[$concrete] = null;

		return $this;
	}

	/**
	 * Returns a value indicating whether the container has the definition of the specified name.
	 * @param string $class class name, interface name or alias name
	 * @return boolean whether the container has the definition of the specified name..
	 * @see set()
	 */
	public function has($class)
	{
		return isset($this->_definitions[$this->getAlias($class)]);
	}

	/**
	 * Returns a value indicating whether the given name corresponds to a registered singleton.
	 * @param string $class class name, interface name or alias name
	 * @param boolean $checkInstance whether to check if the singleton has been instantiated.
	 * @return boolean whether the given name corresponds to a registered singleton. If `$checkInstance` is true,
	 * the method should return a value indicating whether the singleton has been instantiated.
	 */
	public function hasSingleton($class, $checkInstance = false)
	{
		$class = $this->getAlias($class);

		return $checkInstance ? isset($this->_singletons[$class]) : array_key_exists($class, $this->_singletons);
	}

	/**
	 * Removes the definition for the specified name.
	 * @param string $class class name, interface name or alias name
	 */
	public function clear($class)
	{
		$concrete = $this->getAlias($class);
		unset ($this->_aliases[$class]);

		unset($this->_definitions[$concrete], $this->_singletons[$concrete]);
	}

	/**
	 * Normalizes the class definition.
	 * @param string $class class name
	 * @param string|array|callable $definition the class definition
	 * @return array the normalized class definition
	 * @throws InvalidConfigException if the definition is invalid.
	 */
	protected function normalizeDefinition($class, $definition)
	{
		if (empty($definition)) {
			return ['class' => $class];
		} elseif (is_string($definition)) {
			return ['class' => $definition];
		} elseif (is_callable($definition, true) || is_object($definition)) {
			return $definition;
		} elseif (is_array($definition)) {
			if (!isset($definition['class'])) {
				if (strpos($class, '\\') !== false) {
					$definition['class'] = $class;
				} else {
					throw new EGException("A class definition requires a \"class\" member.");
				}
			}
			return $definition;
		} else {
			throw new EGException("Unsupported definition type for \"$class\": " . gettype($definition));
		}
	}

	/**
	 * Returns the list of the object definitions or the loaded shared objects.
	 * @return array the list of the object definitions or the loaded shared objects (type or ID => definition or instance).
	 */
	public function getDefinitions()
	{
		return $this->_definitions;
	}

	/**
	 * Creates an instance of the specified class.
	 * This method will resolve dependencies of the specified class, instantiate them, and inject
	 * them into the new instance of the specified class.
	 * @param string $class the class name
	 * @param array $params constructor parameters
	 * @param array $config configurations to be applied to the new instance
	 * @return object the newly created instance of the specified class
	 */
	protected function build($class, $params, $config)
	{
		/* @var $reflection ReflectionClass */
		list ($reflection, $dependencies) = $this->getDependencies($class);

		foreach ($params as $index => $param) {
			$dependencies[$index] = $param;
		}

		if (!empty($dependencies) && is_a($class, 'blink\core\Configurable', true)) {
			// set $config as the last parameter (existing one will be overwritten)
			$dependencies[count($dependencies) - 1] = $config;
			$dependencies = $this->resolveDependencies($dependencies, $reflection);
			return $reflection->newInstanceArgs($dependencies);
		} else {
			$dependencies = $this->resolveDependencies($dependencies, $reflection);
			$object = $reflection->newInstanceArgs($dependencies);
			foreach ($config as $name => $value) {
				$object->$name = $value;
			}
			return $object;
		}
	}

	/**
	 * Merges the user-specified constructor parameters with the ones registered via [[set()]].
	 * @param string $class class name, interface name or alias name
	 * @param array $params the constructor parameters
	 * @return array the merged parameters
	 */
	protected function mergeParams($class, $params)
	{
		if (empty($this->_params[$class])) {
			return $params;
		} elseif (empty($params)) {
			return $this->_params[$class];
		} else {
			$ps = $this->_params[$class];
			foreach ($params as $index => $value) {
				$ps[$index] = $value;
			}
			return $ps;
		}
	}

	/**
	 * Returns the dependencies of the specified class.
	 * @param string $class class name, interface name or alias name
	 * @return array the dependencies of the specified class.
	 */
	protected function getDependencies($class)
	{
		if (isset($this->_reflections[$class])) {
			return [$this->_reflections[$class], $this->_dependencies[$class]];
		}

		$dependencies = [];
		$reflection = new \ReflectionClass($class);

		$constructor = $reflection->getConstructor();
		if ($constructor !== null) {
			foreach ($constructor->getParameters() as $param) {
				if ($param->isDefaultValueAvailable()) {
					$dependencies[] = $param->getDefaultValue();
				} else {
					$c = $param->getClass();
					$dependencies[] = EGInstance::of($c === null ? null : $c->getName());
				}
			}
		}

		$this->_reflections[$class] = $reflection;
		$this->_dependencies[$class] = $dependencies;

		return [$reflection, $dependencies];
	}

	/**
	 * Resolves dependencies by replacing them with the actual object instances.
	 * @param array $dependencies the dependencies
	 * @param ReflectionClass $reflection the class reflection associated with the dependencies
	 * @return array the resolved dependencies
	 * @throws InvalidConfigException if a dependency cannot be resolved or if a dependency cannot be fulfilled.
	 */
	protected function resolveDependencies($dependencies, $reflection = null)
	{
		foreach ($dependencies as $index => $dependency) {
			if ($dependency instanceof EGInstance) {
				if ($dependency->id !== null) {
					$dependencies[$index] = $this->get($dependency->id);
				} elseif ($reflection !== null) {
					$name = $reflection->getConstructor()->getParameters()[$index]->getName();
					$class = $reflection->getName();
					throw new EGException("Missing required parameter \"$name\" when instantiating \"$class\".");
				}
			}
		}
		return $dependencies;
	}
}


text:
using OfficeDevPnP.MSGraphAPIDemo.Components;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using OfficeDevPnP.MSGraphAPIDemo.Models;
using System.Threading;

namespace OfficeDevPnP.MSGraphAPIDemo.Controllers
{
    public class FilesController : Controller
    {
        // GET: Files
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult PlayWithFiles()
        {
            var drive = FilesHelper.GetUserPersonalDrive();
            var root = FilesHelper.GetUserPersonalDriveRoot();
            var childrenItems = FilesHelper.ListFolderChildren(drive.Id, root.Id);

            var newFileOnRoot = UploadSampleFile(drive, root, Server.MapPath("~/AppIcon.png"));

            // Collect information about children items in the root folder
            StringBuilder sb = new StringBuilder();
            String oneFolderId = null;

            foreach (var item in childrenItems)
            {
                if (item.Folder != null)
                {
                    sb.AppendFormat("Found folder {0} with {1} child items.\n", item.Name, item.Folder.ChildCount);
                    if (item.Name == "One Folder")
                    {
                        oneFolderId = item.Id;
                    }
                }
                else
                {
                    sb.AppendFormat("Found file {0}.\n", item.Name);
                }
            }
            var filesLog = sb.ToString();

            // Create a new folder in the root folder
            var newFolder = FilesHelper.CreateFolder(drive.Id, root.Id,
                new Models.DriveItem
                {
                    Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}",
                    Folder = new Models.Folder { },
                });

            var newFile = UploadSampleFile(drive, newFolder, Server.MapPath("~/AppIcon.png"));
            UpdateSampleFile(drive, newFile, Server.MapPath("~/SP2016-MinRoles.jpg"));

            // Create another folder in the root folder
            var anotherFolder = FilesHelper.CreateFolder(drive.Id, root.Id,
                new Models.DriveItem
                {
                    Name = $"Folder Created via API - {DateTime.Now.GetHashCode()}",
                    Folder = new Models.Folder { },
                });

            var movedItem = FilesHelper.MoveDriveItem(drive.Id, newFile.Id, "moved.jpg", anotherFolder.Name);
            var movedFolder = FilesHelper.MoveDriveItem(drive.Id, anotherFolder.Id, "Moved Folder", newFolder.Name);

            var searchResult = FilesHelper.Search("PnPLogo", drive.Id, root.Id);

            if (searchResult != null && searchResult.Count > 0)
            {
                var firstFileResult = searchResult.FirstOrDefault(i => i.File != null);

                try
                {
                    var thumbnails = FilesHelper.GetFileThumbnails(drive.Id, firstFileResult.Id);
                    var thumbnailMedium = FilesHelper.GetFileThumbnail(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium);
                    var thumbnailImage = FilesHelper.GetFileThumbnailImage(drive.Id, firstFileResult.Id, Models.ThumbnailSize.Medium);
                }
                catch (Exception)
                {
                    // Something wrong while getting the thumbnail,
                    // We will have to handle it properly ...
                }
            }

            if (newFileOnRoot != null)
            {
                var permission = FilesHelper.GetDriveItemPermission(newFileOnRoot.Id, "0");
                FilesHelper.DeleteFile(drive.Id, newFileOnRoot.Id);
            }

            try
            {
                var sharingPermission = FilesHelper.CreateSharingLink(newFolder.Id,
                SharingLinkType.View, SharingLinkScope.Anonymous);
            }
            catch (Exception)
            {
                // Something wrong while getting the sharing link,
                // We will have to handle it properly ...
            }

            if (!String.IsNullOrEmpty(oneFolderId))
            {
                var newFolderChildren = FilesHelper.ListFolderChildren(drive.Id, newFolder.Id);
                var file = newFolderChildren.FirstOrDefault(f => f.Name == "moved.jpg");

                if (file != null)
                {
                    String jpegContentType = "image/jpeg";
                    Stream fileContent = FilesHelper.GetFileContent(drive.Id, file.Id, jpegContentType);
                    return (base.File(fileContent, jpegContentType, file.Name));
                }
            }

            return View("Index");
        }

        private Models.DriveItem UploadSampleFile(Models.Drive drive, Models.DriveItem newFolder, String filePath)
        {
            Models.DriveItem result = null;
            Stream memPhoto = getFileContent(filePath);

            try
            {
                if (memPhoto.Length > 0)
                {
                    String contentType = "image/png";
                    result = FilesHelper.UploadFile(drive.Id, newFolder.Id,
                        new Models.DriveItem
                        {
                            File = new Models.File { },
                            Name = "PnPLogo.png",
                            ConflictBehavior = "rename",
                        },
                        memPhoto,
                        contentType);
                }
            }
            catch (Exception ex)
            {
                // Handle the exception
            }

            return (result);
        }

        private void UpdateSampleFile(Drive drive, DriveItem newFile, String filePath)
        {
            FilesHelper.RenameFile(drive.Id, newFile.Id, "SP2016-MinRoles.jpg");

            Stream memPhoto = getFileContent(filePath);

            try
            {
                if (memPhoto.Length > 0)
                {
                    String contentType = "image/jpeg";
                    FilesHelper.UpdateFileContent(
                        drive.Id,
                        newFile.Id,
                        memPhoto,
                    contentType);
                }
            }
            catch (Exception ex)
            {
                // Handle the exception
            }
        }

        private static Stream getFileContent(String filePath)
        {
            MemoryStream memPhoto = new MemoryStream();
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                Byte[] newPhoto = new Byte[fs.Length];
                fs.Read(newPhoto, 0, (Int32)(fs.Length - 1));
                memPhoto.Write(newPhoto, 0, newPhoto.Length);
                memPhoto.Position = 0;
            }

            return memPhoto;
        }
    }
}


text:
FROM inthecloud247/kdocker-base
MAINTAINER inthecloud247 "inthecloud247@gmail.com"

# openjdk7
RUN apt-get -y install --no-install-recommends openjdk-7-jdk

# set JAVA_HOME
ENV JAVA_HOME /usr/lib/jvm/java-7-openjdk-amd64


text:
"""curses.wrapper

Contains one function, wrapper(), which runs another function which
should be the rest of your curses-based application.  If the
application raises an exception, wrapper() will restore the terminal
to a sane state so you can read the resulting traceback.

"""

import sys, curses

def wrapper(func, *args, **kwds):
    """Wrapper function that initializes curses and calls another function,
    restoring normal keyboard/screen behavior on error.
    The callable object 'func' is then passed the main window 'stdscr'
    as its first argument, followed by any other arguments passed to
    wrapper().
    """

    res = None
    try:
        # Initialize curses
        stdscr=curses.initscr()

        # Turn off echoing of keys, and enter cbreak mode,
        # where no buffering is performed on keyboard input
        curses.noecho()
        curses.cbreak()

        # In keypad mode, escape sequences for special keys
        # (like the cursor keys) will be interpreted and
        # a special value like curses.KEY_LEFT will be returned
        stdscr.keypad(1)

        # Start color, too.  Harmless if the terminal doesn't have
        # color; user can test with has_color() later on.  The try/catch
        # works around a minor bit of over-conscientiousness in the curses
        # module -- the error return from C start_color() is ignorable.
        try:
            curses.start_color()
        except:
            pass

        return func(stdscr, *args, **kwds)
    finally:
        # Set everything back to normal
        stdscr.keypad(0)
        curses.echo()
        curses.nocbreak()
        curses.endwin()


text:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Malware.MDKWhitelistExtractor;

namespace DocGen
{
    public class Program
    {
        public static async Task<int> Main()
        {
            var commandLine = new CommandLine(Environment.CommandLine);
            try
            {
                var program = new Program();
                return await program.Run(commandLine);
            }
            catch (Exception e)
            {
                if (commandLine.IndexOf("-verbose") >= 0)
                    Console.WriteLine(e);
                else
                    Console.WriteLine(e.Message);
                return -1;
            }
        }

        async Task<int> Run(CommandLine commandLine)
        {
            var cts = new CancellationTokenSource();
            var spinTask = SpinAsync(cts.Token);
            try
            {
                var path = Environment.CurrentDirectory;
                var cacheIndex = commandLine.IndexOf("-cache");
                if (cacheIndex >= 0)
                    path = Path.GetFullPath(commandLine[cacheIndex + 1]);

                var update = commandLine.IndexOf("-update") >= 0;

                if (update)
                    await WhitelistAndTerminalCaches.Update(path);

                string output = null;
                var outputIndex = commandLine.IndexOf("-output");
                if (outputIndex >= 0)
                    output = Path.GetFullPath(commandLine[outputIndex + 1]);
                if (output != null)
                    await GenerateDocs(path, output);

                return 0;
            }
            finally
            {
                cts.Cancel();
                await spinTask;
            }
        }

        async Task GenerateDocs(string path, string output)
        {
            //var whitelist = Whitelist.Load(Path.Combine(path, "whitelist.cache"));
            await ProgrammableBlockApi.Update(Path.Combine(path, "whitelist.cache"), Path.Combine(output, "api"));

            Terminals.Update(Path.Combine(path, "terminal.cache"), Path.Combine(output, "List-Of-Terminal-Properties-And-Actions.md"));
        }

        async Task SpinAsync(CancellationToken cancellationToken)
        {
            var l = Console.CursorLeft;
            var t = Console.CursorTop;

            var animations = new[] { '|', '/', '-', '\\' };
            long i = 0;
            while (!cancellationToken.IsCancellationRequested)
            {
                var rl = Console.CursorLeft;
                var rt = Console.CursorTop;
                Console.SetCursorPosition(l, t);
                Console.Write(animations[i % animations.Length]);
                i++;
                Console.SetCursorPosition(rl, rt);
                try
                {
                    await Task.Delay(250, cancellationToken);
                }
                catch (TaskCanceledException)
                {
                    return;
                }
            }
        }
    }
}


text:
<?php

namespace BookStack\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'BookStack\Events\SomeEvent' => [
            'BookStack\Listeners\EventListener',
        ],
    ];

    /**
     * Register any other events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    }
}


text:
cask "nagbar" do
  version "1.3.6"
  sha256 "31efe0ff0428dc1d45e04c8e4954dc25fd7f4f7839bb1adc763b626f44efc17d"

  # github.com/volendavidov/NagBar/ was verified as official when first introduced to the cask
  url "https://github.com/volendavidov/NagBar/releases/download/#{version}/NagBar.zip"
  appcast "https://github.com/volendavidov/NagBar/releases.atom"
  name "NagBar"
  desc "Status bar monitor for Nagios, Icinga/2 and Thruk"
  homepage "https://sites.google.com/site/nagbarapp/home"

  app "NagBar.app"

  zap trash: [
    "~/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.volendavidov.nagbar.sfl*",
    "~/Caches/com.volendavidov.NagBar",
    "~/Preferences/com.volendavidov.NagBar.plist",
  ]
end


text:
import { wireList } from '../../utils/dc/wires';

import SchemaList from '../components/SchemaList';
import api from '../api';

var List = ({items}) => (

Schemas

      <SchemaList items={items} />

);

export default wireList({
  loadItems: api.loadItems
})(List);


text:
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary Author="汪荣(QQ:386666951)" >

    <!-- SystemCloseButton资源定义 -->
    <ImageBrush x:Key="sysbtn_close_normal" ImageSource="ControlDemo/Theme/images/system/close_n.png" Stretch="None" />
    <ImageBrush x:Key="sysbtn_close_hover" ImageSource="ControlDemo/Theme/images/system/close_h.png" Stretch="None" />
    <ImageBrush x:Key="sysbtn_close_down" ImageSource="ControlDemo/Theme/images/system/close_n.png" Stretch="None" />

    <!-- SystemMaxButton资源定义 -->
    <ImageBrush x:Key="sysbtn_max_normal" ImageSource="ControlDemo/Theme/images/system/max_n.png" Stretch="None" />
    <ImageBrush x:Key="sysbtn_max_hover" ImageSource="ControlDemo/Theme/images/system/max_h.png" Stretch="None" />

    <!-- SystemRestoreButton资源定义 -->
    <ImageBrush x:Key="sysbtn_restore_normal" ImageSource="ControlDemo/Theme/images/system/restore_n.png" Stretch="None" />
    <ImageBrush x:Key="sysbtn_restore_hover" ImageSource="ControlDemo/Theme/images/system/restore_h.png" Stretch="None" />

    <!-- SystemMinButton资源定义 -->
    <ImageBrush x:Key="sysbtn_min_normal" ImageSource="ControlDemo/Theme/images/system/min_n.png" Stretch="None" />
    <ImageBrush x:Key="sysbtn_min_hover" ImageSource="ControlDemo/Theme/images/system/min_h.png" Stretch="None" />
	<ImageBrush x:Key="sysbtn_min_down" ImageSource="ControlDemo/Theme/images/system/min_n.png" Stretch="None" />

    <Style TargetType="CloseButton">
        <Setter Property="ToolTip" Value="关闭"/>
        <Setter Property="Background" Value="{DynamicResource sysbtn_close_normal}" />
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate TargetType="CloseButton">
                    <Border Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}">
                        <ContentPresenter ToolTip="{TemplateBinding ToolTip}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsPressed" Value="True" >
                <Setter Property="Background" Value="{DynamicResource sysbtn_close_down}" />
            </Trigger>
            <Trigger Property="IsMouseOver" Value="True" >
                <Setter Property="Background" Value="{DynamicResource sysbtn_close_hover}" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="MinimizeButton">
        <Setter Property="ToolTip" Value="最小化" />
        <Setter Property="Background" Value="{DynamicResource sysbtn_min_normal}" />
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate TargetType="MinimizeButton">
                    <Border Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}">
                        <ContentPresenter ToolTip="{TemplateBinding ToolTip}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="IsPressed" Value="True" >
                <Setter Property="Background" Value="{DynamicResource sysbtn_min_down}" />
            </Trigger>
            <Trigger Property="IsMouseOver" Value="True" >
                <Setter Property="Background" Value="{DynamicResource sysbtn_min_hover}" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <Style TargetType="MaximizeButton">
        <Setter Property="Background" Value="{DynamicResource sysbtn_max_normal}" />
        <Setter Property="ToolTip" Value="最大化" />
        <Setter Property="Template" >
            <Setter.Value>
                <ControlTemplate TargetType="MaximizeButton">
                    <Border Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}">
                        <ContentPresenter ToolTip="{TemplateBinding ToolTip}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="WindowState" Value="Maximized" />
                    <Condition Property="IsMouseOver" Value="True" />
                </MultiTrigger.Conditions>
                <Setter Property="ToolTip" Value="向下还原" />
                <Setter Property="Background" Value="{DynamicResource sysbtn_restore_hover}" />
            </MultiTrigger>
            <MultiTrigger>
                <MultiTrigger.Conditions>
                    <Condition Property="WindowState" Value="Maximized" />
                    <Condition Property="IsPressed" Value="True" />
                </MultiTrigger.Conditions>
                <Setter Property="Background" Value="{DynamicResource sysbtn_restore_down}" />
            </MultiTrigger>
            <Trigger Property="WindowState" Value="Maximized" >
                <Setter Property="Background" Value="{DynamicResource sysbtn_restore_normal}" />
            </Trigger>
            <Trigger Property="IsPressed" Value="True" >
                <Setter Property="Background" Value="{DynamicResource sysbtn_max_down}" />
            </Trigger>
            <Trigger Property="IsMouseOver" Value="True" >
                <Setter Property="Background" Value="{DynamicResource sysbtn_max_hover}" />
            </Trigger>
        </Style.Triggers>
    </Style>
</ResourceDictionary>


text:
monad-ran
=========

A large number of monads written in the form of right Kan extensions and "right Kan extension transformers". This includes the entire monad-transformer library, IO, ST s, and STM.

Some of these perform nicely on certain benchmarks.

Others could stand to be rewritten to provide strictness guarantees that are more inline with the behavior of the MTL.

More information on right Kan extensions in Haskell can be found here:

* <http://comonad.com/reader/2008/kan-extensions/>

* <http://comonad.com/reader/2008/kan-extensions-ii/>

* <http://comonad.com/reader/2008/kan-extension-iii/>


text:
Aluno {{vm.aluno.id}}

    <jhi-alert-error></jhi-alert-error>

Dre

            {{vm.aluno.dre}}

Nome

            {{vm.aluno.nome}}

Data Matricula

            {{vm.aluno.dataMatricula | date:'medium'}}

Turno

            {{vm.aluno.turno}}

Status Inscricao

            {{vm.aluno.statusInscricao}}

Cpf

            {{vm.aluno.cpf}}

Nome Mae

            {{vm.aluno.nomeMae}}

Nome Pai

            {{vm.aluno.nomePai}}

Endereco

            {{vm.aluno.endereco}}

Usuario

            {{vm.aluno.usuarioId}}

    <button type="submit"
            ui-sref="{{ vm.previousState }}"
            class="btn btn-info">
          Back
    </button>

    <button type="button" ui-sref="aluno-detail.edit({id:vm.aluno.id})" class="btn btn-primary">

         Edit
    </button>


text:
package dualcore;

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

import battlecode.common.Direction;
import battlecode.common.GameActionException;
import battlecode.common.GameConstants;
import battlecode.common.MapLocation;
import battlecode.common.Robot;
import battlecode.common.RobotController;
import battlecode.common.RobotType;

public class HQ extends AbstractRobotType {

	private int ySize;
	private int xSize;
	private MapLocation myHq;
	private MapLocation otherHq;
	private MapAnalyzer mapAnalyzer;
	private Team[] teams;
	private Direction spawningDefault;
	private int teamId = 0;
	private Set<MapLocation> pastPastrLocations = new HashSet<MapLocation>();

	public HQ(RobotController rc) {
		super(rc);
	}

	@Override
	protected void act() throws GameActionException {
		Team.updateSoldierCount(rc, teams);
		// Check if a robot is spawnable and spawn one if it is
		if (rc.isActive() && rc.senseRobotCount() < GameConstants.MAX_ROBOTS) {
			Channel.assignTeamId(rc, teamId);
			teamId = (teamId + 1) % teams.length;
			Robot[] closeOpponents = rc.senseNearbyGameObjects(Robot.class,
					RobotType.HQ.sensorRadiusSquared, rc.getTeam().opponent());
			if (Soldier.size(closeOpponents) > 0) {
				Direction away = rc.senseLocationOf(closeOpponents[0])
						.directionTo(myHq);
				spawningDefault = away;
			}
			if (rc.canMove(spawningDefault))
				rc.spawn(spawningDefault);
			else {
				int i = 0;
				Direction dir = spawningDefault;
				while (!rc.canMove(dir) && i < C.DIRECTIONS.length) {
					dir = dir.rotateLeft();
				}
				if (rc.canMove(dir)) {
					rc.spawn(dir);
				}
			}
		}
		if (rc.senseRobotCount() < 1) {
			// location between our HQ and opponent's HQ:
			MapLocation target = new MapLocation(
					(myHq.x * 3 / 4 + otherHq.x / 4),
					(myHq.y * 3 / 4 + otherHq.y / 4));

			teams[0].setTask(Task.ACCUMULATE, target);
			teams[1].setTask(Task.ACCUMULATE, target);
			teams[2].setTask(Task.ACCUMULATE, target);
		} else {
			MapLocation[] pastrLocations = rc.sensePastrLocations(rc.getTeam()
					.opponent());
			if (Soldier.size(pastrLocations) > 0) {
				teams[0].setTask(Task.GOTO, pastrLocations[0]);
				teams[1].setTask(Task.GOTO, pastrLocations[0]);
			} else {
				if (rc.senseRobotCount() > 5) {
					mapAnalyzer = new MapAnalyzer(rc, myHq, otherHq, ySize,
							xSize);
					if (!pastPastrLocations.contains(mapAnalyzer
							.evaluateBestPastrLoc())) {
						teams[2].setTask(Task.BUILD_PASTR,
								mapAnalyzer.evaluateBestPastrLoc());
						teams[1].setTask(Task.BUILD_NOISETOWER,
								mapAnalyzer.evaluateBestPastrLoc());
						pastPastrLocations.add(mapAnalyzer
								.evaluateBestPastrLoc());
					}
				}
			}
		}
	}

	@Override
	protected void init() throws GameActionException {
		ySize = rc.getMapHeight();
		xSize = rc.getMapWidth();
		myHq = rc.senseHQLocation();
		otherHq = rc.senseEnemyHQLocation();
		teams = Team.getTeams(rc);

		mapAnalyzer = new MapAnalyzer(rc, myHq, otherHq, ySize, xSize);
		// mapAnalyzer.generateRealDistanceMap(); // TODO: too expensive
		// mapAnalyzer.printMapAnalysisDistance();
		spawningDefault = myHq.directionTo(otherHq);
		int i = 0;
		while (!rc.canMove(spawningDefault) && i < C.DIRECTIONS.length) {
			spawningDefault = C.DIRECTIONS[i];
			i++;
		}
	}
}


text:
'use strict';

module.exports = (config)=> (req, res, next)=> {
    const fs = require('fs');
    const path = require('path');
    const fsext = require('fs-extra');
    const core = require('saturn-core');

    // work manager thread
    let {thread} = req.modules;

    // express saturn middleware
    let app = {};

    // npm install @workspace
    app.install = (args)=> new Promise((resolve)=> {
        let {WORKSPACE_PATH, lib, runpath} = args;

        lib = JSON.parse(lib);

        let npmlibs = core.compile.node_modules(lib.value, path.join(WORKSPACE_PATH, runpath));

        if (fs.existsSync(path.join(WORKSPACE_PATH, runpath, 'package.json')) == false)
            fs.writeFileSync(path.join(WORKSPACE_PATH, runpath, 'package.json'), JSON.stringify({}));

        thread.install(npmlibs, path.join(WORKSPACE_PATH, runpath), runpath).then(resolve);
    });

    app.save = (args)=> new Promise((resolve)=> {
        // initialize variables
        let {WORKSPACE_PATH, TMP_PATH, lib, scripts, config} = args;

        // check required files
        if (!fs.existsSync(WORKSPACE_PATH)) fsext.mkdirsSync(WORKSPACE_PATH);
        if (!fs.existsSync(TMP_PATH)) fsext.mkdirsSync(TMP_PATH);

        // save project info.
        if (lib)
            fs.writeFileSync(path.join(TMP_PATH, 'lib.json'), lib);
        if (scripts)
            fs.writeFileSync(path.join(TMP_PATH, 'scripts.json'), scripts);
        if (config)
            fs.writeFileSync(path.join(TMP_PATH, 'config.json'), config);

        resolve();
    });

    req.saturn = app;

    next();
};


text:
import datetime
from hubbot.response import IRCResponse, ResponseType
from hubbot.moduleinterface import ModuleInterface

class Nope(ModuleInterface):
    help = "Nope."
    seconds = 300
    last_triggered = datetime.datetime.min

    def should_trigger(self, message):
        """
        @type message: hubbot.message.IRCMessage
        """
        if message.message_string.lower().startswith("nope"):
            if (datetime.datetime.now() - self.last_triggered).seconds >= self.seconds:
                self.last_triggered = datetime.datetime.now()
                return True
        else:
            return False

    def on_trigger(self, message):
        """
        @type message: hubbot.message.IRCMessage
        """
        return IRCResponse(ResponseType.SAY, "I don't think so either.", message.reply_to)


text:
require 'github_client'
require 'git_lib_ext'

GITHUB = Github.new(oauth_token: ENV['GIT_OAUTH_TOKEN'], client_id: ENV['GIT_APP_ID'], client_secret: ENV['GIT_APP_SECRET'])
GithubClient.init(oauth_token: ENV['GIT_OAUTH_TOKEN'], client_id: ENV['GIT_APP_ID'], client_secret: ENV['GIT_APP_SECRET'])

YAML.load_file('config/code_curiosity_config.yml').tap do |config|
  ROUND_CONFIG =  config['round']
  REPOSITORY_CONFIG = config['repository']
  SCORING_ENGINE_CONFIG = config['scoring_engine']
  USER = config['user']
  REDEEM = config['redeem']
  SPONSOR = config['sponsor']
  SUBSCRIPTIONS = config['subscriptions']
  SPONSORER_THRESHOLD = config['sponsor_display_threshold']
  REDEEM_THRESHOLD = config['redeem_request_threshold']
  ACCOUNT = config['account']
  ORGANIZATIONAL_SPONSORERS = config['organizational_sponsorers']
end

COMMIT_RATINGS = (0..5).to_a
ACTIVITY_RATINGS = (0..2).to_a

INFO = YAML.load_file('config/info.yml')

MARKDOWN = Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true)


text:
There is no reliable way to distinguish a zero-size buffer from a non-buffer
based on the return values alone: a NULL with zero size is returned
for a non-buffer.  The same values may be returned for a zero-size buffer (although
it is also possible that a non-NULL pointer is returned).  Use
duk_is_buffer_data() when type
checking a buffer or a buffer object.


text: ./plot.R -i benchmark.seqkit.files_size.tsv --width 5.5 --height 5.5